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. // Query is the main function for the SqlQueryEndpoint
  84. func (e *sqlQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *TsdbQuery) (*Response, error) {
  85. result := &Response{
  86. Results: make(map[string]*QueryResult),
  87. }
  88. session := e.engine.NewSession()
  89. defer session.Close()
  90. db := session.DB()
  91. for _, query := range tsdbQuery.Queries {
  92. rawSQL := query.Model.Get("rawSql").MustString()
  93. if rawSQL == "" {
  94. continue
  95. }
  96. queryResult := &QueryResult{Meta: simplejson.New(), RefId: query.RefId}
  97. result.Results[query.RefId] = queryResult
  98. rawSQL, err := e.macroEngine.Interpolate(query, tsdbQuery.TimeRange, rawSQL)
  99. if err != nil {
  100. queryResult.Error = err
  101. continue
  102. }
  103. queryResult.Meta.Set("sql", rawSQL)
  104. rows, err := db.Query(rawSQL)
  105. if err != nil {
  106. queryResult.Error = err
  107. continue
  108. }
  109. defer rows.Close()
  110. format := query.Model.Get("format").MustString("time_series")
  111. switch format {
  112. case "time_series":
  113. err := e.transformToTimeSeries(query, rows, queryResult, tsdbQuery)
  114. if err != nil {
  115. queryResult.Error = err
  116. continue
  117. }
  118. case "table":
  119. err := e.transformToTable(query, rows, queryResult, tsdbQuery)
  120. if err != nil {
  121. queryResult.Error = err
  122. continue
  123. }
  124. }
  125. }
  126. return result, nil
  127. }
  128. func (e *sqlQueryEndpoint) transformToTable(query *Query, rows *core.Rows, result *QueryResult, tsdbQuery *TsdbQuery) error {
  129. columnNames, err := rows.Columns()
  130. columnCount := len(columnNames)
  131. if err != nil {
  132. return err
  133. }
  134. rowLimit := 1000000
  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. rowLimit := 1000000
  184. rowCount := 0
  185. timeIndex := -1
  186. metricIndex := -1
  187. // check columns of resultset: a column named time is mandatory
  188. // the first text column is treated as metric name unless a column named metric is present
  189. for i, col := range columnNames {
  190. for _, tc := range e.timeColumnNames {
  191. if col == tc {
  192. timeIndex = i
  193. continue
  194. }
  195. }
  196. switch col {
  197. case "metric":
  198. metricIndex = i
  199. default:
  200. if metricIndex == -1 {
  201. columnType := columnTypes[i].DatabaseTypeName()
  202. for _, mct := range e.metricColumnTypes {
  203. if columnType == mct {
  204. metricIndex = i
  205. continue
  206. }
  207. }
  208. }
  209. }
  210. }
  211. if timeIndex == -1 {
  212. return fmt.Errorf("Found no column named %s", strings.Join(e.timeColumnNames, " or "))
  213. }
  214. fillMissing := query.Model.Get("fill").MustBool(false)
  215. var fillInterval float64
  216. fillValue := null.Float{}
  217. if fillMissing {
  218. fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
  219. if !query.Model.Get("fillNull").MustBool(false) {
  220. fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
  221. fillValue.Valid = true
  222. }
  223. }
  224. for rows.Next() {
  225. var timestamp float64
  226. var value null.Float
  227. var metric string
  228. if rowCount > rowLimit {
  229. return fmt.Errorf("query row limit exceeded, limit %d", rowLimit)
  230. }
  231. values, err := e.rowTransformer.Transform(columnTypes, rows)
  232. if err != nil {
  233. return err
  234. }
  235. // converts column named time to unix timestamp in milliseconds to make
  236. // native mysql datetime types and epoch dates work in
  237. // annotation and table queries.
  238. ConvertSqlTimeColumnToEpochMs(values, timeIndex)
  239. switch columnValue := values[timeIndex].(type) {
  240. case int64:
  241. timestamp = float64(columnValue)
  242. case float64:
  243. timestamp = columnValue
  244. default:
  245. return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp, got: %T %v", columnValue, columnValue)
  246. }
  247. if metricIndex >= 0 {
  248. if columnValue, ok := values[metricIndex].(string); ok {
  249. metric = columnValue
  250. } else {
  251. 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])
  252. }
  253. }
  254. for i, col := range columnNames {
  255. if i == timeIndex || i == metricIndex {
  256. continue
  257. }
  258. if value, err = ConvertSqlValueColumnToFloat(col, values[i]); err != nil {
  259. return err
  260. }
  261. if metricIndex == -1 {
  262. metric = col
  263. }
  264. series, exist := pointsBySeries[metric]
  265. if !exist {
  266. series = &TimeSeries{Name: metric}
  267. pointsBySeries[metric] = series
  268. seriesByQueryOrder.PushBack(metric)
  269. }
  270. if fillMissing {
  271. var intervalStart float64
  272. if !exist {
  273. intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
  274. } else {
  275. intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
  276. }
  277. // align interval start
  278. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  279. for i := intervalStart; i < timestamp; i += fillInterval {
  280. series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
  281. rowCount++
  282. }
  283. }
  284. series.Points = append(series.Points, TimePoint{value, null.FloatFrom(timestamp)})
  285. e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
  286. }
  287. }
  288. for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
  289. key := elem.Value.(string)
  290. result.Series = append(result.Series, pointsBySeries[key])
  291. if fillMissing {
  292. series := pointsBySeries[key]
  293. // fill in values from last fetched value till interval end
  294. intervalStart := series.Points[len(series.Points)-1][1].Float64
  295. intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
  296. // align interval start
  297. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  298. for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
  299. series.Points = append(series.Points, TimePoint{fillValue, null.FloatFrom(i)})
  300. rowCount++
  301. }
  302. }
  303. }
  304. result.Meta.Set("rowCount", rowCount)
  305. return nil
  306. }
  307. // ConvertSqlTimeColumnToEpochMs converts column named time to unix timestamp in milliseconds
  308. // to make native datetime types and epoch dates work in annotation and table queries.
  309. func ConvertSqlTimeColumnToEpochMs(values RowValues, timeIndex int) {
  310. if timeIndex >= 0 {
  311. switch value := values[timeIndex].(type) {
  312. case time.Time:
  313. values[timeIndex] = float64(value.UnixNano()) / float64(time.Millisecond)
  314. case *time.Time:
  315. if value != nil {
  316. values[timeIndex] = float64((*value).UnixNano()) / float64(time.Millisecond)
  317. }
  318. case int64:
  319. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  320. case *int64:
  321. if value != nil {
  322. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  323. }
  324. case uint64:
  325. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  326. case *uint64:
  327. if value != nil {
  328. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  329. }
  330. case int32:
  331. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  332. case *int32:
  333. if value != nil {
  334. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  335. }
  336. case uint32:
  337. values[timeIndex] = int64(EpochPrecisionToMs(float64(value)))
  338. case *uint32:
  339. if value != nil {
  340. values[timeIndex] = int64(EpochPrecisionToMs(float64(*value)))
  341. }
  342. case float64:
  343. values[timeIndex] = EpochPrecisionToMs(value)
  344. case *float64:
  345. if value != nil {
  346. values[timeIndex] = EpochPrecisionToMs(*value)
  347. }
  348. case float32:
  349. values[timeIndex] = EpochPrecisionToMs(float64(value))
  350. case *float32:
  351. if value != nil {
  352. values[timeIndex] = EpochPrecisionToMs(float64(*value))
  353. }
  354. }
  355. }
  356. }
  357. // ConvertSqlValueColumnToFloat converts timeseries value column to float.
  358. func ConvertSqlValueColumnToFloat(columnName string, columnValue interface{}) (null.Float, error) {
  359. var value null.Float
  360. switch typedValue := columnValue.(type) {
  361. case int:
  362. value = null.FloatFrom(float64(typedValue))
  363. case *int:
  364. if typedValue == nil {
  365. value.Valid = false
  366. } else {
  367. value = null.FloatFrom(float64(*typedValue))
  368. }
  369. case int64:
  370. value = null.FloatFrom(float64(typedValue))
  371. case *int64:
  372. if typedValue == nil {
  373. value.Valid = false
  374. } else {
  375. value = null.FloatFrom(float64(*typedValue))
  376. }
  377. case int32:
  378. value = null.FloatFrom(float64(typedValue))
  379. case *int32:
  380. if typedValue == nil {
  381. value.Valid = false
  382. } else {
  383. value = null.FloatFrom(float64(*typedValue))
  384. }
  385. case int16:
  386. value = null.FloatFrom(float64(typedValue))
  387. case *int16:
  388. if typedValue == nil {
  389. value.Valid = false
  390. } else {
  391. value = null.FloatFrom(float64(*typedValue))
  392. }
  393. case int8:
  394. value = null.FloatFrom(float64(typedValue))
  395. case *int8:
  396. if typedValue == nil {
  397. value.Valid = false
  398. } else {
  399. value = null.FloatFrom(float64(*typedValue))
  400. }
  401. case uint:
  402. value = null.FloatFrom(float64(typedValue))
  403. case *uint:
  404. if typedValue == nil {
  405. value.Valid = false
  406. } else {
  407. value = null.FloatFrom(float64(*typedValue))
  408. }
  409. case uint64:
  410. value = null.FloatFrom(float64(typedValue))
  411. case *uint64:
  412. if typedValue == nil {
  413. value.Valid = false
  414. } else {
  415. value = null.FloatFrom(float64(*typedValue))
  416. }
  417. case uint32:
  418. value = null.FloatFrom(float64(typedValue))
  419. case *uint32:
  420. if typedValue == nil {
  421. value.Valid = false
  422. } else {
  423. value = null.FloatFrom(float64(*typedValue))
  424. }
  425. case uint16:
  426. value = null.FloatFrom(float64(typedValue))
  427. case *uint16:
  428. if typedValue == nil {
  429. value.Valid = false
  430. } else {
  431. value = null.FloatFrom(float64(*typedValue))
  432. }
  433. case uint8:
  434. value = null.FloatFrom(float64(typedValue))
  435. case *uint8:
  436. if typedValue == nil {
  437. value.Valid = false
  438. } else {
  439. value = null.FloatFrom(float64(*typedValue))
  440. }
  441. case float64:
  442. value = null.FloatFrom(typedValue)
  443. case *float64:
  444. value = null.FloatFromPtr(typedValue)
  445. case float32:
  446. value = null.FloatFrom(float64(typedValue))
  447. case *float32:
  448. if typedValue == nil {
  449. value.Valid = false
  450. } else {
  451. value = null.FloatFrom(float64(*typedValue))
  452. }
  453. case nil:
  454. value.Valid = false
  455. default:
  456. return null.NewFloat(0, false), fmt.Errorf("Value column must have numeric datatype, column: %s type: %T value: %v", columnName, typedValue, typedValue)
  457. }
  458. return value, nil
  459. }