stackdriver.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. package stackdriver
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "math"
  9. "net/http"
  10. "net/url"
  11. "path"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "golang.org/x/net/context/ctxhttp"
  17. "github.com/grafana/grafana/pkg/api/pluginproxy"
  18. "github.com/grafana/grafana/pkg/components/null"
  19. "github.com/grafana/grafana/pkg/components/simplejson"
  20. "github.com/grafana/grafana/pkg/log"
  21. "github.com/grafana/grafana/pkg/models"
  22. "github.com/grafana/grafana/pkg/plugins"
  23. "github.com/grafana/grafana/pkg/setting"
  24. "github.com/grafana/grafana/pkg/tsdb"
  25. "github.com/opentracing/opentracing-go"
  26. )
  27. var (
  28. slog log.Logger
  29. legendKeyFormat *regexp.Regexp
  30. metricNameFormat *regexp.Regexp
  31. )
  32. // StackdriverExecutor executes queries for the Stackdriver datasource
  33. type StackdriverExecutor struct {
  34. httpClient *http.Client
  35. dsInfo *models.DataSource
  36. }
  37. // NewStackdriverExecutor initializes a http client
  38. func NewStackdriverExecutor(dsInfo *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
  39. httpClient, err := dsInfo.GetHttpClient()
  40. if err != nil {
  41. return nil, err
  42. }
  43. return &StackdriverExecutor{
  44. httpClient: httpClient,
  45. dsInfo: dsInfo,
  46. }, nil
  47. }
  48. func init() {
  49. slog = log.New("tsdb.stackdriver")
  50. tsdb.RegisterTsdbQueryEndpoint("stackdriver", NewStackdriverExecutor)
  51. legendKeyFormat = regexp.MustCompile(`\{\{\s*(.+?)\s*\}\}`)
  52. metricNameFormat = regexp.MustCompile(`([\w\d_]+)\.googleapis\.com/(.+)`)
  53. }
  54. // Query takes in the frontend queries, parses them into the Stackdriver query format
  55. // executes the queries against the Stackdriver API and parses the response into
  56. // the time series or table format
  57. func (e *StackdriverExecutor) Query(ctx context.Context, dsInfo *models.DataSource, tsdbQuery *tsdb.TsdbQuery) (*tsdb.Response, error) {
  58. var result *tsdb.Response
  59. var err error
  60. queryType := tsdbQuery.Queries[0].Model.Get("type").MustString("")
  61. switch queryType {
  62. case "annotationQuery":
  63. result, err = e.executeAnnotationQuery(ctx, tsdbQuery)
  64. case "timeSeriesQuery":
  65. fallthrough
  66. default:
  67. result, err = e.executeTimeSeriesQuery(ctx, tsdbQuery)
  68. }
  69. return result, err
  70. }
  71. func (e *StackdriverExecutor) executeTimeSeriesQuery(ctx context.Context, tsdbQuery *tsdb.TsdbQuery) (*tsdb.Response, error) {
  72. result := &tsdb.Response{
  73. Results: make(map[string]*tsdb.QueryResult),
  74. }
  75. queries, err := e.buildQueries(tsdbQuery)
  76. if err != nil {
  77. return nil, err
  78. }
  79. for _, query := range queries {
  80. queryRes, resp, err := e.executeQuery(ctx, query, tsdbQuery)
  81. if err != nil {
  82. return nil, err
  83. }
  84. err = e.parseResponse(queryRes, resp, query)
  85. if err != nil {
  86. queryRes.Error = err
  87. }
  88. result.Results[query.RefID] = queryRes
  89. }
  90. return result, nil
  91. }
  92. func (e *StackdriverExecutor) buildQueries(tsdbQuery *tsdb.TsdbQuery) ([]*StackdriverQuery, error) {
  93. stackdriverQueries := []*StackdriverQuery{}
  94. startTime, err := tsdbQuery.TimeRange.ParseFrom()
  95. if err != nil {
  96. return nil, err
  97. }
  98. endTime, err := tsdbQuery.TimeRange.ParseTo()
  99. if err != nil {
  100. return nil, err
  101. }
  102. durationSeconds := int(endTime.Sub(startTime).Seconds())
  103. for _, query := range tsdbQuery.Queries {
  104. var target string
  105. metricType := query.Model.Get("metricType").MustString()
  106. filterParts := query.Model.Get("filters").MustArray()
  107. params := url.Values{}
  108. params.Add("interval.startTime", startTime.UTC().Format(time.RFC3339))
  109. params.Add("interval.endTime", endTime.UTC().Format(time.RFC3339))
  110. params.Add("filter", buildFilterString(metricType, filterParts))
  111. params.Add("view", query.Model.Get("view").MustString("FULL"))
  112. setAggParams(&params, query, durationSeconds)
  113. target = params.Encode()
  114. if setting.Env == setting.DEV {
  115. slog.Debug("Stackdriver request", "params", params)
  116. }
  117. groupBys := query.Model.Get("groupBys").MustArray()
  118. groupBysAsStrings := make([]string, 0)
  119. for _, groupBy := range groupBys {
  120. groupBysAsStrings = append(groupBysAsStrings, groupBy.(string))
  121. }
  122. aliasBy := query.Model.Get("aliasBy").MustString()
  123. stackdriverQueries = append(stackdriverQueries, &StackdriverQuery{
  124. Target: target,
  125. Params: params,
  126. RefID: query.RefId,
  127. GroupBys: groupBysAsStrings,
  128. AliasBy: aliasBy,
  129. })
  130. }
  131. return stackdriverQueries, nil
  132. }
  133. func reverse(s string) string {
  134. chars := []rune(s)
  135. for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
  136. chars[i], chars[j] = chars[j], chars[i]
  137. }
  138. return string(chars)
  139. }
  140. func interpolateFilterWildcards(value string) string {
  141. matches := strings.Count(value, "*")
  142. if matches == 2 && strings.HasSuffix(value, "*") && strings.HasPrefix(value, "*") {
  143. value = strings.Replace(value, "*", "", -1)
  144. value = fmt.Sprintf(`has_substring("%s")`, value)
  145. } else if matches == 1 && strings.HasPrefix(value, "*") {
  146. value = strings.Replace(value, "*", "", 1)
  147. value = fmt.Sprintf(`ends_with("%s")`, value)
  148. } else if matches == 1 && strings.HasSuffix(value, "*") {
  149. value = reverse(strings.Replace(reverse(value), "*", "", 1))
  150. value = fmt.Sprintf(`starts_with("%s")`, value)
  151. } else if matches != 0 {
  152. re := regexp.MustCompile(`[-\/^$+?.()|[\]{}]`)
  153. value = string(re.ReplaceAllFunc([]byte(value), func(in []byte) []byte {
  154. return []byte(strings.Replace(string(in), string(in), `\\`+string(in), 1))
  155. }))
  156. value = strings.Replace(value, "*", ".*", -1)
  157. value = strings.Replace(value, `"`, `\\"`, -1)
  158. value = fmt.Sprintf(`monitoring.regex.full_match("^%s$")`, value)
  159. }
  160. return value
  161. }
  162. func buildFilterString(metricType string, filterParts []interface{}) string {
  163. filterString := ""
  164. for i, part := range filterParts {
  165. mod := i % 4
  166. if part == "AND" {
  167. filterString += " "
  168. } else if mod == 2 {
  169. operator := filterParts[i-1]
  170. if operator == "=~" || operator == "!=~" {
  171. filterString = reverse(strings.Replace(reverse(filterString), "~", "", 1))
  172. filterString += fmt.Sprintf(`monitoring.regex.full_match("%s")`, part)
  173. } else if strings.Contains(part.(string), "*") {
  174. filterString += interpolateFilterWildcards(part.(string))
  175. } else {
  176. filterString += fmt.Sprintf(`"%s"`, part)
  177. }
  178. } else {
  179. filterString += part.(string)
  180. }
  181. }
  182. return strings.Trim(fmt.Sprintf(`metric.type="%s" %s`, metricType, filterString), " ")
  183. }
  184. func setAggParams(params *url.Values, query *tsdb.Query, durationSeconds int) {
  185. primaryAggregation := query.Model.Get("primaryAggregation").MustString()
  186. perSeriesAligner := query.Model.Get("perSeriesAligner").MustString()
  187. alignmentPeriod := query.Model.Get("alignmentPeriod").MustString()
  188. if primaryAggregation == "" {
  189. primaryAggregation = "REDUCE_NONE"
  190. }
  191. if perSeriesAligner == "" {
  192. perSeriesAligner = "ALIGN_MEAN"
  193. }
  194. if alignmentPeriod == "grafana-auto" || alignmentPeriod == "" {
  195. alignmentPeriodValue := int(math.Max(float64(query.IntervalMs)/1000, 60.0))
  196. alignmentPeriod = "+" + strconv.Itoa(alignmentPeriodValue) + "s"
  197. }
  198. if alignmentPeriod == "stackdriver-auto" {
  199. alignmentPeriodValue := int(math.Max(float64(durationSeconds), 60.0))
  200. if alignmentPeriodValue < 60*60*23 {
  201. alignmentPeriod = "+60s"
  202. } else if alignmentPeriodValue < 60*60*24*6 {
  203. alignmentPeriod = "+300s"
  204. } else {
  205. alignmentPeriod = "+3600s"
  206. }
  207. }
  208. re := regexp.MustCompile("[0-9]+")
  209. seconds, err := strconv.ParseInt(re.FindString(alignmentPeriod), 10, 64)
  210. if err != nil || seconds > 3600 {
  211. alignmentPeriod = "+3600s"
  212. }
  213. params.Add("aggregation.crossSeriesReducer", primaryAggregation)
  214. params.Add("aggregation.perSeriesAligner", perSeriesAligner)
  215. params.Add("aggregation.alignmentPeriod", alignmentPeriod)
  216. groupBys := query.Model.Get("groupBys").MustArray()
  217. if len(groupBys) > 0 {
  218. for i := 0; i < len(groupBys); i++ {
  219. params.Add("aggregation.groupByFields", groupBys[i].(string))
  220. }
  221. }
  222. }
  223. func (e *StackdriverExecutor) executeQuery(ctx context.Context, query *StackdriverQuery, tsdbQuery *tsdb.TsdbQuery) (*tsdb.QueryResult, StackdriverResponse, error) {
  224. queryResult := &tsdb.QueryResult{Meta: simplejson.New(), RefId: query.RefID}
  225. req, err := e.createRequest(ctx, e.dsInfo)
  226. if err != nil {
  227. queryResult.Error = err
  228. return queryResult, StackdriverResponse{}, nil
  229. }
  230. req.URL.RawQuery = query.Params.Encode()
  231. queryResult.Meta.Set("rawQuery", req.URL.RawQuery)
  232. alignmentPeriod, ok := req.URL.Query()["aggregation.alignmentPeriod"]
  233. if ok {
  234. re := regexp.MustCompile("[0-9]+")
  235. seconds, err := strconv.ParseInt(re.FindString(alignmentPeriod[0]), 10, 64)
  236. if err == nil {
  237. queryResult.Meta.Set("alignmentPeriod", seconds)
  238. }
  239. }
  240. span, ctx := opentracing.StartSpanFromContext(ctx, "stackdriver query")
  241. span.SetTag("target", query.Target)
  242. span.SetTag("from", tsdbQuery.TimeRange.From)
  243. span.SetTag("until", tsdbQuery.TimeRange.To)
  244. span.SetTag("datasource_id", e.dsInfo.Id)
  245. span.SetTag("org_id", e.dsInfo.OrgId)
  246. defer span.Finish()
  247. opentracing.GlobalTracer().Inject(
  248. span.Context(),
  249. opentracing.HTTPHeaders,
  250. opentracing.HTTPHeadersCarrier(req.Header))
  251. res, err := ctxhttp.Do(ctx, e.httpClient, req)
  252. if err != nil {
  253. queryResult.Error = err
  254. return queryResult, StackdriverResponse{}, nil
  255. }
  256. data, err := e.unmarshalResponse(res)
  257. if err != nil {
  258. queryResult.Error = err
  259. return queryResult, StackdriverResponse{}, nil
  260. }
  261. return queryResult, data, nil
  262. }
  263. func (e *StackdriverExecutor) unmarshalResponse(res *http.Response) (StackdriverResponse, error) {
  264. body, err := ioutil.ReadAll(res.Body)
  265. defer res.Body.Close()
  266. if err != nil {
  267. return StackdriverResponse{}, err
  268. }
  269. if res.StatusCode/100 != 2 {
  270. slog.Error("Request failed", "status", res.Status, "body", string(body))
  271. return StackdriverResponse{}, fmt.Errorf(string(body))
  272. }
  273. var data StackdriverResponse
  274. err = json.Unmarshal(body, &data)
  275. if err != nil {
  276. slog.Error("Failed to unmarshal Stackdriver response", "error", err, "status", res.Status, "body", string(body))
  277. return StackdriverResponse{}, err
  278. }
  279. return data, nil
  280. }
  281. func (e *StackdriverExecutor) parseResponse(queryRes *tsdb.QueryResult, data StackdriverResponse, query *StackdriverQuery) error {
  282. metricLabels := make(map[string][]string)
  283. resourceLabels := make(map[string][]string)
  284. for _, series := range data.TimeSeries {
  285. points := make([]tsdb.TimePoint, 0)
  286. defaultMetricName := series.Metric.Type
  287. for key, value := range series.Metric.Labels {
  288. if !containsLabel(metricLabels[key], value) {
  289. metricLabels[key] = append(metricLabels[key], value)
  290. }
  291. if len(query.GroupBys) == 0 || containsLabel(query.GroupBys, "metric.label."+key) {
  292. defaultMetricName += " " + value
  293. }
  294. }
  295. for key, value := range series.Resource.Labels {
  296. if !containsLabel(resourceLabels[key], value) {
  297. resourceLabels[key] = append(resourceLabels[key], value)
  298. }
  299. if containsLabel(query.GroupBys, "resource.label."+key) {
  300. defaultMetricName += " " + value
  301. }
  302. }
  303. // reverse the order to be ascending
  304. if series.ValueType != "DISTRIBUTION" {
  305. for i := len(series.Points) - 1; i >= 0; i-- {
  306. point := series.Points[i]
  307. value := point.Value.DoubleValue
  308. if series.ValueType == "INT64" {
  309. parsedValue, err := strconv.ParseFloat(point.Value.IntValue, 64)
  310. if err == nil {
  311. value = parsedValue
  312. }
  313. }
  314. if series.ValueType == "BOOL" {
  315. if point.Value.BoolValue {
  316. value = 1
  317. } else {
  318. value = 0
  319. }
  320. }
  321. points = append(points, tsdb.NewTimePoint(null.FloatFrom(value), float64((point.Interval.EndTime).Unix())*1000))
  322. }
  323. metricName := formatLegendKeys(series.Metric.Type, defaultMetricName, series.Metric.Labels, series.Resource.Labels, make(map[string]string), query)
  324. queryRes.Series = append(queryRes.Series, &tsdb.TimeSeries{
  325. Name: metricName,
  326. Points: points,
  327. })
  328. } else {
  329. buckets := make(map[int]*tsdb.TimeSeries)
  330. for i := len(series.Points) - 1; i >= 0; i-- {
  331. point := series.Points[i]
  332. if len(point.Value.DistributionValue.BucketCounts) == 0 {
  333. continue
  334. }
  335. maxKey := 0
  336. for i := 0; i < len(point.Value.DistributionValue.BucketCounts); i++ {
  337. value, err := strconv.ParseFloat(point.Value.DistributionValue.BucketCounts[i], 64)
  338. if err != nil {
  339. continue
  340. }
  341. if _, ok := buckets[i]; !ok {
  342. // set lower bounds
  343. // https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries#Distribution
  344. bucketBound := calcBucketBound(point.Value.DistributionValue.BucketOptions, i)
  345. additionalLabels := map[string]string{"bucket": bucketBound}
  346. buckets[i] = &tsdb.TimeSeries{
  347. Name: formatLegendKeys(series.Metric.Type, defaultMetricName, series.Metric.Labels, series.Resource.Labels, additionalLabels, query),
  348. Points: make([]tsdb.TimePoint, 0),
  349. }
  350. if maxKey < i {
  351. maxKey = i
  352. }
  353. }
  354. buckets[i].Points = append(buckets[i].Points, tsdb.NewTimePoint(null.FloatFrom(value), float64((point.Interval.EndTime).Unix())*1000))
  355. }
  356. // fill empty bucket
  357. for i := 0; i < maxKey; i++ {
  358. if _, ok := buckets[i]; !ok {
  359. bucketBound := calcBucketBound(point.Value.DistributionValue.BucketOptions, i)
  360. additionalLabels := map[string]string{"bucket": bucketBound}
  361. buckets[i] = &tsdb.TimeSeries{
  362. Name: formatLegendKeys(series.Metric.Type, defaultMetricName, series.Metric.Labels, series.Resource.Labels, additionalLabels, query),
  363. Points: make([]tsdb.TimePoint, 0),
  364. }
  365. }
  366. }
  367. }
  368. for i := 0; i < len(buckets); i++ {
  369. queryRes.Series = append(queryRes.Series, buckets[i])
  370. }
  371. }
  372. }
  373. queryRes.Meta.Set("resourceLabels", resourceLabels)
  374. queryRes.Meta.Set("metricLabels", metricLabels)
  375. queryRes.Meta.Set("groupBys", query.GroupBys)
  376. return nil
  377. }
  378. func containsLabel(labels []string, newLabel string) bool {
  379. for _, val := range labels {
  380. if val == newLabel {
  381. return true
  382. }
  383. }
  384. return false
  385. }
  386. func formatLegendKeys(metricType string, defaultMetricName string, metricLabels map[string]string, resourceLabels map[string]string, additionalLabels map[string]string, query *StackdriverQuery) string {
  387. if query.AliasBy == "" {
  388. return defaultMetricName
  389. }
  390. result := legendKeyFormat.ReplaceAllFunc([]byte(query.AliasBy), func(in []byte) []byte {
  391. metaPartName := strings.Replace(string(in), "{{", "", 1)
  392. metaPartName = strings.Replace(metaPartName, "}}", "", 1)
  393. metaPartName = strings.TrimSpace(metaPartName)
  394. if metaPartName == "metric.type" {
  395. return []byte(metricType)
  396. }
  397. metricPart := replaceWithMetricPart(metaPartName, metricType)
  398. if metricPart != nil {
  399. return metricPart
  400. }
  401. metaPartName = strings.Replace(metaPartName, "metric.label.", "", 1)
  402. if val, exists := metricLabels[metaPartName]; exists {
  403. return []byte(val)
  404. }
  405. metaPartName = strings.Replace(metaPartName, "resource.label.", "", 1)
  406. if val, exists := resourceLabels[metaPartName]; exists {
  407. return []byte(val)
  408. }
  409. if val, exists := additionalLabels[metaPartName]; exists {
  410. return []byte(val)
  411. }
  412. return in
  413. })
  414. return string(result)
  415. }
  416. func replaceWithMetricPart(metaPartName string, metricType string) []byte {
  417. // https://cloud.google.com/monitoring/api/v3/metrics-details#label_names
  418. shortMatches := metricNameFormat.FindStringSubmatch(metricType)
  419. if metaPartName == "metric.name" {
  420. if len(shortMatches) > 0 {
  421. return []byte(shortMatches[2])
  422. }
  423. }
  424. if metaPartName == "metric.service" {
  425. if len(shortMatches) > 0 {
  426. return []byte(shortMatches[1])
  427. }
  428. }
  429. return nil
  430. }
  431. func calcBucketBound(bucketOptions StackdriverBucketOptions, n int) string {
  432. bucketBound := "0"
  433. if n == 0 {
  434. return bucketBound
  435. }
  436. if bucketOptions.LinearBuckets != nil {
  437. bucketBound = strconv.FormatInt(bucketOptions.LinearBuckets.Offset+(bucketOptions.LinearBuckets.Width*int64(n-1)), 10)
  438. } else if bucketOptions.ExponentialBuckets != nil {
  439. bucketBound = strconv.FormatInt(int64(bucketOptions.ExponentialBuckets.Scale*math.Pow(bucketOptions.ExponentialBuckets.GrowthFactor, float64(n-1))), 10)
  440. } else if bucketOptions.ExplicitBuckets != nil {
  441. bucketBound = strconv.FormatInt(bucketOptions.ExplicitBuckets.Bounds[(n-1)], 10)
  442. }
  443. return bucketBound
  444. }
  445. func (e *StackdriverExecutor) createRequest(ctx context.Context, dsInfo *models.DataSource) (*http.Request, error) {
  446. u, _ := url.Parse(dsInfo.Url)
  447. u.Path = path.Join(u.Path, "render")
  448. req, err := http.NewRequest(http.MethodGet, "https://monitoring.googleapis.com/", nil)
  449. if err != nil {
  450. slog.Error("Failed to create request", "error", err)
  451. return nil, fmt.Errorf("Failed to create request. error: %v", err)
  452. }
  453. req.Header.Set("Content-Type", "application/json")
  454. req.Header.Set("User-Agent", fmt.Sprintf("Grafana/%s", setting.BuildVersion))
  455. // find plugin
  456. plugin, ok := plugins.DataSources[dsInfo.Type]
  457. if !ok {
  458. return nil, errors.New("Unable to find datasource plugin Stackdriver")
  459. }
  460. projectName := dsInfo.JsonData.Get("defaultProject").MustString()
  461. proxyPass := fmt.Sprintf("stackdriver%s", "v3/projects/"+projectName+"/timeSeries")
  462. var stackdriverRoute *plugins.AppPluginRoute
  463. for _, route := range plugin.Routes {
  464. if route.Path == "stackdriver" {
  465. stackdriverRoute = route
  466. break
  467. }
  468. }
  469. pluginproxy.ApplyRoute(ctx, req, proxyPass, stackdriverRoute, dsInfo)
  470. return req, nil
  471. }