Skip to content

Instantly share code, notes, and snippets.

@hostmaster
Created November 26, 2012 11:27
Show Gist options
  • Save hostmaster/4147748 to your computer and use it in GitHub Desktop.
Save hostmaster/4147748 to your computer and use it in GitHub Desktop.
A perl script that helps sum up OpenVZ container memory usage
#!/usr/bin/perl
use strict;
use warnings;
# Author: David J. Weller-Fahy
# Inspired by
# Placed in the public domain
my($field, $res_bytes, $res_pages, $value, $total);
print("$0 must be run by a SuperUser!\n") and exit(1) if ($< != 0);
# If no command-line parameters are used, stick with the default.
@ARGV = ('/proc/user_beancounters') unless @ARGV;
# These are the resources we care about.
$res_bytes = "dgramrcvbuf|kmemsize|othersockbuf|tcprcvbuf|tcpsndbuf|";
$res_pages .= "privvmpages|vmguarpages";
$total = 0;
# Iterate over the files specified in @ARGV.
while (<>) {
# Get rid of the UID and trailing colon.
s![[:digit:]]+:!! if m!kmemsize!;
# Strip leading/trailing whitespace.
s!^[[:space:]]+!!;
s![[:space:]]+$!!;
# We only care about the lines containing the resources in
# $res_(bytes|pages), so skip all other lines.
next unless m!^(?:$res_bytes$res_pages)!;
# Set the field to extract.
$field = (m!^kmemsize! ? 2 : 1);
# Grab the resource and value.
$value = (split)[$field];
# If this is a 'page' resource, multiply by the number of bytes in a page.
$value *= 4096 if m!^(?:$res_pages)!;
# Add this value to the total.
$total += $value;
}
# Original used 1024000 (??). Not sure why, the value below is 1024*1024.
$total /= 1048576;
# Print the number of MB used, rounded to 2 decimal places.
printf("Total MiB used: %.2f\n", $total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment