metric_find_query.go 35 KB

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