sql_engine.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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/setting"
  14. "github.com/grafana/grafana/pkg/infra/log"
  15. "github.com/grafana/grafana/pkg/tsdb"
  16. "github.com/grafana/grafana/pkg/components/null"
  17. "github.com/go-xorm/core"
  18. "github.com/go-xorm/xorm"
  19. "github.com/grafana/grafana/pkg/components/simplejson"
  20. "github.com/grafana/grafana/pkg/models"
  21. )
  22. // SqlMacroEngine interpolates macros into sql. It takes in the Query to have access to query context and
  23. // timeRange to be able to generate queries that use from and to.
  24. type SqlMacroEngine interface {
  25. Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error)
  26. }
  27. // SqlTableRowTransformer transforms a query result row to RowValues with proper types.
  28. type SqlTableRowTransformer interface {
  29. Transform(columnTypes []*sql.ColumnType, rows *core.Rows) (tsdb.RowValues, error)
  30. }
  31. type engineCacheType struct {
  32. cache map[int64]*xorm.Engine
  33. versions map[int64]int
  34. sync.Mutex
  35. }
  36. var engineCache = engineCacheType{
  37. cache: make(map[int64]*xorm.Engine),
  38. versions: make(map[int64]int),
  39. }
  40. var sqlIntervalCalculator = tsdb.NewIntervalCalculator(nil)
  41. var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
  42. return xorm.NewEngine(driverName, connectionString)
  43. }
  44. type sqlQueryEndpoint struct {
  45. macroEngine SqlMacroEngine
  46. rowTransformer SqlTableRowTransformer
  47. engine *xorm.Engine
  48. timeColumnNames []string
  49. metricColumnTypes []string
  50. log log.Logger
  51. }
  52. type SqlQueryEndpointConfiguration struct {
  53. DriverName string
  54. Datasource *models.DataSource
  55. ConnectionString string
  56. TimeColumnNames []string
  57. MetricColumnTypes []string
  58. }
  59. var NewSqlQueryEndpoint = func(config *SqlQueryEndpointConfiguration, rowTransformer SqlTableRowTransformer, macroEngine SqlMacroEngine, log log.Logger) (tsdb.TsdbQueryEndpoint, error) {
  60. queryEndpoint := sqlQueryEndpoint{
  61. rowTransformer: rowTransformer,
  62. macroEngine: macroEngine,
  63. timeColumnNames: []string{"time"},
  64. log: log,
  65. }
  66. if len(config.TimeColumnNames) > 0 {
  67. queryEndpoint.timeColumnNames = config.TimeColumnNames
  68. }
  69. if len(config.MetricColumnTypes) > 0 {
  70. queryEndpoint.metricColumnTypes = config.MetricColumnTypes
  71. }
  72. engineCache.Lock()
  73. defer engineCache.Unlock()
  74. if engine, present := engineCache.cache[config.Datasource.Id]; present {
  75. if version := engineCache.versions[config.Datasource.Id]; version == config.Datasource.Version {
  76. queryEndpoint.engine = engine
  77. return &queryEndpoint, nil
  78. }
  79. }
  80. engine, err := NewXormEngine(config.DriverName, config.ConnectionString)
  81. if err != nil {
  82. return nil, err
  83. }
  84. maxOpenConns := config.Datasource.JsonData.Get("maxOpenConns").MustInt(0)
  85. engine.SetMaxOpenConns(maxOpenConns)
  86. maxIdleConns := config.Datasource.JsonData.Get("maxIdleConns").MustInt(2)
  87. engine.SetMaxIdleConns(maxIdleConns)
  88. connMaxLifetime := config.Datasource.JsonData.Get("connMaxLifetime").MustInt(14400)
  89. engine.SetConnMaxLifetime(time.Duration(connMaxLifetime) * time.Second)
  90. engineCache.versions[config.Datasource.Id] = config.Datasource.Version
  91. engineCache.cache[config.Datasource.Id] = engine
  92. queryEndpoint.engine = engine
  93. return &queryEndpoint, nil
  94. }
  95. const rowLimit = 1000000
  96. // Query is the main function for the SqlQueryEndpoint
  97. func (e *sqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *tsdb.TsdbQuery) (*tsdb.Response, error) {
  98. result := &tsdb.Response{
  99. Results: make(map[string]*tsdb.QueryResult),
  100. }
  101. var wg sync.WaitGroup
  102. for _, query := range tsdbQuery.Queries {
  103. rawSQL := query.Model.Get("rawSql").MustString()
  104. if rawSQL == "" {
  105. continue
  106. }
  107. queryResult := &tsdb.QueryResult{Meta: simplejson.New(), RefId: query.RefId}
  108. result.Results[query.RefId] = queryResult
  109. // global substitutions
  110. rawSQL, err := Interpolate(query, tsdbQuery.TimeRange, rawSQL)
  111. if err != nil {
  112. queryResult.Error = err
  113. continue
  114. }
  115. // datasource specific substitutions
  116. rawSQL, err = e.macroEngine.Interpolate(query, tsdbQuery.TimeRange, rawSQL)
  117. if err != nil {
  118. queryResult.Error = err
  119. continue
  120. }
  121. queryResult.Meta.Set("sql", rawSQL)
  122. wg.Add(1)
  123. go func(rawSQL string, query *tsdb.Query, queryResult *tsdb.QueryResult) {
  124. defer wg.Done()
  125. session := e.engine.NewSession()
  126. defer session.Close()
  127. db := session.DB()
  128. rows, err := db.Query(rawSQL)
  129. if err != nil {
  130. queryResult.Error = err
  131. return
  132. }
  133. defer rows.Close()
  134. format := query.Model.Get("format").MustString("time_series")
  135. switch format {
  136. case "time_series":
  137. err := e.transformToTimeSeries(query, rows, queryResult, tsdbQuery)
  138. if err != nil {
  139. queryResult.Error = err
  140. return
  141. }
  142. case "table":
  143. err := e.transformToTable(query, rows, queryResult, tsdbQuery)
  144. if err != nil {
  145. queryResult.Error = err
  146. return
  147. }
  148. }
  149. }(rawSQL, query, queryResult)
  150. }
  151. wg.Wait()
  152. return result, nil
  153. }
  154. // global macros/substitutions for all sql datasources
  155. var Interpolate = func(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) {
  156. minInterval, err := tsdb.GetIntervalFrom(query.DataSource, query.Model, time.Second*60)
  157. if err != nil {
  158. return sql, nil
  159. }
  160. interval := sqlIntervalCalculator.Calculate(timeRange, minInterval)
  161. sql = strings.Replace(sql, "$__interval_ms", strconv.FormatInt(interval.Milliseconds(), 10), -1)
  162. sql = strings.Replace(sql, "$__interval", interval.Text, -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 *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult, tsdbQuery *tsdb.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 := &tsdb.Table{
  176. Columns: make([]tsdb.TableColumn, columnCount),
  177. Rows: make([]tsdb.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 *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult, tsdbQuery *tsdb.TsdbQuery) error {
  211. pointsBySeries := make(map[string]*tsdb.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 = &tsdb.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, tsdb.TimePoint{fillValue, null.FloatFrom(i)})
  342. rowCount++
  343. }
  344. }
  345. series.Points = append(series.Points, tsdb.TimePoint{value, null.FloatFrom(timestamp)})
  346. if setting.Env == setting.DEV {
  347. e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
  348. }
  349. }
  350. }
  351. for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
  352. key := elem.Value.(string)
  353. result.Series = append(result.Series, pointsBySeries[key])
  354. if fillMissing {
  355. series := pointsBySeries[key]
  356. // fill in values from last fetched value till interval end
  357. intervalStart := series.Points[len(series.Points)-1][1].Float64
  358. intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
  359. if fillPrevious {
  360. if len(series.Points) > 0 {
  361. fillValue = series.Points[len(series.Points)-1][0]
  362. } else {
  363. fillValue.Valid = false
  364. }
  365. }
  366. // align interval start
  367. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  368. for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
  369. series.Points = append(series.Points, tsdb.TimePoint{fillValue, null.FloatFrom(i)})
  370. rowCount++
  371. }
  372. }
  373. }
  374. result.Meta.Set("rowCount", rowCount)
  375. return nil
  376. }
  377. // ConvertSqlTimeColumnToEpochMs converts column named time to unix timestamp in milliseconds
  378. // to make native datetime types and epoch dates work in annotation and table queries.
  379. func ConvertSqlTimeColumnToEpochMs(values tsdb.RowValues, timeIndex int) {
  380. if timeIndex >= 0 {
  381. switch value := values[timeIndex].(type) {
  382. case time.Time:
  383. values[timeIndex] = float64(value.UnixNano()) / float64(time.Millisecond)
  384. case *time.Time:
  385. if value != nil {
  386. values[timeIndex] = float64((*value).UnixNano()) / float64(time.Millisecond)
  387. }
  388. case int64:
  389. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(value)))
  390. case *int64:
  391. if value != nil {
  392. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(*value)))
  393. }
  394. case uint64:
  395. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(value)))
  396. case *uint64:
  397. if value != nil {
  398. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(*value)))
  399. }
  400. case int32:
  401. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(value)))
  402. case *int32:
  403. if value != nil {
  404. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(*value)))
  405. }
  406. case uint32:
  407. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(value)))
  408. case *uint32:
  409. if value != nil {
  410. values[timeIndex] = int64(tsdb.EpochPrecisionToMs(float64(*value)))
  411. }
  412. case float64:
  413. values[timeIndex] = tsdb.EpochPrecisionToMs(value)
  414. case *float64:
  415. if value != nil {
  416. values[timeIndex] = tsdb.EpochPrecisionToMs(*value)
  417. }
  418. case float32:
  419. values[timeIndex] = tsdb.EpochPrecisionToMs(float64(value))
  420. case *float32:
  421. if value != nil {
  422. values[timeIndex] = tsdb.EpochPrecisionToMs(float64(*value))
  423. }
  424. }
  425. }
  426. }
  427. // ConvertSqlValueColumnToFloat converts timeseries value column to float.
  428. func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (null.Float, error) {
  429. var value null.Float
  430. switch typedValue := columnValue.(type) {
  431. case int:
  432. value = null.FloatFrom(float64(typedValue))
  433. case *int:
  434. if typedValue == nil {
  435. value.Valid = false
  436. } else {
  437. value = null.FloatFrom(float64(*typedValue))
  438. }
  439. case int64:
  440. value = null.FloatFrom(float64(typedValue))
  441. case *int64:
  442. if typedValue == nil {
  443. value.Valid = false
  444. } else {
  445. value = null.FloatFrom(float64(*typedValue))
  446. }
  447. case int32:
  448. value = null.FloatFrom(float64(typedValue))
  449. case *int32:
  450. if typedValue == nil {
  451. value.Valid = false
  452. } else {
  453. value = null.FloatFrom(float64(*typedValue))
  454. }
  455. case int16:
  456. value = null.FloatFrom(float64(typedValue))
  457. case *int16:
  458. if typedValue == nil {
  459. value.Valid = false
  460. } else {
  461. value = null.FloatFrom(float64(*typedValue))
  462. }
  463. case int8:
  464. value = null.FloatFrom(float64(typedValue))
  465. case *int8:
  466. if typedValue == nil {
  467. value.Valid = false
  468. } else {
  469. value = null.FloatFrom(float64(*typedValue))
  470. }
  471. case uint:
  472. value = null.FloatFrom(float64(typedValue))
  473. case *uint:
  474. if typedValue == nil {
  475. value.Valid = false
  476. } else {
  477. value = null.FloatFrom(float64(*typedValue))
  478. }
  479. case uint64:
  480. value = null.FloatFrom(float64(typedValue))
  481. case *uint64:
  482. if typedValue == nil {
  483. value.Valid = false
  484. } else {
  485. value = null.FloatFrom(float64(*typedValue))
  486. }
  487. case uint32:
  488. value = null.FloatFrom(float64(typedValue))
  489. case *uint32:
  490. if typedValue == nil {
  491. value.Valid = false
  492. } else {
  493. value = null.FloatFrom(float64(*typedValue))
  494. }
  495. case uint16:
  496. value = null.FloatFrom(float64(typedValue))
  497. case *uint16:
  498. if typedValue == nil {
  499. value.Valid = false
  500. } else {
  501. value = null.FloatFrom(float64(*typedValue))
  502. }
  503. case uint8:
  504. value = null.FloatFrom(float64(typedValue))
  505. case *uint8:
  506. if typedValue == nil {
  507. value.Valid = false
  508. } else {
  509. value = null.FloatFrom(float64(*typedValue))
  510. }
  511. case float64:
  512. value = null.FloatFrom(typedValue)
  513. case *float64:
  514. value = null.FloatFromPtr(typedValue)
  515. case float32:
  516. value = null.FloatFrom(float64(typedValue))
  517. case *float32:
  518. if typedValue == nil {
  519. value.Valid = false
  520. } else {
  521. value = null.FloatFrom(float64(*typedValue))
  522. }
  523. case nil:
  524. value.Valid = false
  525. default:
  526. return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue)
  527. }
  528. return value, nil
  529. }
  530. func SetupFillmode(query *tsdb.Query, interval time.Duration, fillmode string) error {
  531. query.Model.Set("fill", true)
  532. query.Model.Set("fillInterval", interval.Seconds())
  533. switch fillmode {
  534. case "NULL":
  535. query.Model.Set("fillMode", "null")
  536. case "previous":
  537. query.Model.Set("fillMode", "previous")
  538. default:
  539. query.Model.Set("fillMode", "value")
  540. floatVal, err := strconv.ParseFloat(fillmode, 64)
  541. if err != nil {
  542. return fmt.Errorf("error parsing fill value %v", fillmode)
  543. }
  544. query.Model.Set("fillValue", floatVal)
  545. }
  546. return nil
  547. }
  548. type SqlMacroEngineBase struct{}
  549. func NewSqlMacroEngineBase() *SqlMacroEngineBase {
  550. return &SqlMacroEngineBase{}
  551. }
  552. func (m *SqlMacroEngineBase) ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
  553. result := ""
  554. lastIndex := 0
  555. for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
  556. groups := []string{}
  557. for i := 0; i < len(v); i += 2 {
  558. groups = append(groups, str[v[i]:v[i+1]])
  559. }
  560. result += str[lastIndex:v[0]] + repl(groups)
  561. lastIndex = v[1]
  562. }
  563. return result + str[lastIndex:]
  564. }