sql_engine.go 16 KB

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