datasource.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. './query_ctrl',
  6. './directives',
  7. ],
  8. function (angular, _) {
  9. 'use strict';
  10. var module = angular.module('grafana.services');
  11. module.factory('CloudWatchDatasource', function($q, $http, templateSrv) {
  12. function CloudWatchDatasource(datasource) {
  13. this.type = 'cloudwatch';
  14. this.name = datasource.name;
  15. this.supportMetrics = true;
  16. this.proxyUrl = datasource.url;
  17. this.defaultRegion = datasource.jsonData.defaultRegion;
  18. /* jshint -W101 */
  19. this.supportedRegion = [
  20. 'us-east-1', 'us-west-2', 'us-west-1', 'eu-west-1', 'eu-central-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'sa-east-1'
  21. ];
  22. this.supportedMetrics = {
  23. 'AWS/AutoScaling': [
  24. 'GroupMinSize', 'GroupMaxSize', 'GroupDesiredCapacity', 'GroupInServiceInstances', 'GroupPendingInstances', 'GroupStandbyInstances', 'GroupTerminatingInstances', 'GroupTotalInstances'
  25. ],
  26. 'AWS/Billing': [
  27. 'EstimatedCharges'
  28. ],
  29. 'AWS/CloudFront': [
  30. 'Requests', 'BytesDownloaded', 'BytesUploaded', 'TotalErrorRate', '4xxErrorRate', '5xxErrorRate'
  31. ],
  32. 'AWS/CloudSearch': [
  33. 'SuccessfulRequests', 'SearchableDocuments', 'IndexUtilization', 'Partitions'
  34. ],
  35. 'AWS/DynamoDB': [
  36. 'ConditionalCheckFailedRequests', 'ConsumedReadCapacityUnits', 'ConsumedWriteCapacityUnits', 'OnlineIndexConsumedWriteCapacity', 'OnlineIndexPercentageProgress', 'OnlineIndexThrottleEvents', 'ProvisionedReadCapacityUnits', 'ProvisionedWriteCapacityUnits', 'ReadThrottleEvents', 'ReturnedItemCount', 'SuccessfulRequestLatency', 'SystemErrors', 'ThrottledRequests', 'UserErrors', 'WriteThrottleEvents'
  37. ],
  38. 'AWS/ElastiCache': [
  39. 'CPUUtilization', 'SwapUsage', 'FreeableMemory', 'NetworkBytesIn', 'NetworkBytesOut',
  40. 'BytesUsedForCacheItems', 'BytesReadIntoMemcached', 'BytesWrittenOutFromMemcached', 'CasBadval', 'CasHits', 'CasMisses', 'CmdFlush', 'CmdGet', 'CmdSet', 'CurrConnections', 'CurrItems', 'DecrHits', 'DecrMisses', 'DeleteHits', 'DeleteMisses', 'Evictions', 'GetHits', 'GetMisses', 'IncrHits', 'IncrMisses', 'Reclaimed',
  41. 'CurrConnections', 'Evictions', 'Reclaimed', 'NewConnections', 'BytesUsedForCache', 'CacheHits', 'CacheMisses', 'ReplicationLag', 'GetTypeCmds', 'SetTypeCmds', 'KeyBasedCmds', 'StringBasedCmds', 'HashBasedCmds', 'ListBasedCmds', 'SetBasedCmds', 'SortedSetBasedCmds', 'CurrItems'
  42. ],
  43. 'AWS/EBS': [
  44. 'VolumeReadBytes', 'VolumeWriteBytes', 'VolumeReadOps', 'VolumeWriteOps', 'VolumeTotalReadTime', 'VolumeTotalWriteTime', 'VolumeIdleTime', 'VolumeQueueLength', 'VolumeThroughputPercentage', 'VolumeConsumedReadWriteOps'
  45. ],
  46. 'AWS/EC2': [
  47. 'CPUCreditUsage', 'CPUCreditBalance', 'CPUUtilization', 'DiskReadOps', 'DiskWriteOps', 'DiskReadBytes', 'DiskWriteBytes', 'NetworkIn', 'NetworkOut', 'StatusCheckFailed', 'StatusCheckFailed_Instance', 'StatusCheckFailed_System'
  48. ],
  49. 'AWS/ELB': [
  50. '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'
  51. ],
  52. 'AWS/ElasticMapReduce': [
  53. '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'
  54. ],
  55. 'AWS/Kinesis': [
  56. 'PutRecord.Bytes', 'PutRecord.Latency', 'PutRecord.Success', 'PutRecords.Bytes', 'PutRecords.Latency', 'PutRecords.Records', 'PutRecords.Success', 'IncomingBytes', 'IncomingRecords', 'GetRecords.Bytes', 'GetRecords.IteratorAgeMilliseconds', 'GetRecords.Latency', 'GetRecords.Success'
  57. ],
  58. 'AWS/ML': [
  59. 'PredictCount', 'PredictFailureCount'
  60. ],
  61. 'AWS/OpsWorks': [
  62. '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'
  63. ],
  64. 'AWS/Redshift': [
  65. 'CPUUtilization', 'DatabaseConnections', 'HealthStatus', 'MaintenanceMode', 'NetworkReceiveThroughput', 'NetworkTransmitThroughput', 'PercentageDiskSpaceUsed', 'ReadIOPS', 'ReadLatency', 'ReadThroughput', 'WriteIOPS', 'WriteLatency', 'WriteThroughput'
  66. ],
  67. 'AWS/RDS': [
  68. 'BinLogDiskUsage', 'CPUUtilization', 'DatabaseConnections', 'DiskQueueDepth', 'FreeableMemory', 'FreeStorageSpace', 'ReplicaLag', 'SwapUsage', 'ReadIOPS', 'WriteIOPS', 'ReadLatency', 'WriteLatency', 'ReadThroughput', 'WriteThroughput', 'NetworkReceiveThroughput', 'NetworkTransmitThroughput'
  69. ],
  70. 'AWS/Route53': [
  71. 'HealthCheckStatus', 'HealthCheckPercentageHealthy'
  72. ],
  73. 'AWS/SNS': [
  74. 'NumberOfMessagesPublished', 'PublishSize', 'NumberOfNotificationsDelivered', 'NumberOfNotificationsFailed'
  75. ],
  76. 'AWS/SQS': [
  77. 'NumberOfMessagesSent', 'SentMessageSize', 'NumberOfMessagesReceived', 'NumberOfEmptyReceives', 'NumberOfMessagesDeleted', 'ApproximateNumberOfMessagesDelayed', 'ApproximateNumberOfMessagesVisible', 'ApproximateNumberOfMessagesNotVisible'
  78. ],
  79. 'AWS/S3': [
  80. 'BucketSizeBytes', 'NumberOfObjects'
  81. ],
  82. 'AWS/SWF': [
  83. 'DecisionTaskScheduleToStartTime', 'DecisionTaskStartToCloseTime', 'DecisionTasksCompleted', 'StartedDecisionTasksTimedOutOnClose', 'WorkflowStartToCloseTime', 'WorkflowsCanceled', 'WorkflowsCompleted', 'WorkflowsContinuedAsNew', 'WorkflowsFailed', 'WorkflowsTerminated', 'WorkflowsTimedOut'
  84. ],
  85. 'AWS/StorageGateway': [
  86. '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'
  87. ],
  88. 'AWS/WorkSpaces': [
  89. 'Available', 'Unhealthy', 'ConnectionAttempt', 'ConnectionSuccess', 'ConnectionFailure', 'SessionLaunchTime', 'InSessionLatency', 'SessionDisconnect'
  90. ],
  91. };
  92. this.supportedDimensions = {
  93. 'AWS/AutoScaling': [
  94. 'AutoScalingGroupName'
  95. ],
  96. 'AWS/Billing': [
  97. 'ServiceName', 'LinkedAccount', 'Currency'
  98. ],
  99. 'AWS/CloudFront': [
  100. 'DistributionId', 'Region'
  101. ],
  102. 'AWS/CloudSearch': [
  103. ],
  104. 'AWS/DynamoDB': [
  105. 'TableName', 'GlobalSecondaryIndexName', 'Operation'
  106. ],
  107. 'AWS/ElastiCache': [
  108. 'CacheClusterId', 'CacheNodeId'
  109. ],
  110. 'AWS/EBS': [
  111. 'VolumeId'
  112. ],
  113. 'AWS/EC2': [
  114. 'AutoScalingGroupName', 'ImageId', 'InstanceId', 'InstanceType'
  115. ],
  116. 'AWS/ELB': [
  117. 'LoadBalancerName', 'AvailabilityZone'
  118. ],
  119. 'AWS/ElasticMapReduce': [
  120. 'ClusterId', 'JobId'
  121. ],
  122. 'AWS/Kinesis': [
  123. 'StreamName'
  124. ],
  125. 'AWS/ML': [
  126. 'MLModelId', 'RequestMode'
  127. ],
  128. 'AWS/OpsWorks': [
  129. 'StackId', 'LayerId', 'InstanceId'
  130. ],
  131. 'AWS/Redshift': [
  132. 'NodeID', 'ClusterIdentifier'
  133. ],
  134. 'AWS/RDS': [
  135. 'DBInstanceIdentifier', 'DatabaseClass', 'EngineName'
  136. ],
  137. 'AWS/Route53': [
  138. 'HealthCheckId'
  139. ],
  140. 'AWS/SNS': [
  141. 'Application', 'Platform', 'TopicName'
  142. ],
  143. 'AWS/SQS': [
  144. 'QueueName'
  145. ],
  146. 'AWS/S3': [
  147. 'BucketName', 'StorageType'
  148. ],
  149. 'AWS/SWF': [
  150. 'Domain', 'ActivityTypeName', 'ActivityTypeVersion'
  151. ],
  152. 'AWS/StorageGateway': [
  153. 'GatewayId', 'GatewayName', 'VolumeId'
  154. ],
  155. 'AWS/WorkSpaces': [
  156. 'DirectoryId', 'WorkspaceId'
  157. ],
  158. };
  159. /* jshint +W101 */
  160. /* load custom metrics definitions */
  161. var self = this;
  162. $q.all(
  163. _.chain(datasource.jsonData.customMetricsAttributes)
  164. .reject(function(u) {
  165. return _.isEmpty(u);
  166. })
  167. .map(function(u) {
  168. return $http({ method: 'GET', url: u });
  169. })
  170. )
  171. .then(function(allResponse) {
  172. _.chain(allResponse)
  173. .map(function(d) {
  174. return d.data.Metrics;
  175. })
  176. .flatten()
  177. .reject(function(metric) {
  178. return metric.Namespace.indexOf('AWS/') === 0;
  179. })
  180. .map(function(metric) {
  181. metric.Dimensions = _.chain(metric.Dimensions)
  182. .map(function(d) {
  183. return d.Name;
  184. })
  185. .value().sort();
  186. return metric;
  187. })
  188. .uniq(function(metric) {
  189. return metric.Namespace + metric.MetricName + metric.Dimensions.join('');
  190. })
  191. .each(function(metric) {
  192. if (!_.has(self.supportedMetrics, metric.Namespace)) {
  193. self.supportedMetrics[metric.Namespace] = [];
  194. }
  195. self.supportedMetrics[metric.Namespace].push(metric.MetricName);
  196. if (!_.has(self.supportedDimensions, metric.Namespace)) {
  197. self.supportedDimensions[metric.Namespace] = [];
  198. }
  199. self.supportedDimensions[metric.Namespace] = _.union(self.supportedDimensions[metric.Namespace], metric.Dimensions);
  200. });
  201. });
  202. }
  203. // Called once per panel (graph)
  204. CloudWatchDatasource.prototype.query = function(options) {
  205. var start = convertToCloudWatchTime(options.range.from);
  206. var end = convertToCloudWatchTime(options.range.to);
  207. var queries = [];
  208. _.each(options.targets, _.bind(function(target) {
  209. if (!target.namespace || !target.metricName || _.isEmpty(target.statistics)) {
  210. return;
  211. }
  212. var query = {};
  213. query.region = templateSrv.replace(target.region, options.scopedVars);
  214. query.namespace = templateSrv.replace(target.namespace, options.scopedVars);
  215. query.metricName = templateSrv.replace(target.metricName, options.scopedVars);
  216. query.dimensions = convertDimensionFormat(target.dimensions);
  217. query.statistics = getActivatedStatistics(target.statistics);
  218. query.period = parseInt(target.period, 10);
  219. var range = end - start;
  220. // CloudWatch limit datapoints up to 1440
  221. if (range / query.period >= 1440) {
  222. query.period = Math.floor(range / 1440 / 60) * 60;
  223. }
  224. queries.push(query);
  225. }, this));
  226. // No valid targets, return the empty result to save a round trip.
  227. if (_.isEmpty(queries)) {
  228. var d = $q.defer();
  229. d.resolve({ data: [] });
  230. return d.promise;
  231. }
  232. var allQueryPromise = _.map(queries, _.bind(function(query) {
  233. return this.performTimeSeriesQuery(query, start, end);
  234. }, this));
  235. return $q.all(allQueryPromise)
  236. .then(function(allResponse) {
  237. var result = [];
  238. _.each(allResponse, function(response, index) {
  239. var metrics = transformMetricData(response, options.targets[index]);
  240. _.each(metrics, function(m) {
  241. result.push(m);
  242. });
  243. });
  244. return { data: result };
  245. });
  246. };
  247. CloudWatchDatasource.prototype.performTimeSeriesQuery = function(query, start, end) {
  248. var cloudwatch = this.getAwsClient(query.region, 'CloudWatch');
  249. var params = {
  250. Namespace: query.namespace,
  251. MetricName: query.metricName,
  252. Dimensions: query.dimensions,
  253. Statistics: query.statistics,
  254. StartTime: start,
  255. EndTime: end,
  256. Period: query.period
  257. };
  258. return cloudwatch.getMetricStatistics(params);
  259. };
  260. CloudWatchDatasource.prototype.getRegions = function() {
  261. return $q.when(this.supportedRegion);
  262. };
  263. CloudWatchDatasource.prototype.getNamespaces = function() {
  264. return $q.when(_.keys(this.supportedMetrics));
  265. };
  266. CloudWatchDatasource.prototype.getMetrics = function(namespace) {
  267. namespace = templateSrv.replace(namespace);
  268. return $q.when(this.supportedMetrics[namespace] || []);
  269. };
  270. CloudWatchDatasource.prototype.getDimensionKeys = function(namespace) {
  271. namespace = templateSrv.replace(namespace);
  272. return $q.when(this.supportedDimensions[namespace] || []);
  273. };
  274. CloudWatchDatasource.prototype.getDimensionValues = function(region, namespace, metricName, dimensions) {
  275. region = templateSrv.replace(region);
  276. namespace = templateSrv.replace(namespace);
  277. metricName = templateSrv.replace(metricName);
  278. var cloudwatch = this.getAwsClient(region, 'CloudWatch');
  279. var params = {
  280. Namespace: namespace,
  281. MetricName: metricName
  282. };
  283. if (!_.isEmpty(dimensions)) {
  284. params.Dimensions = convertDimensionFormat(dimensions);
  285. }
  286. return cloudwatch.listMetrics(params).then(function(data) {
  287. var suggestData = _.chain(data.Metrics).map(function(metric) {
  288. return metric.Dimensions;
  289. }).reject(function(metric) {
  290. return _.isEmpty(metric);
  291. }).value();
  292. return suggestData;
  293. });
  294. };
  295. CloudWatchDatasource.prototype.performEC2DescribeInstances = function(region, filters, instanceIds) {
  296. var ec2 = this.getAwsClient(region, 'EC2');
  297. var params = {};
  298. if (filters.length > 0) {
  299. params.Filters = filters;
  300. }
  301. if (instanceIds.length > 0) {
  302. params.InstanceIds = instanceIds;
  303. }
  304. return ec2.describeInstances(params);
  305. };
  306. CloudWatchDatasource.prototype.metricFindQuery = function(query) {
  307. var region;
  308. var namespace;
  309. var metricName;
  310. var transformSuggestData = function(suggestData) {
  311. return _.map(suggestData, function(v) {
  312. return { text: v };
  313. });
  314. };
  315. var regionQuery = query.match(/^region\(\)/);
  316. if (regionQuery) {
  317. return this.getRegions().then(transformSuggestData);
  318. }
  319. var namespaceQuery = query.match(/^namespace\(\)/);
  320. if (namespaceQuery) {
  321. return this.getNamespaces().then(transformSuggestData);
  322. }
  323. var metricNameQuery = query.match(/^metrics\(([^\)]+?)\)/);
  324. if (metricNameQuery) {
  325. namespace = templateSrv.replace(metricNameQuery[1]);
  326. return this.getMetrics(namespace).then(transformSuggestData);
  327. }
  328. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)\)/);
  329. if (dimensionKeysQuery) {
  330. namespace = templateSrv.replace(dimensionKeysQuery[1]);
  331. return this.getDimensionKeys(namespace).then(transformSuggestData);
  332. }
  333. var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?([^)]*))?\)/);
  334. if (dimensionValuesQuery) {
  335. region = templateSrv.replace(dimensionValuesQuery[1]);
  336. namespace = templateSrv.replace(dimensionValuesQuery[2]);
  337. metricName = templateSrv.replace(dimensionValuesQuery[3]);
  338. var dimensionPart = templateSrv.replace(dimensionValuesQuery[5]);
  339. var dimensions = {};
  340. if (!_.isEmpty(dimensionPart)) {
  341. _.each(dimensionPart.split(','), function(v) {
  342. var t = v.split('=');
  343. if (t.length !== 2) {
  344. throw new Error('Invalid query format');
  345. }
  346. dimensions[t[0]] = t[1];
  347. });
  348. }
  349. return this.getDimensionValues(region, namespace, metricName, dimensions)
  350. .then(function(suggestData) {
  351. return _.map(suggestData, function(dimensions) {
  352. var result = _.chain(dimensions)
  353. .sortBy(function(dimension) {
  354. return dimension.Name;
  355. })
  356. .map(function(dimension) {
  357. return dimension.Name + '=' + dimension.Value;
  358. })
  359. .value().join(',');
  360. return { text: result };
  361. });
  362. });
  363. }
  364. var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  365. if (ebsVolumeIdsQuery) {
  366. region = templateSrv.replace(ebsVolumeIdsQuery[1]);
  367. var instanceId = templateSrv.replace(ebsVolumeIdsQuery[2]);
  368. var instanceIds = [
  369. instanceId
  370. ];
  371. return this.performEC2DescribeInstances(region, [], instanceIds).then(function(result) {
  372. var volumeIds = _.map(result.Reservations[0].Instances[0].BlockDeviceMappings, function(mapping) {
  373. return mapping.EBS.VolumeID;
  374. });
  375. return transformSuggestData(volumeIds);
  376. });
  377. }
  378. return $q.when([]);
  379. };
  380. CloudWatchDatasource.prototype.testDatasource = function() {
  381. /* use billing metrics for test */
  382. var region = 'us-east-1';
  383. var namespace = 'AWS/Billing';
  384. var metricName = 'EstimatedCharges';
  385. var dimensions = {};
  386. return this.performSuggestDimensionValues(region, namespace, metricName, dimensions).then(function () {
  387. return { status: 'success', message: 'Data source is working', title: 'Success' };
  388. });
  389. };
  390. CloudWatchDatasource.prototype.getAwsClient = function(region, service) {
  391. var self = this;
  392. var generateRequestProxy = function(service, action) {
  393. return function(params) {
  394. var data = {
  395. region: region,
  396. service: service,
  397. action: action,
  398. parameters: params
  399. };
  400. var options = {
  401. method: 'POST',
  402. url: self.proxyUrl,
  403. data: data
  404. };
  405. return $http(options);
  406. };
  407. };
  408. switch (service) {
  409. case 'CloudWatch': {
  410. return {
  411. getMetricStatistics: generateRequestProxy('CloudWatch', 'GetMetricStatistics'),
  412. listMetrics: generateRequestProxy('CloudWatch', 'ListMetrics')
  413. };
  414. }
  415. case 'EC2': {
  416. return {
  417. describeInstances: generateRequestProxy('EC2', 'DescribeInstances')
  418. };
  419. }
  420. }
  421. };
  422. CloudWatchDatasource.prototype.getDefaultRegion = function() {
  423. return this.defaultRegion;
  424. };
  425. function transformMetricData(md, options) {
  426. var result = [];
  427. var dimensionPart = templateSrv.replace(JSON.stringify(options.dimensions));
  428. _.each(getActivatedStatistics(options.statistics), function(s) {
  429. var originalSettings = _.templateSettings;
  430. _.templateSettings = {
  431. interpolate: /\{\{(.+?)\}\}/g
  432. };
  433. var template = _.template(options.legendFormat);
  434. var metricLabel;
  435. if (_.isEmpty(options.legendFormat)) {
  436. metricLabel = md.Label + '_' + s + dimensionPart;
  437. } else {
  438. var d = convertDimensionFormat(options.dimensions);
  439. metricLabel = template({
  440. Region: templateSrv.replace(options.region),
  441. Namespace: templateSrv.replace(options.namespace),
  442. MetricName: templateSrv.replace(options.metricName),
  443. Dimensions: d,
  444. Statistics: s
  445. });
  446. }
  447. _.templateSettings = originalSettings;
  448. var dps = _.map(md.Datapoints, function(value) {
  449. return [value[s], new Date(value.Timestamp).getTime()];
  450. });
  451. dps = _.sortBy(dps, function(dp) { return dp[1]; });
  452. result.push({ target: metricLabel, datapoints: dps });
  453. });
  454. return result;
  455. }
  456. function getActivatedStatistics(statistics) {
  457. var activatedStatistics = [];
  458. _.each(statistics, function(v, k) {
  459. if (v) {
  460. activatedStatistics.push(k);
  461. }
  462. });
  463. return activatedStatistics;
  464. }
  465. function convertToCloudWatchTime(date) {
  466. return Math.round(date.valueOf() / 1000);
  467. }
  468. function convertDimensionFormat(dimensions) {
  469. return _.map(_.keys(dimensions), function(key) {
  470. return {
  471. Name: templateSrv.replace(key),
  472. Value: templateSrv.replace(dimensions[key])
  473. };
  474. });
  475. }
  476. return CloudWatchDatasource;
  477. });
  478. });