stackdriver.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. re := regexp.MustCompile("[*]")
  142. matches := len(re.FindAllStringIndex(value, -1))
  143. if matches == 2 && strings.HasSuffix(value, "*") && strings.HasPrefix(value, "*") {
  144. value = strings.Replace(value, "*", "", -1)
  145. value = fmt.Sprintf(`has_substring("%s")`, value)
  146. } else if matches == 1 && strings.HasPrefix(value, "*") {
  147. value = strings.Replace(value, "*", "", 1)
  148. value = fmt.Sprintf(`ends_with("%s")`, value)
  149. } else if matches == 1 && strings.HasSuffix(value, "*") {
  150. value = reverse(strings.Replace(reverse(value), "*", "", 1))
  151. value = fmt.Sprintf(`starts_with("%s")`, value)
  152. } else if matches != 0 {
  153. re := regexp.MustCompile(`[-\/^$+?.()|[\]{}]`)
  154. value = string(re.ReplaceAllFunc([]byte(value), func(in []byte) []byte {
  155. return []byte(strings.Replace(string(in), string(in), `\\`+string(in), 1))
  156. }))
  157. value = strings.Replace(value, "*", ".*", -1)
  158. value = strings.Replace(value, `"`, `\\"`, -1)
  159. value = fmt.Sprintf(`monitoring.regex.full_match("^%s$")`, value)
  160. }
  161. return value
  162. }
  163. func buildFilterString(metricType string, filterParts []interface{}) string {
  164. filterString := ""
  165. for i, part := range filterParts {
  166. mod := i % 4
  167. if part == "AND" {
  168. filterString += " "
  169. } else if mod == 2 {
  170. operator := filterParts[i-1]
  171. if operator == "=~" || operator == "!=~" {
  172. filterString = reverse(strings.Replace(reverse(filterString), "~", "", 1))
  173. filterString += fmt.Sprintf(`monitoring.regex.full_match("%s")`, part)
  174. } else if strings.Contains(part.(string), "*") {
  175. filterString += interpolateFilterWildcards(part.(string))
  176. } else {
  177. filterString += fmt.Sprintf(`"%s"`, part)
  178. }
  179. } else {
  180. filterString += part.(string)
  181. }
  182. }
  183. return strings.Trim(fmt.Sprintf(`metric.type="%s" %s`, metricType, filterString), " ")
  184. }
  185. func setAggParams(params *url.Values, query *tsdb.Query, durationSeconds int) {
  186. primaryAggregation := query.Model.Get("primaryAggregation").MustString()
  187. perSeriesAligner := query.Model.Get("perSeriesAligner").MustString()
  188. alignmentPeriod := query.Model.Get("alignmentPeriod").MustString()
  189. if primaryAggregation == "" {
  190. primaryAggregation = "REDUCE_NONE"
  191. }
  192. if perSeriesAligner == "" {
  193. perSeriesAligner = "ALIGN_MEAN"
  194. }
  195. if alignmentPeriod == "grafana-auto" || alignmentPeriod == "" {
  196. alignmentPeriodValue := int(math.Max(float64(query.IntervalMs)/1000, 60.0))
  197. alignmentPeriod = "+" + strconv.Itoa(alignmentPeriodValue) + "s"
  198. }
  199. if alignmentPeriod == "stackdriver-auto" {
  200. alignmentPeriodValue := int(math.Max(float64(durationSeconds), 60.0))
  201. if alignmentPeriodValue < 60*60*23 {
  202. alignmentPeriod = "+60s"
  203. } else if alignmentPeriodValue < 60*60*24*6 {
  204. alignmentPeriod = "+300s"
  205. } else {
  206. alignmentPeriod = "+3600s"
  207. }
  208. }
  209. re := regexp.MustCompile("[0-9]+")
  210. seconds, err := strconv.ParseInt(re.FindString(alignmentPeriod), 10, 64)
  211. if err != nil || seconds > 3600 {
  212. alignmentPeriod = "+3600s"
  213. }
  214. params.Add("aggregation.crossSeriesReducer", primaryAggregation)
  215. params.Add("aggregation.perSeriesAligner", perSeriesAligner)
  216. params.Add("aggregation.alignmentPeriod", alignmentPeriod)
  217. groupBys := query.Model.Get("groupBys").MustArray()
  218. if len(groupBys) > 0 {
  219. for i := 0; i < len(groupBys); i++ {
  220. params.Add("aggregation.groupByFields", groupBys[i].(string))
  221. }
  222. }
  223. }
  224. func (e *StackdriverExecutor) executeQuery(ctx context.Context, query *StackdriverQuery, tsdbQuery *tsdb.TsdbQuery) (*tsdb.QueryResult, StackdriverResponse, error) {
  225. queryResult := &tsdb.QueryResult{Meta: simplejson.New(), RefId: query.RefID}
  226. req, err := e.createRequest(ctx, e.dsInfo)
  227. if err != nil {
  228. queryResult.Error = err
  229. return queryResult, StackdriverResponse{}, nil
  230. }
  231. req.URL.RawQuery = query.Params.Encode()
  232. queryResult.Meta.Set("rawQuery", req.URL.RawQuery)
  233. alignmentPeriod, ok := req.URL.Query()["aggregation.alignmentPeriod"]
  234. if ok {
  235. re := regexp.MustCompile("[0-9]+")
  236. seconds, err := strconv.ParseInt(re.FindString(alignmentPeriod[0]), 10, 64)
  237. if err == nil {
  238. queryResult.Meta.Set("alignmentPeriod", seconds)
  239. }
  240. }
  241. span, ctx := opentracing.StartSpanFromContext(ctx, "stackdriver query")
  242. span.SetTag("target", query.Target)
  243. span.SetTag("from", tsdbQuery.TimeRange.From)
  244. span.SetTag("until", tsdbQuery.TimeRange.To)
  245. span.SetTag("datasource_id", e.dsInfo.Id)
  246. span.SetTag("org_id", e.dsInfo.OrgId)
  247. defer span.Finish()
  248. opentracing.GlobalTracer().Inject(
  249. span.Context(),
  250. opentracing.HTTPHeaders,
  251. opentracing.HTTPHeadersCarrier(req.Header))
  252. res, err := ctxhttp.Do(ctx, e.httpClient, req)
  253. if err != nil {
  254. queryResult.Error = err
  255. return queryResult, StackdriverResponse{}, nil
  256. }
  257. data, err := e.unmarshalResponse(res)
  258. if err != nil {
  259. queryResult.Error = err
  260. return queryResult, StackdriverResponse{}, nil
  261. }
  262. return queryResult, data, nil
  263. }
  264. func (e *StackdriverExecutor) unmarshalResponse(res *http.Response) (StackdriverResponse, error) {
  265. body, err := ioutil.ReadAll(res.Body)
  266. defer res.Body.Close()
  267. if err != nil {
  268. return StackdriverResponse{}, err
  269. }
  270. if res.StatusCode/100 != 2 {
  271. slog.Error("Request failed", "status", res.Status, "body", string(body))
  272. return StackdriverResponse{}, fmt.Errorf(string(body))
  273. }
  274. var data StackdriverResponse
  275. err = json.Unmarshal(body, &data)
  276. if err != nil {
  277. slog.Error("Failed to unmarshal Stackdriver response", "error", err, "status", res.Status, "body", string(body))
  278. return StackdriverResponse{}, err
  279. }
  280. return data, nil
  281. }
  282. func (e *StackdriverExecutor) parseResponse(queryRes *tsdb.QueryResult, data StackdriverResponse, query *StackdriverQuery) error {
  283. metricLabels := make(map[string][]string)
  284. resourceLabels := make(map[string][]string)
  285. for _, series := range data.TimeSeries {
  286. points := make([]tsdb.TimePoint, 0)
  287. defaultMetricName := series.Metric.Type
  288. for key, value := range series.Metric.Labels {
  289. if !containsLabel(metricLabels[key], value) {
  290. metricLabels[key] = append(metricLabels[key], value)
  291. }
  292. if len(query.GroupBys) == 0 || containsLabel(query.GroupBys, "metric.label."+key) {
  293. defaultMetricName += " " + value
  294. }
  295. }
  296. for key, value := range series.Resource.Labels {
  297. if !containsLabel(resourceLabels[key], value) {
  298. resourceLabels[key] = append(resourceLabels[key], value)
  299. }
  300. if containsLabel(query.GroupBys, "resource.label."+key) {
  301. defaultMetricName += " " + value
  302. }
  303. }
  304. // reverse the order to be ascending
  305. if series.ValueType != "DISTRIBUTION" {
  306. for i := len(series.Points) - 1; i >= 0; i-- {
  307. point := series.Points[i]
  308. value := point.Value.DoubleValue
  309. if series.ValueType == "INT64" {
  310. parsedValue, err := strconv.ParseFloat(point.Value.IntValue, 64)
  311. if err == nil {
  312. value = parsedValue
  313. }
  314. }
  315. if series.ValueType == "BOOL" {
  316. if point.Value.BoolValue {
  317. value = 1
  318. } else {
  319. value = 0
  320. }
  321. }
  322. points = append(points, tsdb.NewTimePoint(null.FloatFrom(value), float64((point.Interval.EndTime).Unix())*1000))
  323. }
  324. metricName := formatLegendKeys(series.Metric.Type, defaultMetricName, series.Metric.Labels, series.Resource.Labels, make(map[string]string), query)
  325. queryRes.Series = append(queryRes.Series, &tsdb.TimeSeries{
  326. Name: metricName,
  327. Points: points,
  328. })
  329. } else {
  330. buckets := make(map[int]*tsdb.TimeSeries)
  331. for i := len(series.Points) - 1; i >= 0; i-- {
  332. point := series.Points[i]
  333. if len(point.Value.DistributionValue.BucketCounts) == 0 {
  334. continue
  335. }
  336. maxKey := 0
  337. for i := 0; i < len(point.Value.DistributionValue.BucketCounts); i++ {
  338. value, err := strconv.ParseFloat(point.Value.DistributionValue.BucketCounts[i], 64)
  339. if err != nil {
  340. continue
  341. }
  342. if _, ok := buckets[i]; !ok {
  343. // set lower bounds
  344. // https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries#Distribution
  345. bucketBound := calcBucketBound(point.Value.DistributionValue.BucketOptions, i)
  346. additionalLabels := map[string]string{"bucket": bucketBound}
  347. buckets[i] = &tsdb.TimeSeries{
  348. Name: formatLegendKeys(series.Metric.Type, defaultMetricName, series.Metric.Labels, series.Resource.Labels, additionalLabels, query),
  349. Points: make([]tsdb.TimePoint, 0),
  350. }
  351. if maxKey < i {
  352. maxKey = i
  353. }
  354. }
  355. buckets[i].Points = append(buckets[i].Points, tsdb.NewTimePoint(null.FloatFrom(value), float64((point.Interval.EndTime).Unix())*1000))
  356. }
  357. // fill empty bucket
  358. for i := 0; i < maxKey; i++ {
  359. if _, ok := buckets[i]; !ok {
  360. bucketBound := calcBucketBound(point.Value.DistributionValue.BucketOptions, i)
  361. additionalLabels := map[string]string{"bucket": bucketBound}
  362. buckets[i] = &tsdb.TimeSeries{
  363. Name: formatLegendKeys(series.Metric.Type, defaultMetricName, series.Metric.Labels, series.Resource.Labels, additionalLabels, query),
  364. Points: make([]tsdb.TimePoint, 0),
  365. }
  366. }
  367. }
  368. }
  369. for i := 0; i < len(buckets); i++ {
  370. queryRes.Series = append(queryRes.Series, buckets[i])
  371. }
  372. }
  373. }
  374. queryRes.Meta.Set("resourceLabels", resourceLabels)
  375. queryRes.Meta.Set("metricLabels", metricLabels)
  376. queryRes.Meta.Set("groupBys", query.GroupBys)
  377. return nil
  378. }
  379. func containsLabel(labels []string, newLabel string) bool {
  380. for _, val := range labels {
  381. if val == newLabel {
  382. return true
  383. }
  384. }
  385. return false
  386. }
  387. func formatLegendKeys(metricType string, defaultMetricName string, metricLabels map[string]string, resourceLabels map[string]string, additionalLabels map[string]string, query *StackdriverQuery) string {
  388. if query.AliasBy == "" {
  389. return defaultMetricName
  390. }
  391. result := legendKeyFormat.ReplaceAllFunc([]byte(query.AliasBy), func(in []byte) []byte {
  392. metaPartName := strings.Replace(string(in), "{{", "", 1)
  393. metaPartName = strings.Replace(metaPartName, "}}", "", 1)
  394. metaPartName = strings.TrimSpace(metaPartName)
  395. if metaPartName == "metric.type" {
  396. return []byte(metricType)
  397. }
  398. metricPart := replaceWithMetricPart(metaPartName, metricType)
  399. if metricPart != nil {
  400. return metricPart
  401. }
  402. metaPartName = strings.Replace(metaPartName, "metric.label.", "", 1)
  403. if val, exists := metricLabels[metaPartName]; exists {
  404. return []byte(val)
  405. }
  406. metaPartName = strings.Replace(metaPartName, "resource.label.", "", 1)
  407. if val, exists := resourceLabels[metaPartName]; exists {
  408. return []byte(val)
  409. }
  410. if val, exists := additionalLabels[metaPartName]; exists {
  411. return []byte(val)
  412. }
  413. return in
  414. })
  415. return string(result)
  416. }
  417. func replaceWithMetricPart(metaPartName string, metricType string) []byte {
  418. // https://cloud.google.com/monitoring/api/v3/metrics-details#label_names
  419. shortMatches := metricNameFormat.FindStringSubmatch(metricType)
  420. if metaPartName == "metric.name" {
  421. if len(shortMatches) > 0 {
  422. return []byte(shortMatches[2])
  423. }
  424. }
  425. if metaPartName == "metric.service" {
  426. if len(shortMatches) > 0 {
  427. return []byte(shortMatches[1])
  428. }
  429. }
  430. return nil
  431. }
  432. func calcBucketBound(bucketOptions StackdriverBucketOptions, n int) string {
  433. bucketBound := "0"
  434. if n == 0 {
  435. return bucketBound
  436. }
  437. if bucketOptions.LinearBuckets != nil {
  438. bucketBound = strconv.FormatInt(bucketOptions.LinearBuckets.Offset+(bucketOptions.LinearBuckets.Width*int64(n-1)), 10)
  439. } else if bucketOptions.ExponentialBuckets != nil {
  440. bucketBound = strconv.FormatInt(int64(bucketOptions.ExponentialBuckets.Scale*math.Pow(bucketOptions.ExponentialBuckets.GrowthFactor, float64(n-1))), 10)
  441. } else if bucketOptions.ExplicitBuckets != nil {
  442. bucketBound = strconv.FormatInt(bucketOptions.ExplicitBuckets.Bounds[(n-1)], 10)
  443. }
  444. return bucketBound
  445. }
  446. func (e *StackdriverExecutor) createRequest(ctx context.Context, dsInfo *models.DataSource) (*http.Request, error) {
  447. u, _ := url.Parse(dsInfo.Url)
  448. u.Path = path.Join(u.Path, "render")
  449. req, err := http.NewRequest(http.MethodGet, "https://monitoring.googleapis.com/", nil)
  450. if err != nil {
  451. slog.Error("Failed to create request", "error", err)
  452. return nil, fmt.Errorf("Failed to create request. error: %v", err)
  453. }
  454. req.Header.Set("Content-Type", "application/json")
  455. req.Header.Set("User-Agent", fmt.Sprintf("Grafana/%s", setting.BuildVersion))
  456. // find plugin
  457. plugin, ok := plugins.DataSources[dsInfo.Type]
  458. if !ok {
  459. return nil, errors.New("Unable to find datasource plugin Stackdriver")
  460. }
  461. projectName := dsInfo.JsonData.Get("defaultProject").MustString()
  462. proxyPass := fmt.Sprintf("stackdriver%s", "v3/projects/"+projectName+"/timeSeries")
  463. var stackdriverRoute *plugins.AppPluginRoute
  464. for _, route := range plugin.Routes {
  465. if route.Path == "stackdriver" {
  466. stackdriverRoute = route
  467. break
  468. }
  469. }
  470. pluginproxy.ApplyRoute(ctx, req, proxyPass, stackdriverRoute, dsInfo)
  471. return req, nil
  472. }