sql_engine.go 17 KB

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