PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/src/application/libraries/Zend/Service/Amazon/Ec2/CloudWatch.php

https://bitbucket.org/masnug/grc276-blog-laravel
PHP | 357 lines | 108 code | 33 blank | 216 comment | 16 complexity | cd70088d7369194a61829234f25750e0 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Service_Amazon
  17. * @subpackage Ec2
  18. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: CloudWatch.php 23775 2011-03-01 17:25:24Z ralph $
  21. */
  22. /**
  23. * @see Zend_Service_Amazon_Ec2_Abstract
  24. */
  25. require_once 'Zend/Service/Amazon/Ec2/Abstract.php';
  26. /**
  27. * An Amazon EC2 interface that allows yout to run, terminate, reboot and describe Amazon
  28. * Ec2 Instances.
  29. *
  30. * @category Zend
  31. * @package Zend_Service_Amazon
  32. * @subpackage Ec2
  33. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  34. * @license http://framework.zend.com/license/new-bsd New BSD License
  35. */
  36. class Zend_Service_Amazon_Ec2_CloudWatch extends Zend_Service_Amazon_Ec2_Abstract
  37. {
  38. /**
  39. * The HTTP query server
  40. */
  41. protected $_ec2Endpoint = 'monitoring.amazonaws.com';
  42. /**
  43. * The API version to use
  44. */
  45. protected $_ec2ApiVersion = '2009-05-15';
  46. /**
  47. * XML Namespace for the CloudWatch Stuff
  48. */
  49. protected $_xmlNamespace = 'http://monitoring.amazonaws.com/doc/2009-05-15/';
  50. /**
  51. * The following metrics are available from each EC2 instance.
  52. *
  53. * CPUUtilization: The percentage of allocated EC2 compute units that are
  54. * currently in use on the instance. This metric identifies the processing
  55. * power required to run an application upon a selected instance.
  56. *
  57. * NetworkIn: The number of bytes received on all network interfaces by
  58. * the instance. This metric identifies the volume of incoming network
  59. * traffic to an application on a single instance.
  60. *
  61. * NetworkOut: The number of bytes sent out on all network interfaces
  62. * by the instance. This metric identifies the volume of outgoing network
  63. * traffic to an application on a single instance.
  64. *
  65. * DiskWriteOps: Completed write operations to all hard disks available to
  66. * the instance. This metric identifies the rate at which an application
  67. * writes to a hard disk. This can be used to determine the speed in which
  68. * an application saves data to a hard disk.
  69. *
  70. * DiskReadBytes: Bytes read from all disks available to the instance. This
  71. * metric is used to determine the volume of the data the application reads
  72. * from the hard disk of the instance. This can be used to determine the
  73. * speed of the application for the customer.
  74. *
  75. * DiskReadOps: Completed read operations from all disks available to the
  76. * instances. This metric identifies the rate at which an application reads
  77. * a disk. This can be used to determine the speed in which an application
  78. * reads data from a hard disk.
  79. *
  80. * DiskWriteBytes: Bytes written to all disks available to the instance. This
  81. * metric is used to determine the volume of the data the application writes
  82. * onto the hard disk of the instance. This can be used to determine the speed
  83. * of the application for the customer.
  84. *
  85. * Latency: Time taken between a request and the corresponding response as seen
  86. * by the load balancer.
  87. *
  88. * RequestCount: The number of requests processed by the LoadBalancer.
  89. *
  90. * HealthyHostCount: The number of healthy instances. Both Load Balancing dimensions,
  91. * LoadBalancerName and AvailabilityZone, should be specified when retreiving
  92. * HealthyHostCount.
  93. *
  94. * UnHealthyHostCount: The number of unhealthy instances. Both Load Balancing dimensions,
  95. * LoadBalancerName and AvailabilityZone, should be specified when retreiving
  96. * UnHealthyHostCount.
  97. *
  98. * Amazon CloudWatch data for a new EC2 instance becomes available typically
  99. * within one minute of the end of the first aggregation period for the new
  100. * instance. You can use the currently available dimensions for EC2 instances
  101. * along with these metrics in order to refine the slice of data you want returned,
  102. * such as metric CPUUtilization and dimension ImageId to get all CPUUtilization
  103. * data for instances using the specified AMI.
  104. *
  105. * @var array
  106. */
  107. protected $_validMetrics = array('CPUUtilization', 'NetworkIn', 'NetworkOut',
  108. 'DiskWriteOps', 'DiskReadBytes', 'DiskReadOps',
  109. 'DiskWriteBytes', 'Latency', 'RequestCount',
  110. 'HealthyHostCount', 'UnHealthyHostCount');
  111. /**
  112. * Amazon CloudWatch not only aggregates the raw data coming in, it also computes
  113. * several statistics on the data. The following table lists the statistics that you can request:
  114. *
  115. * Minimum: The lowest value observed during the specified period. This can be used to
  116. * determine low volumes of activity for your application.
  117. *
  118. * Maximum: The highest value observed during the specified period. You can use this to
  119. * determine high volumes of activity for your application.
  120. *
  121. * Sum: The sum of all values received (if appropriate, for example a rate would not be
  122. * summed, but a number of items would be). This statistic is useful for determining
  123. * the total volume of a metric.
  124. *
  125. * Average: The Average of all values received during the specified period. By comparing
  126. * this statistic with the minimum and maximum statistics, you can determine the full
  127. * scope of a metric and how close the average use is to the minimum and the maximum.
  128. * This will allow you to increase or decrease your resources as needed.
  129. *
  130. * Samples: The count (number) of measures used. This statistic is always returned to
  131. * show the user the size of the dataset collected. This will allow the user to properly
  132. * weight the data.
  133. *
  134. * Statistics are computed within a period you specify, such as all CPUUtilization within a
  135. * five minute period. At a minimum, all data is aggregated into one minute intervals. This
  136. * is the minimum resolution of the data. It is this data that can be aggregated into larger
  137. * periods of time that you request.
  138. *
  139. * Aggregate data is generally available from the service within one minute from the end of the
  140. * aggregation period. Delays in data propagation might cause late or partially late data in
  141. * some cases. If your data is delayed, you should check the service’s Health Dashboard for
  142. * any current operational issues with either Amazon CloudWatch or the services collecting
  143. * the data, such as EC2 or Elastic Load Balancing.
  144. *
  145. * @var array
  146. */
  147. protected $_validStatistics = array('Average', 'Maximum', 'Minimum', 'Samples', 'Sum');
  148. /**
  149. * Valid Dimention Keys for getMetricStatistics
  150. *
  151. * ImageId: This dimension filters the data you request for all instances running
  152. * this EC2 Amazon Machine Image (AMI).
  153. *
  154. * AvailabilityZone: This dimension filters the data you request for all instances
  155. * running in that EC2 Availability Zone.
  156. *
  157. * AutoScalingGroupName: This dimension filters the data you request for all instances
  158. * in a specified capacity group. An AutoScalingGroup is a collection of instances
  159. * defined by customers of the Auto Scaling service. This dimension is only available
  160. * for EC2 metrics when the instances are in such an AutoScalingGroup.
  161. *
  162. * InstanceId: This dimension filters the data you request for only the identified
  163. * instance. This allows a user to pinpoint an exact instance from which to monitor data.
  164. *
  165. * InstanceType: This dimension filters the data you request for all instances running
  166. * with this specified instance type. This allows a user to catagorize his data by the
  167. * type of instance running. For example, a user might compare data from an m1.small instance
  168. * and an m1.large instance to determine which has the better business value for his application.
  169. *
  170. * LoadBalancerName: This dimension filters the data you request for the specified LoadBalancer
  171. * name. A LoadBalancer is represented by a DNS name and provides the single destination to
  172. * which all requests intended for your application should be directed. This metric allows
  173. * you to examine data from all instances connected to a single LoadBalancer.
  174. *
  175. * @var array
  176. */
  177. protected $_validDimensionsKeys = array('ImageId', 'AvailabilityZone', 'AutoScalingGroupName',
  178. 'InstanceId', 'InstanceType', 'LoadBalancerName');
  179. /**
  180. * Returns data for one or more statistics of given a metric
  181. *
  182. * Note:
  183. * The maximum number of datapoints that the Amazon CloudWatch service will
  184. * return in a single GetMetricStatistics request is 1,440. If a request is
  185. * made that would generate more datapoints than this amount, Amazon CloudWatch
  186. * will return an error. You can alter your request by narrowing the time range
  187. * (StartTime, EndTime) or increasing the Period in your single request. You may
  188. * also get all of the data at the granularity you originally asked for by making
  189. * multiple requests with adjacent time ranges.
  190. *
  191. * @param array $options The options you want to get statistics for:
  192. * ** Required **
  193. * MeasureName: The measure name that corresponds to
  194. * the measure for the gathered metric. Valid EC2 Values are
  195. * CPUUtilization, NetworkIn, NetworkOut, DiskWriteOps
  196. * DiskReadBytes, DiskReadOps, DiskWriteBytes. Valid Elastic
  197. * Load Balancing Metrics are Latency, RequestCount, HealthyHostCount
  198. * UnHealthyHostCount
  199. * Statistics: The statistics to be returned for the given metric. Valid
  200. * values are Average, Maximum, Minimum, Samples, Sum. You can specify
  201. * this as a string or as an array of values. If you don't specify one
  202. * it will default to Average instead of failing out. If you specify an incorrect
  203. * option it will just skip it.
  204. * ** Optional **
  205. * Dimensions: Amazon CloudWatch allows you to specify one Dimension to further filter
  206. * metric data on. If you don't specify a dimension, the service returns the aggregate
  207. * of all the measures with the given measure name and time range.
  208. * Unit: The standard unit of Measurement for a given Measure. Valid Values: Seconds,
  209. * Percent, Bytes, Bits, Count, Bytes/Second, Bits/Second, Count/Second, and None
  210. * Constraints: When using count/second as the unit, you should use Sum as the statistic
  211. * instead of Average. Otherwise, the sample returns as equal to the number of requests
  212. * instead of the number of 60-second intervals. This will cause the Average to
  213. * always equals one when the unit is count/second.
  214. * StartTime: The timestamp of the first datapoint to return, inclusive. For example,
  215. * 2008-02-26T19:00:00+00:00. We round your value down to the nearest minute.
  216. * You can set your start time for more than two weeks in the past. However,
  217. * you will only get data for the past two weeks. (in ISO 8601 format)
  218. * Constraints: Must be before EndTime
  219. * EndTime: The timestamp to use for determining the last datapoint to return. This is
  220. * the last datapoint to fetch, exclusive. For example, 2008-02-26T20:00:00+00:00.
  221. * (in ISO 8601 format)
  222. */
  223. public function getMetricStatistics(array $options)
  224. {
  225. $_usedStatistics = array();
  226. $params = array();
  227. $params['Action'] = 'GetMetricStatistics';
  228. if (!isset($options['Period'])) {
  229. $options['Period'] = 60;
  230. }
  231. if (!isset($options['Namespace'])) {
  232. $options['Namespace'] = 'AWS/EC2';
  233. }
  234. if (!isset($options['MeasureName']) || !in_array($options['MeasureName'], $this->_validMetrics, true)) {
  235. throw new Zend_Service_Amazon_Ec2_Exception('Invalid Metric Type: ' . $options['MeasureName']);
  236. }
  237. if(!isset($options['Statistics'])) {
  238. $options['Statistics'][] = 'Average';
  239. } elseif(!is_array($options['Statistics'])) {
  240. $options['Statistics'][] = $options['Statistics'];
  241. }
  242. foreach($options['Statistics'] as $k=>$s) {
  243. if(!in_array($s, $this->_validStatistics, true)) continue;
  244. $options['Statistics.member.' . ($k+1)] = $s;
  245. $_usedStatistics[] = $s;
  246. }
  247. unset($options['Statistics']);
  248. if(isset($options['StartTime'])) {
  249. if(!is_numeric($options['StartTime'])) $options['StartTime'] = strtotime($options['StartTime']);
  250. $options['StartTime'] = gmdate('c', $options['StartTime']);
  251. } else {
  252. $options['StartTime'] = gmdate('c', strtotime('-1 hour'));
  253. }
  254. if(isset($options['EndTime'])) {
  255. if(!is_numeric($options['EndTime'])) $options['EndTime'] = strtotime($options['EndTime']);
  256. $options['EndTime'] = gmdate('c', $options['EndTime']);
  257. } else {
  258. $options['EndTime'] = gmdate('c');
  259. }
  260. if(isset($options['Dimensions'])) {
  261. $x = 1;
  262. foreach($options['Dimensions'] as $dimKey=>$dimVal) {
  263. if(!in_array($dimKey, $this->_validDimensionsKeys, true)) continue;
  264. $options['Dimensions.member.' . $x . '.Name'] = $dimKey;
  265. $options['Dimensions.member.' . $x . '.Value'] = $dimVal;
  266. $x++;
  267. }
  268. unset($options['Dimensions']);
  269. }
  270. $params = array_merge($params, $options);
  271. $response = $this->sendRequest($params);
  272. $response->setNamespace($this->_xmlNamespace);
  273. $xpath = $response->getXPath();
  274. $nodes = $xpath->query('//ec2:GetMetricStatisticsResult/ec2:Datapoints/ec2:member');
  275. $return = array();
  276. $return['label'] = $xpath->evaluate('string(//ec2:GetMetricStatisticsResult/ec2:Label/text())');
  277. foreach ( $nodes as $node ) {
  278. $item = array();
  279. $item['Timestamp'] = $xpath->evaluate('string(ec2:Timestamp/text())', $node);
  280. $item['Unit'] = $xpath->evaluate('string(ec2:Unit/text())', $node);
  281. $item['Samples'] = $xpath->evaluate('string(ec2:Samples/text())', $node);
  282. foreach($_usedStatistics as $us) {
  283. $item[$us] = $xpath->evaluate('string(ec2:' . $us . '/text())', $node);
  284. }
  285. $return['datapoints'][] = $item;
  286. unset($item, $node);
  287. }
  288. return $return;
  289. }
  290. /**
  291. * Return the Metrics that are aviable for your current monitored instances
  292. *
  293. * @param string $nextToken The NextToken parameter is an optional parameter
  294. * that allows you to retrieve the next set of results
  295. * for your ListMetrics query.
  296. * @return array
  297. */
  298. public function listMetrics($nextToken = null)
  299. {
  300. $params = array();
  301. $params['Action'] = 'ListMetrics';
  302. if (!empty($nextToken)) {
  303. $params['NextToken'] = $nextToken;
  304. }
  305. $response = $this->sendRequest($params);
  306. $response->setNamespace($this->_xmlNamespace);
  307. $xpath = $response->getXPath();
  308. $nodes = $xpath->query('//ec2:ListMetricsResult/ec2:Metrics/ec2:member');
  309. $return = array();
  310. foreach ( $nodes as $node ) {
  311. $item = array();
  312. $item['MeasureName'] = $xpath->evaluate('string(ec2:MeasureName/text())', $node);
  313. $item['Namespace'] = $xpath->evaluate('string(ec2:Namespace/text())', $node);
  314. $item['Deminsions']['name'] = $xpath->evaluate('string(ec2:Dimensions/ec2:member/ec2:Name/text())', $node);
  315. $item['Deminsions']['value'] = $xpath->evaluate('string(ec2:Dimensions/ec2:member/ec2:Value/text())', $node);
  316. if (empty($item['Deminsions']['name'])) {
  317. $item['Deminsions'] = array();
  318. }
  319. $return[] = $item;
  320. unset($item, $node);
  321. }
  322. return $return;
  323. }
  324. }