CloudWatch.php 17 KB

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