batch.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package tsdb
  2. import (
  3. "context"
  4. "errors"
  5. )
  6. type Batch struct {
  7. DataSourceId int64
  8. Queries QuerySlice
  9. Depends map[string]bool
  10. Done bool
  11. Started bool
  12. }
  13. type BatchSlice []*Batch
  14. func newBatch(dsId int64, queries QuerySlice) *Batch {
  15. return &Batch{
  16. DataSourceId: dsId,
  17. Queries: queries,
  18. Depends: make(map[string]bool),
  19. }
  20. }
  21. func (bg *Batch) process(ctx context.Context, queryContext *QueryContext) {
  22. executor := getExecutorFor(bg.Queries[0].DataSource)
  23. if executor == nil {
  24. bg.Done = true
  25. result := &BatchResult{
  26. Error: errors.New("Could not find executor for data source type: " + bg.Queries[0].DataSource.PluginId),
  27. QueryResults: make(map[string]*QueryResult),
  28. }
  29. for _, query := range bg.Queries {
  30. result.QueryResults[query.RefId] = &QueryResult{Error: result.Error}
  31. }
  32. queryContext.ResultsChan <- result
  33. return
  34. }
  35. res := executor.Execute(ctx, bg.Queries, queryContext)
  36. bg.Done = true
  37. queryContext.ResultsChan <- res
  38. }
  39. func (bg *Batch) addQuery(query *Query) {
  40. bg.Queries = append(bg.Queries, query)
  41. }
  42. func (bg *Batch) allDependenciesAreIn(context *QueryContext) bool {
  43. for key := range bg.Depends {
  44. if _, exists := context.Results[key]; !exists {
  45. return false
  46. }
  47. }
  48. return true
  49. }
  50. func getBatches(req *Request) (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, QuerySlice{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. }