cloudwatch.go 9.8 KB

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