metric_find_query.go 37 KB

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