2016-06-06 16:31:21 +08:00
|
|
|
package tsdb
|
|
|
|
|
2017-03-31 17:45:25 +08:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
2016-07-20 20:28:02 +08:00
|
|
|
|
2016-10-03 15:38:03 +08:00
|
|
|
type HandleRequestFunc func(ctx context.Context, req *Request) (*Response, error)
|
|
|
|
|
|
|
|
func HandleRequest(ctx context.Context, req *Request) (*Response, error) {
|
2017-09-21 00:31:34 +08:00
|
|
|
tsdbQuery := NewQueryContext(req.Queries, req.TimeRange)
|
2016-06-06 16:31:21 +08:00
|
|
|
|
|
|
|
batches, err := getBatches(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
currentlyExecuting := 0
|
2017-09-21 00:31:34 +08:00
|
|
|
resultsChan := make(chan *BatchResult)
|
2016-06-06 16:31:21 +08:00
|
|
|
|
|
|
|
for _, batch := range batches {
|
|
|
|
if len(batch.Depends) == 0 {
|
|
|
|
currentlyExecuting += 1
|
|
|
|
batch.Started = true
|
2017-09-21 00:31:34 +08:00
|
|
|
go batch.process(ctx, resultsChan, tsdbQuery)
|
2016-06-06 16:31:21 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-21 00:31:34 +08:00
|
|
|
response := &Response{
|
|
|
|
Results: make(map[string]*QueryResult),
|
|
|
|
}
|
2016-06-06 16:31:21 +08:00
|
|
|
|
|
|
|
for currentlyExecuting != 0 {
|
|
|
|
select {
|
2017-09-21 00:31:34 +08:00
|
|
|
case batchResult := <-resultsChan:
|
2016-06-06 16:31:21 +08:00
|
|
|
currentlyExecuting -= 1
|
|
|
|
|
|
|
|
response.BatchTimings = append(response.BatchTimings, batchResult.Timings)
|
|
|
|
|
2016-06-06 23:11:46 +08:00
|
|
|
if batchResult.Error != nil {
|
|
|
|
return nil, batchResult.Error
|
|
|
|
}
|
|
|
|
|
2016-06-06 16:31:21 +08:00
|
|
|
for refId, result := range batchResult.QueryResults {
|
2017-09-21 00:31:34 +08:00
|
|
|
response.Results[refId] = result
|
2016-06-06 16:31:21 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, batch := range batches {
|
|
|
|
// not interested in started batches
|
|
|
|
if batch.Started {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-09-21 00:31:34 +08:00
|
|
|
if batch.allDependenciesAreIn(response) {
|
2016-06-06 16:31:21 +08:00
|
|
|
currentlyExecuting += 1
|
|
|
|
batch.Started = true
|
2017-09-21 00:31:34 +08:00
|
|
|
go batch.process(ctx, resultsChan, tsdbQuery)
|
2016-06-06 16:31:21 +08:00
|
|
|
}
|
|
|
|
}
|
2016-10-03 20:33:47 +08:00
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, ctx.Err()
|
2016-06-06 16:31:21 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-21 00:31:34 +08:00
|
|
|
//response.Results = tsdbQuery.Results
|
2016-06-06 16:31:21 +08:00
|
|
|
return response, nil
|
|
|
|
}
|