metrics.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package cloudwatch
  2. import (
  3. "encoding/json"
  4. "sort"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/aws/aws-sdk-go/aws"
  9. "github.com/aws/aws-sdk-go/aws/awsutil"
  10. "github.com/aws/aws-sdk-go/aws/session"
  11. "github.com/aws/aws-sdk-go/service/cloudwatch"
  12. "github.com/grafana/grafana/pkg/metrics"
  13. "github.com/grafana/grafana/pkg/middleware"
  14. "github.com/grafana/grafana/pkg/util"
  15. )
  16. var metricsMap map[string][]string
  17. var dimensionsMap map[string][]string
  18. type CustomMetricsCache struct {
  19. Expire time.Time
  20. Cache []string
  21. }
  22. var customMetricsMetricsMap map[string]map[string]map[string]*CustomMetricsCache
  23. var customMetricsDimensionsMap map[string]map[string]map[string]*CustomMetricsCache
  24. func init() {
  25. metricsMap = map[string][]string{
  26. "AWS/ApiGateway": {"4XXError", "5XXError", "CacheHitCount", "CacheMissCount", "Count", "IntegrationLatency", "Latency"},
  27. "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", "NewConnectionCount", "ProcessedBytes", "RejectedConnectionCount", "RequestCount", "TargetConnectionErrorCount", "TargetResponseTime", "TargetTLSNegotiationErrorCount", "UnHealthyHostCount"},
  28. "AWS/AutoScaling": {"GroupMinSize", "GroupMaxSize", "GroupDesiredCapacity", "GroupInServiceInstances", "GroupPendingInstances", "GroupStandbyInstances", "GroupTerminatingInstances", "GroupTotalInstances"},
  29. "AWS/Billing": {"EstimatedCharges"},
  30. "AWS/CloudFront": {"Requests", "BytesDownloaded", "BytesUploaded", "TotalErrorRate", "4xxErrorRate", "5xxErrorRate"},
  31. "AWS/CloudSearch": {"SuccessfulRequests", "SearchableDocuments", "IndexUtilization", "Partitions"},
  32. "AWS/DynamoDB": {"ConditionalCheckFailedRequests", "ConsumedReadCapacityUnits", "ConsumedWriteCapacityUnits", "OnlineIndexConsumedWriteCapacity", "OnlineIndexPercentageProgress", "OnlineIndexThrottleEvents", "ProvisionedReadCapacityUnits", "ProvisionedWriteCapacityUnits", "ReadThrottleEvents", "ReturnedBytes", "ReturnedItemCount", "ReturnedRecordsCount", "SuccessfulRequestLatency", "SystemErrors", "ThrottledRequests", "UserErrors", "WriteThrottleEvents"},
  33. "AWS/EBS": {"VolumeReadBytes", "VolumeWriteBytes", "VolumeReadOps", "VolumeWriteOps", "VolumeTotalReadTime", "VolumeTotalWriteTime", "VolumeIdleTime", "VolumeQueueLength", "VolumeThroughputPercentage", "VolumeConsumedReadWriteOps", "BurstBalance"},
  34. "AWS/EC2": {"CPUCreditUsage", "CPUCreditBalance", "CPUUtilization", "DiskReadOps", "DiskWriteOps", "DiskReadBytes", "DiskWriteBytes", "NetworkIn", "NetworkOut", "NetworkPacketsIn", "NetworkPacketsOut", "StatusCheckFailed", "StatusCheckFailed_Instance", "StatusCheckFailed_System"},
  35. "AWS/EC2Spot": {"AvailableInstancePoolsCount", "BidsSubmittedForCapacity", "EligibleInstancePoolCount", "FulfilledCapacity", "MaxPercentCapacityAllocation", "PendingCapacity", "PercentCapacityAllocation", "TargetCapacity", "TerminatingCapacity"},
  36. "AWS/ECS": {"CPUReservation", "MemoryReservation", "CPUUtilization", "MemoryUtilization"},
  37. "AWS/EFS": {"BurstCreditBalance", "ClientConnections", "DataReadIOBytes", "DataWriteIOBytes", "MetadataIOBytes", "TotalIOBytes", "PermittedThroughput", "PercentIOLimit"},
  38. "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"},
  39. "AWS/ElastiCache": {
  40. "CPUUtilization", "FreeableMemory", "NetworkBytesIn", "NetworkBytesOut", "SwapUsage",
  41. "BytesUsedForCacheItems", "BytesReadIntoMemcached", "BytesWrittenOutFromMemcached", "CasBadval", "CasHits", "CasMisses", "CmdFlush", "CmdGet", "CmdSet", "CurrConnections", "CurrItems", "DecrHits", "DecrMisses", "DeleteHits", "DeleteMisses", "Evictions", "GetHits", "GetMisses", "IncrHits", "IncrMisses", "Reclaimed",
  42. "BytesUsedForHash", "CmdConfigGet", "CmdConfigSet", "CmdTouch", "CurrConfig", "EvictedUnfetched", "ExpiredUnfetched", "SlabsMoved", "TouchHits", "TouchMisses",
  43. "NewConnections", "NewItems", "UnusedMemory",
  44. "BytesUsedForCache", "CacheHits", "CacheMisses", "CurrConnections", "Evictions", "HyperLogLogBasedCmds", "NewConnections", "Reclaimed", "ReplicationBytes", "ReplicationLag", "SaveInProgress",
  45. "CurrItems", "GetTypeCmds", "HashBasedCmds", "KeyBasedCmds", "ListBasedCmds", "SetBasedCmds", "SetTypeCmds", "SortedSetBasedCmds", "StringBasedCmds",
  46. },
  47. "AWS/ElasticBeanstalk": {
  48. "EnvironmentHealth",
  49. "ApplicationLatencyP10", "ApplicationLatencyP50", "ApplicationLatencyP75", "ApplicationLatencyP85", "ApplicationLatencyP90", "ApplicationLatencyP95", "ApplicationLatencyP99", "ApplicationLatencyP99.9",
  50. "ApplicationRequests2xx", "ApplicationRequests3xx", "ApplicationRequests4xx", "ApplicationRequests5xx", "ApplicationRequestsTotal",
  51. "CPUIdle", "CPUIowait", "CPUIrq", "CPUNice", "CPUSoftirq", "CPUSystem", "CPUUser",
  52. "InstanceHealth", "InstancesDegraded", "InstancesInfo", "InstancesNoData", "InstancesOk", "InstancesPending", "InstancesSevere", "InstancesUnknown", "InstancesWarning",
  53. "LoadAverage1min", "LoadAverage5min",
  54. "RootFilesystemUtil",
  55. },
  56. "AWS/ElasticMapReduce": {"IsIdle", "JobsRunning", "JobsFailed",
  57. "MapTasksRunning", "MapTasksRemaining", "MapSlotsOpen", "RemainingMapTasksPerSlot", "ReduceTasksRunning", "ReduceTasksRemaining", "ReduceSlotsOpen",
  58. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "TaskNodesRunning", "TaskNodesPending", "LiveTaskTrackers",
  59. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "TotalLoad",
  60. "BackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup",
  61. "IsIdle", "ContainerAllocated", "ContainerReserved", "ContainerPending", "AppsCompleted", "AppsFailed", "AppsKilled", "AppsPending", "AppsRunning", "AppsSubmitted",
  62. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "MRTotalNodes", "MRActiveNodes", "MRLostNodes", "MRUnhealthyNodes", "MRDecommissionedNodes", "MRRebootedNodes",
  63. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "CorruptBlocks", "TotalLoad", "MemoryTotalMB", "MemoryReservedMB", "MemoryAvailableMB", "MemoryAllocatedMB", "PendingDeletionBlocks", "UnderReplicatedBlocks", "DfsPendingReplicationBlocks", "CapacityRemainingGB",
  64. "HbaseBackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup"},
  65. "AWS/ES": {"ClusterStatus.green", "ClusterStatus.yellow", "ClusterStatus.red", "Nodes", "SearchableDocuments", "DeletedDocuments", "CPUUtilization", "FreeStorageSpace", "JVMMemoryPressure", "AutomatedSnapshotFailure", "MasterCPUUtilization", "MasterFreeStorageSpace", "MasterJVMMemoryPressure", "ReadLatency", "WriteLatency", "ReadThroughput", "WriteThroughput", "DiskQueueLength", "ReadIOPS", "WriteIOPS"},
  66. "AWS/Events": {"Invocations", "FailedInvocations", "TriggeredRules", "MatchedEvents", "ThrottledRules"},
  67. "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"},
  68. "AWS/IoT": {"PublishIn.Success", "PublishOut.Success", "Subscribe.Success", "Ping.Success", "Connect.Success", "GetThingShadow.Accepted"},
  69. "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"},
  70. "AWS/KinesisAnalytics": {"Bytes", "MillisBehindLatest", "Records", "Success"},
  71. "AWS/Lambda": {"Invocations", "Errors", "Duration", "Throttles"},
  72. "AWS/Logs": {"IncomingBytes", "IncomingLogEvents", "ForwardedBytes", "ForwardedLogEvents", "DeliveryErrors", "DeliveryThrottling"},
  73. "AWS/ML": {"PredictCount", "PredictFailureCount"},
  74. "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"},
  75. "AWS/Redshift": {"CPUUtilization", "DatabaseConnections", "HealthStatus", "MaintenanceMode", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "PercentageDiskSpaceUsed", "ReadIOPS", "ReadLatency", "ReadThroughput", "WriteIOPS", "WriteLatency", "WriteThroughput"},
  76. "AWS/RDS": {"ActiveTransactions", "AuroraBinlogReplicaLag", "AuroraReplicaLag", "AuroraReplicaLagMaximum", "AuroraReplicaLagMinimum", "BinLogDiskUsage", "BlockedTransactions", "BufferCacheHitRatio", "CommitLatency", "CommitThroughput", "CPUCreditBalance", "CPUCreditUsage", "CPUUtilization", "DatabaseConnections", "DDLLatency", "DDLThroughput", "Deadlocks", "DiskQueueDepth", "DMLLatency", "DMLThroughput", "FailedSqlStatements", "FreeableMemory", "FreeStorageSpace", "LoginFailures", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "ReadIOPS", "ReadLatency", "ReadThroughput", "ReplicaLag", "ResultSetCacheHitRatio", "SelectLatency", "SelectThroughput", "SwapUsage", "TotalConnections", "VolumeReadIOPS", "VolumeWriteIOPS", "WriteIOPS", "WriteLatency", "WriteThroughput"},
  77. "AWS/Route53": {"HealthCheckStatus", "HealthCheckPercentageHealthy", "ConnectionTime", "SSLHandshakeTime", "TimeToFirstByte"},
  78. "AWS/S3": {"BucketSizeBytes", "NumberOfObjects"},
  79. "AWS/SNS": {"NumberOfMessagesPublished", "PublishSize", "NumberOfNotificationsDelivered", "NumberOfNotificationsFailed"},
  80. "AWS/SQS": {"NumberOfMessagesSent", "SentMessageSize", "NumberOfMessagesReceived", "NumberOfEmptyReceives", "NumberOfMessagesDeleted", "ApproximateNumberOfMessagesDelayed", "ApproximateNumberOfMessagesVisible", "ApproximateNumberOfMessagesNotVisible"},
  81. "AWS/StorageGateway": {"CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "CloudBytesDownloaded", "CloudDownloadLatency", "CloudBytesUploaded", "UploadBufferFree", "UploadBufferPercentUsed", "UploadBufferUsed", "QueuedWrites", "ReadBytes", "ReadTime", "TotalCacheSize", "WriteBytes", "WriteTime", "TimeSinceLastRecoveryPoint", "WorkingStorageFree", "WorkingStoragePercentUsed", "WorkingStorageUsed",
  82. "CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "ReadBytes", "ReadTime", "WriteBytes", "WriteTime", "QueuedWrites"},
  83. "AWS/SWF": {"DecisionTaskScheduleToStartTime", "DecisionTaskStartToCloseTime", "DecisionTasksCompleted", "StartedDecisionTasksTimedOutOnClose", "WorkflowStartToCloseTime", "WorkflowsCanceled", "WorkflowsCompleted", "WorkflowsContinuedAsNew", "WorkflowsFailed", "WorkflowsTerminated", "WorkflowsTimedOut",
  84. "ActivityTaskScheduleToCloseTime", "ActivityTaskScheduleToStartTime", "ActivityTaskStartToCloseTime", "ActivityTasksCanceled", "ActivityTasksCompleted", "ActivityTasksFailed", "ScheduledActivityTasksTimedOutOnClose", "ScheduledActivityTasksTimedOutOnStart", "StartedActivityTasksTimedOutOnClose", "StartedActivityTasksTimedOutOnHeartbeat"},
  85. "AWS/WAF": {"AllowedRequests", "BlockedRequests", "CountedRequests"},
  86. "AWS/WorkSpaces": {"Available", "Unhealthy", "ConnectionAttempt", "ConnectionSuccess", "ConnectionFailure", "SessionLaunchTime", "InSessionLatency", "SessionDisconnect"},
  87. "KMS": {"SecondsUntilKeyMaterialExpiration"},
  88. }
  89. dimensionsMap = map[string][]string{
  90. "AWS/ApiGateway": {"ApiName", "Method", "Resource", "Stage"},
  91. "AWS/ApplicationELB": {"LoadBalancer", "TargetGroup", "AvailabilityZone"},
  92. "AWS/AutoScaling": {"AutoScalingGroupName"},
  93. "AWS/Billing": {"ServiceName", "LinkedAccount", "Currency"},
  94. "AWS/CloudFront": {"DistributionId", "Region"},
  95. "AWS/CloudSearch": {},
  96. "AWS/DynamoDB": {"TableName", "GlobalSecondaryIndexName", "Operation", "StreamLabel"},
  97. "AWS/EBS": {"VolumeId"},
  98. "AWS/EC2": {"AutoScalingGroupName", "ImageId", "InstanceId", "InstanceType"},
  99. "AWS/EC2Spot": {"AvailabilityZone", "FleetRequestId", "InstanceType"},
  100. "AWS/ECS": {"ClusterName", "ServiceName"},
  101. "AWS/EFS": {"FileSystemId"},
  102. "AWS/ELB": {"LoadBalancerName", "AvailabilityZone"},
  103. "AWS/ElastiCache": {"CacheClusterId", "CacheNodeId"},
  104. "AWS/ElasticBeanstalk": {"EnvironmentName", "InstanceId"},
  105. "AWS/ElasticMapReduce": {"ClusterId", "JobFlowId", "JobId"},
  106. "AWS/ES": {"ClientId", "DomainName"},
  107. "AWS/Events": {"RuleName"},
  108. "AWS/Firehose": {"DeliveryStreamName"},
  109. "AWS/IoT": {"Protocol"},
  110. "AWS/Kinesis": {"StreamName", "ShardID"},
  111. "AWS/KinesisAnalytics": {"Flow", "Id", "Application"},
  112. "AWS/Lambda": {"FunctionName", "Resource", "Version", "Alias"},
  113. "AWS/Logs": {"LogGroupName", "DestinationType", "FilterName"},
  114. "AWS/ML": {"MLModelId", "RequestMode"},
  115. "AWS/OpsWorks": {"StackId", "LayerId", "InstanceId"},
  116. "AWS/Redshift": {"NodeID", "ClusterIdentifier"},
  117. "AWS/RDS": {"DBInstanceIdentifier", "DBClusterIdentifier", "DatabaseClass", "EngineName"},
  118. "AWS/Route53": {"HealthCheckId"},
  119. "AWS/S3": {"BucketName", "StorageType"},
  120. "AWS/SNS": {"Application", "Platform", "TopicName"},
  121. "AWS/SQS": {"QueueName"},
  122. "AWS/StorageGateway": {"GatewayId", "GatewayName", "VolumeId"},
  123. "AWS/SWF": {"Domain", "WorkflowTypeName", "WorkflowTypeVersion", "ActivityTypeName", "ActivityTypeVersion"},
  124. "AWS/WAF": {"Rule", "WebACL"},
  125. "AWS/WorkSpaces": {"DirectoryId", "WorkspaceId"},
  126. "KMS": {"KeyId"},
  127. }
  128. customMetricsMetricsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  129. customMetricsDimensionsMap = make(map[string]map[string]map[string]*CustomMetricsCache)
  130. }
  131. // Whenever this list is updated, frontend list should also be updated.
  132. // Please update the region list in public/app/plugins/datasource/cloudwatch/partials/config.html
  133. func handleGetRegions(req *cwRequest, c *middleware.Context) {
  134. regions := []string{
  135. "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "ap-south-1", "ca-central-1", "cn-north-1",
  136. "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",
  137. }
  138. result := []interface{}{}
  139. for _, region := range regions {
  140. result = append(result, util.DynMap{"text": region, "value": region})
  141. }
  142. c.JSON(200, result)
  143. }
  144. func handleGetNamespaces(req *cwRequest, c *middleware.Context) {
  145. keys := []string{}
  146. for key := range metricsMap {
  147. keys = append(keys, key)
  148. }
  149. customNamespaces := req.DataSource.JsonData.Get("customMetricsNamespaces").MustString()
  150. if customNamespaces != "" {
  151. for _, key := range strings.Split(customNamespaces, ",") {
  152. keys = append(keys, key)
  153. }
  154. }
  155. sort.Sort(sort.StringSlice(keys))
  156. result := []interface{}{}
  157. for _, key := range keys {
  158. result = append(result, util.DynMap{"text": key, "value": key})
  159. }
  160. c.JSON(200, result)
  161. }
  162. func handleGetMetrics(req *cwRequest, c *middleware.Context) {
  163. reqParam := &struct {
  164. Parameters struct {
  165. Namespace string `json:"namespace"`
  166. } `json:"parameters"`
  167. }{}
  168. json.Unmarshal(req.Body, reqParam)
  169. var namespaceMetrics []string
  170. if !isCustomMetrics(reqParam.Parameters.Namespace) {
  171. var exists bool
  172. if namespaceMetrics, exists = metricsMap[reqParam.Parameters.Namespace]; !exists {
  173. c.JsonApiErr(404, "Unable to find namespace "+reqParam.Parameters.Namespace, nil)
  174. return
  175. }
  176. } else {
  177. var err error
  178. cwData := req.GetDatasourceInfo()
  179. cwData.Namespace = reqParam.Parameters.Namespace
  180. if namespaceMetrics, err = getMetricsForCustomMetrics(cwData, getAllMetrics); err != nil {
  181. c.JsonApiErr(500, "Unable to call AWS API", err)
  182. return
  183. }
  184. }
  185. sort.Sort(sort.StringSlice(namespaceMetrics))
  186. result := []interface{}{}
  187. for _, name := range namespaceMetrics {
  188. result = append(result, util.DynMap{"text": name, "value": name})
  189. }
  190. c.JSON(200, result)
  191. }
  192. func handleGetDimensions(req *cwRequest, c *middleware.Context) {
  193. reqParam := &struct {
  194. Parameters struct {
  195. Namespace string `json:"namespace"`
  196. } `json:"parameters"`
  197. }{}
  198. json.Unmarshal(req.Body, reqParam)
  199. var dimensionValues []string
  200. if !isCustomMetrics(reqParam.Parameters.Namespace) {
  201. var exists bool
  202. if dimensionValues, exists = dimensionsMap[reqParam.Parameters.Namespace]; !exists {
  203. c.JsonApiErr(404, "Unable to find dimension "+reqParam.Parameters.Namespace, nil)
  204. return
  205. }
  206. } else {
  207. var err error
  208. dsInfo := req.GetDatasourceInfo()
  209. dsInfo.Namespace = reqParam.Parameters.Namespace
  210. if dimensionValues, err = getDimensionsForCustomMetrics(dsInfo, getAllMetrics); err != nil {
  211. c.JsonApiErr(500, "Unable to call AWS API", err)
  212. return
  213. }
  214. }
  215. sort.Sort(sort.StringSlice(dimensionValues))
  216. result := []interface{}{}
  217. for _, name := range dimensionValues {
  218. result = append(result, util.DynMap{"text": name, "value": name})
  219. }
  220. c.JSON(200, result)
  221. }
  222. func getAllMetrics(cwData *datasourceInfo) (cloudwatch.ListMetricsOutput, error) {
  223. creds, err := getCredentials(cwData)
  224. if err != nil {
  225. return cloudwatch.ListMetricsOutput{}, err
  226. }
  227. cfg := &aws.Config{
  228. Region: aws.String(cwData.Region),
  229. Credentials: creds,
  230. }
  231. svc := cloudwatch.New(session.New(cfg), cfg)
  232. params := &cloudwatch.ListMetricsInput{
  233. Namespace: aws.String(cwData.Namespace),
  234. }
  235. var resp cloudwatch.ListMetricsOutput
  236. err = svc.ListMetricsPages(params,
  237. func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
  238. metrics.M_Aws_CloudWatch_ListMetrics.Inc(1)
  239. metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
  240. for _, metric := range metrics {
  241. resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
  242. }
  243. return !lastPage
  244. })
  245. if err != nil {
  246. return resp, err
  247. }
  248. return resp, nil
  249. }
  250. var metricsCacheLock sync.Mutex
  251. func getMetricsForCustomMetrics(dsInfo *datasourceInfo, getAllMetrics func(*datasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  252. result, err := getAllMetrics(dsInfo)
  253. if err != nil {
  254. return []string{}, err
  255. }
  256. metricsCacheLock.Lock()
  257. defer metricsCacheLock.Unlock()
  258. if _, ok := customMetricsMetricsMap[dsInfo.Profile]; !ok {
  259. customMetricsMetricsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  260. }
  261. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  262. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  263. }
  264. if _, ok := customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  265. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  266. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  267. }
  268. if customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  269. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  270. }
  271. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  272. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  273. for _, metric := range result.Metrics {
  274. if isDuplicate(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName) {
  275. continue
  276. }
  277. customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *metric.MetricName)
  278. }
  279. return customMetricsMetricsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  280. }
  281. var dimensionsCacheLock sync.Mutex
  282. func getDimensionsForCustomMetrics(dsInfo *datasourceInfo, getAllMetrics func(*datasourceInfo) (cloudwatch.ListMetricsOutput, error)) ([]string, error) {
  283. result, err := getAllMetrics(dsInfo)
  284. if err != nil {
  285. return []string{}, err
  286. }
  287. dimensionsCacheLock.Lock()
  288. defer dimensionsCacheLock.Unlock()
  289. if _, ok := customMetricsDimensionsMap[dsInfo.Profile]; !ok {
  290. customMetricsDimensionsMap[dsInfo.Profile] = make(map[string]map[string]*CustomMetricsCache)
  291. }
  292. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region]; !ok {
  293. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region] = make(map[string]*CustomMetricsCache)
  294. }
  295. if _, ok := customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace]; !ok {
  296. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace] = &CustomMetricsCache{}
  297. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  298. }
  299. if customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire.After(time.Now()) {
  300. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  301. }
  302. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = make([]string, 0)
  303. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Expire = time.Now().Add(5 * time.Minute)
  304. for _, metric := range result.Metrics {
  305. for _, dimension := range metric.Dimensions {
  306. if isDuplicate(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name) {
  307. continue
  308. }
  309. customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache = append(customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, *dimension.Name)
  310. }
  311. }
  312. return customMetricsDimensionsMap[dsInfo.Profile][dsInfo.Region][dsInfo.Namespace].Cache, nil
  313. }
  314. func isDuplicate(nameList []string, target string) bool {
  315. for _, name := range nameList {
  316. if name == target {
  317. return true
  318. }
  319. }
  320. return false
  321. }
  322. func isCustomMetrics(namespace string) bool {
  323. return strings.Index(namespace, "AWS/") != 0
  324. }