stackdriver_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. package stackdriver
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "testing"
  7. "time"
  8. "github.com/grafana/grafana/pkg/components/simplejson"
  9. "github.com/grafana/grafana/pkg/tsdb"
  10. . "github.com/smartystreets/goconvey/convey"
  11. )
  12. func TestStackdriver(t *testing.T) {
  13. Convey("Stackdriver", t, func() {
  14. executor := &StackdriverExecutor{}
  15. Convey("Parse queries from frontend and build Stackdriver API queries", func() {
  16. fromStart := time.Date(2018, 3, 15, 13, 0, 0, 0, time.UTC).In(time.Local)
  17. tsdbQuery := &tsdb.TsdbQuery{
  18. TimeRange: &tsdb.TimeRange{
  19. From: fmt.Sprintf("%v", fromStart.Unix()*1000),
  20. To: fmt.Sprintf("%v", fromStart.Add(34*time.Minute).Unix()*1000),
  21. },
  22. Queries: []*tsdb.Query{
  23. {
  24. Model: simplejson.NewFromAny(map[string]interface{}{
  25. "metricType": "a/metric/type",
  26. "view": "FULL",
  27. "aliasBy": "testalias",
  28. "type": "timeSeriesQuery",
  29. }),
  30. RefId: "A",
  31. },
  32. },
  33. }
  34. Convey("and query has no aggregation set", func() {
  35. queries, err := executor.buildQueries(tsdbQuery)
  36. So(err, ShouldBeNil)
  37. So(len(queries), ShouldEqual, 1)
  38. So(queries[0].RefID, ShouldEqual, "A")
  39. So(queries[0].Target, ShouldEqual, "aggregation.alignmentPeriod=%2B60s&aggregation.crossSeriesReducer=REDUCE_NONE&aggregation.perSeriesAligner=ALIGN_MEAN&filter=metric.type%3D%22a%2Fmetric%2Ftype%22&interval.endTime=2018-03-15T13%3A34%3A00Z&interval.startTime=2018-03-15T13%3A00%3A00Z&view=FULL")
  40. So(len(queries[0].Params), ShouldEqual, 7)
  41. So(queries[0].Params["interval.startTime"][0], ShouldEqual, "2018-03-15T13:00:00Z")
  42. So(queries[0].Params["interval.endTime"][0], ShouldEqual, "2018-03-15T13:34:00Z")
  43. So(queries[0].Params["aggregation.perSeriesAligner"][0], ShouldEqual, "ALIGN_MEAN")
  44. So(queries[0].Params["filter"][0], ShouldEqual, "metric.type=\"a/metric/type\"")
  45. So(queries[0].Params["view"][0], ShouldEqual, "FULL")
  46. So(queries[0].AliasBy, ShouldEqual, "testalias")
  47. })
  48. Convey("and query has filters", func() {
  49. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  50. "metricType": "a/metric/type",
  51. "filters": []interface{}{"key", "=", "value", "AND", "key2", "=", "value2"},
  52. })
  53. queries, err := executor.buildQueries(tsdbQuery)
  54. So(err, ShouldBeNil)
  55. So(len(queries), ShouldEqual, 1)
  56. So(queries[0].Params["filter"][0], ShouldEqual, `metric.type="a/metric/type" key="value" key2="value2"`)
  57. })
  58. Convey("and alignmentPeriod is set to grafana-auto", func() {
  59. Convey("and IntervalMs is larger than 60000", func() {
  60. tsdbQuery.Queries[0].IntervalMs = 1000000
  61. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  62. "alignmentPeriod": "grafana-auto",
  63. "filters": []interface{}{"key", "=", "value", "AND", "key2", "=", "value2"},
  64. })
  65. queries, err := executor.buildQueries(tsdbQuery)
  66. So(err, ShouldBeNil)
  67. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+1000s`)
  68. })
  69. Convey("and IntervalMs is less than 60000", func() {
  70. tsdbQuery.Queries[0].IntervalMs = 30000
  71. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  72. "alignmentPeriod": "grafana-auto",
  73. "filters": []interface{}{"key", "=", "value", "AND", "key2", "=", "value2"},
  74. })
  75. queries, err := executor.buildQueries(tsdbQuery)
  76. So(err, ShouldBeNil)
  77. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+60s`)
  78. })
  79. })
  80. Convey("and alignmentPeriod is set to stackdriver-auto", func() {
  81. Convey("and range is two hours", func() {
  82. tsdbQuery.TimeRange.From = "1538033322461"
  83. tsdbQuery.TimeRange.To = "1538040522461"
  84. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  85. "target": "target",
  86. "alignmentPeriod": "stackdriver-auto",
  87. })
  88. queries, err := executor.buildQueries(tsdbQuery)
  89. So(err, ShouldBeNil)
  90. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+60s`)
  91. })
  92. Convey("and range is 22 hours", func() {
  93. tsdbQuery.TimeRange.From = "1538034524922"
  94. tsdbQuery.TimeRange.To = "1538113724922"
  95. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  96. "target": "target",
  97. "alignmentPeriod": "stackdriver-auto",
  98. })
  99. queries, err := executor.buildQueries(tsdbQuery)
  100. So(err, ShouldBeNil)
  101. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+60s`)
  102. })
  103. Convey("and range is 23 hours", func() {
  104. tsdbQuery.TimeRange.From = "1538034567985"
  105. tsdbQuery.TimeRange.To = "1538117367985"
  106. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  107. "target": "target",
  108. "alignmentPeriod": "stackdriver-auto",
  109. })
  110. queries, err := executor.buildQueries(tsdbQuery)
  111. So(err, ShouldBeNil)
  112. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+300s`)
  113. })
  114. Convey("and range is 7 days", func() {
  115. tsdbQuery.TimeRange.From = "1538036324073"
  116. tsdbQuery.TimeRange.To = "1538641124073"
  117. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  118. "target": "target",
  119. "alignmentPeriod": "stackdriver-auto",
  120. })
  121. queries, err := executor.buildQueries(tsdbQuery)
  122. So(err, ShouldBeNil)
  123. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+3600s`)
  124. })
  125. })
  126. Convey("and alignmentPeriod is set in frontend", func() {
  127. Convey("and alignment period is too big", func() {
  128. tsdbQuery.Queries[0].IntervalMs = 1000
  129. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  130. "alignmentPeriod": "+360000s",
  131. })
  132. queries, err := executor.buildQueries(tsdbQuery)
  133. So(err, ShouldBeNil)
  134. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+3600s`)
  135. })
  136. Convey("and alignment period is within accepted range", func() {
  137. tsdbQuery.Queries[0].IntervalMs = 1000
  138. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  139. "alignmentPeriod": "+600s",
  140. })
  141. queries, err := executor.buildQueries(tsdbQuery)
  142. So(err, ShouldBeNil)
  143. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, `+600s`)
  144. })
  145. })
  146. Convey("and query has aggregation mean set", func() {
  147. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  148. "metricType": "a/metric/type",
  149. "primaryAggregation": "REDUCE_MEAN",
  150. "view": "FULL",
  151. })
  152. queries, err := executor.buildQueries(tsdbQuery)
  153. So(err, ShouldBeNil)
  154. So(len(queries), ShouldEqual, 1)
  155. So(queries[0].RefID, ShouldEqual, "A")
  156. So(queries[0].Target, ShouldEqual, "aggregation.alignmentPeriod=%2B60s&aggregation.crossSeriesReducer=REDUCE_MEAN&aggregation.perSeriesAligner=ALIGN_MEAN&filter=metric.type%3D%22a%2Fmetric%2Ftype%22&interval.endTime=2018-03-15T13%3A34%3A00Z&interval.startTime=2018-03-15T13%3A00%3A00Z&view=FULL")
  157. So(len(queries[0].Params), ShouldEqual, 7)
  158. So(queries[0].Params["interval.startTime"][0], ShouldEqual, "2018-03-15T13:00:00Z")
  159. So(queries[0].Params["interval.endTime"][0], ShouldEqual, "2018-03-15T13:34:00Z")
  160. So(queries[0].Params["aggregation.crossSeriesReducer"][0], ShouldEqual, "REDUCE_MEAN")
  161. So(queries[0].Params["aggregation.perSeriesAligner"][0], ShouldEqual, "ALIGN_MEAN")
  162. So(queries[0].Params["aggregation.alignmentPeriod"][0], ShouldEqual, "+60s")
  163. So(queries[0].Params["filter"][0], ShouldEqual, "metric.type=\"a/metric/type\"")
  164. So(queries[0].Params["view"][0], ShouldEqual, "FULL")
  165. })
  166. Convey("and query has group bys", func() {
  167. tsdbQuery.Queries[0].Model = simplejson.NewFromAny(map[string]interface{}{
  168. "metricType": "a/metric/type",
  169. "primaryAggregation": "REDUCE_NONE",
  170. "groupBys": []interface{}{"metric.label.group1", "metric.label.group2"},
  171. "view": "FULL",
  172. })
  173. queries, err := executor.buildQueries(tsdbQuery)
  174. So(err, ShouldBeNil)
  175. So(len(queries), ShouldEqual, 1)
  176. So(queries[0].RefID, ShouldEqual, "A")
  177. So(queries[0].Target, ShouldEqual, "aggregation.alignmentPeriod=%2B60s&aggregation.crossSeriesReducer=REDUCE_NONE&aggregation.groupByFields=metric.label.group1&aggregation.groupByFields=metric.label.group2&aggregation.perSeriesAligner=ALIGN_MEAN&filter=metric.type%3D%22a%2Fmetric%2Ftype%22&interval.endTime=2018-03-15T13%3A34%3A00Z&interval.startTime=2018-03-15T13%3A00%3A00Z&view=FULL")
  178. So(len(queries[0].Params), ShouldEqual, 8)
  179. So(queries[0].Params["interval.startTime"][0], ShouldEqual, "2018-03-15T13:00:00Z")
  180. So(queries[0].Params["interval.endTime"][0], ShouldEqual, "2018-03-15T13:34:00Z")
  181. So(queries[0].Params["aggregation.perSeriesAligner"][0], ShouldEqual, "ALIGN_MEAN")
  182. So(queries[0].Params["aggregation.groupByFields"][0], ShouldEqual, "metric.label.group1")
  183. So(queries[0].Params["aggregation.groupByFields"][1], ShouldEqual, "metric.label.group2")
  184. So(queries[0].Params["filter"][0], ShouldEqual, "metric.type=\"a/metric/type\"")
  185. So(queries[0].Params["view"][0], ShouldEqual, "FULL")
  186. })
  187. })
  188. Convey("Parse stackdriver response in the time series format", func() {
  189. Convey("when data from query aggregated to one time series", func() {
  190. data, err := loadTestFile("./test-data/1-series-response-agg-one-metric.json")
  191. So(err, ShouldBeNil)
  192. So(len(data.TimeSeries), ShouldEqual, 1)
  193. res := &tsdb.QueryResult{Meta: simplejson.New(), RefId: "A"}
  194. query := &StackdriverQuery{}
  195. err = executor.parseResponse(res, data, query)
  196. So(err, ShouldBeNil)
  197. So(len(res.Series), ShouldEqual, 1)
  198. So(res.Series[0].Name, ShouldEqual, "serviceruntime.googleapis.com/api/request_count")
  199. So(len(res.Series[0].Points), ShouldEqual, 3)
  200. Convey("timestamps should be in ascending order", func() {
  201. So(res.Series[0].Points[0][0].Float64, ShouldEqual, 0.05)
  202. So(res.Series[0].Points[0][1].Float64, ShouldEqual, 1536670020000)
  203. So(res.Series[0].Points[1][0].Float64, ShouldEqual, 1.05)
  204. So(res.Series[0].Points[1][1].Float64, ShouldEqual, 1536670080000)
  205. So(res.Series[0].Points[2][0].Float64, ShouldEqual, 1.0666666666667)
  206. So(res.Series[0].Points[2][1].Float64, ShouldEqual, 1536670260000)
  207. })
  208. })
  209. Convey("when data from query with no aggregation", func() {
  210. data, err := loadTestFile("./test-data/2-series-response-no-agg.json")
  211. So(err, ShouldBeNil)
  212. So(len(data.TimeSeries), ShouldEqual, 3)
  213. res := &tsdb.QueryResult{Meta: simplejson.New(), RefId: "A"}
  214. query := &StackdriverQuery{}
  215. err = executor.parseResponse(res, data, query)
  216. So(err, ShouldBeNil)
  217. Convey("Should add labels to metric name", func() {
  218. So(len(res.Series), ShouldEqual, 3)
  219. So(res.Series[0].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time collector-asia-east-1")
  220. So(res.Series[1].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time collector-europe-west-1")
  221. So(res.Series[2].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time collector-us-east-1")
  222. })
  223. Convey("Should parse to time series", func() {
  224. So(len(res.Series[0].Points), ShouldEqual, 3)
  225. So(res.Series[0].Points[0][0].Float64, ShouldEqual, 9.8566497180145)
  226. So(res.Series[0].Points[1][0].Float64, ShouldEqual, 9.7323568146676)
  227. So(res.Series[0].Points[2][0].Float64, ShouldEqual, 9.7730520330369)
  228. })
  229. Convey("Should add meta for labels to the response", func() {
  230. metricLabels := res.Meta.Get("metricLabels").Interface().(map[string][]string)
  231. So(metricLabels, ShouldNotBeNil)
  232. So(len(metricLabels["instance_name"]), ShouldEqual, 3)
  233. So(metricLabels["instance_name"][0], ShouldEqual, "collector-asia-east-1")
  234. So(metricLabels["instance_name"][1], ShouldEqual, "collector-europe-west-1")
  235. So(metricLabels["instance_name"][2], ShouldEqual, "collector-us-east-1")
  236. resourceLabels := res.Meta.Get("resourceLabels").Interface().(map[string][]string)
  237. So(resourceLabels, ShouldNotBeNil)
  238. So(len(resourceLabels["zone"]), ShouldEqual, 3)
  239. So(resourceLabels["zone"][0], ShouldEqual, "asia-east1-a")
  240. So(resourceLabels["zone"][1], ShouldEqual, "europe-west1-b")
  241. So(resourceLabels["zone"][2], ShouldEqual, "us-east1-b")
  242. So(len(resourceLabels["project_id"]), ShouldEqual, 1)
  243. So(resourceLabels["project_id"][0], ShouldEqual, "grafana-prod")
  244. })
  245. })
  246. Convey("when data from query with no aggregation and group bys", func() {
  247. data, err := loadTestFile("./test-data/2-series-response-no-agg.json")
  248. So(err, ShouldBeNil)
  249. So(len(data.TimeSeries), ShouldEqual, 3)
  250. res := &tsdb.QueryResult{Meta: simplejson.New(), RefId: "A"}
  251. query := &StackdriverQuery{GroupBys: []string{"metric.label.instance_name", "resource.label.zone"}}
  252. err = executor.parseResponse(res, data, query)
  253. So(err, ShouldBeNil)
  254. Convey("Should add instance name and zone labels to metric name", func() {
  255. So(len(res.Series), ShouldEqual, 3)
  256. So(res.Series[0].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time collector-asia-east-1 asia-east1-a")
  257. So(res.Series[1].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time collector-europe-west-1 europe-west1-b")
  258. So(res.Series[2].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time collector-us-east-1 us-east1-b")
  259. })
  260. })
  261. Convey("when data from query with no aggregation and alias by", func() {
  262. data, err := loadTestFile("./test-data/2-series-response-no-agg.json")
  263. So(err, ShouldBeNil)
  264. So(len(data.TimeSeries), ShouldEqual, 3)
  265. res := &tsdb.QueryResult{Meta: simplejson.New(), RefId: "A"}
  266. Convey("and the alias pattern is for metric type, a metric label and a resource label", func() {
  267. query := &StackdriverQuery{AliasBy: "{{metric.type}} - {{metric.label.instance_name}} - {{resource.label.zone}}", GroupBys: []string{"metric.label.instance_name", "resource.label.zone"}}
  268. err = executor.parseResponse(res, data, query)
  269. So(err, ShouldBeNil)
  270. Convey("Should use alias by formatting and only show instance name", func() {
  271. So(len(res.Series), ShouldEqual, 3)
  272. So(res.Series[0].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time - collector-asia-east-1 - asia-east1-a")
  273. So(res.Series[1].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time - collector-europe-west-1 - europe-west1-b")
  274. So(res.Series[2].Name, ShouldEqual, "compute.googleapis.com/instance/cpu/usage_time - collector-us-east-1 - us-east1-b")
  275. })
  276. })
  277. Convey("and the alias pattern is for metric name", func() {
  278. query := &StackdriverQuery{AliasBy: "metric {{metric.name}} service {{metric.service}}", GroupBys: []string{"metric.label.instance_name", "resource.label.zone"}}
  279. err = executor.parseResponse(res, data, query)
  280. So(err, ShouldBeNil)
  281. Convey("Should use alias by formatting and only show instance name", func() {
  282. So(len(res.Series), ShouldEqual, 3)
  283. So(res.Series[0].Name, ShouldEqual, "metric instance/cpu/usage_time service compute")
  284. So(res.Series[1].Name, ShouldEqual, "metric instance/cpu/usage_time service compute")
  285. So(res.Series[2].Name, ShouldEqual, "metric instance/cpu/usage_time service compute")
  286. })
  287. })
  288. })
  289. })
  290. Convey("when interpolating filter wildcards", func() {
  291. Convey("and wildcard is used in the beginning and the end of the word", func() {
  292. Convey("and theres no wildcard in the middle of the word", func() {
  293. value := interpolateFilterWildcards("*-central1*")
  294. So(value, ShouldEqual, `has_substring("-central1")`)
  295. })
  296. Convey("and there is a wildcard in the middle of the word", func() {
  297. value := interpolateFilterWildcards("*-cent*ral1*")
  298. So(value, ShouldNotStartWith, `has_substring`)
  299. })
  300. })
  301. Convey("and wildcard is used in the beginning of the word", func() {
  302. Convey("and there is not a wildcard elsewhere in the word", func() {
  303. value := interpolateFilterWildcards("*-central1")
  304. So(value, ShouldEqual, `ends_with("-central1")`)
  305. })
  306. Convey("and there is a wildcard elsewhere in the word", func() {
  307. value := interpolateFilterWildcards("*-cent*al1")
  308. So(value, ShouldNotStartWith, `ends_with`)
  309. })
  310. })
  311. Convey("and wildcard is used at the end of the word", func() {
  312. Convey("and there is not a wildcard elsewhere in the word", func() {
  313. value := interpolateFilterWildcards("us-central*")
  314. So(value, ShouldEqual, `starts_with("us-central")`)
  315. })
  316. Convey("and there is a wildcard elsewhere in the word", func() {
  317. value := interpolateFilterWildcards("*us-central*")
  318. So(value, ShouldNotStartWith, `starts_with`)
  319. })
  320. })
  321. Convey("and wildcard is used in the middle of the word", func() {
  322. Convey("and there is only one wildcard", func() {
  323. value := interpolateFilterWildcards("us-ce*tral1-b")
  324. So(value, ShouldEqual, `monitoring.regex.full_match("^us\\-ce.*tral1\\-b$")`)
  325. })
  326. Convey("and there is more than one wildcard", func() {
  327. value := interpolateFilterWildcards("us-ce*tra*1-b")
  328. So(value, ShouldEqual, `monitoring.regex.full_match("^us\\-ce.*tra.*1\\-b$")`)
  329. })
  330. })
  331. Convey("and wildcard is used in the middle of the word and in the beginning of the word", func() {
  332. value := interpolateFilterWildcards("*s-ce*tral1-b")
  333. So(value, ShouldEqual, `monitoring.regex.full_match("^.*s\\-ce.*tral1\\-b$")`)
  334. })
  335. Convey("and wildcard is used in the middle of the word and in the ending of the word", func() {
  336. value := interpolateFilterWildcards("us-ce*tral1-*")
  337. So(value, ShouldEqual, `monitoring.regex.full_match("^us\\-ce.*tral1\\-.*$")`)
  338. })
  339. Convey("and no wildcard is used", func() {
  340. value := interpolateFilterWildcards("us-central1-a}")
  341. So(value, ShouldEqual, `us-central1-a}`)
  342. })
  343. })
  344. Convey("when building filter string", func() {
  345. Convey("and there are wildcards in a filter value", func() {
  346. filterParts := []interface{}{"zone", "=", "*-central1*"}
  347. value := buildFilterString("somemetrictype", filterParts)
  348. So(value, ShouldEqual, `metric.type="somemetrictype" zone=has_substring("-central1")`)
  349. })
  350. Convey("and there are no wildcards in any filter value", func() {
  351. filterParts := []interface{}{"zone", "=", "us-central1-a"}
  352. value := buildFilterString("somemetrictype", filterParts)
  353. So(value, ShouldEqual, `metric.type="somemetrictype" zone="us-central1-a"`)
  354. })
  355. })
  356. })
  357. }
  358. func loadTestFile(path string) (StackdriverResponse, error) {
  359. var data StackdriverResponse
  360. jsonBody, err := ioutil.ReadFile(path)
  361. if err != nil {
  362. return data, err
  363. }
  364. err = json.Unmarshal(jsonBody, &data)
  365. return data, err
  366. }