Skip to content

Instantly share code, notes, and snippets.

@cbiggins
Last active August 14, 2017 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cbiggins/fa656876ecaa7d210c19 to your computer and use it in GitHub Desktop.
Save cbiggins/fa656876ecaa7d210c19 to your computer and use it in GitHub Desktop.
Puts current system load into cloudwatch. Uses a lock file as created by Kevin Traas here; http://php.net/manual/en/function.getmypid.php
#!/usr/bin/php
<?php
define('LOCK_FILE', "/var/run/".basename( $argv[0], ".php" ).".lock" );
if( isLocked() ) die( "Already running.\n" );
# The rest of your script goes here....
require 'vendor/autoload.php';
use Aws\Common\Aws;
$aws = Aws::factory();
$load = sys_getloadavg();
use Aws\CloudWatch\CloudWatchClient;
$conf = array(
"key" => "key",
"secret" => "secret",
"region" => "ap-southeast-2"
);
$client = CloudWatchClient::factory($conf);
$guzzle = new Guzzle\Http\Client();
// Get our instance deets
$request = $guzzle->get('http://169.254.169.254/latest/meta-data/instance-id');
$response = $request->send();
$instanceId = $response->getBody(true);
$client->putMetricData(array(
'Namespace' => 'NS',
'MetricData' => array(
array(
'MetricName' => 'NSLoad',
'Value' => (float) $load[0],
'Timestamp' => time(),
'Unit' => 'None',
'Dimensions' => array(
array('Name' => 'InstanceId', 'Value' => $instanceId),
array('Name' => 'AutoScalingGroupName', 'Value' => 'SNSWebGroup'),
),
),
)
));
unlink( LOCK_FILE );
exit(0);
function isLocked()
{
# If lock file exists, check if stale. If exists and is not stale, return TRUE
# Else, create lock file and return FALSE.
if( file_exists( LOCK_FILE ) )
{
# check if it's stale
$lockingPID = trim( file_get_contents( LOCK_FILE ) );
# Get all active PIDs.
$pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );
# If PID is still active, return true
if( in_array( $lockingPID, $pids ) ) return true;
# Lock-file is stale, so kill it. Then move on to re-creating it.
echo "Removing stale lock file.\n";
unlink( LOCK_FILE );
}
file_put_contents( LOCK_FILE, getmypid() . "\n" );
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment