metrics.go 20 KB

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