sql_engine.go 14 KB

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