metric_find_query.go 34 KB

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