queryCtrl.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. define([
  2. 'angular',
  3. 'lodash',
  4. ],
  5. function (angular, _) {
  6. 'use strict';
  7. var module = angular.module('grafana.controllers');
  8. /* jshint -W101 */
  9. var supportedMetrics = {
  10. "AWS/AutoScaling": [
  11. "GroupMinSize", "GroupMaxSize", "GroupDesiredCapacity", "GroupInServiceInstances", "GroupPendingInstances", "GroupStandbyInstances", "GroupTerminatingInstances", "GroupTotalInstances"
  12. ],
  13. "AWS/Billing": [
  14. "EstimatedCharges"
  15. ],
  16. "AWS/CloudFront": [
  17. "Requests", "BytesDownloaded", "BytesUploaded", "TotalErrorRate", "4xxErrorRate", "5xxErrorRate"
  18. ],
  19. "AWS/CloudSearch": [
  20. "SuccessfulRequests", "SearchableDocuments", "IndexUtilization", "Partitions"
  21. ],
  22. "AWS/DynamoDB": [
  23. "ConditionalCheckFailedRequests", "ConsumedReadCapacityUnits", "ConsumedWriteCapacityUnits", "OnlineIndexConsumedWriteCapacity", "OnlineIndexPercentageProgress", "OnlineIndexThrottleEvents", "ProvisionedReadCapacityUnits", "ProvisionedWriteCapacityUnits", "ReadThrottleEvents", "ReturnedItemCount", "SuccessfulRequestLatency", "SystemErrors", "ThrottledRequests", "UserErrors", "WriteThrottleEvents"
  24. ],
  25. "AWS/ElastiCache": [
  26. "CPUUtilization", "SwapUsage", "FreeableMemory", "NetworkBytesIn", "NetworkBytesOut",
  27. "BytesUsedForCacheItems", "BytesReadIntoMemcached", "BytesWrittenOutFromMemcached", "CasBadval", "CasHits", "CasMisses", "CmdFlush", "CmdGet", "CmdSet", "CurrConnections", "CurrItems", "DecrHits", "DecrMisses", "DeleteHits", "DeleteMisses", "Evictions", "GetHits", "GetMisses", "IncrHits", "IncrMisses", "Reclaimed",
  28. "CurrConnections", "Evictions", "Reclaimed", "NewConnections", "BytesUsedForCache", "CacheHits", "CacheMisses", "ReplicationLag", "GetTypeCmds", "SetTypeCmds", "KeyBasedCmds", "StringBasedCmds", "HashBasedCmds", "ListBasedCmds", "SetBasedCmds", "SortedSetBasedCmds", "CurrItems"
  29. ],
  30. "AWS/EBS": [
  31. "VolumeReadBytes", "VolumeWriteBytes", "VolumeReadOps", "VolumeWriteOps", "VolumeTotalReadTime", "VolumeTotalWriteTime", "VolumeIdleTime", "VolumeQueueLength", "VolumeThroughputPercentage", "VolumeConsumedReadWriteOps",
  32. ],
  33. "AWS/EC2": [
  34. "CPUCreditUsage", "CPUCreditBalance", "CPUUtilization", "DiskReadOps", "DiskWriteOps", "DiskReadBytes", "DiskWriteBytes", "NetworkIn", "NetworkOut", "StatusCheckFailed", "StatusCheckFailed_Instance", "StatusCheckFailed_System"
  35. ],
  36. "AWS/ELB": [
  37. "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"
  38. ],
  39. "AWS/ElasticMapReduce": [
  40. "CoreNodesPending", "CoreNodesRunning", "HBaseBackupFailed", "HBaseMostRecentBackupDuration", "HBaseTimeSinceLastSuccessfulBackup", "HDFSBytesRead", "HDFSBytesWritten", "HDFSUtilization", "IsIdle", "JobsFailed", "JobsRunning", "LiveDataNodes", "LiveTaskTrackers", "MapSlotsOpen", "MissingBlocks", "ReduceSlotsOpen", "RemainingMapTasks", "RemainingMapTasksPerSlot", "RemainingReduceTasks", "RunningMapTasks", "RunningReduceTasks", "S3BytesRead", "S3BytesWritten", "TaskNodesPending", "TaskNodesRunning", "TotalLoad"
  41. ],
  42. "AWS/Kinesis": [
  43. "PutRecord.Bytes", "PutRecord.Latency", "PutRecord.Success", "PutRecords.Bytes", "PutRecords.Latency", "PutRecords.Records", "PutRecords.Success", "IncomingBytes", "IncomingRecords", "GetRecords.Bytes", "GetRecords.IteratorAgeMilliseconds", "GetRecords.Latency", "GetRecords.Success"
  44. ],
  45. "AWS/ML": [
  46. "PredictCount", "PredictFailureCount"
  47. ],
  48. "AWS/OpsWorks": [
  49. "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"
  50. ],
  51. "AWS/Redshift": [
  52. "CPUUtilization", "DatabaseConnections", "HealthStatus", "MaintenanceMode", "NetworkReceiveThroughput", "NetworkTransmitThroughput", "PercentageDiskSpaceUsed", "ReadIOPS", "ReadLatency", "ReadThroughput", "WriteIOPS", "WriteLatency", "WriteThroughput"
  53. ],
  54. "AWS/RDS": [
  55. "BinLogDiskUsage", "CPUUtilization", "DatabaseConnections", "DiskQueueDepth", "FreeableMemory", "FreeStorageSpace", "ReplicaLag", "SwapUsage", "ReadIOPS", "WriteIOPS", "ReadLatency", "WriteLatency", "ReadThroughput", "WriteThroughput", "NetworkReceiveThroughput", "NetworkTransmitThroughput"
  56. ],
  57. "AWS/Route53": [
  58. "HealthCheckStatus", "HealthCheckPercentageHealthy"
  59. ],
  60. "AWS/SNS": [
  61. "NumberOfMessagesPublished", "PublishSize", "NumberOfNotificationsDelivered", "NumberOfNotificationsFailed"
  62. ],
  63. "AWS/SQS": [
  64. "NumberOfMessagesSent", "SentMessageSize", "NumberOfMessagesReceived", "NumberOfEmptyReceives", "NumberOfMessagesDeleted", "ApproximateNumberOfMessagesDelayed", "ApproximateNumberOfMessagesVisible", "ApproximateNumberOfMessagesNotVisible"
  65. ],
  66. "AWS/S3": [
  67. "BucketSizeBytes", "NumberOfObjects"
  68. ],
  69. "AWS/SWF": [
  70. "DecisionTaskScheduleToStartTime", "DecisionTaskStartToCloseTime", "DecisionTasksCompleted", "StartedDecisionTasksTimedOutOnClose", "WorkflowStartToCloseTime", "WorkflowsCanceled", "WorkflowsCompleted", "WorkflowsContinuedAsNew", "WorkflowsFailed", "WorkflowsTerminated", "WorkflowsTimedOut"
  71. ],
  72. "AWS/StorageGateway": [
  73. "CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "CloudBytesDownloaded", "CloudDownloadLatency", "CloudBytesUploaded", "UploadBufferFree", "UploadBufferPercentUsed", "UploadBufferUsed", "QueuedWrites", "ReadBytes", "ReadTime", "TotalCacheSize", "WriteBytes", "WriteTime", "WorkingStorageFree", "WorkingStoragePercentUsed", "WorkingStorageUsed", "CacheHitPercent", "CachePercentUsed", "CachePercentDirty", "ReadBytes", "ReadTime", "WriteBytes", "WriteTime", "QueuedWrites"
  74. ],
  75. "AWS/WorkSpaces": [
  76. "Available", "Unhealthy", "ConnectionAttempt", "ConnectionSuccess", "ConnectionFailure", "SessionLaunchTime", "InSessionLatency", "SessionDisconnect"
  77. ],
  78. };
  79. /* jshint +W101 */
  80. var supportedDimensions = {
  81. "AWS/AutoScaling": [
  82. "AutoScalingGroupName"
  83. ],
  84. "AWS/Billing": [
  85. "ServiceName", "LinkedAccount", "Currency"
  86. ],
  87. "AWS/CloudFront": [
  88. "DistributionId", "Region"
  89. ],
  90. "AWS/CloudSearch": [
  91. ],
  92. "AWS/DynamoDB": [
  93. "TableName", "GlobalSecondaryIndexName", "Operation"
  94. ],
  95. "AWS/ElastiCache": [
  96. "CacheClusterId", "CacheNodeId"
  97. ],
  98. "AWS/EBS": [
  99. "VolumeId"
  100. ],
  101. "AWS/EC2": [
  102. "AutoScalingGroupName", "ImageId", "InstanceId", "InstanceType"
  103. ],
  104. "AWS/ELB": [
  105. "LoadBalancerName", "AvailabilityZone"
  106. ],
  107. "AWS/ElasticMapReduce": [
  108. "ClusterId", "JobId"
  109. ],
  110. "AWS/Kinesis": [
  111. "StreamName"
  112. ],
  113. "AWS/ML": [
  114. "MLModelId", "RequestMode"
  115. ],
  116. "AWS/OpsWorks": [
  117. "StackId", "LayerId", "InstanceId"
  118. ],
  119. "AWS/Redshift": [
  120. "NodeID", "ClusterIdentifier"
  121. ],
  122. "AWS/RDS": [
  123. "DBInstanceIdentifier", "DatabaseClass", "EngineName"
  124. ],
  125. "AWS/Route53": [
  126. "HealthCheckId"
  127. ],
  128. "AWS/SNS": [
  129. "Application", "Platform", "TopicName"
  130. ],
  131. "AWS/SQS": [
  132. "QueueName"
  133. ],
  134. "AWS/S3": [
  135. "BucketName", "StorageType"
  136. ],
  137. "AWS/SWF": [
  138. "Domain", "ActivityTypeName", "ActivityTypeVersion"
  139. ],
  140. "AWS/StorageGateway": [
  141. "GatewayId", "GatewayName", "VolumeId"
  142. ],
  143. "AWS/WorkSpaces": [
  144. "DirectoryId", "WorkspaceId"
  145. ],
  146. };
  147. module.controller('CloudWatchQueryCtrl', function($scope) {
  148. $scope.init = function() {
  149. $scope.target.namespace = $scope.target.namespace || '';
  150. $scope.target.metricName = $scope.target.metricName || '';
  151. $scope.target.dimensions = $scope.target.dimensions || {};
  152. $scope.target.statistics = $scope.target.statistics || {};
  153. $scope.target.period = $scope.target.period || 60;
  154. $scope.target.errors = validateTarget();
  155. };
  156. $scope.refreshMetricData = function() {
  157. $scope.target.errors = validateTarget($scope.target);
  158. // this does not work so good
  159. if (!_.isEqual($scope.oldTarget, $scope.target) && _.isEmpty($scope.target.errors)) {
  160. $scope.oldTarget = angular.copy($scope.target);
  161. $scope.get_data();
  162. }
  163. };
  164. $scope.moveMetricQuery = function(fromIndex, toIndex) {
  165. _.move($scope.panel.targets, fromIndex, toIndex);
  166. };
  167. $scope.duplicate = function() {
  168. var clone = angular.copy($scope.target);
  169. $scope.panel.targets.push(clone);
  170. };
  171. $scope.suggestNamespace = function(query, callback) { // jshint unused:false
  172. return _.keys(supportedMetrics);
  173. };
  174. $scope.suggestMetrics = function(query, callback) { // jshint unused:false
  175. return supportedMetrics[$scope.target.namespace] || [];
  176. };
  177. $scope.suggestDimensionKeys = function(query, callback) { // jshint unused:false
  178. return supportedDimensions[$scope.target.namespace] || [];
  179. };
  180. $scope.suggestDimensionValues = function(query, callback) {
  181. if (!$scope.target.namespace || !$scope.target.metricName) {
  182. return callback([]);
  183. }
  184. var params = {
  185. Namespace: $scope.target.namespace,
  186. MetricName: $scope.target.metricName
  187. };
  188. if (!_.isEmpty($scope.target.dimensions)) {
  189. params.Dimensions = $scope.target.dimensions;
  190. }
  191. $scope.datasource
  192. .performSuggestQuery(params)
  193. .then(function(result) {
  194. var suggestData = _.chain(result.Metrics)
  195. .map(function(metric) {
  196. return metric.Dimensions;
  197. })
  198. .flatten(true)
  199. .filter(function(dimension) {
  200. return dimension.Name === $scope.target.currentDimensionKey;
  201. })
  202. .map(function(metric) {
  203. return metric;
  204. })
  205. .pluck('Value')
  206. .uniq()
  207. .value();
  208. callback(suggestData);
  209. }, function() {
  210. callback([]);
  211. });
  212. };
  213. $scope.addDimension = function() {
  214. if (!$scope.addDimensionMode) {
  215. $scope.addDimensionMode = true;
  216. return;
  217. }
  218. if (!$scope.target.dimensions) {
  219. $scope.target.dimensions = {};
  220. }
  221. $scope.target.dimensions[$scope.target.currentDimensionKey] = $scope.target.currentDimensionValue;
  222. $scope.target.currentDimensionKey = '';
  223. $scope.target.currentDimensionValue = '';
  224. $scope.refreshMetricData();
  225. $scope.addDimensionMode = false;
  226. };
  227. $scope.removeDimension = function(key) {
  228. delete $scope.target.dimensions[key];
  229. $scope.refreshMetricData();
  230. };
  231. $scope.statisticsOptionChanged = function() {
  232. $scope.refreshMetricData();
  233. };
  234. // TODO: validate target
  235. function validateTarget() {
  236. var errs = {};
  237. if ($scope.target.period < 60 || ($scope.target.period % 60) !== 0) {
  238. errs.period = 'Period must be at least 60 seconds and must be a multiple of 60';
  239. }
  240. return errs;
  241. }
  242. });
  243. });