batch.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package tsdb
  2. import "context"
  3. type Batch struct {
  4. DataSourceId int64
  5. Queries []*Query
  6. Depends map[string]bool
  7. Done bool
  8. Started bool
  9. }
  10. type BatchSlice []*Batch
  11. func newBatch(dsId int64, queries []*Query) *Batch {
  12. return &Batch{
  13. DataSourceId: dsId,
  14. Queries: queries,
  15. Depends: make(map[string]bool),
  16. }
  17. }
  18. func (bg *Batch) process(ctx context.Context, resultChan chan *BatchResult, tsdbQuery *TsdbQuery) {
  19. executor, err := getTsdbQueryEndpointFor(bg.Queries[0].DataSource)
  20. if err != nil {
  21. bg.Done = true
  22. result := &BatchResult{
  23. Error: err,
  24. QueryResults: make(map[string]*QueryResult),
  25. }
  26. for _, query := range bg.Queries {
  27. result.QueryResults[query.RefId] = &QueryResult{Error: result.Error}
  28. }
  29. resultChan <- result
  30. return
  31. }
  32. res := executor.Query(ctx, &TsdbQuery{
  33. Queries: bg.Queries,
  34. TimeRange: tsdbQuery.TimeRange,
  35. })
  36. bg.Done = true
  37. resultChan <- res
  38. }
  39. func (bg *Batch) addQuery(query *Query) {
  40. bg.Queries = append(bg.Queries, query)
  41. }
  42. func (bg *Batch) allDependenciesAreIn(res *Response) bool {
  43. for key := range bg.Depends {
  44. if _, exists := res.Results[key]; !exists {
  45. return false
  46. }
  47. }
  48. return true
  49. }
  50. func getBatches(req *TsdbQuery) (BatchSlice, error) {
  51. batches := make(BatchSlice, 0)
  52. for _, query := range req.Queries {
  53. if foundBatch := findMatchingBatchGroup(query, batches); foundBatch != nil {
  54. foundBatch.addQuery(query)
  55. } else {
  56. newBatch := newBatch(query.DataSource.Id, []*Query{query})
  57. batches = append(batches, newBatch)
  58. for _, refId := range query.Depends {
  59. for _, batch := range batches {
  60. for _, batchQuery := range batch.Queries {
  61. if batchQuery.RefId == refId {
  62. newBatch.Depends[refId] = true
  63. }
  64. }
  65. }
  66. }
  67. }
  68. }
  69. return batches, nil
  70. }
  71. func findMatchingBatchGroup(query *Query, batches BatchSlice) *Batch {
  72. for _, batch := range batches {
  73. if batch.DataSourceId == query.DataSource.Id {
  74. return batch
  75. }
  76. }
  77. return nil
  78. }