postgres.go 8.1 KB

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