metric_find_query.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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/Logs": {"IncomingBytes", "IncomingLogEvents", "ForwardedBytes", "ForwardedLogEvents", "DeliveryErrors", "DeliveryThrottling"},
  83. "AWS/ML": {"PredictCount", "PredictFailureCount"},
  84. "AWS/NATGateway": {"PacketsOutToDestination", "PacketsOutToSource", "PacketsInFromSource", "PacketsInFromDestination", "BytesOutToDestination", "BytesOutToSource", "BytesInFromSource", "BytesInFromDestination", "ErrorPortAllocation", "ActiveConnectionCount", "ConnectionAttemptCount", "ConnectionEstablishedCount", "IdleTimeoutCount", "PacketsDropCount"},
  85. "AWS/NetworkELB": {"ActiveFlowCount", "ConsumedLCUs", "HealthyHostCount", "NewFlowCount", "ProcessedBytes", "TCP_Client_Reset_Count", "TCP_ELB_Reset_Count", "TCP_Target_Reset_Count", "UnHealthyHostCount"},
  86. "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"},
  87. "AWS/Redshift": {"CPUUtilization", "DatabaseConnections", "HealthStatus", "MaintenanceMode", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "PercentageDiskSpaceUsed", "ReadIOPS", "ReadLatency", "ReadThroughput", "WriteIOPS", "WriteLatency", "WriteThroughput"},
  88. "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"},
  89. "AWS/Route53": {"ChildHealthCheckHealthyCount", "HealthCheckStatus", "HealthCheckPercentageHealthy", "ConnectionTime", "SSLHandshakeTime", "TimeToFirstByte"},
  90. "AWS/S3": {"BucketSizeBytes", "NumberOfObjects", "AllRequests", "GetRequests", "PutRequests", "DeleteRequests", "HeadRequests", "PostRequests", "ListRequests", "BytesDownloaded", "BytesUploaded", "4xxErrors", "5xxErrors", "FirstByteLatency", "TotalRequestLatency"},
  91. "AWS/SES": {"Bounce", "Complaint", "Delivery", "Reject", "Send"},
  92. "AWS/SNS": {"NumberOfMessagesPublished", "PublishSize", "NumberOfNotificationsDelivered", "NumberOfNotificationsFailed"},
  93. "AWS/SQS": {"NumberOfMessagesSent", "SentMessageSize", "NumberOfMessagesReceived", "NumberOfEmptyReceives", "NumberOfMessagesDeleted", "ApproximateAgeOfOldestMessage", "ApproximateNumberOfMessagesDelayed", "ApproximateNumberOfMessagesVisible", "ApproximateNumberOfMessagesNotVisible"},
  94. "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"},
  95. "AWS/StorageGateway": {"CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "CloudBytesDownloaded", "CloudDownloadLatency", "CloudBytesUploaded", "UploadBufferFree", "UploadBufferPercentUsed", "UploadBufferUsed", "QueuedWrites", "ReadBytes", "ReadTime", "TotalCacheSize", "WriteBytes", "WriteTime", "TimeSinceLastRecoveryPoint", "WorkingStorageFree", "WorkingStoragePercentUsed", "WorkingStorageUsed",
  96. "CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "ReadBytes", "ReadTime", "WriteBytes", "WriteTime", "QueuedWrites"},
  97. "AWS/SWF": {"DecisionTaskScheduleToStartTime", "DecisionTaskStartToCloseTime", "DecisionTasksCompleted", "StartedDecisionTasksTimedOutOnClose", "WorkflowStartToCloseTime", "WorkflowsCanceled", "WorkflowsCompleted", "WorkflowsContinuedAsNew", "WorkflowsFailed", "WorkflowsTerminated", "WorkflowsTimedOut",
  98. "ActivityTaskScheduleToCloseTime", "ActivityTaskScheduleToStartTime", "ActivityTaskStartToCloseTime", "ActivityTasksCanceled", "ActivityTasksCompleted", "ActivityTasksFailed", "ScheduledActivityTasksTimedOutOnClose", "ScheduledActivityTasksTimedOutOnStart", "StartedActivityTasksTimedOutOnClose", "StartedActivityTasksTimedOutOnHeartbeat"},
  99. "AWS/VPN": {"TunnelState", "TunnelDataIn", "TunnelDataOut"},
  100. "Rekognition": {"SuccessfulRequestCount", "ThrottledCount", "ResponseTime", "DetectedFaceCount", "DetectedLabelCount", "ServerErrorCount", "UserErrorCount"},
  101. "WAF": {"AllowedRequests", "BlockedRequests", "CountedRequests"},
  102. "AWS/WorkSpaces": {"Available", "Unhealthy", "ConnectionAttempt", "ConnectionSuccess", "ConnectionFailure", "SessionLaunchTime", "InSessionLatency", "SessionDisconnect"},
  103. "KMS": {"SecondsUntilKeyMaterialExpiration"},
  104. }
  105. dimensionsMap = map[string][]string{
  106. "AWS/AmazonMQ": {"Broker", "Topic", "Queue"},
  107. "AWS/ApiGateway": {"ApiName", "Method", "Resource", "Stage"},
  108. "AWS/ApplicationELB": {"LoadBalancer", "TargetGroup", "AvailabilityZone"},
  109. "AWS/AutoScaling": {"AutoScalingGroupName"},
  110. "AWS/Billing": {"ServiceName", "LinkedAccount", "Currency"},
  111. "AWS/CloudFront": {"DistributionId", "Region"},
  112. "AWS/CloudSearch": {},
  113. "AWS/DMS": {"ReplicationInstanceIdentifier", "ReplicationTaskIdentifier"},
  114. "AWS/DynamoDB": {"TableName", "GlobalSecondaryIndexName", "Operation", "StreamLabel"},
  115. "AWS/EBS": {"VolumeId"},
  116. "AWS/EC2": {"AutoScalingGroupName", "ImageId", "InstanceId", "InstanceType"},
  117. "AWS/EC2Spot": {"AvailabilityZone", "FleetRequestId", "InstanceType"},
  118. "AWS/ECS": {"ClusterName", "ServiceName"},
  119. "AWS/EFS": {"FileSystemId"},
  120. "AWS/ELB": {"LoadBalancerName", "AvailabilityZone"},
  121. "AWS/ElastiCache": {"CacheClusterId", "CacheNodeId"},
  122. "AWS/ElasticBeanstalk": {"EnvironmentName", "InstanceId"},
  123. "AWS/ElasticMapReduce": {"ClusterId", "JobFlowId", "JobId"},
  124. "AWS/ES": {"ClientId", "DomainName"},
  125. "AWS/Events": {"RuleName"},
  126. "AWS/Firehose": {"DeliveryStreamName"},
  127. "AWS/IoT": {"Protocol"},
  128. "AWS/Kinesis": {"StreamName", "ShardId"},
  129. "AWS/KinesisAnalytics": {"Flow", "Id", "Application"},
  130. "AWS/Lambda": {"FunctionName", "Resource", "Version", "Alias"},
  131. "AWS/Logs": {"LogGroupName", "DestinationType", "FilterName"},
  132. "AWS/ML": {"MLModelId", "RequestMode"},
  133. "AWS/NATGateway": {"NatGatewayId"},
  134. "AWS/NetworkELB": {"LoadBalancer", "TargetGroup", "AvailabilityZone"},
  135. "AWS/OpsWorks": {"StackId", "LayerId", "InstanceId"},
  136. "AWS/Redshift": {"NodeID", "ClusterIdentifier"},
  137. "AWS/RDS": {"DBInstanceIdentifier", "DBClusterIdentifier", "DbClusterIdentifier", "DatabaseClass", "EngineName", "Role"},
  138. "AWS/Route53": {"HealthCheckId", "Region"},
  139. "AWS/S3": {"BucketName", "StorageType", "FilterId"},
  140. "AWS/SES": {},
  141. "AWS/SNS": {"Application", "Platform", "TopicName"},
  142. "AWS/SQS": {"QueueName"},
  143. "AWS/States": {"StateMachineArn", "ActivityArn", "LambdaFunctionArn"},
  144. "AWS/StorageGateway": {"GatewayId", "GatewayName", "VolumeId"},
  145. "AWS/SWF": {"Domain", "WorkflowTypeName", "WorkflowTypeVersion", "ActivityTypeName", "ActivityTypeVersion"},
  146. "AWS/VPN": {"VpnId", "TunnelIpAddress"},
  147. "Rekognition": {},
  148. "WAF": {"Rule", "WebACL"},
  149. "AWS/WorkSpaces": {"DirectoryId", "WorkspaceId"},
  150. "KMS": {"KeyId"},
  151. }
  152. customMetricsMetricsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  153. customMetricsDimensionsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  154. }
  155. func (e *CloudWatchExecutor) executeMetricFindQuery(ctx context.Context, queryContext *tsdb.TsdbQuery) (*tsdb.Response, error) {
  156. result := &tsdb.Response{
  157. Results: make(map[string]*tsdb.QueryResult),
  158. }
  159. firstQuery := queryContext.Queries[0]
  160. queryResult := &tsdb.QueryResult{Meta: simplejson.New(), RefId: firstQuery.RefId}
  161. parameters := firstQuery.Model
  162. subType := firstQuery.Model.Get("subtype").MustString()
  163. var data []suggestData
  164. var err error
  165. switch subType {
  166. case "regions":
  167. data, err = e.handleGetRegions(ctx, parameters, queryContext)
  168. case "namespaces":
  169. data, err = e.handleGetNamespaces(ctx, parameters, queryContext)
  170. case "metrics":
  171. data, err = e.handleGetMetrics(ctx, parameters, queryContext)
  172. case "dimension_keys":
  173. data, err = e.handleGetDimensions(ctx, parameters, queryContext)
  174. case "dimension_values":
  175. data, err = e.handleGetDimensionValues(ctx, parameters, queryContext)
  176. case "ebs_volume_ids":
  177. data, err = e.handleGetEbsVolumeIds(ctx, parameters, queryContext)
  178. case "ec2_instance_attribute":
  179. data, err = e.handleGetEc2InstanceAttribute(ctx, parameters, queryContext)
  180. }
  181. transformToTable(data, queryResult)
  182. result.Results[firstQuery.RefId] = queryResult
  183. return result, err
  184. }
  185. func transformToTable(data []suggestData, result *tsdb.QueryResult) {
  186. table := &tsdb.Table{
  187. Columns: make([]tsdb.TableColumn, 2),
  188. Rows: make([]tsdb.RowValues, 0),
  189. }
  190. table.Columns[0].Text = "text"
  191. table.Columns[1].Text = "value"
  192. for _, r := range data {
  193. values := make([]interface{}, 2)
  194. values[0] = r.Text
  195. values[1] = r.Value
  196. table.Rows = append(table.Rows, values)
  197. }
  198. result.Tables = append(result.Tables, table)
  199. result.Meta.Set("rowCount", len(data))
  200. }
  201. func parseMultiSelectValue(input string) []string {
  202. trimmedInput := strings.TrimSpace(input)
  203. if strings.HasPrefix(trimmedInput, "{") {
  204. values := strings.Split(strings.TrimRight(strings.TrimLeft(trimmedInput, "{"), "}"), ",")
  205. trimValues := make([]string, len(values))
  206. for i, v := range values {
  207. trimValues[i] = strings.TrimSpace(v)
  208. }
  209. return trimValues
  210. }
  211. return []string{trimmedInput}
  212. }
  213. // Whenever this list is updated, frontend list should also be updated.
  214. // Please update the region list in public/app/plugins/datasource/cloudwatch/partials/config.html
  215. func (e *CloudWatchExecutor) handleGetRegions(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  216. regions := []string{
  217. "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "ap-south-1", "ca-central-1", "cn-north-1", "cn-northwest-1",
  218. "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",
  219. }
  220. result := make([]suggestData, 0)
  221. for _, region := range regions {
  222. result = append(result, suggestData{Text: region, Value: region})
  223. }
  224. return result, nil
  225. }
  226. func (e *CloudWatchExecutor) handleGetNamespaces(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  227. keys := []string{}
  228. for key := range metricsMap {
  229. keys = append(keys, key)
  230. }
  231. customNamespaces := e.DataSource.JsonData.Get("customMetricsNamespaces").MustString()
  232. if customNamespaces != "" {
  233. keys = append(keys, strings.Split(customNamespaces, ",")...)
  234. }
  235. sort.Strings(keys)
  236. result := make([]suggestData, 0)
  237. for _, key := range keys {
  238. result = append(result, suggestData{Text: key, Value: key})
  239. }
  240. return result, nil
  241. }
  242. func (e *CloudWatchExecutor) handleGetMetrics(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  243. region := parameters.Get("region").MustString()
  244. namespace := parameters.Get("namespace").MustString()
  245. var namespaceMetrics []string
  246. if !isCustomMetrics(namespace) {
  247. var exists bool
  248. if namespaceMetrics, exists = metricsMap[namespace]; !exists {
  249. return nil, errors.New("Unable to find namespace " + namespace)
  250. }
  251. } else {
  252. var err error
  253. dsInfo := e.getDsInfo(region)
  254. dsInfo.Namespace = namespace
  255. if namespaceMetrics, err = getMetricsForCustomMetrics(dsInfo, getAllMetrics); err != nil {
  256. return nil, errors.New("Unable to call AWS API")
  257. }
  258. }
  259. sort.Strings(namespaceMetrics)
  260. result := make([]suggestData, 0)
  261. for _, name := range namespaceMetrics {
  262. result = append(result, suggestData{Text: name, Value: name})
  263. }
  264. return result, nil
  265. }
  266. func (e *CloudWatchExecutor) handleGetDimensions(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  267. region := parameters.Get("region").MustString()
  268. namespace := parameters.Get("namespace").MustString()
  269. var dimensionValues []string
  270. if !isCustomMetrics(namespace) {
  271. var exists bool
  272. if dimensionValues, exists = dimensionsMap[namespace]; !exists {
  273. return nil, errors.New("Unable to find dimension " + namespace)
  274. }
  275. } else {
  276. var err error
  277. dsInfo := e.getDsInfo(region)
  278. dsInfo.Namespace = namespace
  279. if dimensionValues, err = getDimensionsForCustomMetrics(dsInfo, getAllMetrics); err != nil {
  280. return nil, errors.New("Unable to call AWS API")
  281. }
  282. }
  283. sort.Strings(dimensionValues)
  284. result := make([]suggestData, 0)
  285. for _, name := range dimensionValues {
  286. result = append(result, suggestData{Text: name, Value: name})
  287. }
  288. return result, nil
  289. }
  290. func (e *CloudWatchExecutor) handleGetDimensionValues(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  291. region := parameters.Get("region").MustString()
  292. namespace := parameters.Get("namespace").MustString()
  293. metricName := parameters.Get("metricName").MustString()
  294. dimensionKey := parameters.Get("dimensionKey").MustString()
  295. dimensionsJson := parameters.Get("dimensions").MustMap()
  296. var dimensions []*cloudwatch.DimensionFilter
  297. for k, v := range dimensionsJson {
  298. if vv, ok := v.(string); ok {
  299. dimensions = append(dimensions, &cloudwatch.DimensionFilter{
  300. Name: aws.String(k),
  301. Value: aws.String(vv),
  302. })
  303. }
  304. }
  305. metrics, err := e.cloudwatchListMetrics(region, namespace, metricName, dimensions)
  306. if err != nil {
  307. return nil, err
  308. }
  309. result := make([]suggestData, 0)
  310. dupCheck := make(map[string]bool)
  311. for _, metric := range metrics.Metrics {
  312. for _, dim := range metric.Dimensions {
  313. if *dim.Name == dimensionKey {
  314. if _, exists := dupCheck[*dim.Value]; exists {
  315. continue
  316. }
  317. dupCheck[*dim.Value] = true
  318. result = append(result, suggestData{Text: *dim.Value, Value: *dim.Value})
  319. }
  320. }
  321. }
  322. sort.Slice(result, func(i, j int) bool {
  323. return result[i].Text < result[j].Text
  324. })
  325. return result, nil
  326. }
  327. func (e *CloudWatchExecutor) ensureClientSession(region string) error {
  328. if e.ec2Svc == nil {
  329. dsInfo := e.getDsInfo(region)
  330. cfg, err := e.getAwsConfig(dsInfo)
  331. if err != nil {
  332. return fmt.Errorf("Failed to call ec2:getAwsConfig, %v", err)
  333. }
  334. sess, err := session.NewSession(cfg)
  335. if err != nil {
  336. return fmt.Errorf("Failed to call ec2:NewSession, %v", err)
  337. }
  338. e.ec2Svc = ec2.New(sess, cfg)
  339. }
  340. return nil
  341. }
  342. func (e *CloudWatchExecutor) handleGetEbsVolumeIds(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  343. region := parameters.Get("region").MustString()
  344. instanceId := parameters.Get("instanceId").MustString()
  345. err := e.ensureClientSession(region)
  346. if err != nil {
  347. return nil, err
  348. }
  349. instanceIds := aws.StringSlice(parseMultiSelectValue(instanceId))
  350. instances, err := e.ec2DescribeInstances(region, nil, instanceIds)
  351. if err != nil {
  352. return nil, err
  353. }
  354. result := make([]suggestData, 0)
  355. for _, reservation := range instances.Reservations {
  356. for _, instance := range reservation.Instances {
  357. for _, mapping := range instance.BlockDeviceMappings {
  358. result = append(result, suggestData{Text: *mapping.Ebs.VolumeId, Value: *mapping.Ebs.VolumeId})
  359. }
  360. }
  361. }
  362. return result, nil
  363. }
  364. func (e *CloudWatchExecutor) handleGetEc2InstanceAttribute(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  365. region := parameters.Get("region").MustString()
  366. attributeName := parameters.Get("attributeName").MustString()
  367. filterJson := parameters.Get("filters").MustMap()
  368. var filters []*ec2.Filter
  369. for k, v := range filterJson {
  370. if vv, ok := v.([]interface{}); ok {
  371. var vvvvv []*string
  372. for _, vvv := range vv {
  373. if vvvv, ok := vvv.(string); ok {
  374. vvvvv = append(vvvvv, &vvvv)
  375. }
  376. }
  377. filters = append(filters, &ec2.Filter{
  378. Name: aws.String(k),
  379. Values: vvvvv,
  380. })
  381. }
  382. }
  383. err := e.ensureClientSession(region)
  384. if err != nil {
  385. return nil, err
  386. }
  387. instances, err := e.ec2DescribeInstances(region, filters, nil)
  388. if err != nil {
  389. return nil, err
  390. }
  391. result := make([]suggestData, 0)
  392. dupCheck := make(map[string]bool)
  393. for _, reservation := range instances.Reservations {
  394. for _, instance := range reservation.Instances {
  395. tags := make(map[string]string)
  396. for _, tag := range instance.Tags {
  397. tags[*tag.Key] = *tag.Value
  398. }
  399. var data string
  400. if strings.Index(attributeName, "Tags.") == 0 {
  401. tagName := attributeName[5:]
  402. data = tags[tagName]
  403. } else {
  404. attributePath := strings.Split(attributeName, ".")
  405. v := reflect.ValueOf(instance)
  406. for _, key := range attributePath {
  407. if v.Kind() == reflect.Ptr {
  408. v = v.Elem()
  409. }
  410. if v.Kind() != reflect.Struct {
  411. return nil, errors.New("invalid attribute path")
  412. }
  413. v = v.FieldByName(key)
  414. }
  415. if attr, ok := v.Interface().(*string); ok {
  416. data = *attr
  417. } else {
  418. return nil, errors.New("invalid attribute path")
  419. }
  420. }
  421. if _, exists := dupCheck[data]; exists {
  422. continue
  423. }
  424. dupCheck[data] = true
  425. result = append(result, suggestData{Text: data, Value: data})
  426. }
  427. }
  428. sort.Slice(result, func(i, j int) bool {
  429. return result[i].Text < result[j].Text
  430. })
  431. return result, nil
  432. }
  433. func (e *CloudWatchExecutor) cloudwatchListMetrics(region string, namespace string, metricName string, dimensions []*cloudwatch.DimensionFilter) (*cloudwatch.ListMetricsOutput, error) {
  434. svc, err := e.getClient(region)
  435. if err != nil {
  436. return nil, err
  437. }
  438. params := &cloudwatch.ListMetricsInput{
  439. Namespace: aws.String(namespace),
  440. MetricName: aws.String(metricName),
  441. Dimensions: dimensions,
  442. }
  443. var resp cloudwatch.ListMetricsOutput
  444. err = svc.ListMetricsPages(params,
  445. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  446. metrics.M_Aws_CloudWatch_ListMetrics.Inc()
  447. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  448. for _, metric := range metrics {
  449. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  450. }
  451. return !lastPage
  452. })
  453. if err != nil {
  454. return nil, fmt.Errorf("Failed to call cloudwatch:ListMetrics, %v", err)
  455. }
  456. return &resp, nil
  457. }
  458. func (e *CloudWatchExecutor) ec2DescribeInstances(region string, filters []*ec2.Filter, instanceIds []*string) (*ec2.DescribeInstancesOutput, error) {
  459. params := &ec2.DescribeInstancesInput{
  460. Filters: filters,
  461. InstanceIds: instanceIds,
  462. }
  463. var resp ec2.DescribeInstancesOutput
  464. err := e.ec2Svc.DescribeInstancesPages(params,
  465. func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
  466. reservations, _ := awsutil.ValuesAtPath(page, "Reservations")
  467. for _, reservation := range reservations {
  468. resp.Reservations = append(resp.Reservations, reservation.(*ec2.Reservation))
  469. }
  470. return !lastPage
  471. })
  472. if err != nil {
  473. return nil, errors.New("Failed to call ec2:DescribeInstances")
  474. }
  475. return &resp, nil
  476. }
  477. func getAllMetrics(cwData *DatasourceInfo) (cloudwatch.ListMetricsOutput, error) {
  478. creds, err := GetCredentials(cwData)
  479. if err != nil {
  480. return cloudwatch.ListMetricsOutput{}, err
  481. }
  482. cfg := &aws.Config{
  483. Region: aws.String(cwData.Region),
  484. Credentials: creds,
  485. }
  486. sess, err := session.NewSession(cfg)
  487. if err != nil {
  488. return cloudwatch.ListMetricsOutput{}, err
  489. }
  490. svc := cloudwatch.New(sess, cfg)
  491. params := &cloudwatch.ListMetricsInput{
  492. Namespace: aws.String(cwData.Namespace),
  493. }
  494. var resp cloudwatch.ListMetricsOutput
  495. err = svc.ListMetricsPages(params,
  496. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  497. metrics.M_Aws_CloudWatch_ListMetrics.Inc()
  498. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  499. for _, metric := range metrics {
  500. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  501. }
  502. return !lastPage
  503. })
  504. return resp, err
  505. }
  506. var metricsCacheLock sync.Mutex
  507. func getMetricsForCustomMetrics(dsInfo *DatasourceInfo, getAllMetrics func(*DatasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  508. metricsCacheLock.Lock()
  509. defer metricsCacheLock.Unlock()
  510. if _, ok := customMetricsMetricsMap[dsInfo.Profile]; !ok {
  511. customMetricsMetricsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  512. }
  513. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  514. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  515. }
  516. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  517. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  518. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  519. }
  520. if customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  521. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  522. }
  523. result, err := getAllMetrics(dsInfo)
  524. if err != nil {
  525. return []string{}, err
  526. }
  527. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  528. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  529. for _, metric := range result.Metrics {
  530. if isDuplicate(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName) {
  531. continue
  532. }
  533. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName)
  534. }
  535. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  536. }
  537. var dimensionsCacheLock sync.Mutex
  538. func getDimensionsForCustomMetrics(dsInfo *DatasourceInfo, getAllMetrics func(*DatasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  539. dimensionsCacheLock.Lock()
  540. defer dimensionsCacheLock.Unlock()
  541. if _, ok := customMetricsDimensionsMap[dsInfo.Profile]; !ok {
  542. customMetricsDimensionsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  543. }
  544. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  545. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  546. }
  547. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  548. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  549. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  550. }
  551. if customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  552. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  553. }
  554. result, err := getAllMetrics(dsInfo)
  555. if err != nil {
  556. return []string{}, err
  557. }
  558. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  559. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  560. for _, metric := range result.Metrics {
  561. for _, dimension := range metric.Dimensions {
  562. if isDuplicate(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name) {
  563. continue
  564. }
  565. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name)
  566. }
  567. }
  568. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  569. }
  570. func isDuplicate(nameList []string, target string) bool {
  571. for _, name := range nameList {
  572. if name == target {
  573. return true
  574. }
  575. }
  576. return false
  577. }
  578. func isCustomMetrics(namespace string) bool {
  579. return strings.Index(namespace, "AWS/") != 0
  580. }