datasource.js 21 KB

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