metrics.go 20 KB

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