metrics.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package cloudwatch
  2. import (
  3. "encoding/json"
  4. "sort"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/aws/aws-sdk-go/aws"
  9. "github.com/aws/aws-sdk-go/aws/awsutil"
  10. "github.com/aws/aws-sdk-go/aws/session"
  11. "github.com/aws/aws-sdk-go/service/cloudwatch"
  12. "github.com/grafana/grafana/pkg/middleware"
  13. "github.com/grafana/grafana/pkg/util"
  14. )
  15. var metricsMap map[string][]string
  16. var dimensionsMap map[string][]string
  17. type CustomMetricsCache struct {
  18. Expire time.Time
  19. Cache []string
  20. }
  21. var customMetricsMetricsMap map[string]map[string]map[string]*CustomMetricsCache
  22. var customMetricsDimensionsMap map[string]map[string]map[string]*CustomMetricsCache
  23. func init() {
  24. metricsMap = map[string][]string{
  25. "AWS/ApiGateway": {"4XXError", "5XXError", "CacheHitCount", "CacheMissCount", "Count", "IntegrationLatency", "Latency"},
  26. "AWS/ApplicationELB": {"ActiveConnectionCount", "ClientTLSNegotiationErrorCount", "HealthyHostCount", "HTTPCode_ELB_4XX_Count", "HTTPCode_ELB_5XX_Count", "HTTPCode_Target_2XX_Count", "HTTPCode_Target_3XX_Count", "HTTPCode_Target_4XX_Count", "HTTPCode_Target_5XX_Count", "NewConnectionCount", "ProcessedBytes", "RejectedConnectionCount", "RequestCount", "TargetConnectionErrorCount", "TargetResponseTime", "TargetTLSNegotiationErrorCount", "UnhealthyHostCount"},
  27. "AWS/AutoScaling": {"GroupMinSize", "GroupMaxSize", "GroupDesiredCapacity", "GroupInServiceInstances", "GroupPendingInstances", "GroupStandbyInstances", "GroupTerminatingInstances", "GroupTotalInstances"},
  28. "AWS/Billing": {"EstimatedCharges"},
  29. "AWS/CloudFront": {"Requests", "BytesDownloaded", "BytesUploaded", "TotalErrorRate", "4xxErrorRate", "5xxErrorRate"},
  30. "AWS/CloudSearch": {"SuccessfulRequests", "SearchableDocuments", "IndexUtilization", "Partitions"},
  31. "AWS/DynamoDB": {"ConditionalCheckFailedRequests", "ConsumedReadCapacityUnits", "ConsumedWriteCapacityUnits", "OnlineIndexConsumedWriteCapacity", "OnlineIndexPercentageProgress", "OnlineIndexThrottleEvents", "ProvisionedReadCapacityUnits", "ProvisionedWriteCapacityUnits", "ReadThrottleEvents", "ReturnedBytes", "ReturnedItemCount", "ReturnedRecordsCount", "SuccessfulRequestLatency", "SystemErrors", "ThrottledRequests", "UserErrors", "WriteThrottleEvents"},
  32. "AWS/EBS": {"VolumeReadBytes", "VolumeWriteBytes", "VolumeReadOps", "VolumeWriteOps", "VolumeTotalReadTime", "VolumeTotalWriteTime", "VolumeIdleTime", "VolumeQueueLength", "VolumeThroughputPercentage", "VolumeConsumedReadWriteOps", "BurstBalance"},
  33. "AWS/EC2": {"CPUCreditUsage", "CPUCreditBalance", "CPUUtilization", "DiskReadOps", "DiskWriteOps", "DiskReadBytes", "DiskWriteBytes", "NetworkIn", "NetworkOut", "NetworkPacketsIn", "NetworkPacketsOut", "StatusCheckFailed", "StatusCheckFailed_Instance", "StatusCheckFailed_System"},
  34. "AWS/EC2Spot": {"AvailableInstancePoolsCount", "BidsSubmittedForCapacity", "EligibleInstancePoolCount", "FulfilledCapacity", "MaxPercentCapacityAllocation", "PendingCapacity", "PercentCapacityAllocation", "TargetCapacity", "TerminatingCapacity"},
  35. "AWS/ECS": {"CPUReservation", "MemoryReservation", "CPUUtilization", "MemoryUtilization"},
  36. "AWS/EFS": {"BurstCreditBalance", "ClientConnections", "DataReadIOBytes", "DataWriteIOBytes", "MetadataIOBytes", "TotalIOBytes", "PermittedThroughput", "PercentIOLimit"},
  37. "AWS/ELB": {"HealthyHostCount", "UnHealthyHostCount", "RequestCount", "Latency", "HTTPCode_ELB_4XX", "HTTPCode_ELB_5XX", "HTTPCode_Backend_2XX", "HTTPCode_Backend_3XX", "HTTPCode_Backend_4XX", "HTTPCode_Backend_5XX", "BackendConnectionErrors", "SurgeQueueLength", "SpilloverCount"},
  38. "AWS/ElastiCache": {
  39. "CPUUtilization", "FreeableMemory", "NetworkBytesIn", "NetworkBytesOut", "SwapUsage",
  40. "BytesUsedForCacheItems", "BytesReadIntoMemcached", "BytesWrittenOutFromMemcached", "CasBadval", "CasHits", "CasMisses", "CmdFlush", "CmdGet", "CmdSet", "CurrConnections", "CurrItems", "DecrHits", "DecrMisses", "DeleteHits", "DeleteMisses", "Evictions", "GetHits", "GetMisses", "IncrHits", "IncrMisses", "Reclaimed",
  41. "BytesUsedForHash", "CmdConfigGet", "CmdConfigSet", "CmdTouch", "CurrConfig", "EvictedUnfetched", "ExpiredUnfetched", "SlabsMoved", "TouchHits", "TouchMisses",
  42. "NewConnections", "NewItems", "UnusedMemory",
  43. "BytesUsedForCache", "CacheHits", "CacheMisses", "CurrConnections", "Evictions", "HyperLogLogBasedCmds", "NewConnections", "Reclaimed", "ReplicationBytes", "ReplicationLag", "SaveInProgress",
  44. "CurrItems", "GetTypeCmds", "HashBasedCmds", "KeyBasedCmds", "ListBasedCmds", "SetBasedCmds", "SetTypeCmds", "SortedSetBasedCmds", "StringBasedCmds",
  45. },
  46. "AWS/ElasticBeanstalk": {
  47. "EnvironmentHealth",
  48. "ApplicationLatencyP10", "ApplicationLatencyP50", "ApplicationLatencyP75", "ApplicationLatencyP85", "ApplicationLatencyP90", "ApplicationLatencyP95", "ApplicationLatencyP99", "ApplicationLatencyP99.9",
  49. "ApplicationRequests2xx", "ApplicationRequests3xx", "ApplicationRequests4xx", "ApplicationRequests5xx", "ApplicationRequestsTotal",
  50. "CPUIdle", "CPUIowait", "CPUIrq", "CPUNice", "CPUSoftirq", "CPUSystem", "CPUUser",
  51. "InstanceHealth", "InstancesDegraded", "InstancesInfo", "InstancesNoData", "InstancesOk", "InstancesPending", "InstancesSevere", "InstancesUnknown", "InstancesWarning",
  52. "LoadAverage1min", "LoadAverage5min",
  53. "RootFilesystemUtil",
  54. },
  55. "AWS/ElasticMapReduce": {"IsIdle", "JobsRunning", "JobsFailed",
  56. "MapTasksRunning", "MapTasksRemaining", "MapSlotsOpen", "RemainingMapTasksPerSlot", "ReduceTasksRunning", "ReduceTasksRemaining", "ReduceSlotsOpen",
  57. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "TaskNodesRunning", "TaskNodesPending", "LiveTaskTrackers",
  58. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "TotalLoad",
  59. "BackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup",
  60. "IsIdle", "ContainerAllocated", "ContainerReserved", "ContainerPending", "AppsCompleted", "AppsFailed", "AppsKilled", "AppsPending", "AppsRunning", "AppsSubmitted",
  61. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "MRTotalNodes", "MRActiveNodes", "MRLostNodes", "MRUnhealthyNodes", "MRDecommissionedNodes", "MRRebootedNodes",
  62. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "CorruptBlocks", "TotalLoad", "MemoryTotalMB", "MemoryReservedMB", "MemoryAvailableMB", "MemoryAllocatedMB", "PendingDeletionBlocks", "UnderReplicatedBlocks", "DfsPendingReplicationBlocks", "CapacityRemainingGB",
  63. "HbaseBackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup"},
  64. "AWS/ES": {"ClusterStatus.green", "ClusterStatus.yellow", "ClusterStatus.red", "Nodes", "SearchableDocuments", "DeletedDocuments", "CPUUtilization", "FreeStorageSpace", "JVMMemoryPressure", "AutomatedSnapshotFailure", "MasterCPUUtilization", "MasterFreeStorageSpace", "MasterJVMMemoryPressure", "ReadLatency", "WriteLatency", "ReadThroughput", "WriteThroughput", "DiskQueueLength", "ReadIOPS", "WriteIOPS"},
  65. "AWS/Events": {"Invocations", "FailedInvocations", "TriggeredRules", "MatchedEvents", "ThrottledRules"},
  66. "AWS/Kinesis": {"GetRecords.Bytes", "GetRecords.IteratorAge", "GetRecords.IteratorAgeMilliseconds", "GetRecords.Latency", "GetRecords.Records", "GetRecords.Success", "IncomingBytes", "IncomingRecords", "PutRecord.Bytes", "PutRecord.Latency", "PutRecord.Success", "PutRecords.Bytes", "PutRecords.Latency", "PutRecords.Records", "PutRecords.Success", "ReadProvisionedThroughputExceeded", "WriteProvisionedThroughputExceeded", "IteratorAgeMilliseconds", "OutgoingBytes", "OutgoingRecords"},
  67. "AWS/Lambda": {"Invocations", "Errors", "Duration", "Throttles"},
  68. "AWS/Logs": {"IncomingBytes", "IncomingLogEvents", "ForwardedBytes", "ForwardedLogEvents", "DeliveryErrors", "DeliveryThrottling"},
  69. "AWS/ML": {"PredictCount", "PredictFailureCount"},
  70. "AWS/OpsWorks": {"cpu_idle", "cpu_nice", "cpu_system", "cpu_user", "cpu_waitio", "load_1", "load_5", "load_15", "memory_buffers", "memory_cached", "memory_free", "memory_swap", "memory_total", "memory_used", "procs"},
  71. "AWS/Redshift": {"CPUUtilization", "DatabaseConnections", "HealthStatus", "MaintenanceMode", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "PercentageDiskSpaceUsed", "ReadIOPS", "ReadLatency", "ReadThroughput", "WriteIOPS", "WriteLatency", "WriteThroughput"},
  72. "AWS/RDS": {"BinLogDiskUsage", "CPUUtilization", "CPUCreditUsage", "CPUCreditBalance", "DatabaseConnections", "DiskQueueDepth", "FreeableMemory", "FreeStorageSpace", "ReplicaLag", "SwapUsage", "ReadIOPS", "WriteIOPS", "ReadLatency", "WriteLatency", "ReadThroughput", "WriteThroughput", "NetworkReceiveThroughput", "NetworkTransmitThroughput"},
  73. "AWS/Route53": {"HealthCheckStatus", "HealthCheckPercentageHealthy", "ConnectionTime", "SSLHandshakeTime", "TimeToFirstByte"},
  74. "AWS/S3": {"BucketSizeBytes", "NumberOfObjects"},
  75. "AWS/SNS": {"NumberOfMessagesPublished", "PublishSize", "NumberOfNotificationsDelivered", "NumberOfNotificationsFailed"},
  76. "AWS/SQS": {"NumberOfMessagesSent", "SentMessageSize", "NumberOfMessagesReceived", "NumberOfEmptyReceives", "NumberOfMessagesDeleted", "ApproximateNumberOfMessagesDelayed", "ApproximateNumberOfMessagesVisible", "ApproximateNumberOfMessagesNotVisible"},
  77. "AWS/StorageGateway": {"CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "CloudBytesDownloaded", "CloudDownloadLatency", "CloudBytesUploaded", "UploadBufferFree", "UploadBufferPercentUsed", "UploadBufferUsed", "QueuedWrites", "ReadBytes", "ReadTime", "TotalCacheSize", "WriteBytes", "WriteTime", "TimeSinceLastRecoveryPoint", "WorkingStorageFree", "WorkingStoragePercentUsed", "WorkingStorageUsed",
  78. "CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "ReadBytes", "ReadTime", "WriteBytes", "WriteTime", "QueuedWrites"},
  79. "AWS/SWF": {"DecisionTaskScheduleToStartTime", "DecisionTaskStartToCloseTime", "DecisionTasksCompleted", "StartedDecisionTasksTimedOutOnClose", "WorkflowStartToCloseTime", "WorkflowsCanceled", "WorkflowsCompleted", "WorkflowsContinuedAsNew", "WorkflowsFailed", "WorkflowsTerminated", "WorkflowsTimedOut",
  80. "ActivityTaskScheduleToCloseTime", "ActivityTaskScheduleToStartTime", "ActivityTaskStartToCloseTime", "ActivityTasksCanceled", "ActivityTasksCompleted", "ActivityTasksFailed", "ScheduledActivityTasksTimedOutOnClose", "ScheduledActivityTasksTimedOutOnStart", "StartedActivityTasksTimedOutOnClose", "StartedActivityTasksTimedOutOnHeartbeat"},
  81. "AWS/WAF": {"AllowedRequests", "BlockedRequests", "CountedRequests"},
  82. "AWS/WorkSpaces": {"Available", "Unhealthy", "ConnectionAttempt", "ConnectionSuccess", "ConnectionFailure", "SessionLaunchTime", "InSessionLatency", "SessionDisconnect"},
  83. }
  84. dimensionsMap = map[string][]string{
  85. "AWS/ApiGateway": {"ApiName", "Method", "Resource", "Stage"},
  86. "AWS/ApplicationELB": {"LoadBalancer", "TargetGroup", "AvailabilityZone"},
  87. "AWS/AutoScaling": {"AutoScalingGroupName"},
  88. "AWS/Billing": {"ServiceName", "LinkedAccount", "Currency"},
  89. "AWS/CloudFront": {"DistributionId", "Region"},
  90. "AWS/CloudSearch": {},
  91. "AWS/DynamoDB": {"TableName", "GlobalSecondaryIndexName", "Operation", "StreamLabel"},
  92. "AWS/EBS": {"VolumeId"},
  93. "AWS/EC2": {"AutoScalingGroupName", "ImageId", "InstanceId", "InstanceType"},
  94. "AWS/EC2Spot": {"AvailabilityZone", "FleetRequestId", "InstanceType"},
  95. "AWS/ECS": {"ClusterName", "ServiceName"},
  96. "AWS/EFS": {"FileSystemId"},
  97. "AWS/ELB": {"LoadBalancerName", "AvailabilityZone"},
  98. "AWS/ElastiCache": {"CacheClusterId", "CacheNodeId"},
  99. "AWS/ElasticBeanstalk": {"EnvironmentName", "InstanceId"},
  100. "AWS/ElasticMapReduce": {"ClusterId", "JobFlowId", "JobId"},
  101. "AWS/ES": {"ClientId", "DomainName"},
  102. "AWS/Events": {"RuleName"},
  103. "AWS/Kinesis": {"StreamName", "ShardID"},
  104. "AWS/Lambda": {"FunctionName", "Resource", "Version", "Alias"},
  105. "AWS/Logs": {"LogGroupName", "DestinationType", "FilterName"},
  106. "AWS/ML": {"MLModelId", "RequestMode"},
  107. "AWS/OpsWorks": {"StackId", "LayerId", "InstanceId"},
  108. "AWS/Redshift": {"NodeID", "ClusterIdentifier"},
  109. "AWS/RDS": {"DBInstanceIdentifier", "DBClusterIdentifier", "DatabaseClass", "EngineName"},
  110. "AWS/Route53": {"HealthCheckId"},
  111. "AWS/S3": {"BucketName", "StorageType"},
  112. "AWS/SNS": {"Application", "Platform", "TopicName"},
  113. "AWS/SQS": {"QueueName"},
  114. "AWS/StorageGateway": {"GatewayId", "GatewayName", "VolumeId"},
  115. "AWS/SWF": {"Domain", "WorkflowTypeName", "WorkflowTypeVersion", "ActivityTypeName", "ActivityTypeVersion"},
  116. "AWS/WAF": {"Rule", "WebACL"},
  117. "AWS/WorkSpaces": {"DirectoryId", "WorkspaceId"},
  118. }
  119. customMetricsMetricsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  120. customMetricsDimensionsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  121. }
  122. // Whenever this list is updated, frontend list should also be updated.
  123. // Please update the region list in public/app/plugins/datasource/cloudwatch/partials/config.html
  124. func handleGetRegions(req *cwRequest, c *middleware.Context) {
  125. regions := []string{
  126. "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "cn-north-1",
  127. "eu-central-1", "eu-west-1", "sa-east-1", "us-east-1", "us-west-1", "us-west-2",
  128. }
  129. result := []interface{}{}
  130. for _, region := range regions {
  131. result = append(result, util.DynMap{"text": region, "value": region})
  132. }
  133. c.JSON(200, result)
  134. }
  135. func handleGetNamespaces(req *cwRequest, c *middleware.Context) {
  136. keys := []string{}
  137. for key := range metricsMap {
  138. keys = append(keys, key)
  139. }
  140. customNamespaces := req.DataSource.JsonData.Get("customMetricsNamespaces").MustString()
  141. if customNamespaces != "" {
  142. for _, key := range strings.Split(customNamespaces, ",") {
  143. keys = append(keys, key)
  144. }
  145. }
  146. sort.Sort(sort.StringSlice(keys))
  147. result := []interface{}{}
  148. for _, key := range keys {
  149. result = append(result, util.DynMap{"text": key, "value": key})
  150. }
  151. c.JSON(200, result)
  152. }
  153. func handleGetMetrics(req *cwRequest, c *middleware.Context) {
  154. reqParam := &struct {
  155. Parameters struct {
  156. Namespace string `json:"namespace"`
  157. } `json:"parameters"`
  158. }{}
  159. json.Unmarshal(req.Body, reqParam)
  160. var namespaceMetrics []string
  161. if !isCustomMetrics(reqParam.Parameters.Namespace) {
  162. var exists bool
  163. if namespaceMetrics, exists = metricsMap[reqParam.Parameters.Namespace]; !exists {
  164. c.JsonApiErr(404, "Unable to find namespace "+reqParam.Parameters.Namespace, nil)
  165. return
  166. }
  167. } else {
  168. var err error
  169. assumeRoleArn := req.DataSource.JsonData.Get("assumeRoleArn").MustString()
  170. if namespaceMetrics, err = getMetricsForCustomMetrics(req.Region, reqParam.Parameters.Namespace, req.DataSource.Database, assumeRoleArn, getAllMetrics); err != nil {
  171. c.JsonApiErr(500, "Unable to call AWS API", err)
  172. return
  173. }
  174. }
  175. sort.Sort(sort.StringSlice(namespaceMetrics))
  176. result := []interface{}{}
  177. for _, name := range namespaceMetrics {
  178. result = append(result, util.DynMap{"text": name, "value": name})
  179. }
  180. c.JSON(200, result)
  181. }
  182. func handleGetDimensions(req *cwRequest, c *middleware.Context) {
  183. reqParam := &struct {
  184. Parameters struct {
  185. Namespace string `json:"namespace"`
  186. } `json:"parameters"`
  187. }{}
  188. json.Unmarshal(req.Body, reqParam)
  189. var dimensionValues []string
  190. if !isCustomMetrics(reqParam.Parameters.Namespace) {
  191. var exists bool
  192. if dimensionValues, exists = dimensionsMap[reqParam.Parameters.Namespace]; !exists {
  193. c.JsonApiErr(404, "Unable to find dimension "+reqParam.Parameters.Namespace, nil)
  194. return
  195. }
  196. } else {
  197. var err error
  198. assumeRoleArn := req.DataSource.JsonData.Get("assumeRoleArn").MustString()
  199. if dimensionValues, err = getDimensionsForCustomMetrics(req.Region, reqParam.Parameters.Namespace, req.DataSource.Database, assumeRoleArn, getAllMetrics); err != nil {
  200. c.JsonApiErr(500, "Unable to call AWS API", err)
  201. return
  202. }
  203. }
  204. sort.Sort(sort.StringSlice(dimensionValues))
  205. result := []interface{}{}
  206. for _, name := range dimensionValues {
  207. result = append(result, util.DynMap{"text": name, "value": name})
  208. }
  209. c.JSON(200, result)
  210. }
  211. func getAllMetrics(region string, namespace string, database string, assumeRoleArn string) (cloudwatch.ListMetricsOutput, error) {
  212. cfg := &aws.Config{
  213. Region: aws.String(region),
  214. Credentials: getCredentials(database, region, assumeRoleArn),
  215. }
  216. svc := cloudwatch.New(session.New(cfg), cfg)
  217. params := &cloudwatch.ListMetricsInput{
  218. Namespace: aws.String(namespace),
  219. }
  220. var resp cloudwatch.ListMetricsOutput
  221. err := svc.ListMetricsPages(params,
  222. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  223. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  224. for _, metric := range metrics {
  225. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  226. }
  227. return !lastPage
  228. })
  229. if err != nil {
  230. return resp, err
  231. }
  232. return resp, nil
  233. }
  234. var metricsCacheLock sync.Mutex
  235. func getMetricsForCustomMetrics(region string, namespace string, database string, assumeRoleArn string, getAllMetrics func(string, string, string, string) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  236. result, err := getAllMetrics(region, namespace, database, assumeRoleArn)
  237. if err != nil {
  238. return []string{}, err
  239. }
  240. metricsCacheLock.Lock()
  241. defer metricsCacheLock.Unlock()
  242. if _, ok := customMetricsMetricsMap[database]; !ok {
  243. customMetricsMetricsMap[database] = make(map[string]map[string]*CustomMetricsCache)
  244. }
  245. if _, ok := customMetricsMetricsMap[database][region]; !ok {
  246. customMetricsMetricsMap[database][region] = make(map[string]*CustomMetricsCache)
  247. }
  248. if _, ok := customMetricsMetricsMap[database][region][namespace]; !ok {
  249. customMetricsMetricsMap[database][region][namespace] = &CustomMetricsCache{}
  250. customMetricsMetricsMap[database][region][namespace].Cache = make([]string, 0)
  251. }
  252. if customMetricsMetricsMap[database][region][namespace].Expire.After(time.Now()) {
  253. return customMetricsMetricsMap[database][region][namespace].Cache, nil
  254. }
  255. customMetricsMetricsMap[database][region][namespace].Cache = make([]string, 0)
  256. customMetricsMetricsMap[database][region][namespace].Expire = time.Now().Add(5 * time.Minute)
  257. for _, metric := range result.Metrics {
  258. if isDuplicate(customMetricsMetricsMap[database][region][namespace].Cache, *metric.MetricName) {
  259. continue
  260. }
  261. customMetricsMetricsMap[database][region][namespace].Cache = append(customMetricsMetricsMap[database][region][namespace].Cache, *metric.MetricName)
  262. }
  263. return customMetricsMetricsMap[database][region][namespace].Cache, nil
  264. }
  265. var dimensionsCacheLock sync.Mutex
  266. func getDimensionsForCustomMetrics(region string, namespace string, database string, assumeRoleArn string, getAllMetrics func(string, string, string, string) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  267. result, err := getAllMetrics(region, namespace, database, assumeRoleArn)
  268. if err != nil {
  269. return []string{}, err
  270. }
  271. dimensionsCacheLock.Lock()
  272. defer dimensionsCacheLock.Unlock()
  273. if _, ok := customMetricsDimensionsMap[database]; !ok {
  274. customMetricsDimensionsMap[database] = make(map[string]map[string]*CustomMetricsCache)
  275. }
  276. if _, ok := customMetricsDimensionsMap[database][region]; !ok {
  277. customMetricsDimensionsMap[database][region] = make(map[string]*CustomMetricsCache)
  278. }
  279. if _, ok := customMetricsDimensionsMap[database][region][namespace]; !ok {
  280. customMetricsDimensionsMap[database][region][namespace] = &CustomMetricsCache{}
  281. customMetricsDimensionsMap[database][region][namespace].Cache = make([]string, 0)
  282. }
  283. if customMetricsDimensionsMap[database][region][namespace].Expire.After(time.Now()) {
  284. return customMetricsDimensionsMap[database][region][namespace].Cache, nil
  285. }
  286. customMetricsDimensionsMap[database][region][namespace].Cache = make([]string, 0)
  287. customMetricsDimensionsMap[database][region][namespace].Expire = time.Now().Add(5 * time.Minute)
  288. for _, metric := range result.Metrics {
  289. for _, dimension := range metric.Dimensions {
  290. if isDuplicate(customMetricsDimensionsMap[database][region][namespace].Cache, *dimension.Name) {
  291. continue
  292. }
  293. customMetricsDimensionsMap[database][region][namespace].Cache = append(customMetricsDimensionsMap[database][region][namespace].Cache, *dimension.Name)
  294. }
  295. }
  296. return customMetricsDimensionsMap[database][region][namespace].Cache, nil
  297. }
  298. func isDuplicate(nameList []string, target string) bool {
  299. for _, name := range nameList {
  300. if name == target {
  301. return true
  302. }
  303. }
  304. return false
  305. }
  306. func isCustomMetrics(namespace string) bool {
  307. return strings.Index(namespace, "AWS/") != 0
  308. }