metrics.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "github.com/grafana/grafana/pkg/api/dtos"
  7. "github.com/grafana/grafana/pkg/bus"
  8. "github.com/grafana/grafana/pkg/metrics"
  9. "github.com/grafana/grafana/pkg/middleware"
  10. "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/tsdb"
  12. "github.com/grafana/grafana/pkg/tsdb/testdata"
  13. "github.com/grafana/grafana/pkg/util"
  14. )
  15. // POST /api/tsdb/query
  16. func QueryMetrics(c *middleware.Context, reqDto dtos.MetricRequest) Response {
  17. timeRange := tsdb.NewTimeRange(reqDto.From, reqDto.To)
  18. if len(reqDto.Queries) == 0 {
  19. return ApiError(400, "No queries found in query", nil)
  20. }
  21. dsId, err := reqDto.Queries[0].Get("datasourceId").Int64()
  22. if err != nil {
  23. return ApiError(400, "Query missing datasourceId", nil)
  24. }
  25. dsQuery := models.GetDataSourceByIdQuery{Id: dsId}
  26. if err := bus.Dispatch(&dsQuery); err != nil {
  27. return ApiError(500, "failed to fetch data source", err)
  28. }
  29. request := &tsdb.Request{TimeRange: timeRange}
  30. for _, query := range reqDto.Queries {
  31. request.Queries = append(request.Queries, &tsdb.Query{
  32. RefId: query.Get("refId").MustString("A"),
  33. MaxDataPoints: query.Get("maxDataPoints").MustInt64(100),
  34. IntervalMs: query.Get("intervalMs").MustInt64(1000),
  35. Model: query,
  36. DataSource: dsQuery.Result,
  37. })
  38. }
  39. resp, err := tsdb.HandleRequest(context.Background(), request)
  40. if err != nil {
  41. return ApiError(500, "Metric request error", err)
  42. }
  43. statusCode := 200
  44. for _, res := range resp.Results {
  45. if res.Error != nil {
  46. res.ErrorString = res.Error.Error()
  47. resp.Message = res.ErrorString
  48. statusCode = 500
  49. }
  50. }
  51. return Json(statusCode, &resp)
  52. }
  53. // GET /api/tsdb/testdata/scenarios
  54. func GetTestDataScenarios(c *middleware.Context) Response {
  55. result := make([]interface{}, 0)
  56. for _, scenario := range testdata.ScenarioRegistry {
  57. result = append(result, map[string]interface{}{
  58. "id": scenario.Id,
  59. "name": scenario.Name,
  60. "description": scenario.Description,
  61. "stringInput": scenario.StringInput,
  62. })
  63. }
  64. return Json(200, &result)
  65. }
  66. func GetInternalMetrics(c *middleware.Context) Response {
  67. if metrics.UseNilMetrics {
  68. return Json(200, util.DynMap{"message": "Metrics disabled"})
  69. }
  70. snapshots := metrics.MetricStats.GetSnapshots()
  71. resp := make(map[string]interface{})
  72. for _, m := range snapshots {
  73. metricName := m.Name() + m.StringifyTags()
  74. switch metric := m.(type) {
  75. case metrics.Gauge:
  76. resp[metricName] = map[string]interface{}{
  77. "value": metric.Value(),
  78. }
  79. case metrics.Counter:
  80. resp[metricName] = map[string]interface{}{
  81. "count": metric.Count(),
  82. }
  83. case metrics.Timer:
  84. percentiles := metric.Percentiles([]float64{0.25, 0.75, 0.90, 0.99})
  85. resp[metricName] = map[string]interface{}{
  86. "count": metric.Count(),
  87. "min": metric.Min(),
  88. "max": metric.Max(),
  89. "mean": metric.Mean(),
  90. "std": metric.StdDev(),
  91. "p25": percentiles[0],
  92. "p75": percentiles[1],
  93. "p90": percentiles[2],
  94. "p99": percentiles[3],
  95. }
  96. }
  97. }
  98. var b []byte
  99. var err error
  100. if b, err = json.MarshalIndent(resp, "", " "); err != nil {
  101. return ApiError(500, "body json marshal", err)
  102. }
  103. return &NormalResponse{
  104. body: b,
  105. status: 200,
  106. header: http.Header{
  107. "Content-Type": []string{"application/json"},
  108. },
  109. }
  110. }
  111. // Genereates a index out of range error
  112. func GenerateError(c *middleware.Context) Response {
  113. var array []string
  114. return Json(200, array[20])
  115. }
  116. // GET /api/tsdb/testdata/gensql
  117. func GenerateSqlTestData(c *middleware.Context) Response {
  118. if err := bus.Dispatch(&models.InsertSqlTestDataCommand{}); err != nil {
  119. return ApiError(500, "Failed to insert test data", err)
  120. }
  121. return Json(200, &util.DynMap{"message": "OK"})
  122. }