sql_engine.go 17 KB

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