metrics.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package cloudwatch
  2. import (
  3. "encoding/json"
  4. "sort"
  5. "github.com/grafana/grafana/pkg/middleware"
  6. "github.com/grafana/grafana/pkg/util"
  7. )
  8. var metricsMap map[string][]string
  9. var dimensionsMap map[string][]string
  10. func init() {
  11. metricsMap = map[string][]string{
  12. "AWS/AutoScaling": {"GroupMinSize", "GroupMaxSize", "GroupDesiredCapacity", "GroupInServiceInstances", "GroupPendingInstances", "GroupStandbyInstances", "GroupTerminatingInstances", "GroupTotalInstances"},
  13. "AWS/Billing": {"EstimatedCharges"},
  14. "AWS/CloudFront": {"Requests", "BytesDownloaded", "BytesUploaded", "TotalErrorRate", "4xxErrorRate", "5xxErrorRate"},
  15. "AWS/CloudSearch": {"SuccessfulRequests", "SearchableDocuments", "IndexUtilization", "Partitions"},
  16. "AWS/DynamoDB": {"ConditionalCheckFailedRequests", "ConsumedReadCapacityUnits", "ConsumedWriteCapacityUnits", "OnlineIndexConsumedWriteCapacity", "OnlineIndexPercentageProgress", "OnlineIndexThrottleEvents", "ProvisionedReadCapacityUnits", "ProvisionedWriteCapacityUnits", "ReadThrottleEvents", "ReturnedItemCount", "SuccessfulRequestLatency", "SystemErrors", "ThrottledRequests", "UserErrors", "WriteThrottleEvents"},
  17. "AWS/ECS": {"CPUUtilization", "MemoryUtilization"},
  18. "AWS/ElastiCache": {
  19. "CPUUtilization", "FreeableMemory", "NetworkBytesIn", "NetworkBytesOut", "SwapUsage",
  20. "BytesUsedForCacheItems", "BytesReadIntoMemcached", "BytesWrittenOutFromMemcached", "CasBadval", "CasHits", "CasMisses", "CmdFlush", "CmdGet", "CmdSet", "CurrConnections", "CurrItems", "DecrHits", "DecrMisses", "DeleteHits", "DeleteMisses", "Evictions", "GetHits", "GetMisses", "IncrHits", "IncrMisses", "Reclaimed",
  21. "BytesUsedForHash", "CmdConfigGet", "CmdConfigSet", "CmdTouch", "CurrConfig", "EvictedUnfetched", "ExpiredUnfetched", "SlabsMoved", "TouchHits", "TouchMisses",
  22. "NewConnections", "NewItems", "UnusedMemory",
  23. "BytesUsedForCache", "CacheHits", "CacheMisses", "CurrConnections", "Evictions", "HyperLogLogBasedCmds", "NewConnections", "Reclaimed", "ReplicationBytes", "ReplicationLag", "SaveInProgress",
  24. "CurrItems", "GetTypeCmds", "HashBasedCmds", "KeyBasedCmds", "ListBasedCmds", "SetBasedCmds", "SetTypeCmds", "SortedSetBasedCmds", "StringBasedCmds",
  25. },
  26. "AWS/EBS": {"VolumeReadBytes", "VolumeWriteBytes", "VolumeReadOps", "VolumeWriteOps", "VolumeTotalReadTime", "VolumeTotalWriteTime", "VolumeIdleTime", "VolumeQueueLength", "VolumeThroughputPercentage", "VolumeConsumedReadWriteOps"},
  27. "AWS/EC2": {"CPUCreditUsage", "CPUCreditBalance", "CPUUtilization", "DiskReadOps", "DiskWriteOps", "DiskReadBytes", "DiskWriteBytes", "NetworkIn", "NetworkOut", "StatusCheckFailed", "StatusCheckFailed_Instance", "StatusCheckFailed_System"},
  28. "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"},
  29. "AWS/ElasticMapReduce": {"IsIdle", "JobsRunning", "JobsFailed",
  30. "MapTasksRunning", "MapTasksRemaining", "MapSlotsOpen", "RemainingMapTasksPerSlot", "ReduceTasksRunning", "ReduceTasksRemaining", "ReduceSlotsOpen",
  31. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "TaskNodesRunning", "TaskNodesPending", "LiveTaskTrackers",
  32. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "TotalLoad",
  33. "BackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup",
  34. "IsIdle", "ContainerAllocated", "ContainerReserved", "ContainerPending", "AppsCompleted", "AppsFailed", "AppsKilled", "AppsPending", "AppsRunning", "AppsSubmitted",
  35. "CoreNodesRunning", "CoreNodesPending", "LiveDataNodes", "MRTotalNodes", "MRActiveNodes", "MRLostNodes", "MRUnhealthyNodes", "MRDecommissionedNodes", "MRRebootedNodes",
  36. "S3BytesWritten", "S3BytesRead", "HDFSUtilization", "HDFSBytesRead", "HDFSBytesWritten", "MissingBlocks", "CorruptBlocks", "TotalLoad", "MemoryTotalMB", "MemoryReservedMB", "MemoryAvailableMB", "MemoryAllocatedMB", "PendingDeletionBlocks", "UnderReplicatedBlocks", "DfsPendingReplicationBlocks", "CapacityRemainingGB",
  37. "HbaseBackupFailed", "MostRecentBackupDuration", "TimeSinceLastSuccessfulBackup"},
  38. "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"},
  39. "AWS/Kinesis": {"PutRecord.Bytes", "PutRecord.Latency", "PutRecord.Success", "PutRecords.Bytes", "PutRecords.Latency", "PutRecords.Records", "PutRecords.Success", "IncomingBytes", "IncomingRecords", "GetRecords.Bytes", "GetRecords.IteratorAgeMilliseconds", "GetRecords.Latency", "GetRecords.Success"},
  40. "AWS/Lambda": {"Invocations", "Errors", "Duration", "Throttles"},
  41. "AWS/ML": {"PredictCount", "PredictFailureCount"},
  42. "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"},
  43. "AWS/Redshift": {"CPUUtilization", "DatabaseConnections", "HealthStatus", "MaintenanceMode", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "PercentageDiskSpaceUsed", "ReadIOPS", "ReadLatency", "ReadThroughput", "WriteIOPS", "WriteLatency", "WriteThroughput"},
  44. "AWS/RDS": {"BinLogDiskUsage", "CPUUtilization", "CPUCreditUsage", "CPUCreditBalance", "DatabaseConnections", "DiskQueueDepth", "FreeableMemory", "FreeStorageSpace", "ReplicaLag", "SwapUsage", "ReadIOPS", "WriteIOPS", "ReadLatency", "WriteLatency", "ReadThroughput", "WriteThroughput", "NetworkReceiveThroughput", "NetworkTransmitThroughput"},
  45. "AWS/Route53": {"HealthCheckStatus", "HealthCheckPercentageHealthy"},
  46. "AWS/SNS": {"NumberOfMessagesPublished", "PublishSize", "NumberOfNotificationsDelivered", "NumberOfNotificationsFailed"},
  47. "AWS/SQS": {"NumberOfMessagesSent", "SentMessageSize", "NumberOfMessagesReceived", "NumberOfEmptyReceives", "NumberOfMessagesDeleted", "ApproximateNumberOfMessagesDelayed", "ApproximateNumberOfMessagesVisible", "ApproximateNumberOfMessagesNotVisible"},
  48. "AWS/S3": {"BucketSizeBytes", "NumberOfObjects"},
  49. "AWS/SWF": {"DecisionTaskScheduleToStartTime", "DecisionTaskStartToCloseTime", "DecisionTasksCompleted", "StartedDecisionTasksTimedOutOnClose", "WorkflowStartToCloseTime", "WorkflowsCanceled", "WorkflowsCompleted", "WorkflowsContinuedAsNew", "WorkflowsFailed", "WorkflowsTerminated", "WorkflowsTimedOut",
  50. "ActivityTaskScheduleToCloseTime", "ActivityTaskScheduleToStartTime", "ActivityTaskStartToCloseTime", "ActivityTasksCanceled", "ActivityTasksCompleted", "ActivityTasksFailed", "ScheduledActivityTasksTimedOutOnClose", "ScheduledActivityTasksTimedOutOnStart", "StartedActivityTasksTimedOutOnClose", "StartedActivityTasksTimedOutOnHeartbeat"},
  51. "AWS/StorageGateway": {"CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "CloudBytesDownloaded", "CloudDownloadLatency", "CloudBytesUploaded", "UploadBufferFree", "UploadBufferPercentUsed", "UploadBufferUsed", "QueuedWrites", "ReadBytes", "ReadTime", "TotalCacheSize", "WriteBytes", "WriteTime", "TimeSinceLastRecoveryPoint", "WorkingStorageFree", "WorkingStoragePercentUsed", "WorkingStorageUsed",
  52. "CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "ReadBytes", "ReadTime", "WriteBytes", "WriteTime", "QueuedWrites"},
  53. "AWS/WAF": {"AllowedRequests", "BlockedRequests", "CountedRequests"},
  54. "AWS/WorkSpaces": {"Available", "Unhealthy", "ConnectionAttempt", "ConnectionSuccess", "ConnectionFailure", "SessionLaunchTime", "InSessionLatency", "SessionDisconnect"},
  55. }
  56. dimensionsMap = map[string][]string{
  57. "AWS/AutoScaling": {"AutoScalingGroupName"},
  58. "AWS/Billing": {"ServiceName", "LinkedAccount", "Currency"},
  59. "AWS/CloudFront": {"DistributionId", "Region"},
  60. "AWS/CloudSearch": {},
  61. "AWS/DynamoDB": {"TableName", "GlobalSecondaryIndexName", "Operation"},
  62. "AWS/ECS": {"ClusterName", "ServiceName"},
  63. "AWS/ElastiCache": {"CacheClusterId", "CacheNodeId"},
  64. "AWS/EBS": {"VolumeId"},
  65. "AWS/EC2": {"AutoScalingGroupName", "ImageId", "InstanceId", "InstanceType"},
  66. "AWS/ELB": {"LoadBalancerName", "AvailabilityZone"},
  67. "AWS/ElasticMapReduce": {"ClusterId", "JobFlowId", "JobId"},
  68. "AWS/ES": {},
  69. "AWS/Kinesis": {"StreamName"},
  70. "AWS/Lambda": {"FunctionName"},
  71. "AWS/ML": {"MLModelId", "RequestMode"},
  72. "AWS/OpsWorks": {"StackId", "LayerId", "InstanceId"},
  73. "AWS/Redshift": {"NodeID", "ClusterIdentifier"},
  74. "AWS/RDS": {"DBInstanceIdentifier", "DatabaseClass", "EngineName"},
  75. "AWS/Route53": {"HealthCheckId"},
  76. "AWS/SNS": {"Application", "Platform", "TopicName"},
  77. "AWS/SQS": {"QueueName"},
  78. "AWS/S3": {"BucketName", "StorageType"},
  79. "AWS/SWF": {"Domain", "WorkflowTypeName", "WorkflowTypeVersion", "ActivityTypeName", "ActivityTypeVersion"},
  80. "AWS/StorageGateway": {"GatewayId", "GatewayName", "VolumeId"},
  81. "AWS/WAF": {"Rule", "WebACL"},
  82. "AWS/WorkSpaces": {"DirectoryId", "WorkspaceId"},
  83. }
  84. }
  85. // Whenever this list is updated, frontend list should also be updated.
  86. // Please update the region list in public/app/plugins/datasource/cloudwatch/partials/config.html
  87. func handleGetRegions(req *cwRequest, c *middleware.Context) {
  88. regions := []string{
  89. "ap-northeast-1", "ap-southeast-1", "ap-southeast-2", "cn-north-1",
  90. "eu-central-1", "eu-west-1", "sa-east-1", "us-east-1", "us-west-1", "us-west-2",
  91. }
  92. result := []interface{}{}
  93. for _, region := range regions {
  94. result = append(result, util.DynMap{"text": region, "value": region})
  95. }
  96. c.JSON(200, result)
  97. }
  98. func handleGetNamespaces(req *cwRequest, c *middleware.Context) {
  99. keys := []string{}
  100. for key := range metricsMap {
  101. keys = append(keys, key)
  102. }
  103. sort.Sort(sort.StringSlice(keys))
  104. result := []interface{}{}
  105. for _, key := range keys {
  106. result = append(result, util.DynMap{"text": key, "value": key})
  107. }
  108. c.JSON(200, result)
  109. }
  110. func handleGetMetrics(req *cwRequest, c *middleware.Context) {
  111. reqParam := &struct {
  112. Parameters struct {
  113. Namespace string `json:"namespace"`
  114. } `json:"parameters"`
  115. }{}
  116. json.Unmarshal(req.Body, reqParam)
  117. namespaceMetrics, exists := metricsMap[reqParam.Parameters.Namespace]
  118. if !exists {
  119. c.JsonApiErr(404, "Unable to find namespace "+reqParam.Parameters.Namespace, nil)
  120. return
  121. }
  122. sort.Sort(sort.StringSlice(namespaceMetrics))
  123. result := []interface{}{}
  124. for _, name := range namespaceMetrics {
  125. result = append(result, util.DynMap{"text": name, "value": name})
  126. }
  127. c.JSON(200, result)
  128. }
  129. func handleGetDimensions(req *cwRequest, c *middleware.Context) {
  130. reqParam := &struct {
  131. Parameters struct {
  132. Namespace string `json:"namespace"`
  133. } `json:"parameters"`
  134. }{}
  135. json.Unmarshal(req.Body, reqParam)
  136. dimensionValues, exists := dimensionsMap[reqParam.Parameters.Namespace]
  137. if !exists {
  138. c.JsonApiErr(404, "Unable to find dimension "+reqParam.Parameters.Namespace, nil)
  139. return
  140. }
  141. sort.Sort(sort.StringSlice(dimensionValues))
  142. result := []interface{}{}
  143. for _, name := range dimensionValues {
  144. result = append(result, util.DynMap{"text": name, "value": name})
  145. }
  146. c.JSON(200, result)
  147. }