Plan 9 from Bell Labs’s /usr/web/sources/contrib/stallion/src/collectd/users.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <thread.h>
#include <bio.h>
#include "collectd.h"

#define	MAXUSERS	128

static int
lookup(char *base[], long nel, char *s)
{
	long i;

	for(i = 0; i < nel; ++i)
		if(strcmp(base[i], s) == 0)
			return i;
	return -1;
}

static ulong
getusers(char *file)
{
	int fd;
	Dir *dir;
	long i, n;
	ulong nusers;
	char *users[MAXUSERS];

	nusers = 0;
	fd = open(file, OREAD);
	if(fd < 0)
		sysfatal("couldn't open %s: %r", file);
	n = dirreadall(fd, &dir);
	for(i = 0; i < n; ++i)
		if(lookup(users, nusers, dir[i].uid) < 0)
			users[nusers++] = dir[i].uid;
	free(dir);
	close(fd);

	return nusers;
}

static void
submit(Channel *c, double value)
{
	Packet *pp;

	pp = palloc();
	pp->host = estrdup(hostname);
	pp->interval = interval;
	pp->time = time(nil);
	pp->plugin = estrdup("users");
	pp->type = estrdup("users");
	addgauge(pp, value);

	if(nbsendp(c, pp) < 1)
		pfree(pp);
}

void
usersproc(void *arg)
{
	char *p;
	Channel *c;

	/*
	 * Reporting users doesn't make much sense on terminals;
	 * skip this plugin for these systems.
	 */
	p = getenv("service");
	if(p && strcmp(p, "terminal") == 0)
		exits(nil);
	free(p);

	c = arg;
	for(;;){
		snooze();

		/*
		 * There is not a good method for determining the
		 * number of active users.  The following method is
		 * similar to who(1), though less discerning when it
		 * comes to checking for broken processes.
		 */
		submit(c, getusers("/proc"));
	}
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].