private function addCloudwatchAlarm($sqsName, $region, $accessKey, $secretKey) { $data['region'] = $region; if ($accessKey != null && $secretKey != null) { $data['key'] = $accessKey; $data['secret'] = $secretKey; } $cwClient = new CloudWatchClient($data); $cwClient->putMetricAlarm(['AlarmName' => sprintf('Syrup %s queue is full', $sqsName), 'ActionsEnabled' => true, 'AlarmActions' => ['arn:aws:sns:us-east-1:147946154733:Connection_SQS_Alerts'], 'MetricName' => 'ApproximateNumberOfMessagesVisible', 'Namespace' => 'AWS/SQS', 'Statistic' => 'Average', 'Dimensions' => [['Name' => 'QueueName', 'Value' => $sqsName]], 'Period' => 300, 'EvaluationPeriods' => 1, 'Threshold' => 5, 'ComparisonOperator' => 'GreaterThanOrEqualToThreshold']); }
protected function execute(InputInterface $input, OutputInterface $output) { $noWatch = $input->getOption('no-watch'); $queueId = $this->getQueueId(); $snsConfig = $this->getContainer()->getParameter('sns'); $region = isset($snsConfig['region']) ? $snsConfig['region'] : 'us-east-1'; /** @var QueueFactory $queueFactory */ $queueFactory = $this->getContainer()->get('syrup.queue_factory'); $sqs = $queueFactory->create($queueId, $region, $snsConfig['key'], $snsConfig['secret']); /** @var Connection $conn */ $conn = $this->getContainer()->get('doctrine.dbal.syrup_connection'); $stmt = $conn->query("SELECT * FROM queues WHERE id='{$queueId}'"); $res = $stmt->fetchAll(); if (empty($res)) { $conn->insert('queues', ['id' => $queueId, 'access_key' => $snsConfig['key'], 'secret_key' => $snsConfig['secret'], 'region' => $region, 'url' => $sqs->get('QueueUrl')]); } $sqsClient = new SqsClient(['region' => $region, 'version' => '2012-11-05', 'credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']]]); $sqsArn = $sqsClient->getQueueArn($sqs->get('QueueUrl')); // subscribe SQS to SNS $snsClient = new SnsClient(['region' => $region, 'version' => '2010-03-31', 'credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']]]); $snsClient->subscribe(['TopicArn' => $snsConfig['topic_arn'], 'Protocol' => 'sqs', 'Endpoint' => $sqsArn]); // add policy to SQS to allow SNS sending messages to it $sqsPolicy = '{ "Version": "2008-10-17", "Id": "' . $sqsArn . '/SQSDefaultPolicy", "Statement": [ { "Sid": "sqs-sns", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "SQS:SendMessage", "Resource": "' . $sqsArn . '", "Condition": { "ArnEquals": { "aws:SourceArn": "' . $snsConfig['topic_arn'] . '" } } } ] }'; $sqsClient->setQueueAttributes(['QueueUrl' => $sqs->get('QueueUrl'), 'Attributes' => ['Policy' => $sqsPolicy]]); $output->writeln("SQS created and registered to SNS"); // Add Cloudwatch alarm if (!$noWatch) { $cwClient = new CloudWatchClient(['region' => $region, 'version' => '2010-08-01', 'credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']]]); $cwClient->putMetricAlarm(['AlarmName' => sprintf('Syrup %s queue is full', $queueId), 'ActionsEnabled' => true, 'AlarmActions' => [$snsConfig['alarm_topic_arn']], 'MetricName' => 'ApproximateNumberOfMessagesVisible', 'Namespace' => 'AWS/SQS', 'Statistic' => 'Average', 'Dimensions' => [['Name' => 'QueueName', 'Value' => $queueId]], 'Period' => 300, 'EvaluationPeriods' => 1, 'Threshold' => 5, 'ComparisonOperator' => 'GreaterThanOrEqualToThreshold']); $output->writeln("Cloudwatch alarm created"); } }
/** * @covers Aws\CloudWatch\CloudWatchClient::factory */ public function testFactoryInitializesClient() { $client = CloudWatchClient::factory(array('key' => 'foo', 'secret' => 'bar', 'region' => 'us-west-2')); $this->assertInstanceOf('Aws\\Common\\Signature\\SignatureV2', $client->getSignature()); $this->assertInstanceOf('Aws\\Common\\Credentials\\Credentials', $client->getCredentials()); $this->assertEquals('https://monitoring.us-west-2.amazonaws.com', $client->getBaseUrl()); }
function getCloudWatchClient($conf) { if (isset($conf->aws->profil)) { return CloudWatchClient::factory(array('profil' => $conf->aws->profil, 'region' => $conf->aws->region, 'version' => '2010-08-01')); } return CloudWatchClient::factory(array('credentials' => array('key' => $conf->aws->key, 'secret' => $conf->aws->secret), 'region' => $conf->aws->region, 'version' => '2010-08-01')); }
public function testMetricOperations() { $namespace = 'AWSSDKPHP'; $metricName = 'CloudWatchTests'; $dimensions = array(array('Name' => 'Prefix', 'Value' => $this->getResourcePrefix())); self::log('Put some data to a metric.'); $this->cloudwatch->putMetricData(array('Namespace' => $namespace, 'MetricData' => array(array('MetricName' => $metricName, 'Timestamp' => time(), 'Value' => rand(1, 20) + rand(1, 59) / 100, 'Unit' => Unit::KILOBYTES, 'Dimensions' => $dimensions)))); self::log('Make sure the metric exists.'); $found = false; foreach ($this->cloudwatch->getIterator('ListMetrics', array('Namespace' => $namespace)) as $metric) { if ($found = $metric['MetricName'] == $metricName && $metric['Dimensions'] == $dimensions) { break; } } if (!$found) { $this->markTestSkipped('The CloudWatch metric you created has not yet been picked up by CloudWatch. This ' . 'can take up to 15 minutes to occur. Please run this test again later.'); } self::log('Verify the statistics of the data that has been put.'); $result = $this->cloudwatch->getMetricStatistics(array('Namespace' => $namespace, 'MetricName' => $metricName, 'Dimensions' => $dimensions, 'StartTime' => strtotime('-1 days'), 'EndTime' => strtotime('now'), 'Period' => 3000, 'Statistics' => array(Statistic::MAXIMUM, Statistic::MINIMUM))); $min = min($result->getPath('Datapoints/*/Minimum')); $max = max($result->getPath('Datapoints/*/Maximum')); $this->assertGreaterThan(1, $min); $this->assertLessThan(22, $max); }
/** * @param CollectorAccessInterface $collector * @return int */ public function requestValue(CollectorAccessInterface $collector) { $metric = $collector->getMetric(); $identifier = isset($metric['identifier']) ? $metric['identifier'] : null; $container = MonolistWatcherBundle::getContainer(); $awsConfig = $container->getParameter('aws'); if ($awsConfig['enabled'] == false) { return null; //TODO write to log or handle it on another way } $client = CloudWatchClient::factory(array('key' => $awsConfig['access_key'], 'secret' => $awsConfig['secret_key'], 'region' => 'eu-west-1')); $result = $client->getMetricStatistics(array('Namespace' => 'AWS/ELB', 'MetricName' => 'UnHealthyHostCount', 'Dimensions' => array(array('Name' => 'LoadBalancerName', 'Value' => $identifier)), 'StartTime' => strtotime('-2 min'), 'EndTime' => strtotime('now'), 'Period' => 60, 'Statistics' => array('Maximum', 'Minimum'))); $resultArray = $result->get('Datapoints'); $lastResult = empty($resultArray) ? null : array_pop($resultArray); return intval($lastResult['Maximum']); }
public function getConsumedCapacity($indexName = self::PRIMARY_INDEX, $period = 60, $num_of_period = 5, $timeshift = -300) { $cloudwatch = new CloudWatchClient(["profile" => $this->config['profile'], "region" => $this->config['region'], "version" => "2010-08-01"]); $end = time() + $timeshift; $end -= $end % $period; $start = $end - $num_of_period * $period; $requestArgs = ["Namespace" => "AWS/DynamoDB", "Dimensions" => [["Name" => "TableName", "Value" => $this->tableName]], "MetricName" => "ConsumedReadCapacityUnits", "StartTime" => date('c', $start), "EndTime" => date('c', $end), "Period" => 60, "Statistics" => ["Sum"]]; if ($indexName != self::PRIMARY_INDEX) { $requestArgs['Dimensions'][] = ["Name" => "GlobalSecondaryIndexName", "Value" => $indexName]; } $result = $cloudwatch->getMetricStatistics($requestArgs); $total_read = 0; $total_count = 0; foreach ($result['Datapoints'] as $data) { $total_count++; $total_read += $data['Sum']; } $readUsed = $total_count ? $total_read / $total_count / 60 : 0; $requestArgs['MetricName'] = 'ConsumedWriteCapacityUnits'; $result = $cloudwatch->getMetricStatistics($requestArgs); $total_write = 0; $total_count = 0; foreach ($result['Datapoints'] as $data) { $total_count++; $total_write += $data['Sum']; } $writeUsed = $total_count ? $total_write / $total_count / 60 : 0; return [$readUsed, $writeUsed]; }
private function getCloudWatchClient() { return CloudWatchClient::factory($this->getConnectionOptions()); }
/** * @param array $config * * @return array */ protected function getCpuUtilization($config) { $client = CloudWatchClient::factory(['key' => $config['key'], 'secret' => $config['secret'], 'region' => $config['region']]); $result = $client->getMetricStatistics(['Namespace' => 'AWS/EC2', 'MetricName' => 'CPUUtilization', 'Dimensions' => [['Name' => $config['dimension_name'], 'Value' => $config['dimension_value']]], 'StartTime' => strtotime($config['begin']), 'EndTime' => strtotime('now'), 'Period' => 900, 'Statistics' => ['Average']]); $result = $result->toArray(); $data = []; foreach ($result['Datapoints'] as $row) { $data[] = ['x' => (strtotime($row['Timestamp']) + 7200) * 1000, 'y' => round($row['Average'], 3)]; } usort($data, function ($first, $second) { if ($first['x'] > $second['x']) { return 1; } return $first['x'] == $second['x'] ? 0 : -1; }); return ['chart.html.twig', ['data' => $data, 'name' => $config['environment'] . ' - CPU']]; }
<?php require 'vendor/autoload.php'; use Aws\CloudWatch\CloudWatchClient; use Symfony\Component\Yaml\Yaml; try { $file = realpath(dirname(__FILE__)) . '/config/config.yml'; if ($file && file_exists($file)) { $config = Yaml::parse(file_get_contents($file)); } else { die('No config.yml was found. Use config/config.yml.sample as base example'); } $client = new CloudWatchClient(['region' => $config['amazon']['amazonRegion'], 'version' => $config['amazon']['amazonVersion'], 'credentials' => ['key' => $config['amazon']['amazonKey'], 'secret' => $config['amazon']['amazonSecret']]]); $date = new DateTime(null, new DateTimeZone('America/Toronto')); $endTime = $date->getTimestamp(); $date = $date->sub(new DateInterval('P1D')); $startTime = $date->getTimestamp(); $metrics = $client->getMetricStatistics(['Namespace' => 'AWS/RDS', 'MetricName' => 'FreeStorageSpace', 'DBInstanceIdentifier' => $config['amazon']['amazonRDSdb'], 'StartTime' => $startTime, 'EndTime' => $endTime, 'Period' => 3600 * 6, 'Statistics' => ['Maximum'], 'Unit' => 'Bytes']); if (is_object($metrics)) { $dataList = $metrics['Datapoints']; $x = sizeof($dataList); if ($x > 0) { foreach ($dataList as $data) { $size = number_format($data['Maximum'] / 1073741824, 2) . ' GB'; $pct = number_format($size * 100 / 307.2, 2); echo "[{$x}] " . $size . " or {$pct}% of space still available" . PHP_EOL; // Space available to use $x--; } } }
public function __construct() { parent::__construct(); $this->cloud_watch_client = CloudWatchClient::factory(['region' => 'us-east-1']); }