metric_find_query.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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. region := parameters.Get("region").MustString()
  182. dsInfo := e.getDsInfo(region)
  183. cfg, err := e.getAwsConfig(dsInfo)
  184. if err != nil {
  185. return nil, fmt.Errorf("Failed to call ec2:DescribeInstances, %v", err)
  186. }
  187. sess, err := session.NewSession(cfg)
  188. if err != nil {
  189. return nil, fmt.Errorf("Failed to call ec2:DescribeInstances, %v", err)
  190. }
  191. e.ec2Svc = ec2.New(sess, cfg)
  192. data, err = e.handleGetEc2InstanceAttribute(ctx, parameters, queryContext)
  193. break
  194. }
  195. transformToTable(data, queryResult)
  196. result.Results[firstQuery.RefId] = queryResult
  197. return result, err
  198. }
  199. func transformToTable(data []suggestData, result *tsdb.QueryResult) {
  200. table := &tsdb.Table{
  201. Columns: make([]tsdb.TableColumn, 2),
  202. Rows: make([]tsdb.RowValues, 0),
  203. }
  204. table.Columns[0].Text = "text"
  205. table.Columns[1].Text = "value"
  206. for _, r := range data {
  207. values := make([]interface{}, 2)
  208. values[0] = r.Text
  209. values[1] = r.Value
  210. table.Rows = append(table.Rows, values)
  211. }
  212. result.Tables = append(result.Tables, table)
  213. result.Meta.Set("rowCount", len(data))
  214. }
  215. // Whenever this list is updated, frontend list should also be updated.
  216. // Please update the region list in public/app/plugins/datasource/cloudwatch/partials/config.html
  217. func (e *CloudWatchExecutor) handleGetRegions(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  218. regions := []string{
  219. "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "ap-south-1", "ca-central-1", "cn-north-1",
  220. "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",
  221. }
  222. result := make([]suggestData, 0)
  223. for _, region := range regions {
  224. result = append(result, suggestData{Text: region, Value: region})
  225. }
  226. return result, nil
  227. }
  228. func (e *CloudWatchExecutor) handleGetNamespaces(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  229. keys := []string{}
  230. for key := range metricsMap {
  231. keys = append(keys, key)
  232. }
  233. customNamespaces := e.DataSource.JsonData.Get("customMetricsNamespaces").MustString()
  234. if customNamespaces != "" {
  235. keys = append(keys, strings.Split(customNamespaces, ",")...)
  236. }
  237. sort.Sort(sort.StringSlice(keys))
  238. result := make([]suggestData, 0)
  239. for _, key := range keys {
  240. result = append(result, suggestData{Text: key, Value: key})
  241. }
  242. return result, nil
  243. }
  244. func (e *CloudWatchExecutor) handleGetMetrics(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  245. region := parameters.Get("region").MustString()
  246. namespace := parameters.Get("namespace").MustString()
  247. var namespaceMetrics []string
  248. if !isCustomMetrics(namespace) {
  249. var exists bool
  250. if namespaceMetrics, exists = metricsMap[namespace]; !exists {
  251. return nil, errors.New("Unable to find namespace " + namespace)
  252. }
  253. } else {
  254. var err error
  255. dsInfo := e.getDsInfo(region)
  256. dsInfo.Namespace = namespace
  257. if namespaceMetrics, err = getMetricsForCustomMetrics(dsInfo, getAllMetrics); err != nil {
  258. return nil, errors.New("Unable to call AWS API")
  259. }
  260. }
  261. sort.Sort(sort.StringSlice(namespaceMetrics))
  262. result := make([]suggestData, 0)
  263. for _, name := range namespaceMetrics {
  264. result = append(result, suggestData{Text: name, Value: name})
  265. }
  266. return result, nil
  267. }
  268. func (e *CloudWatchExecutor) handleGetDimensions(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  269. region := parameters.Get("region").MustString()
  270. namespace := parameters.Get("namespace").MustString()
  271. var dimensionValues []string
  272. if !isCustomMetrics(namespace) {
  273. var exists bool
  274. if dimensionValues, exists = dimensionsMap[namespace]; !exists {
  275. return nil, errors.New("Unable to find dimension " + namespace)
  276. }
  277. } else {
  278. var err error
  279. dsInfo := e.getDsInfo(region)
  280. dsInfo.Namespace = namespace
  281. if dimensionValues, err = getDimensionsForCustomMetrics(dsInfo, getAllMetrics); err != nil {
  282. return nil, errors.New("Unable to call AWS API")
  283. }
  284. }
  285. sort.Sort(sort.StringSlice(dimensionValues))
  286. result := make([]suggestData, 0)
  287. for _, name := range dimensionValues {
  288. result = append(result, suggestData{Text: name, Value: name})
  289. }
  290. return result, nil
  291. }
  292. func (e *CloudWatchExecutor) handleGetDimensionValues(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  293. region := parameters.Get("region").MustString()
  294. namespace := parameters.Get("namespace").MustString()
  295. metricName := parameters.Get("metricName").MustString()
  296. dimensionKey := parameters.Get("dimensionKey").MustString()
  297. dimensionsJson := parameters.Get("dimensions").MustMap()
  298. var dimensions []*cloudwatch.DimensionFilter
  299. for k, v := range dimensionsJson {
  300. if vv, ok := v.(string); ok {
  301. dimensions = append(dimensions, &cloudwatch.DimensionFilter{
  302. Name: aws.String(k),
  303. Value: aws.String(vv),
  304. })
  305. }
  306. }
  307. metrics, err := e.cloudwatchListMetrics(region, namespace, metricName, dimensions)
  308. if err != nil {
  309. return nil, err
  310. }
  311. result := make([]suggestData, 0)
  312. dupCheck := make(map[string]bool)
  313. for _, metric := range metrics.Metrics {
  314. for _, dim := range metric.Dimensions {
  315. if *dim.Name == dimensionKey {
  316. if _, exists := dupCheck[*dim.Value]; exists {
  317. continue
  318. }
  319. dupCheck[*dim.Value] = true
  320. result = append(result, suggestData{Text: *dim.Value, Value: *dim.Value})
  321. }
  322. }
  323. }
  324. sort.Slice(result, func(i, j int) bool {
  325. return result[i].Text < result[j].Text
  326. })
  327. return result, nil
  328. }
  329. func (e *CloudWatchExecutor) handleGetEbsVolumeIds(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  330. region := parameters.Get("region").MustString()
  331. instanceId := parameters.Get("instanceId").MustString()
  332. instanceIds := []*string{aws.String(instanceId)}
  333. instances, err := e.ec2DescribeInstances(region, nil, instanceIds)
  334. if err != nil {
  335. return nil, err
  336. }
  337. result := make([]suggestData, 0)
  338. for _, mapping := range instances.Reservations[0].Instances[0].BlockDeviceMappings {
  339. result = append(result, suggestData{Text: *mapping.Ebs.VolumeId, Value: *mapping.Ebs.VolumeId})
  340. }
  341. return result, nil
  342. }
  343. func (e *CloudWatchExecutor) handleGetEc2InstanceAttribute(ctx context.Context, parameters *simplejson.Json, queryContext *tsdb.TsdbQuery) ([]suggestData, error) {
  344. region := parameters.Get("region").MustString()
  345. attributeName := parameters.Get("attributeName").MustString()
  346. filterJson := parameters.Get("filters").MustMap()
  347. var filters []*ec2.Filter
  348. for k, v := range filterJson {
  349. if vv, ok := v.([]interface{}); ok {
  350. var vvvvv []*string
  351. for _, vvv := range vv {
  352. if vvvv, ok := vvv.(string); ok {
  353. vvvvv = append(vvvvv, &vvvv)
  354. }
  355. }
  356. filters = append(filters, &ec2.Filter{
  357. Name: aws.String(k),
  358. Values: vvvvv,
  359. })
  360. }
  361. }
  362. instances, err := e.ec2DescribeInstances(region, filters, nil)
  363. if err != nil {
  364. return nil, err
  365. }
  366. result := make([]suggestData, 0)
  367. dupCheck := make(map[string]bool)
  368. for _, reservation := range instances.Reservations {
  369. for _, instance := range reservation.Instances {
  370. tags := make(map[string]string)
  371. for _, tag := range instance.Tags {
  372. tags[*tag.Key] = *tag.Value
  373. }
  374. var data string
  375. if strings.Index(attributeName, "Tags.") == 0 {
  376. tagName := attributeName[5:]
  377. data = tags[tagName]
  378. } else {
  379. attributePath := strings.Split(attributeName, ".")
  380. v := reflect.ValueOf(instance)
  381. for _, key := range attributePath {
  382. if v.Kind() == reflect.Ptr {
  383. v = v.Elem()
  384. }
  385. if v.Kind() != reflect.Struct {
  386. return nil, errors.New("invalid attribute path")
  387. }
  388. v = v.FieldByName(key)
  389. }
  390. if attr, ok := v.Interface().(*string); ok {
  391. data = *attr
  392. } else {
  393. return nil, errors.New("invalid attribute path")
  394. }
  395. }
  396. if _, exists := dupCheck[data]; exists {
  397. continue
  398. }
  399. dupCheck[data] = true
  400. result = append(result, suggestData{Text: data, Value: data})
  401. }
  402. }
  403. sort.Slice(result, func(i, j int) bool {
  404. return result[i].Text < result[j].Text
  405. })
  406. return result, nil
  407. }
  408. func (e *CloudWatchExecutor) cloudwatchListMetrics(region string, namespace string, metricName string, dimensions []*cloudwatch.DimensionFilter) (*cloudwatch.ListMetricsOutput, error) {
  409. svc, err := e.getClient(region)
  410. if err != nil {
  411. return nil, err
  412. }
  413. params := &cloudwatch.ListMetricsInput{
  414. Namespace: aws.String(namespace),
  415. MetricName: aws.String(metricName),
  416. Dimensions: dimensions,
  417. }
  418. var resp cloudwatch.ListMetricsOutput
  419. err = svc.ListMetricsPages(params,
  420. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  421. metrics.M_Aws_CloudWatch_ListMetrics.Inc()
  422. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  423. for _, metric := range metrics {
  424. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  425. }
  426. return !lastPage
  427. })
  428. if err != nil {
  429. return nil, fmt.Errorf("Failed to call cloudwatch:ListMetrics, %v", err)
  430. }
  431. return &resp, nil
  432. }
  433. func (e *CloudWatchExecutor) ec2DescribeInstances(region string, filters []*ec2.Filter, instanceIds []*string) (*ec2.DescribeInstancesOutput, error) {
  434. params := &ec2.DescribeInstancesInput{
  435. Filters: filters,
  436. InstanceIds: instanceIds,
  437. }
  438. var resp ec2.DescribeInstancesOutput
  439. err := e.ec2Svc.DescribeInstancesPages(params,
  440. func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
  441. reservations, _ := awsutil.ValuesAtPath(page, "Reservations")
  442. for _, reservation := range reservations {
  443. resp.Reservations = append(resp.Reservations, reservation.(*ec2.Reservation))
  444. }
  445. return !lastPage
  446. })
  447. if err != nil {
  448. return nil, errors.New("Failed to call ec2:DescribeInstances")
  449. }
  450. return &resp, nil
  451. }
  452. func getAllMetrics(cwData *DatasourceInfo) (cloudwatch.ListMetricsOutput, error) {
  453. creds, err := GetCredentials(cwData)
  454. if err != nil {
  455. return cloudwatch.ListMetricsOutput{}, err
  456. }
  457. cfg := &aws.Config{
  458. Region: aws.String(cwData.Region),
  459. Credentials: creds,
  460. }
  461. sess, err := session.NewSession(cfg)
  462. if err != nil {
  463. return cloudwatch.ListMetricsOutput{}, err
  464. }
  465. svc := cloudwatch.New(sess, cfg)
  466. params := &cloudwatch.ListMetricsInput{
  467. Namespace: aws.String(cwData.Namespace),
  468. }
  469. var resp cloudwatch.ListMetricsOutput
  470. err = svc.ListMetricsPages(params,
  471. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  472. metrics.M_Aws_CloudWatch_ListMetrics.Inc()
  473. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  474. for _, metric := range metrics {
  475. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  476. }
  477. return !lastPage
  478. })
  479. if err != nil {
  480. return resp, err
  481. }
  482. return resp, nil
  483. }
  484. var metricsCacheLock sync.Mutex
  485. func getMetricsForCustomMetrics(dsInfo *DatasourceInfo, getAllMetrics func(*DatasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  486. metricsCacheLock.Lock()
  487. defer metricsCacheLock.Unlock()
  488. if _, ok := customMetricsMetricsMap[dsInfo.Profile]; !ok {
  489. customMetricsMetricsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  490. }
  491. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  492. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  493. }
  494. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  495. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  496. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  497. }
  498. if customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  499. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  500. }
  501. result, err := getAllMetrics(dsInfo)
  502. if err != nil {
  503. return []string{}, err
  504. }
  505. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  506. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  507. for _, metric := range result.Metrics {
  508. if isDuplicate(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName) {
  509. continue
  510. }
  511. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName)
  512. }
  513. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  514. }
  515. var dimensionsCacheLock sync.Mutex
  516. func getDimensionsForCustomMetrics(dsInfo *DatasourceInfo, getAllMetrics func(*DatasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  517. dimensionsCacheLock.Lock()
  518. defer dimensionsCacheLock.Unlock()
  519. if _, ok := customMetricsDimensionsMap[dsInfo.Profile]; !ok {
  520. customMetricsDimensionsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  521. }
  522. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  523. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  524. }
  525. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  526. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  527. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  528. }
  529. if customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  530. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  531. }
  532. result, err := getAllMetrics(dsInfo)
  533. if err != nil {
  534. return []string{}, err
  535. }
  536. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  537. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  538. for _, metric := range result.Metrics {
  539. for _, dimension := range metric.Dimensions {
  540. if isDuplicate(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name) {
  541. continue
  542. }
  543. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name)
  544. }
  545. }
  546. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  547. }
  548. func isDuplicate(nameList []string, target string) bool {
  549. for _, name := range nameList {
  550. if name == target {
  551. return true
  552. }
  553. }
  554. return false
  555. }
  556. func isCustomMetrics(namespace string) bool {
  557. return strings.Index(namespace, "AWS/") != 0
  558. }