postgres.go 8.2 KB

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