sql_engine.go 17 KB

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