sql_engine.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. package tsdb
  2. import (
  3. "container/list"
  4. "context"
  5. "database/sql"
  6. "fmt"
  7. "math"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/grafana/grafana/pkg/log"
  14. "github.com/grafana/grafana/pkg/components/null"
  15. "github.com/go-xorm/core"
  16. "github.com/go-xorm/xorm"
  17. "github.com/grafana/grafana/pkg/components/simplejson"
  18. "github.com/grafana/grafana/pkg/models"
  19. )
  20. // SqlMacroEngine interpolates macros into sql. It takes in the Query to have access to query context and
  21. // timeRange to be able to generate queries that use from and to.
  22. type SqlMacroEngine interface {
  23. Interpolate(query *Query, timeRange *TimeRange, sql string) (string, error)
  24. }
  25. // SqlTableRowTransformer transforms a query result row to RowValues with proper types.
  26. type SqlTableRowTransformer interface {
  27. Transform(columnTypes []*sql.ColumnType, rows *core.Rows) (RowValues, error)
  28. }
  29. type engineCacheType struct {
  30. cache map[int64]*xorm.Engine
  31. versions map[int64]int
  32. sync.Mutex
  33. }
  34. var engineCache = engineCacheType{
  35. cache: make(map[int64]*xorm.Engine),
  36. versions: make(map[int64]int),
  37. }
  38. var sqlIntervalCalculator = NewIntervalCalculator(nil)
  39. var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
  40. return xorm.NewEngine(driverName, connectionString)
  41. }
  42. type sqlQueryEndpoint struct {
  43. macroEngine SqlMacroEngine
  44. rowTransformer SqlTableRowTransformer
  45. engine *xorm.Engine
  46. timeColumnNames []string
  47. metricColumnTypes []string
  48. log log.Logger
  49. }
  50. type SqlQueryEndpointConfiguration struct {
  51. DriverName string
  52. Datasource *models.DataSource
  53. ConnectionString string
  54. TimeColumnNames []string
  55. MetricColumnTypes []string
  56. }
  57. var NewSqlQueryEndpoint = func(config *SqlQueryEndpointConfiguration, rowTransformer SqlTableRowTransformer, macroEngine SqlMacroEngine, log log.Logger) (TsdbQueryEndpoint, error) {
  58. queryEndpoint := sqlQueryEndpoint{
  59. rowTransformer: rowTransformer,
  60. macroEngine: macroEngine,
  61. timeColumnNames: []string{"time"},
  62. log: log,
  63. }
  64. if len(config.TimeColumnNames) > 0 {
  65. queryEndpoint.timeColumnNames = config.TimeColumnNames
  66. }
  67. if len(config.MetricColumnTypes) > 0 {
  68. queryEndpoint.metricColumnTypes = config.MetricColumnTypes
  69. }
  70. engineCache.Lock()
  71. defer engineCache.Unlock()
  72. if engine, present := engineCache.cache[config.Datasource.Id]; present {
  73. if version := engineCache.versions[config.Datasource.Id]; version == config.Datasource.Version {
  74. queryEndpoint.engine = engine
  75. return &queryEndpoint, nil
  76. }
  77. }
  78. engine, err := NewXormEngine(config.DriverName, config.ConnectionString)
  79. if err != nil {
  80. return nil, err
  81. }
  82. engine.SetMaxOpenConns(10)
  83. engine.SetMaxIdleConns(10)
  84. engineCache.versions[config.Datasource.Id] = config.Datasource.Version
  85. engineCache.cache[config.Datasource.Id] = engine
  86. queryEndpoint.engine = engine
  87. return &queryEndpoint, nil
  88. }
  89. const rowLimit = 1000000
  90. // Query is the main function for the SqlQueryEndpoint
  91. func (e *sqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *TsdbQuery) (*Response, error) {
  92. result := &Response{
  93. Results: make(map[string]*QueryResult),
  94. }
  95. var wg sync.WaitGroup
  96. for _, query := range tsdbQuery.Queries {
  97. rawSQL := query.Model.Get("rawSql").MustString()
  98. if rawSQL == "" {
  99. continue
  100. }
  101. queryResult := &QueryResult{Meta: simplejson.New(), RefId: query.RefId}
  102. result.Results[query.RefId] = queryResult
  103. // global substitutions
  104. rawSQL, err := Interpolate(query, tsdbQuery.TimeRange, rawSQL)
  105. if err != nil {
  106. queryResult.Error = err
  107. continue
  108. }
  109. // datasource specific substitutions
  110. rawSQL, err = e.macroEngine.Interpolate(query, tsdbQuery.TimeRange, rawSQL)
  111. if err != nil {
  112. queryResult.Error = err
  113. continue
  114. }
  115. queryResult.Meta.Set("sql", rawSQL)
  116. wg.Add(1)
  117. go func(rawSQL string, query *Query, queryResult *QueryResult) {
  118. defer wg.Done()
  119. session := e.engine.NewSession()
  120. defer session.Close()
  121. db := session.DB()
  122. rows, err := db.Query(rawSQL)
  123. if err != nil {
  124. queryResult.Error = err
  125. return
  126. }
  127. defer rows.Close()
  128. format := query.Model.Get("format").MustString("time_series")
  129. switch format {
  130. case "time_series":
  131. err := e.transformToTimeSeries(query, rows, queryResult, tsdbQuery)
  132. if err != nil {
  133. queryResult.Error = err
  134. return
  135. }
  136. case "table":
  137. err := e.transformToTable(query, rows, queryResult, tsdbQuery)
  138. if err != nil {
  139. queryResult.Error = err
  140. return
  141. }
  142. }
  143. }(rawSQL, query, queryResult)
  144. }
  145. wg.Wait()
  146. return result, nil
  147. }
  148. // global macros/substitutions for all sql datasources
  149. var Interpolate = func(query *Query, timeRange *TimeRange, sql string) (string, error) {
  150. minInterval, err := GetIntervalFrom(query.DataSource, query.Model, time.Second*60)
  151. if err != nil {
  152. return sql, nil
  153. }
  154. interval := sqlIntervalCalculator.Calculate(timeRange, minInterval)
  155. sql = strings.Replace(sql, "$__interval_ms", strconv.FormatInt(interval.Milliseconds(), 10), -1)
  156. sql = strings.Replace(sql, "$__interval", interval.Text, -1)
  157. return sql, nil
  158. }
  159. func (e *sqlQueryEndpoint) transformToTable(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
  160. columnNames, err := rows.Columns()
  161. columnCount := len(columnNames)
  162. if err != nil {
  163. return err
  164. }
  165. rowCount := 0
  166. timeIndex := -1
  167. table := &Table{
  168. Columns: make([]TableColumn, columnCount),
  169. Rows: make([]RowValues, 0),
  170. }
  171. for i, name := range columnNames {
  172. table.Columns[i].Text = name
  173. for _, tc := range e.timeColumnNames {
  174. if name == tc {
  175. timeIndex = i
  176. break
  177. }
  178. }
  179. }
  180. columnTypes, err := rows.ColumnTypes()
  181. if err != nil {
  182. return err
  183. }
  184. for ; rows.Next(); rowCount++ {
  185. if rowCount > rowLimit {
  186. return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
  187. }
  188. values, err := e.rowTransformer.Transform(columnTypes, rows)
  189. if err != nil {
  190. return err
  191. }
  192. // converts column named time to unix timestamp in milliseconds
  193. // to make native mssql datetime types and epoch dates work in
  194. // annotation and table queries.
  195. ConvertSqlTimeColumnToEpochMs(values, timeIndex)
  196. table.Rows = append(table.Rows, values)
  197. }
  198. result.Tables = append(result.Tables, table)
  199. result.Meta.Set("rowCount", rowCount)
  200. return nil
  201. }
  202. func (e *sqlQueryEndpoint) transformToTimeSeries(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
  203. pointsBySeries := make(map[string]*TimeSeries)
  204. seriesByQueryOrder := list.New()
  205. columnNames, err := rows.Columns()
  206. if err != nil {
  207. return err
  208. }
  209. columnTypes, err := rows.ColumnTypes()
  210. if err != nil {
  211. return err
  212. }
  213. rowCount := 0
  214. timeIndex := -1
  215. metricIndex := -1
  216. metricPrefix := false
  217. var metricPrefixValue string
  218. // check columns of resultset: a column named time is mandatory
  219. // the first text column is treated as metric name unless a column named metric is present
  220. for i, col := range columnNames {
  221. for _, tc := range e.timeColumnNames {
  222. if col == tc {
  223. timeIndex = i
  224. continue
  225. }
  226. }
  227. switch col {
  228. case "metric":
  229. metricIndex = i
  230. default:
  231. if metricIndex == -1 {
  232. columnType := columnTypes[i].DatabaseTypeName()
  233. for _, mct := range e.metricColumnTypes {
  234. if columnType == mct {
  235. metricIndex = i
  236. continue
  237. }
  238. }
  239. }
  240. }
  241. }
  242. // use metric column as prefix with multiple value columns
  243. if metricIndex != -1 && len(columnNames) > 3 {
  244. metricPrefix = true
  245. }
  246. if timeIndex == -1 {
  247. return fmt.Errorf("Found no column named %s", strings.Join(e.timeColumnNames, " or "))
  248. }
  249. fillMissing := query.Model.Get("fill").MustBool(false)
  250. var fillInterval float64
  251. fillValue := null.Float{}
  252. fillPrevious := false
  253. if fillMissing {
  254. fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
  255. switch query.Model.Get("fillMode").MustString() {
  256. case "null":
  257. case "previous":
  258. fillPrevious = true
  259. case "value":
  260. fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
  261. fillValue.Valid = true
  262. }
  263. }
  264. for rows.Next() {
  265. var timestamp float64
  266. var value null.Float
  267. var metric string
  268. if rowCount > rowLimit {
  269. return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
  270. }
  271. values, err := e.rowTransformer.Transform(columnTypes, rows)
  272. if err != nil {
  273. return err
  274. }
  275. // converts column named time to unix timestamp in milliseconds to make
  276. // native mysql datetime types and epoch dates work in
  277. // annotation and table queries.
  278. ConvertSqlTimeColumnToEpochMs(values, timeIndex)
  279. switch columnValue := values[timeIndex].(type) {
  280. case int64:
  281. timestamp = float64(columnValue)
  282. case float64:
  283. timestamp = columnValue
  284. default:
  285. return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp, got: %T %v", columnValue, columnValue)
  286. }
  287. if metricIndex >= 0 {
  288. if columnValue, ok := values[metricIndex].(string); ok {
  289. if metricPrefix {
  290. metricPrefixValue = columnValue
  291. } else {
  292. metric = columnValue
  293. }
  294. } else {
  295. return fmt.Errorf("Column metric must be of type %s. metric column name: %s type: %s but datatype is %T", strings.Join(e.metricColumnTypes, ", "), columnNames[metricIndex], columnTypes[metricIndex].DatabaseTypeName(), values[metricIndex])
  296. }
  297. }
  298. for i, col := range columnNames {
  299. if i == timeIndex || i == metricIndex {
  300. continue
  301. }
  302. if value, err = ConvertSqlValueColumnToFloat(col, values[i]); err != nil {
  303. return err
  304. }
  305. if metricIndex == -1 {
  306. metric = col
  307. } else if metricPrefix {
  308. metric = metricPrefixValue + " " + col
  309. }
  310. series, exist := pointsBySeries[metric]
  311. if !exist {
  312. series = &TimeSeries{Name: metric}
  313. pointsBySeries[metric] = series
  314. seriesByQueryOrder.PushBack(metric)
  315. }
  316. if fillMissing {
  317. var intervalStart float64
  318. if !exist {
  319. intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
  320. } else {
  321. intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
  322. }
  323. if fillPrevious {
  324. if len(series.Points) > 0 {
  325. fillValue = series.Points[len(series.Points)-1][0]
  326. } else {
  327. fillValue.Valid = false
  328. }
  329. }
  330. // align interval start
  331. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  332. for i := intervalStart; i < timestamp; i += fillInterval {
  333. series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
  334. rowCount++
  335. }
  336. }
  337. series.Points = append(series.Points, TimePoint{value, null.FloatFrom(timestamp)})
  338. e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
  339. }
  340. }
  341. for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
  342. key := elem.Value.(string)
  343. result.Series = append(result.Series, pointsBySeries[key])
  344. if fillMissing {
  345. series := pointsBySeries[key]
  346. // fill in values from last fetched value till interval end
  347. intervalStart := series.Points[len(series.Points)-1][1].Float64
  348. intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
  349. if fillPrevious {
  350. if len(series.Points) > 0 {
  351. fillValue = series.Points[len(series.Points)-1][0]
  352. } else {
  353. fillValue.Valid = false
  354. }
  355. }
  356. // align interval start
  357. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  358. for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
  359. series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
  360. rowCount++
  361. }
  362. }
  363. }
  364. result.Meta.Set("rowCount", rowCount)
  365. return nil
  366. }
  367. // ConvertSqlTimeColumnToEpochMs converts column named time to unix timestamp in milliseconds
  368. // to make native datetime types and epoch dates work in annotation and table queries.
  369. func ConvertSqlTimeColumnToEpochMs(values RowValues, timeIndex int) {
  370. if timeIndex >= 0 {
  371. switch value := values[timeIndex].(type) {
  372. case time.Time:
  373. values[timeIndex] = float64(value.UnixNano()) / float64(time.Millisecond)
  374. case *time.Time:
  375. if value != nil {
  376. values[timeIndex] = float64((*value).UnixNano()) / float64(time.Millisecond)
  377. }
  378. case int64:
  379. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  380. case *int64:
  381. if value != nil {
  382. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  383. }
  384. case uint64:
  385. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  386. case *uint64:
  387. if value != nil {
  388. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  389. }
  390. case int32:
  391. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  392. case *int32:
  393. if value != nil {
  394. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  395. }
  396. case uint32:
  397. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  398. case *uint32:
  399. if value != nil {
  400. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  401. }
  402. case float64:
  403. values[timeIndex] = EpochPrecisionToMs(value)
  404. case *float64:
  405. if value != nil {
  406. values[timeIndex] = EpochPrecisionToMs(*value)
  407. }
  408. case float32:
  409. values[timeIndex] = EpochPrecisionToMs(float64(value))
  410. case *float32:
  411. if value != nil {
  412. values[timeIndex] = EpochPrecisionToMs(float64(*value))
  413. }
  414. }
  415. }
  416. }
  417. // ConvertSqlValueColumnToFloat converts timeseries value column to float.
  418. func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (null.Float, error) {
  419. var value null.Float
  420. switch typedValue := columnValue.(type) {
  421. case int:
  422. value = null.FloatFrom(float64(typedValue))
  423. case *int:
  424. if typedValue == nil {
  425. value.Valid = false
  426. } else {
  427. value = null.FloatFrom(float64(*typedValue))
  428. }
  429. case int64:
  430. value = null.FloatFrom(float64(typedValue))
  431. case *int64:
  432. if typedValue == nil {
  433. value.Valid = false
  434. } else {
  435. value = null.FloatFrom(float64(*typedValue))
  436. }
  437. case int32:
  438. value = null.FloatFrom(float64(typedValue))
  439. case *int32:
  440. if typedValue == nil {
  441. value.Valid = false
  442. } else {
  443. value = null.FloatFrom(float64(*typedValue))
  444. }
  445. case int16:
  446. value = null.FloatFrom(float64(typedValue))
  447. case *int16:
  448. if typedValue == nil {
  449. value.Valid = false
  450. } else {
  451. value = null.FloatFrom(float64(*typedValue))
  452. }
  453. case int8:
  454. value = null.FloatFrom(float64(typedValue))
  455. case *int8:
  456. if typedValue == nil {
  457. value.Valid = false
  458. } else {
  459. value = null.FloatFrom(float64(*typedValue))
  460. }
  461. case uint:
  462. value = null.FloatFrom(float64(typedValue))
  463. case *uint:
  464. if typedValue == nil {
  465. value.Valid = false
  466. } else {
  467. value = null.FloatFrom(float64(*typedValue))
  468. }
  469. case uint64:
  470. value = null.FloatFrom(float64(typedValue))
  471. case *uint64:
  472. if typedValue == nil {
  473. value.Valid = false
  474. } else {
  475. value = null.FloatFrom(float64(*typedValue))
  476. }
  477. case uint32:
  478. value = null.FloatFrom(float64(typedValue))
  479. case *uint32:
  480. if typedValue == nil {
  481. value.Valid = false
  482. } else {
  483. value = null.FloatFrom(float64(*typedValue))
  484. }
  485. case uint16:
  486. value = null.FloatFrom(float64(typedValue))
  487. case *uint16:
  488. if typedValue == nil {
  489. value.Valid = false
  490. } else {
  491. value = null.FloatFrom(float64(*typedValue))
  492. }
  493. case uint8:
  494. value = null.FloatFrom(float64(typedValue))
  495. case *uint8:
  496. if typedValue == nil {
  497. value.Valid = false
  498. } else {
  499. value = null.FloatFrom(float64(*typedValue))
  500. }
  501. case float64:
  502. value = null.FloatFrom(typedValue)
  503. case *float64:
  504. value = null.FloatFromPtr(typedValue)
  505. case float32:
  506. value = null.FloatFrom(float64(typedValue))
  507. case *float32:
  508. if typedValue == nil {
  509. value.Valid = false
  510. } else {
  511. value = null.FloatFrom(float64(*typedValue))
  512. }
  513. case nil:
  514. value.Valid = false
  515. default:
  516. return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue)
  517. }
  518. return value, nil
  519. }
  520. func SetupFillmode(query *Query, interval time.Duration, fillmode string) error {
  521. query.Model.Set("fill", true)
  522. query.Model.Set("fillInterval", interval.Seconds())
  523. switch fillmode {
  524. case "NULL":
  525. query.Model.Set("fillMode", "null")
  526. case "previous":
  527. query.Model.Set("fillMode", "previous")
  528. default:
  529. query.Model.Set("fillMode", "value")
  530. floatVal, err := strconv.ParseFloat(fillmode, 64)
  531. if err != nil {
  532. return fmt.Errorf("error parsing fill value %v", fillmode)
  533. }
  534. query.Model.Set("fillValue", floatVal)
  535. }
  536. return nil
  537. }
  538. type SqlMacroEngineBase struct{}
  539. func NewSqlMacroEngineBase() *SqlMacroEngineBase {
  540. return &SqlMacroEngineBase{}
  541. }
  542. func (m *SqlMacroEngineBase) ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
  543. result := ""
  544. lastIndex := 0
  545. for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
  546. groups := []string{}
  547. for i := 0; i < len(v); i += 2 {
  548. groups = append(groups, str[v[i]:v[i+1]])
  549. }
  550. result += str[lastIndex:v[0]] + repl(groups)
  551. lastIndex = v[1]
  552. }
  553. return result + str[lastIndex:]
  554. }