DigitalOcean API and CPU metrics from /proc/stat

TL:DR; DigitalOcean API returns /proc/stat data in its CPU metrics API, and here I’ll show you how to convert that to something usefull.

After years of developers begging, DigitalOcean opened up their Monitoring API. This allows you to load the data that Digital Ocean bases the droplets graphs on. Great news! But how do you use that data? I wrote this post for anyone else wondering what to do with the truckload of data you get from the CPU metrics.

Now, the output of the CPU metrics had me scratching my head for a bit. Because the values didn’t really make sense. The bandwidth API simply gave me the mb/s numbers ready to go, but here something was different. It boils down to two things:

First off, the API basically returns the historic data from /proc/stat, and it is up to you to calculate the correct CPU usage from there. This is what I call usage below, and I calculate it like this:

1 - ( idle / total )

Next issue is that the percentage number you get from that is “since boot”. So it does not tell you the cpu-usage you had at that time specifically. And here I’ll provide some quick insight to how to solve that. In simple terms, you need to find out what the value was, that changed the average to what it currently is.

<?php

/**
 * Converting average since boot back to point in time value
 *
 * @param array $prev Array containing usage and timestamp
 * @param array $current Array containing usage and timestamp
 * @param int $uptime Time since boot – e.g. by running "uptime -s" and converting it to epoch
 * @return void
 */
function calculate_cpu_useage_from_average( $prev, $current, $uptime ){
	// Time from boot til measurement
	$seconds_from_boot_til_measurement = ( $prev['timestamp'] - $uptime );
	
	// Time between measurements
	$seconds_between_measurements = $current['timestamp'] - $prev['timestamp'];
	
	// Measurements in period
	$number_of_measurements = $seconds_from_boot_til_measurement / $seconds_between_measurements;

	// Value of last measurement
	$last_value = $current['usage'] * ( $number_of_measurements + 1 ) - $prev['usage'] * $number_of_measurements;

	return $last_value;
}Code language: HTML, XML (xml)

Let me know if this was of use, or if something wasn’t clear.

I'm a webdeveloper based in Oslo, Norway. I currently work with web development at Nettmaker.

I would like to change the world, but they won't give me the source…

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments