metric_find_query.go 32 KB

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