stackdriver.go 17 KB

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