batch.go 2.0 KB

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