metric_find_query.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. package cloudwatch
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "sort"
  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/session"
  14. "github.com/aws/aws-sdk-go/service/cloudwatch"
  15. "github.com/aws/aws-sdk-go/service/ec2"
  16. "github.com/grafana/grafana/pkg/components/simplejson"
  17. "github.com/grafana/grafana/pkg/metrics"
  18. "github.com/grafana/grafana/pkg/tsdb"
  19. )
  20. var metricsMap map[string][]string
  21. var dimensionsMap map[string][]string
  22. type suggestData struct {
  23. Text string
  24. Value string
  25. }
  26. type CustomMetricsCache struct {
  27. Expire time.Time
  28. Cache []string
  29. }
  30. var customMetricsMetricsMap map[string]map[string]map[string]*CustomMetricsCache
  31. var customMetricsDimensionsMap map[string]map[string]map[string]*CustomMetricsCache
  32. var regionCache sync.Map
  33. func init() {
  34. metricsMap = map[string][]string{
  35. "AWS/AmazonMQ": {"CpuUtilization", "HeapUsage", "NetworkIn", "NetworkOut", "TotalMessageCount", "ConsumerCount", "EnqueueCount", "EnqueueTime", "ExpiredCount", "InflightCount", "DispatchCount", "DequeueCount", "MemoryUsage", "ProducerCount", "QueueSize"},
  36. "AWS/ApiGateway": {"4XXError", "5XXError", "CacheHitCount", "CacheMissCount", "Count", "IntegrationLatency", "Latency"},
  37. "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", "IPv6ProcessedBytes", "IPv6RequestCount", "NewConnectionCount", "ProcessedBytes", "RejectedConnectionCount", "RequestCount", "RequestCountPerTarget", "TargetConnectionErrorCount", "TargetResponseTime", "TargetTLSNegotiationErrorCount", "UnHealthyHostCount"},
  38. "AWS/AutoScaling": {"GroupMinSize", "GroupMaxSize", "GroupDesiredCapacity", "GroupInServiceInstances", "GroupPendingInstances", "GroupStandbyInstances", "GroupTerminatingInstances", "GroupTotalInstances"},
  39. "AWS/Billing": {"EstimatedCharges"},
  40. "AWS/CloudFront": {"Requests", "BytesDownloaded", "BytesUploaded", "TotalErrorRate", "4xxErrorRate", "5xxErrorRate"},
  41. "AWS/CloudSearch": {"SuccessfulRequests", "SearchableDocuments", "IndexUtilization", "Partitions"},
  42. "AWS/CloudHSM": {"HsmUnhealthy", "HsmTemperature", "HsmKeysSessionOccupied", "HsmKeysTokenOccupied", "HsmSslCtxsOccupied", "HsmSessionCount", "HsmUsersAvailable", "HsmUsersMax", "InterfaceEth2OctetsInput", "InterfaceEth2OctetsOutput"},
  43. "AWS/Connect": {"CallsBreachingConcurrencyQuota", "CallBackNotDialableNumber", "CallRecordingUploadError", "CallsPerInterval", "ConcurrentCalls", "ConcurrentCallsPercentage", "ContactFlowErrors", "ContactFlowFatalErrors", "LongestQueueWaitTime", "MissedCalls", "MisconfiguredPhoneNumbers", "PublicSigningKeyUsage", "QueueCapacityExceededError", "QueueSize", "ThrottledCalls", "ToInstancePacketLossRate"},
  44. "AWS/DMS": {"FreeableMemory", "WriteIOPS", "ReadIOPS", "WriteThroughput", "ReadThroughput", "WriteLatency", "ReadLatency", "SwapUsage", "NetworkTransmitThroughput", "NetworkReceiveThroughput", "FullLoadThroughputBandwidthSource", "FullLoadThroughputBandwidthTarget", "FullLoadThroughputRowsSource", "FullLoadThroughputRowsTarget", "CDCIncomingChanges", "CDCChangesMemorySource", "CDCChangesMemoryTarget", "CDCChangesDiskSource", "CDCChangesDiskTarget", "CDCThroughputBandwidthTarget", "CDCThroughputRowsSource", "CDCThroughputRowsTarget", "CDCLatencySource", "CDCLatencyTarget"},
  45. "AWS/DX": {"ConnectionState", "ConnectionBpsEgress", "ConnectionBpsIngress", "ConnectionPpsEgress", "ConnectionPpsIngress", "ConnectionCRCErrorCount", "ConnectionLightLevelTx", "ConnectionLightLevelRx"},
  46. "AWS/DynamoDB": {"ConditionalCheckFailedRequests", "ConsumedReadCapacityUnits", "ConsumedWriteCapacityUnits", "OnlineIndexConsumedWriteCapacity", "OnlineIndexPercentageProgress", "OnlineIndexThrottleEvents", "ProvisionedReadCapacityUnits", "ProvisionedWriteCapacityUnits", "ReadThrottleEvents", "ReturnedBytes", "ReturnedItemCount", "ReturnedRecordsCount", "SuccessfulRequestLatency", "SystemErrors", "TimeToLiveDeletedItemCount", "ThrottledRequests", "UserErrors", "WriteThrottleEvents"},
  47. "AWS/EBS": {"VolumeReadBytes", "VolumeWriteBytes", "VolumeReadOps", "VolumeWriteOps", "VolumeTotalReadTime", "VolumeTotalWriteTime", "VolumeIdleTime", "VolumeQueueLength", "VolumeThroughputPercentage", "VolumeConsumedReadWriteOps", "BurstBalance"},
  48. "AWS/EC2": {"CPUCreditUsage", "CPUCreditBalance", "CPUUtilization", "DiskReadOps", "DiskWriteOps", "DiskReadBytes", "DiskWriteBytes", "NetworkIn", "NetworkOut", "NetworkPacketsIn", "NetworkPacketsOut", "StatusCheckFailed", "StatusCheckFailed_Instance", "StatusCheckFailed_System"},
  49. "AWS/EC2Spot": {"AvailableInstancePoolsCount", "BidsSubmittedForCapacity", "EligibleInstancePoolCount", "FulfilledCapacity", "MaxPercentCapacityAllocation", "PendingCapacity", "PercentCapacityAllocation", "TargetCapacity", "TerminatingCapacity"},
  50. "AWS/ECS": {"CPUReservation", "MemoryReservation", "CPUUtilization", "MemoryUtilization"},
  51. "AWS/EFS": {"BurstCreditBalance", "ClientConnections", "DataReadIOBytes", "DataWriteIOBytes", "MetadataIOBytes", "TotalIOBytes", "PermittedThroughput", "PercentIOLimit"},
  52. "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", "EstimatedALBActiveConnectionCount", "EstimatedALBConsumedLCUs", "EstimatedALBNewConnectionCount", "EstimatedProcessedBytes"},
  53. "AWS/ElastiCache": {
  54. "CPUUtilization", "FreeableMemory", "NetworkBytesIn", "NetworkBytesOut", "SwapUsage",
  55. "BytesUsedForCacheItems", "BytesReadIntoMemcached", "BytesWrittenOutFromMemcached", "CasBadval", "CasHits", "CasMisses", "CmdFlush", "CmdGet", "CmdSet", "CurrConnections", "CurrItems", "DecrHits", "DecrMisses", "DeleteHits", "DeleteMisses", "Evictions", "GetHits", "GetMisses", "IncrHits", "IncrMisses", "Reclaimed",
  56. "BytesUsedForHash", "CmdConfigGet", "CmdConfigSet", "CmdTouch", "CurrConfig", "EvictedUnfetched", "ExpiredUnfetched", "SlabsMoved", "TouchHits", "TouchMisses",
  57. "NewConnections", "NewItems", "UnusedMemory",
  58. "BytesUsedForCache", "CacheHits", "CacheMisses", "CurrConnections", "Evictions", "HyperLogLogBasedCmds", "NewConnections", "Reclaimed", "ReplicationBytes", "ReplicationLag", "SaveInProgress",
  59. "CurrItems", "GetTypeCmds", "HashBasedCmds", "KeyBasedCmds", "ListBasedCmds", "SetBasedCmds", "SetTypeCmds", "SortedSetBasedCmds", "StringBasedCmds",
  60. },
  61. "AWS/ElasticBeanstalk": {
  62. "EnvironmentHealth",
  63. "ApplicationLatencyP10", "ApplicationLatencyP50", "ApplicationLatencyP75", "ApplicationLatencyP85", "ApplicationLatencyP90", "ApplicationLatencyP95", "ApplicationLatencyP99", "ApplicationLatencyP99.9",
  64. "ApplicationRequests2xx", "ApplicationRequests3xx", "ApplicationRequests4xx", "ApplicationRequests5xx", "ApplicationRequestsTotal",
  65. "CPUIdle", "CPUIowait", "CPUIrq", "CPUNice", "CPUSoftirq", "CPUSystem", "CPUUser",
  66. "InstanceHealth", "InstancesDegraded", "InstancesInfo", "InstancesNoData", "InstancesOk", "InstancesPending", "InstancesSevere", "InstancesUnknown", "InstancesWarning",
  67. "LoadAverage1min", "LoadAverage5min",
  68. "RootFilesystemUtil",
  69. },
  70. "AWS/ElasticMapReduce": {"IsIdle", "JobsRunning", "JobsFailed",
  71. "MapTasksRunning", "MapTasksRemaining", "MapSlotsOpen", "RemainingMapTasksPerSlot", "ReduceTasksRunning", "ReduceTasksRemaining", "ReduceSlotsOpen",
  72. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "TaskNodesRunning", "TaskNodesPending", "LiveTaskTrackers",
  73. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "TotalLoad",
  74. "BackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup",
  75. "IsIdle", "ContainerAllocated", "ContainerReserved", "ContainerPending", "AppsCompleted", "AppsFailed", "AppsKilled", "AppsPending", "AppsRunning", "AppsSubmitted",
  76. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "MRTotalNodes", "MRActiveNodes", "MRLostNodes", "MRUnhealthyNodes", "MRDecommissionedNodes", "MRRebootedNodes",
  77. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "CorruptBlocks", "TotalLoad", "MemoryTotalMB", "MemoryReservedMB", "MemoryAvailableMB", "MemoryAllocatedMB", "PendingDeletionBlocks", "UnderReplicatedBlocks", "DfsPendingReplicationBlocks", "CapacityRemainingGB",
  78. "HbaseBackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup"},
  79. "AWS/ES": {"ClusterStatus.green", "ClusterStatus.yellow", "ClusterStatus.red", "ClusterUsedSpace", "Nodes", "SearchableDocuments", "DeletedDocuments", "CPUCreditBalance", "CPUUtilization", "FreeStorageSpace", "JVMMemoryPressure", "AutomatedSnapshotFailure", "MasterCPUCreditBalance", "MasterCPUUtilization", "MasterFreeStorageSpace", "MasterJVMMemoryPressure", "ReadLatency", "WriteLatency", "ReadThroughput", "WriteThroughput", "DiskQueueDepth", "ReadIOPS", "WriteIOPS"},
  80. "AWS/Events": {"Invocations", "FailedInvocations", "TriggeredRules", "MatchedEvents", "ThrottledRules"},
  81. "AWS/Firehose": {"DeliveryToElasticsearch.Bytes", "DeliveryToElasticsearch.Records", "DeliveryToElasticsearch.Success", "DeliveryToRedshift.Bytes", "DeliveryToRedshift.Records", "DeliveryToRedshift.Success", "DeliveryToS3.Bytes", "DeliveryToS3.DataFreshness", "DeliveryToS3.Records", "DeliveryToS3.Success", "IncomingBytes", "IncomingRecords", "DescribeDeliveryStream.Latency", "DescribeDeliveryStream.Requests", "ListDeliveryStreams.Latency", "ListDeliveryStreams.Requests", "PutRecord.Bytes", "PutRecord.Latency", "PutRecord.Requests", "PutRecordBatch.Bytes", "PutRecordBatch.Latency", "PutRecordBatch.Records", "PutRecordBatch.Requests", "UpdateDeliveryStream.Latency", "UpdateDeliveryStream.Requests"},
  82. "AWS/IoT": {"PublishIn.Success", "PublishOut.Success", "Subscribe.Success", "Ping.Success", "Connect.Success", "GetThingShadow.Accepted"},
  83. "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"},
  84. "AWS/KinesisAnalytics": {"Bytes", "MillisBehindLatest", "Records", "Success"},
  85. "AWS/Lambda": {"Invocations", "Errors", "Duration", "Throttles", "IteratorAge"},
  86. "AWS/AppSync": {"Latency", "4XXError", "5XXError"},
  87. "AWS/Logs": {"IncomingBytes", "IncomingLogEvents", "ForwardedBytes", "ForwardedLogEvents", "DeliveryErrors", "DeliveryThrottling"},
  88. "AWS/ML": {"PredictCount", "PredictFailureCount"},
  89. "AWS/NATGateway": {"PacketsOutToDestination", "PacketsOutToSource", "PacketsInFromSource", "PacketsInFromDestination", "BytesOutToDestination", "BytesOutToSource", "BytesInFromSource", "BytesInFromDestination", "ErrorPortAllocation", "ActiveConnectionCount", "ConnectionAttemptCount", "ConnectionEstablishedCount", "IdleTimeoutCount", "PacketsDropCount"},
  90. "AWS/NetworkELB": {"ActiveFlowCount", "ConsumedLCUs", "HealthyHostCount", "NewFlowCount", "ProcessedBytes", "TCP_Client_Reset_Count", "TCP_ELB_Reset_Count", "TCP_Target_Reset_Count", "UnHealthyHostCount"},
  91. "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"},
  92. "AWS/Redshift": {"CPUUtilization", "DatabaseConnections", "HealthStatus", "MaintenanceMode", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "PercentageDiskSpaceUsed", "QueriesCompletedPerSecond", "QueryDuration", "QueryRuntimeBreakdown", "ReadIOPS", "ReadLatency", "ReadThroughput", "WLMQueriesCompletedPerSecond", "WLMQueryDuration", "WLMQueueLength", "WriteIOPS", "WriteLatency", "WriteThroughput"},
  93. "AWS/RDS": {"ActiveTransactions", "AuroraBinlogReplicaLag", "AuroraReplicaLag", "AuroraReplicaLagMaximum", "AuroraReplicaLagMinimum", "BinLogDiskUsage", "BlockedTransactions", "BufferCacheHitRatio", "BurstBalance", "CommitLatency", "CommitThroughput", "BinLogDiskUsage", "CPUCreditBalance", "CPUCreditUsage", "CPUUtilization", "DatabaseConnections", "DDLLatency", "DDLThroughput", "Deadlocks", "DeleteLatency", "DeleteThroughput", "DiskQueueDepth", "DMLLatency", "DMLThroughput", "EngineUptime", "FailedSqlStatements", "FreeableMemory", "FreeLocalStorage", "FreeStorageSpace", "InsertLatency", "InsertThroughput", "LoginFailures", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "NetworkThroughput", "Queries", "ReadIOPS", "ReadLatency", "ReadThroughput", "ReplicaLag", "ResultSetCacheHitRatio", "SelectLatency", "SelectThroughput", "SwapUsage", "TotalConnections", "UpdateLatency", "UpdateThroughput", "VolumeBytesUsed", "VolumeReadIOPS", "VolumeWriteIOPS", "WriteIOPS", "WriteLatency", "WriteThroughput"},
  94. "AWS/Route53": {"ChildHealthCheckHealthyCount", "HealthCheckStatus", "HealthCheckPercentageHealthy", "ConnectionTime", "SSLHandshakeTime", "TimeToFirstByte"},
  95. "AWS/S3": {"BucketSizeBytes", "NumberOfObjects", "AllRequests", "GetRequests", "PutRequests", "DeleteRequests", "HeadRequests", "PostRequests", "ListRequests", "BytesDownloaded", "BytesUploaded", "4xxErrors", "5xxErrors", "FirstByteLatency", "TotalRequestLatency"},
  96. "AWS/SES": {"Bounce", "Complaint", "Delivery", "Reject", "Send"},
  97. "AWS/SNS": {"NumberOfMessagesPublished", "PublishSize", "NumberOfNotificationsDelivered", "NumberOfNotificationsFailed"},
  98. "AWS/SQS": {"NumberOfMessagesSent", "SentMessageSize", "NumberOfMessagesReceived", "NumberOfEmptyReceives", "NumberOfMessagesDeleted", "ApproximateAgeOfOldestMessage", "ApproximateNumberOfMessagesDelayed", "ApproximateNumberOfMessagesVisible", "ApproximateNumberOfMessagesNotVisible"},
  99. "AWS/States": {"ExecutionTime", "ExecutionThrottled", "ExecutionsAborted", "ExecutionsFailed", "ExecutionsStarted", "ExecutionsSucceeded", "ExecutionsTimedOut", "ActivityRunTime", "ActivityScheduleTime", "ActivityTime", "ActivitiesFailed", "ActivitiesHeartbeatTimedOut", "ActivitiesScheduled", "ActivitiesScheduled", "ActivitiesSucceeded", "ActivitiesTimedOut", "LambdaFunctionRunTime", "LambdaFunctionScheduleTime", "LambdaFunctionTime", "LambdaFunctionsFailed", "LambdaFunctionsHeartbeatTimedOut", "LambdaFunctionsScheduled", "LambdaFunctionsStarted", "LambdaFunctionsSucceeded", "LambdaFunctionsTimedOut"},
  100. "AWS/StorageGateway": {"CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "CloudBytesDownloaded", "CloudDownloadLatency", "CloudBytesUploaded", "UploadBufferFree", "UploadBufferPercentUsed", "UploadBufferUsed", "QueuedWrites", "ReadBytes", "ReadTime", "TotalCacheSize", "WriteBytes", "WriteTime", "TimeSinceLastRecoveryPoint", "WorkingStorageFree", "WorkingStoragePercentUsed", "WorkingStorageUsed",
  101. "CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "ReadBytes", "ReadTime", "WriteBytes", "WriteTime", "QueuedWrites"},
  102. "AWS/SWF": {"DecisionTaskScheduleToStartTime", "DecisionTaskStartToCloseTime", "DecisionTasksCompleted", "StartedDecisionTasksTimedOutOnClose", "WorkflowStartToCloseTime", "WorkflowsCanceled", "WorkflowsCompleted", "WorkflowsContinuedAsNew", "WorkflowsFailed", "WorkflowsTerminated", "WorkflowsTimedOut",
  103. "ActivityTaskScheduleToCloseTime", "ActivityTaskScheduleToStartTime", "ActivityTaskStartToCloseTime", "ActivityTasksCanceled", "ActivityTasksCompleted", "ActivityTasksFailed", "ScheduledActivityTasksTimedOutOnClose", "ScheduledActivityTasksTimedOutOnStart", "StartedActivityTasksTimedOutOnClose", "StartedActivityTasksTimedOutOnHeartbeat"},
  104. "AWS/VPN": {"TunnelState", "TunnelDataIn", "TunnelDataOut"},
  105. "Rekognition": {"SuccessfulRequestCount", "ThrottledCount", "ResponseTime", "DetectedFaceCount", "DetectedLabelCount", "ServerErrorCount", "UserErrorCount"},
  106. "WAF": {"AllowedRequests", "BlockedRequests", "CountedRequests"},
  107. "AWS/WorkSpaces": {"Available", "Unhealthy", "ConnectionAttempt", "ConnectionSuccess", "ConnectionFailure", "SessionLaunchTime", "InSessionLatency", "SessionDisconnect"},
  108. "KMS": {"SecondsUntilKeyMaterialExpiration"},
  109. }
  110. dimensionsMap = map[string][]string{
  111. "AWS/AmazonMQ": {"Broker", "Topic", "Queue"},
  112. "AWS/ApiGateway": {"ApiName", "Method", "Resource", "Stage"},
  113. "AWS/ApplicationELB": {"LoadBalancer", "TargetGroup", "AvailabilityZone"},
  114. "AWS/AutoScaling": {"AutoScalingGroupName"},
  115. "AWS/Billing": {"ServiceName", "LinkedAccount", "Currency"},
  116. "AWS/CloudFront": {"DistributionId", "Region"},
  117. "AWS/CloudSearch": {},
  118. "AWS/CloudHSM": {"Region", "ClusterId", "HsmId"},
  119. "AWS/Connect": {"InstanceId", "MetricGroup", "Participant", "QueueName", "Stream Type", "Type of Connection"},
  120. "AWS/DMS": {"ReplicationInstanceIdentifier", "ReplicationTaskIdentifier"},
  121. "AWS/DX": {"ConnectionId"},
  122. "AWS/DynamoDB": {"TableName", "GlobalSecondaryIndexName", "Operation", "StreamLabel"},
  123. "AWS/EBS": {"VolumeId"},
  124. "AWS/EC2": {"AutoScalingGroupName", "ImageId", "InstanceId", "InstanceType"},
  125. "AWS/EC2Spot": {"AvailabilityZone", "FleetRequestId", "InstanceType"},
  126. "AWS/ECS": {"ClusterName", "ServiceName"},
  127. "AWS/EFS": {"FileSystemId"},
  128. "AWS/ELB": {"LoadBalancerName", "AvailabilityZone"},
  129. "AWS/ElastiCache": {"CacheClusterId", "CacheNodeId"},
  130. "AWS/ElasticBeanstalk": {"EnvironmentName", "InstanceId"},
  131. "AWS/ElasticMapReduce": {"ClusterId", "JobFlowId", "JobId"},
  132. "AWS/ES": {"ClientId", "DomainName"},
  133. "AWS/Events": {"RuleName"},
  134. "AWS/Firehose": {"DeliveryStreamName"},
  135. "AWS/IoT": {"Protocol"},
  136. "AWS/Kinesis": {"StreamName", "ShardId"},
  137. "AWS/KinesisAnalytics": {"Flow", "Id", "Application"},
  138. "AWS/Lambda": {"FunctionName", "Resource", "Version", "Alias"},
  139. "AWS/AppSync": {"GraphQLAPIId"},
  140. "AWS/Logs": {"LogGroupName", "DestinationType", "FilterName"},
  141. "AWS/ML": {"MLModelId", "RequestMode"},
  142. "AWS/NATGateway": {"NatGatewayId"},
  143. "AWS/NetworkELB": {"LoadBalancer", "TargetGroup", "AvailabilityZone"},
  144. "AWS/OpsWorks": {"StackId", "LayerId", "InstanceId"},
  145. "AWS/Redshift": {"NodeID", "ClusterIdentifier", "latency", "service class", "wmlid"},
  146. "AWS/RDS": {"DBInstanceIdentifier", "DBClusterIdentifier", "DbClusterIdentifier", "DatabaseClass", "EngineName", "Role"},
  147. "AWS/Route53": {"HealthCheckId", "Region"},
  148. "AWS/S3": {"BucketName", "StorageType", "FilterId"},
  149. "AWS/SES": {},
  150. "AWS/SNS": {"Application", "Platform", "TopicName"},
  151. "AWS/SQS": {"QueueName"},
  152. "AWS/States": {"StateMachineArn", "ActivityArn", "LambdaFunctionArn"},
  153. "AWS/StorageGateway": {"GatewayId", "GatewayName", "VolumeId"},
  154. "AWS/SWF": {"Domain", "WorkflowTypeName", "WorkflowTypeVersion", "ActivityTypeName", "ActivityTypeVersion"},
  155. "AWS/VPN": {"VpnId", "TunnelIpAddress"},
  156. "Rekognition": {},
  157. "WAF": {"Rule", "WebACL"},
  158. "AWS/WorkSpaces": {"DirectoryId", "WorkspaceId"},
  159. "KMS": {"KeyId"},
  160. }
  161. customMetricsMetricsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  162. customMetricsDimensionsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  163. }
  164. func (e *CloudWatchExecutor) executeMetricFindQuery(ctx context.Context, queryContext *tsdb.TsdbQuery) (*tsdb.Response, error) {
  165. result := &tsdb.Response{
  166. Results: make(map[string]*tsdb.QueryResult),
  167. }
  168. firstQuery := queryContext.Queries[0]
  169. queryResult := &tsdb.QueryResult{Meta: simplejson.New(), RefId: firstQuery.RefId}
  170. parameters := firstQuery.Model
  171. subType := firstQuery.Model.Get("subtype").MustString()
  172. var data []suggestData
  173. var err error
  174. switch subType {
  175. case "regions":
  176. data, err = e.handleGetRegions(ctx, parameters, queryContext)
  177. case "namespaces":
  178. data, err = e.handleGetNamespaces(ctx, parameters, queryContext)
  179. case "metrics":
  180. data, err = e.handleGetMetrics(ctx, parameters, queryContext)
  181. case "dimension_keys":
  182. data, err = e.handleGetDimensions(ctx, parameters, queryContext)
  183. case "dimension_values":
  184. data, err = e.handleGetDimensionValues(ctx, parameters, queryContext)
  185. case "ebs_volume_ids":
  186. data, err = e.handleGetEbsVolumeIds(ctx, parameters, queryContext)
  187. case "ec2_instance_attribute":
  188. data, err = e.handleGetEc2InstanceAttribute(ctx, parameters, queryContext)
  189. }
  190. transformToTable(data, queryResult)
  191. result.Results[firstQuery.RefId] = queryResult
  192. return result, err
  193. }
  194. func transformToTable(data []suggestData, result *tsdb.QueryResult) {
  195. table := &tsdb.Table{
  196. Columns: make([]tsdb.TableColumn, 2),
  197. Rows: make([]tsdb.RowValues, 0),
  198. }
  199. table.Columns[0].Text = "text"
  200. table.Columns[1].Text = "value"
  201. for _, r := range data {
  202. values := make([]interface{}, 2)
  203. values[0] = r.Text
  204. values[1] = r.Value
  205. table.Rows = append(table.Rows, values)
  206. }
  207. result.Tables = append(result.Tables, table)
  208. result.Meta.Set("rowCount", len(data))
  209. }
  210. func parseMultiSelectValue(input string) []string {
  211. trimmedInput := strings.TrimSpace(input)
  212. if strings.HasPrefix(trimmedInput, "{") {
  213. values := strings.Split(strings.TrimRight(strings.TrimLeft(trimmedInput, "{"), "}"), ",")
  214. trimValues := make([]string, len(values))
  215. for i, v := range values {
  216. trimValues[i] = strings.TrimSpace(v)
  217. }
  218. return trimValues
  219. }
  220. return []string{trimmedInput}
  221. }
  222. // Whenever this list is updated, frontend list should also be updated.
  223. // Please update the region list in public/app/plugins/datasource/cloudwatch/partials/config.html
  224. func (e *CloudWatchExecutor) handleGetRegions(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  225. dsInfo := e.getDsInfo("default")
  226. profile := dsInfo.Profile
  227. if cache, ok := regionCache.Load(profile); ok {
  228. if cache2, ok2 := cache.([]suggestData); ok2 {
  229. return cache2, nil
  230. }
  231. }
  232. regions := []string{
  233. "ap-northeast-1", "ap-northeast-2", "ap-northeast-3", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ca-central-1",
  234. "eu-central-1", "eu-north-1", "eu-west-1", "eu-west-2", "eu-west-3", "me-south-1", "sa-east-1", "us-east-1", "us-east-2", "us-west-1", "us-west-2",
  235. "cn-north-1", "cn-northwest-1", "us-gov-east-1", "us-gov-west-1", "us-isob-east-1", "us-iso-east-1",
  236. }
  237. err := e.ensureClientSession("default")
  238. if err != nil {
  239. return nil, err
  240. }
  241. r, err := e.ec2Svc.DescribeRegions(&ec2.DescribeRegionsInput{})
  242. if err != nil {
  243. // ignore error for backward compatibility
  244. plog.Error("Failed to get regions", "error", err)
  245. } else {
  246. for _, region := range r.Regions {
  247. exists := false
  248. for _, existingRegion := range regions {
  249. if existingRegion == *region.RegionName {
  250. exists = true
  251. break
  252. }
  253. }
  254. if !exists {
  255. regions = append(regions, *region.RegionName)
  256. }
  257. }
  258. }
  259. sort.Strings(regions)
  260. result := make([]suggestData, 0)
  261. for _, region := range regions {
  262. result = append(result, suggestData{Text: region, Value: region})
  263. }
  264. regionCache.Store(profile, result)
  265. return result, nil
  266. }
  267. func (e *CloudWatchExecutor) handleGetNamespaces(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  268. keys := []string{}
  269. for key := range metricsMap {
  270. keys = append(keys, key)
  271. }
  272. customNamespaces := e.DataSource.JsonData.Get("customMetricsNamespaces").MustString()
  273. if customNamespaces != "" {
  274. keys = append(keys, strings.Split(customNamespaces, ",")...)
  275. }
  276. sort.Strings(keys)
  277. result := make([]suggestData, 0)
  278. for _, key := range keys {
  279. result = append(result, suggestData{Text: key, Value: key})
  280. }
  281. return result, nil
  282. }
  283. func (e *CloudWatchExecutor) handleGetMetrics(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  284. region := parameters.Get("region").MustString()
  285. namespace := parameters.Get("namespace").MustString()
  286. var namespaceMetrics []string
  287. if !isCustomMetrics(namespace) {
  288. var exists bool
  289. if namespaceMetrics, exists = metricsMap[namespace]; !exists {
  290. return nil, errors.New("Unable to find namespace " + namespace)
  291. }
  292. } else {
  293. var err error
  294. dsInfo := e.getDsInfo(region)
  295. dsInfo.Namespace = namespace
  296. if namespaceMetrics, err = getMetricsForCustomMetrics(dsInfo, getAllMetrics); err != nil {
  297. return nil, errors.New("Unable to call AWS API")
  298. }
  299. }
  300. sort.Strings(namespaceMetrics)
  301. result := make([]suggestData, 0)
  302. for _, name := range namespaceMetrics {
  303. result = append(result, suggestData{Text: name, Value: name})
  304. }
  305. return result, nil
  306. }
  307. func (e *CloudWatchExecutor) handleGetDimensions(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  308. region := parameters.Get("region").MustString()
  309. namespace := parameters.Get("namespace").MustString()
  310. var dimensionValues []string
  311. if !isCustomMetrics(namespace) {
  312. var exists bool
  313. if dimensionValues, exists = dimensionsMap[namespace]; !exists {
  314. return nil, errors.New("Unable to find dimension " + namespace)
  315. }
  316. } else {
  317. var err error
  318. dsInfo := e.getDsInfo(region)
  319. dsInfo.Namespace = namespace
  320. if dimensionValues, err = getDimensionsForCustomMetrics(dsInfo, getAllMetrics); err != nil {
  321. return nil, errors.New("Unable to call AWS API")
  322. }
  323. }
  324. sort.Strings(dimensionValues)
  325. result := make([]suggestData, 0)
  326. for _, name := range dimensionValues {
  327. result = append(result, suggestData{Text: name, Value: name})
  328. }
  329. return result, nil
  330. }
  331. func (e *CloudWatchExecutor) handleGetDimensionValues(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  332. region := parameters.Get("region").MustString()
  333. namespace := parameters.Get("namespace").MustString()
  334. metricName := parameters.Get("metricName").MustString()
  335. dimensionKey := parameters.Get("dimensionKey").MustString()
  336. dimensionsJson := parameters.Get("dimensions").MustMap()
  337. var dimensions []*cloudwatch.DimensionFilter
  338. for k, v := range dimensionsJson {
  339. if vv, ok := v.(string); ok {
  340. dimensions = append(dimensions, &cloudwatch.DimensionFilter{
  341. Name: aws.String(k),
  342. Value: aws.String(vv),
  343. })
  344. }
  345. }
  346. metrics, err := e.cloudwatchListMetrics(region, namespace, metricName, dimensions)
  347. if err != nil {
  348. return nil, err
  349. }
  350. result := make([]suggestData, 0)
  351. dupCheck := make(map[string]bool)
  352. for _, metric := range metrics.Metrics {
  353. for _, dim := range metric.Dimensions {
  354. if *dim.Name == dimensionKey {
  355. if _, exists := dupCheck[*dim.Value]; exists {
  356. continue
  357. }
  358. dupCheck[*dim.Value] = true
  359. result = append(result, suggestData{Text: *dim.Value, Value: *dim.Value})
  360. }
  361. }
  362. }
  363. sort.Slice(result, func(i, j int) bool {
  364. return result[i].Text < result[j].Text
  365. })
  366. return result, nil
  367. }
  368. func (e *CloudWatchExecutor) ensureClientSession(region string) error {
  369. if e.ec2Svc == nil {
  370. dsInfo := e.getDsInfo(region)
  371. cfg, err := e.getAwsConfig(dsInfo)
  372. if err != nil {
  373. return fmt.Errorf("Failed to call ec2:getAwsConfig, %v", err)
  374. }
  375. sess, err := session.NewSession(cfg)
  376. if err != nil {
  377. return fmt.Errorf("Failed to call ec2:NewSession, %v", err)
  378. }
  379. e.ec2Svc = ec2.New(sess, cfg)
  380. }
  381. return nil
  382. }
  383. func (e *CloudWatchExecutor) handleGetEbsVolumeIds(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  384. region := parameters.Get("region").MustString()
  385. instanceId := parameters.Get("instanceId").MustString()
  386. err := e.ensureClientSession(region)
  387. if err != nil {
  388. return nil, err
  389. }
  390. instanceIds := aws.StringSlice(parseMultiSelectValue(instanceId))
  391. instances, err := e.ec2DescribeInstances(region, nil, instanceIds)
  392. if err != nil {
  393. return nil, err
  394. }
  395. result := make([]suggestData, 0)
  396. for _, reservation := range instances.Reservations {
  397. for _, instance := range reservation.Instances {
  398. for _, mapping := range instance.BlockDeviceMappings {
  399. result = append(result, suggestData{Text: *mapping.Ebs.VolumeId, Value: *mapping.Ebs.VolumeId})
  400. }
  401. }
  402. }
  403. return result, nil
  404. }
  405. func (e *CloudWatchExecutor) handleGetEc2InstanceAttribute(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  406. region := parameters.Get("region").MustString()
  407. attributeName := parameters.Get("attributeName").MustString()
  408. filterJson := parameters.Get("filters").MustMap()
  409. var filters []*ec2.Filter
  410. for k, v := range filterJson {
  411. if vv, ok := v.([]interface{}); ok {
  412. var vvvvv []*string
  413. for _, vvv := range vv {
  414. if vvvv, ok := vvv.(string); ok {
  415. vvvvv = append(vvvvv, &vvvv)
  416. }
  417. }
  418. filters = append(filters, &ec2.Filter{
  419. Name: aws.String(k),
  420. Values: vvvvv,
  421. })
  422. }
  423. }
  424. err := e.ensureClientSession(region)
  425. if err != nil {
  426. return nil, err
  427. }
  428. instances, err := e.ec2DescribeInstances(region, filters, nil)
  429. if err != nil {
  430. return nil, err
  431. }
  432. result := make([]suggestData, 0)
  433. dupCheck := make(map[string]bool)
  434. for _, reservation := range instances.Reservations {
  435. for _, instance := range reservation.Instances {
  436. tags := make(map[string]string)
  437. for _, tag := range instance.Tags {
  438. tags[*tag.Key] = *tag.Value
  439. }
  440. var data string
  441. if strings.Index(attributeName, "Tags.") == 0 {
  442. tagName := attributeName[5:]
  443. data = tags[tagName]
  444. } else {
  445. attributePath := strings.Split(attributeName, ".")
  446. v := reflect.ValueOf(instance)
  447. for _, key := range attributePath {
  448. if v.Kind() == reflect.Ptr {
  449. v = v.Elem()
  450. }
  451. if v.Kind() != reflect.Struct {
  452. return nil, errors.New("invalid attribute path")
  453. }
  454. v = v.FieldByName(key)
  455. if !v.IsValid() {
  456. return nil, errors.New("invalid attribute path")
  457. }
  458. }
  459. if attr, ok := v.Interface().(*string); ok {
  460. data = *attr
  461. } else {
  462. return nil, errors.New("invalid attribute path")
  463. }
  464. }
  465. if _, exists := dupCheck[data]; exists {
  466. continue
  467. }
  468. dupCheck[data] = true
  469. result = append(result, suggestData{Text: data, Value: data})
  470. }
  471. }
  472. sort.Slice(result, func(i, j int) bool {
  473. return result[i].Text < result[j].Text
  474. })
  475. return result, nil
  476. }
  477. func (e *CloudWatchExecutor) cloudwatchListMetrics(region string, namespace string, metricName string, dimensions []*cloudwatch.DimensionFilter) (*cloudwatch.ListMetricsOutput, error) {
  478. svc, err := e.getClient(region)
  479. if err != nil {
  480. return nil, err
  481. }
  482. params := &cloudwatch.ListMetricsInput{
  483. Namespace: aws.String(namespace),
  484. MetricName: aws.String(metricName),
  485. Dimensions: dimensions,
  486. }
  487. var resp cloudwatch.ListMetricsOutput
  488. err = svc.ListMetricsPages(params,
  489. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  490. metrics.M_Aws_CloudWatch_ListMetrics.Inc()
  491. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  492. for _, metric := range metrics {
  493. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  494. }
  495. return !lastPage
  496. })
  497. if err != nil {
  498. return nil, fmt.Errorf("Failed to call cloudwatch:ListMetrics, %v", err)
  499. }
  500. return &resp, nil
  501. }
  502. func (e *CloudWatchExecutor) ec2DescribeInstances(region string, filters []*ec2.Filter, instanceIds []*string) (*ec2.DescribeInstancesOutput, error) {
  503. params := &ec2.DescribeInstancesInput{
  504. Filters: filters,
  505. InstanceIds: instanceIds,
  506. }
  507. var resp ec2.DescribeInstancesOutput
  508. err := e.ec2Svc.DescribeInstancesPages(params,
  509. func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
  510. reservations, _ := awsutil.ValuesAtPath(page, "Reservations")
  511. for _, reservation := range reservations {
  512. resp.Reservations = append(resp.Reservations, reservation.(*ec2.Reservation))
  513. }
  514. return !lastPage
  515. })
  516. if err != nil {
  517. return nil, errors.New("Failed to call ec2:DescribeInstances")
  518. }
  519. return &resp, nil
  520. }
  521. func getAllMetrics(cwData *DatasourceInfo) (cloudwatch.ListMetricsOutput, error) {
  522. creds, err := GetCredentials(cwData)
  523. if err != nil {
  524. return cloudwatch.ListMetricsOutput{}, err
  525. }
  526. cfg := &aws.Config{
  527. Region: aws.String(cwData.Region),
  528. Credentials: creds,
  529. }
  530. sess, err := session.NewSession(cfg)
  531. if err != nil {
  532. return cloudwatch.ListMetricsOutput{}, err
  533. }
  534. svc := cloudwatch.New(sess, cfg)
  535. params := &cloudwatch.ListMetricsInput{
  536. Namespace: aws.String(cwData.Namespace),
  537. }
  538. var resp cloudwatch.ListMetricsOutput
  539. err = svc.ListMetricsPages(params,
  540. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  541. metrics.M_Aws_CloudWatch_ListMetrics.Inc()
  542. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  543. for _, metric := range metrics {
  544. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  545. }
  546. return !lastPage
  547. })
  548. return resp, err
  549. }
  550. var metricsCacheLock sync.Mutex
  551. func getMetricsForCustomMetrics(dsInfo *DatasourceInfo, getAllMetrics func(*DatasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  552. metricsCacheLock.Lock()
  553. defer metricsCacheLock.Unlock()
  554. if _, ok := customMetricsMetricsMap[dsInfo.Profile]; !ok {
  555. customMetricsMetricsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  556. }
  557. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  558. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  559. }
  560. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  561. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  562. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  563. }
  564. if customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  565. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  566. }
  567. result, err := getAllMetrics(dsInfo)
  568. if err != nil {
  569. return []string{}, err
  570. }
  571. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  572. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  573. for _, metric := range result.Metrics {
  574. if isDuplicate(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName) {
  575. continue
  576. }
  577. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName)
  578. }
  579. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  580. }
  581. var dimensionsCacheLock sync.Mutex
  582. func getDimensionsForCustomMetrics(dsInfo *DatasourceInfo, getAllMetrics func(*DatasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  583. dimensionsCacheLock.Lock()
  584. defer dimensionsCacheLock.Unlock()
  585. if _, ok := customMetricsDimensionsMap[dsInfo.Profile]; !ok {
  586. customMetricsDimensionsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  587. }
  588. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  589. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  590. }
  591. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  592. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  593. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  594. }
  595. if customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  596. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  597. }
  598. result, err := getAllMetrics(dsInfo)
  599. if err != nil {
  600. return []string{}, err
  601. }
  602. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  603. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  604. for _, metric := range result.Metrics {
  605. for _, dimension := range metric.Dimensions {
  606. if isDuplicate(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name) {
  607. continue
  608. }
  609. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name)
  610. }
  611. }
  612. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  613. }
  614. func isDuplicate(nameList []string, target string) bool {
  615. for _, name := range nameList {
  616. if name == target {
  617. return true
  618. }
  619. }
  620. return false
  621. }
  622. func isCustomMetrics(namespace string) bool {
  623. return strings.Index(namespace, "AWS/") != 0
  624. }