cloudwatch.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. package cloudwatch
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/aws/aws-sdk-go/aws"
  12. "github.com/aws/aws-sdk-go/aws/awsutil"
  13. "github.com/aws/aws-sdk-go/aws/credentials"
  14. "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
  15. "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds"
  16. "github.com/aws/aws-sdk-go/aws/ec2metadata"
  17. "github.com/aws/aws-sdk-go/aws/session"
  18. "github.com/aws/aws-sdk-go/service/cloudwatch"
  19. "github.com/aws/aws-sdk-go/service/sts"
  20. "github.com/grafana/grafana/pkg/metrics"
  21. "github.com/grafana/grafana/pkg/middleware"
  22. m "github.com/grafana/grafana/pkg/models"
  23. )
  24. type actionHandler func(*cwRequest, *middleware.Context)
  25. var actionHandlers map[string]actionHandler
  26. type cwRequest struct {
  27. Region string `json:"region"`
  28. Action string `json:"action"`
  29. Body []byte `json:"-"`
  30. DataSource *m.DataSource
  31. }
  32. type DatasourceInfo struct {
  33. Profile string
  34. Region string
  35. AuthType string
  36. AssumeRoleArn string
  37. Namespace string
  38. AccessKey string
  39. SecretKey string
  40. }
  41. func (req *cwRequest) GetDatasourceInfo() *DatasourceInfo {
  42. authType := req.DataSource.JsonData.Get("authType").MustString()
  43. assumeRoleArn := req.DataSource.JsonData.Get("assumeRoleArn").MustString()
  44. accessKey := ""
  45. secretKey := ""
  46. for key, value := range req.DataSource.SecureJsonData.Decrypt() {
  47. if key == "accessKey" {
  48. accessKey = value
  49. }
  50. if key == "secretKey" {
  51. secretKey = value
  52. }
  53. }
  54. return &DatasourceInfo{
  55. AuthType: authType,
  56. AssumeRoleArn: assumeRoleArn,
  57. Region: req.Region,
  58. Profile: req.DataSource.Database,
  59. AccessKey: accessKey,
  60. SecretKey: secretKey,
  61. }
  62. }
  63. func init() {
  64. actionHandlers = map[string]actionHandler{
  65. "ListMetrics": handleListMetrics,
  66. "DescribeAlarms": handleDescribeAlarms,
  67. "DescribeAlarmsForMetric": handleDescribeAlarmsForMetric,
  68. "DescribeAlarmHistory": handleDescribeAlarmHistory,
  69. }
  70. }
  71. type cache struct {
  72. credential *credentials.Credentials
  73. expiration *time.Time
  74. }
  75. var awsCredentialCache map[string]cache = make(map[string]cache)
  76. var credentialCacheLock sync.RWMutex
  77. func GetCredentials(dsInfo *DatasourceInfo) (*credentials.Credentials, error) {
  78. cacheKey := dsInfo.AccessKey + ":" + dsInfo.Profile + ":" + dsInfo.AssumeRoleArn
  79. credentialCacheLock.RLock()
  80. if _, ok := awsCredentialCache[cacheKey]; ok {
  81. if awsCredentialCache[cacheKey].expiration != nil &&
  82. (*awsCredentialCache[cacheKey].expiration).After(time.Now().UTC()) {
  83. result := awsCredentialCache[cacheKey].credential
  84. credentialCacheLock.RUnlock()
  85. return result, nil
  86. }
  87. }
  88. credentialCacheLock.RUnlock()
  89. accessKeyId := ""
  90. secretAccessKey := ""
  91. sessionToken := ""
  92. var expiration *time.Time
  93. expiration = nil
  94. if dsInfo.AuthType == "arn" && strings.Index(dsInfo.AssumeRoleArn, "arn:aws:iam:") == 0 {
  95. params := &sts.AssumeRoleInput{
  96. RoleArn: aws.String(dsInfo.AssumeRoleArn),
  97. RoleSessionName: aws.String("GrafanaSession"),
  98. DurationSeconds: aws.Int64(900),
  99. }
  100. stsSess, err := session.NewSession()
  101. if err != nil {
  102. return nil, err
  103. }
  104. stsCreds := credentials.NewChainCredentials(
  105. []credentials.Provider{
  106. &credentials.EnvProvider{},
  107. &credentials.SharedCredentialsProvider{Filename: "", Profile: dsInfo.Profile},
  108. remoteCredProvider(stsSess),
  109. })
  110. stsConfig := &aws.Config{
  111. Region: aws.String(dsInfo.Region),
  112. Credentials: stsCreds,
  113. }
  114. sess, err := session.NewSession(stsConfig)
  115. if err != nil {
  116. return nil, err
  117. }
  118. svc := sts.New(sess, stsConfig)
  119. resp, err := svc.AssumeRole(params)
  120. if err != nil {
  121. return nil, err
  122. }
  123. if resp.Credentials != nil {
  124. accessKeyId = *resp.Credentials.AccessKeyId
  125. secretAccessKey = *resp.Credentials.SecretAccessKey
  126. sessionToken = *resp.Credentials.SessionToken
  127. expiration = resp.Credentials.Expiration
  128. }
  129. } else {
  130. now := time.Now()
  131. e := now.Add(5 * time.Minute)
  132. expiration = &e
  133. }
  134. sess, err := session.NewSession()
  135. if err != nil {
  136. return nil, err
  137. }
  138. creds := credentials.NewChainCredentials(
  139. []credentials.Provider{
  140. &credentials.StaticProvider{Value: credentials.Value{
  141. AccessKeyID: accessKeyId,
  142. SecretAccessKey: secretAccessKey,
  143. SessionToken: sessionToken,
  144. }},
  145. &credentials.EnvProvider{},
  146. &credentials.StaticProvider{Value: credentials.Value{
  147. AccessKeyID: dsInfo.AccessKey,
  148. SecretAccessKey: dsInfo.SecretKey,
  149. }},
  150. &credentials.SharedCredentialsProvider{Filename: "", Profile: dsInfo.Profile},
  151. remoteCredProvider(sess),
  152. })
  153. credentialCacheLock.Lock()
  154. awsCredentialCache[cacheKey] = cache{
  155. credential: creds,
  156. expiration: expiration,
  157. }
  158. credentialCacheLock.Unlock()
  159. return creds, nil
  160. }
  161. func remoteCredProvider(sess *session.Session) credentials.Provider {
  162. ecsCredURI := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
  163. if len(ecsCredURI) > 0 {
  164. return ecsCredProvider(sess, ecsCredURI)
  165. }
  166. return ec2RoleProvider(sess)
  167. }
  168. func ecsCredProvider(sess *session.Session, uri string) credentials.Provider {
  169. const host = `169.254.170.2`
  170. c := ec2metadata.New(sess)
  171. return endpointcreds.NewProviderClient(
  172. c.Client.Config,
  173. c.Client.Handlers,
  174. fmt.Sprintf("http://%s%s", host, uri),
  175. func(p *endpointcreds.Provider) { p.ExpiryWindow = 5 * time.Minute })
  176. }
  177. func ec2RoleProvider(sess *session.Session) credentials.Provider {
  178. return &ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute}
  179. }
  180. func getAwsConfig(req *cwRequest) (*aws.Config, error) {
  181. creds, err := GetCredentials(req.GetDatasourceInfo())
  182. if err != nil {
  183. return nil, err
  184. }
  185. cfg := &aws.Config{
  186. Region: aws.String(req.Region),
  187. Credentials: creds,
  188. }
  189. return cfg, nil
  190. }
  191. func handleListMetrics(req *cwRequest, c *middleware.Context) {
  192. cfg, err := getAwsConfig(req)
  193. if err != nil {
  194. c.JsonApiErr(500, "Unable to call AWS API", err)
  195. return
  196. }
  197. sess, err := session.NewSession(cfg)
  198. if err != nil {
  199. c.JsonApiErr(500, "Unable to call AWS API", err)
  200. return
  201. }
  202. svc := cloudwatch.New(sess, cfg)
  203. reqParam := &struct {
  204. Parameters struct {
  205. Namespace string `json:"namespace"`
  206. MetricName string `json:"metricName"`
  207. Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"`
  208. } `json:"parameters"`
  209. }{}
  210. json.Unmarshal(req.Body, reqParam)
  211. params := &cloudwatch.ListMetricsInput{
  212. Namespace: aws.String(reqParam.Parameters.Namespace),
  213. MetricName: aws.String(reqParam.Parameters.MetricName),
  214. Dimensions: reqParam.Parameters.Dimensions,
  215. }
  216. var resp cloudwatch.ListMetricsOutput
  217. err = svc.ListMetricsPages(params,
  218. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  219. metrics.M_Aws_CloudWatch_ListMetrics.Inc()
  220. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  221. for _, metric := range metrics {
  222. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  223. }
  224. return !lastPage
  225. })
  226. if err != nil {
  227. c.JsonApiErr(500, "Unable to call AWS API", err)
  228. return
  229. }
  230. c.JSON(200, resp)
  231. }
  232. func handleDescribeAlarms(req *cwRequest, c *middleware.Context) {
  233. cfg, err := getAwsConfig(req)
  234. if err != nil {
  235. c.JsonApiErr(500, "Unable to call AWS API", err)
  236. return
  237. }
  238. sess, err := session.NewSession(cfg)
  239. if err != nil {
  240. c.JsonApiErr(500, "Unable to call AWS API", err)
  241. return
  242. }
  243. svc := cloudwatch.New(sess, cfg)
  244. reqParam := &struct {
  245. Parameters struct {
  246. ActionPrefix string `json:"actionPrefix"`
  247. AlarmNamePrefix string `json:"alarmNamePrefix"`
  248. AlarmNames []*string `json:"alarmNames"`
  249. StateValue string `json:"stateValue"`
  250. } `json:"parameters"`
  251. }{}
  252. json.Unmarshal(req.Body, reqParam)
  253. params := &cloudwatch.DescribeAlarmsInput{
  254. MaxRecords: aws.Int64(100),
  255. }
  256. if reqParam.Parameters.ActionPrefix != "" {
  257. params.ActionPrefix = aws.String(reqParam.Parameters.ActionPrefix)
  258. }
  259. if reqParam.Parameters.AlarmNamePrefix != "" {
  260. params.AlarmNamePrefix = aws.String(reqParam.Parameters.AlarmNamePrefix)
  261. }
  262. if len(reqParam.Parameters.AlarmNames) != 0 {
  263. params.AlarmNames = reqParam.Parameters.AlarmNames
  264. }
  265. if reqParam.Parameters.StateValue != "" {
  266. params.StateValue = aws.String(reqParam.Parameters.StateValue)
  267. }
  268. resp, err := svc.DescribeAlarms(params)
  269. if err != nil {
  270. c.JsonApiErr(500, "Unable to call AWS API", err)
  271. return
  272. }
  273. c.JSON(200, resp)
  274. }
  275. func handleDescribeAlarmsForMetric(req *cwRequest, c *middleware.Context) {
  276. cfg, err := getAwsConfig(req)
  277. if err != nil {
  278. c.JsonApiErr(500, "Unable to call AWS API", err)
  279. return
  280. }
  281. sess, err := session.NewSession(cfg)
  282. if err != nil {
  283. c.JsonApiErr(500, "Unable to call AWS API", err)
  284. return
  285. }
  286. svc := cloudwatch.New(sess, cfg)
  287. reqParam := &struct {
  288. Parameters struct {
  289. Namespace string `json:"namespace"`
  290. MetricName string `json:"metricName"`
  291. Dimensions []*cloudwatch.Dimension `json:"dimensions"`
  292. Statistic string `json:"statistic"`
  293. ExtendedStatistic string `json:"extendedStatistic"`
  294. Period int64 `json:"period"`
  295. } `json:"parameters"`
  296. }{}
  297. json.Unmarshal(req.Body, reqParam)
  298. params := &cloudwatch.DescribeAlarmsForMetricInput{
  299. Namespace: aws.String(reqParam.Parameters.Namespace),
  300. MetricName: aws.String(reqParam.Parameters.MetricName),
  301. Period: aws.Int64(reqParam.Parameters.Period),
  302. }
  303. if len(reqParam.Parameters.Dimensions) != 0 {
  304. params.Dimensions = reqParam.Parameters.Dimensions
  305. }
  306. if reqParam.Parameters.Statistic != "" {
  307. params.Statistic = aws.String(reqParam.Parameters.Statistic)
  308. }
  309. if reqParam.Parameters.ExtendedStatistic != "" {
  310. params.ExtendedStatistic = aws.String(reqParam.Parameters.ExtendedStatistic)
  311. }
  312. resp, err := svc.DescribeAlarmsForMetric(params)
  313. if err != nil {
  314. c.JsonApiErr(500, "Unable to call AWS API", err)
  315. return
  316. }
  317. c.JSON(200, resp)
  318. }
  319. func handleDescribeAlarmHistory(req *cwRequest, c *middleware.Context) {
  320. cfg, err := getAwsConfig(req)
  321. if err != nil {
  322. c.JsonApiErr(500, "Unable to call AWS API", err)
  323. return
  324. }
  325. sess, err := session.NewSession(cfg)
  326. if err != nil {
  327. c.JsonApiErr(500, "Unable to call AWS API", err)
  328. return
  329. }
  330. svc := cloudwatch.New(sess, cfg)
  331. reqParam := &struct {
  332. Parameters struct {
  333. AlarmName string `json:"alarmName"`
  334. HistoryItemType string `json:"historyItemType"`
  335. StartDate int64 `json:"startDate"`
  336. EndDate int64 `json:"endDate"`
  337. } `json:"parameters"`
  338. }{}
  339. json.Unmarshal(req.Body, reqParam)
  340. params := &cloudwatch.DescribeAlarmHistoryInput{
  341. AlarmName: aws.String(reqParam.Parameters.AlarmName),
  342. StartDate: aws.Time(time.Unix(reqParam.Parameters.StartDate, 0)),
  343. EndDate: aws.Time(time.Unix(reqParam.Parameters.EndDate, 0)),
  344. }
  345. if reqParam.Parameters.HistoryItemType != "" {
  346. params.HistoryItemType = aws.String(reqParam.Parameters.HistoryItemType)
  347. }
  348. resp, err := svc.DescribeAlarmHistory(params)
  349. if err != nil {
  350. c.JsonApiErr(500, "Unable to call AWS API", err)
  351. return
  352. }
  353. c.JSON(200, resp)
  354. }
  355. func HandleRequest(c *middleware.Context, ds *m.DataSource) {
  356. var req cwRequest
  357. req.Body, _ = ioutil.ReadAll(c.Req.Request.Body)
  358. req.DataSource = ds
  359. json.Unmarshal(req.Body, &req)
  360. if handler, found := actionHandlers[req.Action]; !found {
  361. c.JsonApiErr(500, "Unexpected AWS Action", errors.New(req.Action))
  362. return
  363. } else {
  364. handler(&req, c)
  365. }
  366. }