#include <u.h>
#include <libc.h>
#include <thread.h>
#include <bio.h>
#include "collectd.h"
Biobuf *
readswap(Biobuf *bp, char *file, Swap *swap)
{
char *p, *q;
if(bp == nil){
bp = Bopen(file, OREAD);
if(bp == nil)
sysfatal("couldn't open %s: %r", file);
}
p = Brdline(bp, '\n');
if(p == nil){
Bterm(bp);
return nil;
}
p[Blinelen(bp)-1] = '\0';
if(q = strchr(p, ' ')){
*q++ = '\0';
swap->name = q;
}else
sysfatal("unexpected swap output");
if(q = strchr(p, '/')){
*q++ = '\0';
swap->m = strtoul(q, nil, 0);
}
swap->n = strtoul(p, nil, 0);
return bp;
}
static void
submit(Channel *c, char *type, double value)
{
Packet *pp;
pp = palloc();
pp->host = estrdup(hostname);
pp->interval = interval;
pp->time = time(nil);
pp->plugin = estrdup("memory");
pp->type = estrdup("memory");
pp->tinst = estrdup(type);
addgauge(pp, value);
if(nbsendp(c, pp) < 1)
pfree(pp);
}
void
memoryproc(void *arg)
{
Channel *c;
Biobuf *bp;
Swap swap;
ulong pagesize;
double total, free;
c = arg;
bp = nil;
for(;;){
snooze();
pagesize = 0;
total = free = 0;
while(bp = readswap(bp, "/dev/swap", &swap)){
if(strcmp(swap.name, "memory") == 0)
total = (double)swap.n;
else if(strcmp(swap.name, "pagesize") == 0)
pagesize = swap.n;
/*
* To avoid confusion, we only report free
* user pages; all other pages (including free
* kernel pages) are considered used.
*/
else if(strcmp(swap.name, "user") == 0)
free = (double)(swap.m-swap.n) * pagesize;
}
submit(c, "used", total-free);
submit(c, "free", free);
}
}
|