sql_engine.go 17 KB

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