postgres.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package postgres
  2. import (
  3. "container/list"
  4. "context"
  5. "fmt"
  6. "math"
  7. "net/url"
  8. "strconv"
  9. "github.com/go-xorm/core"
  10. "github.com/grafana/grafana/pkg/components/null"
  11. "github.com/grafana/grafana/pkg/log"
  12. "github.com/grafana/grafana/pkg/models"
  13. "github.com/grafana/grafana/pkg/tsdb"
  14. )
  15. type PostgresQueryEndpoint struct {
  16. sqlEngine tsdb.SqlEngine
  17. log log.Logger
  18. }
  19. func init() {
  20. tsdb.RegisterTsdbQueryEndpoint("postgres", NewPostgresQueryEndpoint)
  21. }
  22. func NewPostgresQueryEndpoint(datasource *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  23. endpoint := &PostgresQueryEndpoint{
  24. log: log.New("tsdb.postgres"),
  25. }
  26. endpoint.sqlEngine = &tsdb.DefaultSqlEngine{
  27. MacroEngine: NewPostgresMacroEngine(),
  28. }
  29. cnnstr := generateConnectionString(datasource)
  30. endpoint.log.Debug("getEngine", "connection", cnnstr)
  31. if err := endpoint.sqlEngine.InitEngine("postgres", datasource, cnnstr); err != nil {
  32. return nil, err
  33. }
  34. return endpoint, nil
  35. }
  36. func generateConnectionString(datasource *models.DataSource) string {
  37. password := ""
  38. for key, value := range datasource.SecureJsonData.Decrypt() {
  39. if key == "password" {
  40. password = value
  41. break
  42. }
  43. }
  44. sslmode := datasource.JsonData.Get("sslmode").MustString("verify-full")
  45. u := &url.URL{Scheme: "postgres", User: url.UserPassword(datasource.User, password), Host: datasource.Url, Path: datasource.Database, RawQuery: "sslmode=" + sslmode}
  46. return u.String()
  47. }
  48. func (e *PostgresQueryEndpoint) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *tsdb.TsdbQuery) (*tsdb.Response, error) {
  49. return e.sqlEngine.Query(ctx, dsInfo, tsdbQuery, e.transformToTimeSeries, e.transformToTable)
  50. }
  51. func (e PostgresQueryEndpoint) transformToTable(query *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult, tsdbQuery *tsdb.TsdbQuery) error {
  52. columnNames, err := rows.Columns()
  53. if err != nil {
  54. return err
  55. }
  56. table := &tsdb.Table{
  57. Columns: make([]tsdb.TableColumn, len(columnNames)),
  58. Rows: make([]tsdb.RowValues, 0),
  59. }
  60. for i, name := range columnNames {
  61. table.Columns[i].Text = name
  62. }
  63. rowLimit := 1000000
  64. rowCount := 0
  65. timeIndex := -1
  66. // check if there is a column named time
  67. for i, col := range columnNames {
  68. switch col {
  69. case "time":
  70. timeIndex = i
  71. }
  72. }
  73. for ; rows.Next(); rowCount++ {
  74. if rowCount > rowLimit {
  75. return fmt.Errorf("PostgreSQL query row limit exceeded, limit %d", rowLimit)
  76. }
  77. values, err := e.getTypedRowData(rows)
  78. if err != nil {
  79. return err
  80. }
  81. // converts column named time to unix timestamp in milliseconds to make
  82. // native postgres datetime types and epoch dates work in
  83. // annotation and table queries.
  84. tsdb.ConvertSqlTimeColumnToEpochMs(values, timeIndex)
  85. table.Rows = append(table.Rows, values)
  86. }
  87. result.Tables = append(result.Tables, table)
  88. result.Meta.Set("rowCount", rowCount)
  89. return nil
  90. }
  91. func (e PostgresQueryEndpoint) getTypedRowData(rows *core.Rows) (tsdb.RowValues, error) {
  92. types, err := rows.ColumnTypes()
  93. if err != nil {
  94. return nil, err
  95. }
  96. values := make([]interface{}, len(types))
  97. valuePtrs := make([]interface{}, len(types))
  98. for i := 0; i < len(types); i++ {
  99. valuePtrs[i] = &values[i]
  100. }
  101. if err := rows.Scan(valuePtrs...); err != nil {
  102. return nil, err
  103. }
  104. // convert types not handled by lib/pq
  105. // unhandled types are returned as []byte
  106. for i := 0; i < len(types); i++ {
  107. if value, ok := values[i].([]byte); ok {
  108. switch types[i].DatabaseTypeName() {
  109. case "NUMERIC":
  110. if v, err := strconv.ParseFloat(string(value), 64); err == nil {
  111. values[i] = v
  112. } else {
  113. e.log.Debug("Rows", "Error converting numeric to float", value)
  114. }
  115. case "UNKNOWN", "CIDR", "INET", "MACADDR":
  116. // char literals have type UNKNOWN
  117. values[i] = string(value)
  118. default:
  119. e.log.Debug("Rows", "Unknown database type", types[i].DatabaseTypeName(), "value", value)
  120. values[i] = string(value)
  121. }
  122. }
  123. }
  124. return values, nil
  125. }
  126. func (e PostgresQueryEndpoint) transformToTimeSeries(query *tsdb.Query, rows *core.Rows, result *tsdb.QueryResult, tsdbQuery *tsdb.TsdbQuery) error {
  127. pointsBySeries := make(map[string]*tsdb.TimeSeries)
  128. seriesByQueryOrder := list.New()
  129. columnNames, err := rows.Columns()
  130. if err != nil {
  131. return err
  132. }
  133. columnTypes, err := rows.ColumnTypes()
  134. if err != nil {
  135. return err
  136. }
  137. rowLimit := 1000000
  138. rowCount := 0
  139. timeIndex := -1
  140. metricIndex := -1
  141. // check columns of resultset: a column named time is mandatory
  142. // the first text column is treated as metric name unless a column named metric is present
  143. for i, col := range columnNames {
  144. switch col {
  145. case "time":
  146. timeIndex = i
  147. case "metric":
  148. metricIndex = i
  149. default:
  150. if metricIndex == -1 {
  151. switch columnTypes[i].DatabaseTypeName() {
  152. case "UNKNOWN", "TEXT", "VARCHAR", "CHAR":
  153. metricIndex = i
  154. }
  155. }
  156. }
  157. }
  158. if timeIndex == -1 {
  159. return fmt.Errorf("Found no column named time")
  160. }
  161. fillMissing := query.Model.Get("fill").MustBool(false)
  162. var fillInterval float64
  163. fillValue := null.Float{}
  164. if fillMissing {
  165. fillInterval = query.Model.Get("fillInterval").MustFloat64() * 1000
  166. if !query.Model.Get("fillNull").MustBool(false) {
  167. fillValue.Float64 = query.Model.Get("fillValue").MustFloat64()
  168. fillValue.Valid = true
  169. }
  170. }
  171. for rows.Next() {
  172. var timestamp float64
  173. var value null.Float
  174. var metric string
  175. if rowCount > rowLimit {
  176. return fmt.Errorf("PostgreSQL query row limit exceeded, limit %d", rowLimit)
  177. }
  178. values, err := e.getTypedRowData(rows)
  179. if err != nil {
  180. return err
  181. }
  182. // converts column named time to unix timestamp in milliseconds to make
  183. // native mysql datetime types and epoch dates work in
  184. // annotation and table queries.
  185. tsdb.ConvertSqlTimeColumnToEpochMs(values, timeIndex)
  186. switch columnValue := values[timeIndex].(type) {
  187. case int64:
  188. timestamp = float64(columnValue)
  189. case float64:
  190. timestamp = columnValue
  191. default:
  192. return fmt.Errorf("Invalid type for column time, must be of type timestamp or unix timestamp, got: %T %v", columnValue, columnValue)
  193. }
  194. if metricIndex >= 0 {
  195. if columnValue, ok := values[metricIndex].(string); ok {
  196. metric = columnValue
  197. } else {
  198. return fmt.Errorf("Column metric must be of type char,varchar or text, got: %T %v", values[metricIndex], values[metricIndex])
  199. }
  200. }
  201. for i, col := range columnNames {
  202. if i == timeIndex || i == metricIndex {
  203. continue
  204. }
  205. if value, err = tsdb.ConvertSqlValueColumnToFloat(col, values[i]); err != nil {
  206. return err
  207. }
  208. if metricIndex == -1 {
  209. metric = col
  210. }
  211. series, exist := pointsBySeries[metric]
  212. if !exist {
  213. series = &tsdb.TimeSeries{Name: metric}
  214. pointsBySeries[metric] = series
  215. seriesByQueryOrder.PushBack(metric)
  216. }
  217. if fillMissing {
  218. var intervalStart float64
  219. if !exist {
  220. intervalStart = float64(tsdbQuery.TimeRange.MustGetFrom().UnixNano() / 1e6)
  221. } else {
  222. intervalStart = series.Points[len(series.Points)-1][1].Float64 + fillInterval
  223. }
  224. // align interval start
  225. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  226. for i := intervalStart; i < timestamp; i += fillInterval {
  227. series.Points = append(series.Points, tsdb.TimePoint{fillValue, null.FloatFrom(i)})
  228. rowCount++
  229. }
  230. }
  231. series.Points = append(series.Points, tsdb.TimePoint{value, null.FloatFrom(timestamp)})
  232. e.log.Debug("Rows", "metric", metric, "time", timestamp, "value", value)
  233. rowCount++
  234. }
  235. }
  236. for elem := seriesByQueryOrder.Front(); elem != nil; elem = elem.Next() {
  237. key := elem.Value.(string)
  238. result.Series = append(result.Series, pointsBySeries[key])
  239. if fillMissing {
  240. series := pointsBySeries[key]
  241. // fill in values from last fetched value till interval end
  242. intervalStart := series.Points[len(series.Points)-1][1].Float64
  243. intervalEnd := float64(tsdbQuery.TimeRange.MustGetTo().UnixNano() / 1e6)
  244. // align interval start
  245. intervalStart = math.Floor(intervalStart/fillInterval) * fillInterval
  246. for i := intervalStart + fillInterval; i < intervalEnd; i += fillInterval {
  247. series.Points = append(series.Points, tsdb.TimePoint{fillValue, null.FloatFrom(i)})
  248. rowCount++
  249. }
  250. }
  251. }
  252. result.Meta.Set("rowCount", rowCount)
  253. return nil
  254. }