metric_find_query.go 33 KB

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