sql_engine.go 17 KB

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