Quickly start monitoring with our PHP API wrapper

API Wrapper

By Jonathan Sundqvist, Engineer at Server Density.
Published on the 19th May, 2015.

For a long time now Server Density customers have been using our API to automate day-to-day things. Things like creating a bunch of users, viewing alerts or getting historical data from their monitoring account. However making a call to the API with cURL takes ~10 lines of code, which is too much.

TL;DR today we’ve released an api-wrapper in PHP. Instead of 10 lines you’ll now only need 1 line, empowering you to focus on writing an application rather than writing redundant code. Check out this script that we will go into detail explaining below.

Getting started.

First thing’s first, you’ll need a Server Density account and an API token to be able to use the API. Once you login to your account you can create an API token by clicking on the settings menu next to your name. The option of creating an API token will be under the security tab as you can see below:

Adding an API token

Using PHP to create new users.

You can find the api-wrapper that we’ve created at the packagist – right here. From there on you’ll install the package using composer if you haven’t already got it – right here.

Once you have the package installed we can finally start with the fun stuff. To start using the API with the wrapper the first step is to authenticate. So let’s do that.


require __DIR__.'/vendor/autoload.php';
use serverdensity\Client;

$client = Client();
$client->authenticate('api_token_here');

Once you’ve authenticated you can start using the API for creating users, devices, services or getting historical data. Let’s start with creating a user and give that user a tag so we can limit what they will see.

When you create or update anything with the API wrapper we expect it to be an array and we’ll make any transformations needed in the backend. If you want to give a readWrite permission to a user using our tags feature the tag has to be created in advance with the API. But when you’re creating a user, the only thing you’d like to think of is creating a user. So we’ll take care of creating the tag for you.

If you don’t have any tags to add, you can just omit that array entirely.


$user = array(
	'firstName' => 'Chardee',
	'lastName' => 'MacDennis',
	'login' => 'iasip',
	'password' => 'MantisToboggan'
	'emailAddresses' => ['ChardeeMacDennis@iasip.com'],
	'admin' => false,
        'permissions' => array(
            'limited' => true
        )
);

$client->api('users')->create($user, ['My tag']);

If you’re creating a lot of users it’s better to give them a random password and ask the user to reset the password as the first thing they do within the app.

Using PHP to create new devices with tags.

Now that we’ve created a user with the tag ‘My tag’ we want this user to only be able to view a device with the tag ‘My tag’. We can do that easily by creating a device:


$device = array(
	'name' => 'R2D2'
);

$device = $client->api('devices')->create($device, ['My tag']);

Installing the agent on the created device.

Now you’ve created a brand new device on Server Density, the only thing that’s left is to connect the representation of your device and make sure it gets all of its data monitored.

To do that we use the installation script that we provide. You can read more about it in this help article. But what it comes down to is running the following three lines.


shell_exec("curl -Lk https://www.serverdensity.com/downloads/agent-install.sh > install.sh");

shell_exec("chmod +x install.sh");

shell_exec('./install.sh -a https://example.serverdensity.io -k '.$device['agentKey']);

It will fetch the installation script onto your computer and then run it.

Now that you’ve created a user, a device with tags, and started monitoring everything by installing the agent; you’re ready to start exploring all the beautiful data that we’ll start to accumulate.

Start visualising data from Server Density.

Now your Server Density account is monitoring things for you, there’ll be tons of data for you to analyse. Good news, we also have an endpoint so you can slice and dice your data as much as you’d like.

In the example below, we’ll first see what data is available in the past 2 hours. The response will be an array of all available metrics that you could filter for. Now that we know what metrics are available we can pick and choose what to fetch:


$device_id = '5464d72976d3779913e933be';
$available = $client->api('metrics')->available($device_id, time()-7200, time());
print_r($available);

One of the metrics that exist in a normal device is network traffic, so we’ll choose to fetch that specific metric.


$filter = array(
	'networkTraffic' => [
		'eth0' => ['rxMByteS', 'txMByteS'],
		'eth1' => ['rxMByteS', 'txMByteS']
 	]
);
$metrics = $client->api('metrics')->metrics($device_id, $filter, time()-7200, time());

Now we’ve got the metrics, however the response is nested in a tree like structure and it’s somewhat difficult to access the data. So we’ll format the response into something much more manageable. The formatted data will be an array of arrays each containing one of the four data sets that we filtered for.


$data = $client->api('metrics')->formatMetrics($metrics);
echo $data[0]['source'] // Network traffic > eth0 > Received MB\\/s
echo $data[1]['source'] // Network traffic > eth0 > Transmitted MB\\/s
echo $data[2]['source'] // Network traffic > eth1 > Received MB\\/s
echo $data[3]['source'] // Network traffic > eth1 > Transmitted MB\\/s

$data[0]['data'] // contains the actual data in the following format
// [ ['x' => 123123, 'y' => 0.341] ... ]
// If we want to have the x and y points separate we can do that too. 

$separateData = $client->api('metrics')->separateXYdata($data);
$separateData[0]['xPoints'];
$separateData[0]['yPoints'];

With these two formats of the data it should be easy for you to either pop it into a chart (which we will do next) or calculate the sum, average or median of all the y points.

Building the graph.

I chose to visualise the data through a javascript charting software called amCharts. They are pretty neat. But before we can pop in the data into amCharts we need to format it in a way amCharts likes. Luckily, the data is already quite well formatted for this purpose.


$points = $data[0];
$graphData = array();

foreach($points['data'] as $i => $array){
    $graphData[] = array(
        'mydate' => date("Y-m-d H:i", $array['x']),
        'eth1' => $array['y']
    );
}

$jsonGraph = json_encode($graphData);

That’s it! Now you can insert the json object into amCharts and it will work out of the box. You can see below how the graph looks. If you want the code in a coherent chunk, I’ve included everything in a gist for you.

Articles you care about. Delivered.

Help us speak your language. What is your primary tech stack?

Maybe another time