metrics.go 24 KB

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