#include "tally.h"
#include "conf.h"
#include "place.h"
#include "platform.h"
#include "project.h"
#include "stamp.h"
#include "store.h"
#include "upstream.h"
#include "usage.h"
#include "wardrobes.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
constexpr size_t PATH_CAP = 4096;
constexpr size_t PATH_ROOM = 640; // what follows a home folder's path
constexpr size_t GLOB_PATH_MAX = 1024; // a session file's path, with its NUL, at most
constexpr size_t HEAD_MAX = 256; // the first bytes of a session file that are checked again
constexpr size_t EV_BUF = TALLY_EVENTS_FILE_MAX + TALLY_EVENTS_NEW_MAX + 1;
constexpr size_t KEYS = 1u << 20;
constexpr size_t OFF_TEXT = 4194304;
constexpr size_t POOL = 4194304;
constexpr int64_t DAY = 86400;
constexpr size_t TIME_LEN = 19; // "YYYY-MM-DDTHH:MM:SS"
constexpr size_t EVENT_FIELDS = 6;
static_assert(KEYS * 3 / 4 > TALLY_EVENTS_MAX + TALLY_EVENTS_NEW_MAX / 33);
// What can be lowered in a test build, to reach the limits without a great deal of data.
static struct {
size_t events; // events kept
size_t files; // session files known at once
size_t rows; // names in a report
size_t new_bytes; // bytes of events one scan adds
size_t text; // bytes of the offsets file
size_t bytes; // bytes of the events file
size_t pool; // bytes of file names
} lim;
static void limits_init(void)
{
lim.events = TALLY_EVENTS_MAX;
lim.files = TALLY_FILES_MAX;
lim.rows = TALLY_ROWS_MAX;
lim.new_bytes = TALLY_EVENTS_NEW_MAX;
lim.text = OFF_TEXT;
lim.bytes = TALLY_EVENTS_FILE_MAX;
lim.pool = POOL;
#ifdef SUIT_TEST
// SUIT_USAGE_LIMITS=NAME=N,...: events files rows new text bytes pool
const char *v = sys_getenv("SUIT_USAGE_LIMITS");
if (v == nullptr) return;
const struct {
const char *name;
size_t *at;
} known[] = {{"events=", &lim.events}, {"files=", &lim.files}, {"rows=", &lim.rows},
{"new=", &lim.new_bytes}, {"text=", &lim.text}, {"bytes=", &lim.bytes}, {"pool=", &lim.pool}};
for (const char *item = v; *item != '\0';) {
for (size_t i = 0; i < sizeof known / sizeof known[0]; i++) {
size_t n = strlen(known[i].name);
if (strncmp(item, known[i].name, n) == 0) *known[i].at = strtoul(item + n, nullptr, 10);
}
const char *comma = strchr(item, ',');
item = comma != nullptr ? comma + 1 : item + strlen(item);
}
#endif
}
// ---- time -----------------------------------------------------------------------
void tally_civil(int64_t sec, char out[20])
{
if (sec < 0) sec = 0;
int64_t days = sec / DAY;
int64_t rem = sec % DAY;
int64_t z = days + 719468;
int64_t era = z / 146097;
int64_t doe = z - era * 146097;
int64_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
int64_t mp = (5 * doy + 2) / 153;
int64_t d = doy - (153 * mp + 2) / 5 + 1;
int64_t m = mp < 10 ? mp + 3 : mp - 9;
int64_t y = yoe + era * 400 + (m <= 2 ? 1 : 0);
[[maybe_unused]] int n = snprintf(out, 20, "%04d-%02d-%02dT%02d:%02d:%02d", (int)y, (int)m, (int)d,
(int)(rem / 3600), (int)(rem % 3600 / 60), (int)(rem % 60));
ensure(n == 19);
}
static bool field_ok(const char *s, size_t len)
{
return memchr(s, '\t', len) == nullptr && memchr(s, '\n', len) == nullptr;
}
bool tally_time_ok(const char *t, size_t len)
{
static const char shape[] = "dddd-dd-ddTdd:dd:dd";
if (len < TIME_LEN || len > USAGE_TIME_MAX || !field_ok(t, len)) return false;
for (size_t i = 0; i < TIME_LEN; i++) {
bool digit = t[i] >= '0' && t[i] <= '9';
if (shape[i] == 'd' ? !digit : t[i] != shape[i]) return false;
}
return true;
}
static int64_t now_sec;
// ---- the events -------------------------------------------------------------------
static char ev_buf[EV_BUF];
static size_t ev_len;
static uint64_t keys[KEYS];
[[maybe_unused]] static uint32_t nkeys; // read only by ensure
static const char *const kind_words[USE_KIND_COUNT] = {"skill", "agent", "command"};
typedef struct {
const char *f[EVENT_FIELDS]; // time, harness, kind, name, project, id
size_t n[EVENT_FIELDS];
UseKind kind;
} EvLine;
// The event on the LEN bytes of LINE (without its newline). False if it is not one.
static bool ev_parse(const char *line, size_t len, EvLine *e)
{
const char *p = line;
const char *end = line + len;
for (size_t i = 0; i < EVENT_FIELDS; i++) {
const char *tab = i + 1 < EVENT_FIELDS ? memchr(p, '\t', (size_t)(end - p)) : nullptr;
if (i + 1 < EVENT_FIELDS && tab == nullptr) return false;
const char *stop = tab != nullptr ? tab : end;
e->f[i] = p;
e->n[i] = (size_t)(stop - p);
if (e->n[i] == 0) return false;
p = stop + 1;
}
if (memchr(e->f[EVENT_FIELDS - 1], '\t', e->n[EVENT_FIELDS - 1]) != nullptr) return false;
e->kind = USE_SKILL;
while (e->kind < USE_KIND_COUNT &&
!(strlen(kind_words[e->kind]) == e->n[2] && memcmp(kind_words[e->kind], e->f[2], e->n[2]) == 0))
e->kind++;
return e->kind < USE_KIND_COUNT && tally_time_ok(e->f[0], e->n[0]);
}
static uint64_t fnv(uint64_t h, const char *s, size_t n)
{
for (size_t i = 0; i < n; i++) h = (h ^ (uint8_t)s[i]) * 1099511628211ull;
return (h ^ 0xff) * 1099511628211ull; // a separator no field holds
}
// The identity of an invocation: the harness and the call's id, or with no id
// the harness, time, kind and name.
static uint64_t ev_key(const EvLine *e)
{
uint64_t h = 14695981039346656037ull;
h = fnv(h, e->f[1], e->n[1]);
bool has_id = !(e->n[5] == 1 && e->f[5][0] == '-');
if (has_id) {
h = fnv(h, "i", 1);
h = fnv(h, e->f[5], e->n[5]);
} else {
h = fnv(h, "n", 1);
h = fnv(h, e->f[0], e->n[0]);
h = fnv(h, e->f[2], e->n[2]);
h = fnv(h, e->f[3], e->n[3]);
}
return h | 1; // never 0, which marks a free slot
}
// Remember KEY. False if it was there already.
static bool key_add(uint64_t key)
{
ensure(nkeys < KEYS * 3 / 4);
size_t i = key & (KEYS - 1);
while (keys[i] != 0) {
if (keys[i] == key) return false;
i = (i + 1) & (KEYS - 1);
}
keys[i] = key;
nkeys++;
return true;
}
// Check every line of ev_buf, and with KEYED remember each one's key.
static int events_check(const char *path, bool keyed)
{
uint32_t count = 0;
for (size_t at = 0; at < ev_len;) {
const char *nl = memchr(ev_buf + at, '\n', ev_len - at);
count++;
EvLine e;
if (nl == nullptr || !ev_parse(ev_buf + at, (size_t)(nl - (ev_buf + at)), &e)) {
say(STDERR_FILENO, "%s:%u: not an event line (TIME HARNESS KIND NAME PROJECT ID, separated by tabs)\n", path,
count);
return 1;
}
if (count > lim.events) {
say(STDERR_FILENO, "%s: more than %zu events\n", path, lim.events);
return 1;
}
if (keyed) (void)key_add(ev_key(&e));
at = (size_t)(nl - ev_buf) + 1;
}
return 0;
}
static int events_load(const char *path, bool keyed)
{
int err = 0;
ReadResult r = project_read_file(path, ev_buf, lim.bytes, &ev_len, &err);
if (r == READ_MISSING) return 0;
if (r == READ_FAILED) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", path, strerror(err));
return 1;
}
if (r == READ_BIG) {
say(STDERR_FILENO, "suit: %s is over %zu bytes\n", path, lim.bytes);
return 1;
}
return events_check(path, keyed);
}
size_t tally_trim(char *buf, size_t len, const char *cutoff, uint32_t max_events, size_t max_bytes)
{
size_t w = 0;
uint32_t count = 0;
for (size_t at = 0; at < len;) {
size_t n = (size_t)((const char *)memchr(buf + at, '\n', len - at) - (buf + at)) + 1;
if (memcmp(buf + at, cutoff, TIME_LEN) >= 0) {
memmove(buf + w, buf + at, n);
w += n;
count++;
}
at += n;
}
size_t skip = 0;
while (count > max_events || w - skip > max_bytes) {
skip += (size_t)((const char *)memchr(buf + skip, '\n', w - skip) - (buf + skip)) + 1;
count--;
}
memmove(buf, buf + skip, w - skip);
return w - skip;
}
// ---- the offsets -------------------------------------------------------------------
// One session file as the last scan left it.
typedef struct {
const char *harness;
const char *path;
int64_t size;
int64_t mtime;
uint64_t offset; // the start of the first incomplete line
uint32_t headlen;
uint64_t head; // a hash of the first headlen bytes
} Off;
static char off_text[OFF_TEXT + 1];
static size_t off_len;
static bool off_existed;
static Off old_recs[TALLY_FILES_MAX];
static uint32_t nold;
static Off new_recs[TALLY_FILES_MAX];
static uint32_t nnew;
static uint32_t ncarried;
static char npool[POOL];
static size_t npool_used;
static char out_text[OFF_TEXT + 1];
static int off_cmp(const void *pa, const void *pb)
{
const Off *a = pa;
const Off *b = pb;
int c = strcmp(a->harness, b->harness);
return c != 0 ? c : strcmp(a->path, b->path);
}
// The fields of one offsets line, which is changed in place. HARNESS PATH SIZE MTIME OFFSET HEADLEN HEAD.
static bool off_parse(char *line, Off *o)
{
char *f[7];
char *p = line;
for (int i = 0; i < 7; i++) {
char *tab = i < 6 ? strchr(p, '\t') : nullptr;
if (i < 6 && tab == nullptr) return false;
f[i] = p;
if (tab != nullptr) *tab = '\0';
p = tab != nullptr ? tab + 1 : p + strlen(p);
}
char *end;
o->harness = f[0];
o->path = f[1];
o->size = strtoll(f[2], &end, 10);
bool ok = f[0][0] != '\0' && f[1][0] == '/' && *f[2] != '\0' && *end == '\0';
o->mtime = strtoll(f[3], &end, 10);
ok = ok && *f[3] != '\0' && *end == '\0';
o->offset = strtoull(f[4], &end, 10);
ok = ok && *f[4] != '\0' && *end == '\0';
o->headlen = (uint32_t)strtoul(f[5], &end, 10);
ok = ok && *f[5] != '\0' && *end == '\0' && o->headlen <= HEAD_MAX;
o->head = strtoull(f[6], &end, 16);
return ok && *f[6] != '\0' && *end == '\0' && o->size >= 0;
}
static int offsets_load(const char *path)
{
int err = 0;
ReadResult r = project_read_file(path, off_text, lim.text, &off_len, &err);
off_existed = r != READ_MISSING;
if (r == READ_MISSING) return 0;
if (r == READ_FAILED) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", path, strerror(err));
return 1;
}
if (r == READ_BIG) {
say(STDERR_FILENO, "suit: %s is over %zu bytes\n", path, lim.text);
return 1;
}
uint32_t line = 0;
for (char *p = off_text; p < off_text + off_len;) {
char *nl = memchr(p, '\n', (size_t)(off_text + off_len - p));
line++;
if (nl != nullptr) *nl = '\0';
if (nl == nullptr || nold == lim.files || !off_parse(p, &old_recs[nold])) {
say(STDERR_FILENO, "%s:%u: not an offsets line (HARNESS PATH SIZE MTIME OFFSET HEADLEN HEAD, at most %zu of them)\n", path, line,
lim.files);
return 1;
}
nold++;
p = nl + 1;
}
qsort(old_recs, nold, sizeof old_recs[0], off_cmp);
return 0;
}
static const Off *off_find(const char *harness, const char *path)
{
Off key = {.harness = harness, .path = path};
return bsearch(&key, old_recs, nold, sizeof old_recs[0], off_cmp);
}
// Copy S into the pool of paths kept for the new table.
static const char *pool_keep(const char *s)
{
size_t n = strlen(s) + 1;
ensure(npool_used + n <= lim.pool); // the file lists were held to the pool together with what was kept
char *at = npool + npool_used;
memcpy(at, s, n);
npool_used += n;
return at;
}
// The offsets text for the new table, sorted: false if it does not fit.
static bool offsets_text(size_t *len)
{
qsort(new_recs, nnew, sizeof new_recs[0], off_cmp);
size_t w = 0;
for (uint32_t i = 0; i < nnew; i++) {
const Off *o = &new_recs[i];
int n = snprintf(out_text + w, OFF_TEXT + 1 - w, "%s\t%s\t%lld\t%lld\t%llu\t%u\t%llx\n", o->harness, o->path,
(long long)o->size, (long long)o->mtime, (unsigned long long)o->offset, o->headlen,
(unsigned long long)o->head);
ensure(n > 0);
if ((size_t)n > lim.text - w) return false;
w += (size_t)n;
}
*len = w;
return true;
}
// ---- finding session files ---------------------------------------------------------
typedef struct {
const char *path; // in the pool of the harness's files
int64_t size;
int64_t mtime;
} FileEnt;
static char fpool[POOL];
static size_t fpool_used;
static FileEnt fent[TALLY_FILES_MAX];
static uint32_t nfent;
bool tally_wild(const char *pattern, size_t plen, const char *name)
{
const char *end = pattern + plen;
const char *star = nullptr;
const char *mark = name;
while (*name != '\0') {
if (pattern < end && *pattern == '*') {
star = pattern++;
mark = name;
} else if (pattern < end && *pattern == *name) {
pattern++;
name++;
} else if (star != nullptr) {
pattern = star + 1;
name = ++mark;
} else {
return false;
}
}
while (pattern < end && *pattern == '*') pattern++;
return pattern == end;
}
typedef struct {
char path[GLOB_PATH_MAX];
int rc; // 0, or 1 once a message has been said
uint32_t skipped; // names that cannot be kept
} Glob;
static void glob_step(Glob *g, const char *rest, size_t len);
// One name found in the folder g->path (LEN bytes), for the part PART of the pattern.
typedef struct {
Glob *g;
size_t len;
const char *part;
size_t part_len;
const char *rest; // what follows the part, or null at the last part
} Visit;
static int glob_fail(Glob *g, const char *what, const char *path)
{
say(STDERR_FILENO, "suit: cannot %s %s: %s\n", what, path, strerror(errno));
g->rc = 1;
return 1;
}
static int glob_entry(void *state, const char *name)
{
Visit *v = state;
Glob *g = v->g;
if (!tally_wild(v->part, v->part_len, name)) return 0;
size_t n = strlen(name);
if (v->len + 1 + n >= GLOB_PATH_MAX) {
g->skipped++;
return 0;
}
g->path[v->len] = '/';
memcpy(g->path + v->len + 1, name, n + 1);
glob_step(g, v->rest, v->len + 1 + n);
g->path[v->len] = '\0';
return g->rc;
}
// The folder g->path (LEN bytes) and the rest of the pattern, which starts after a slash.
static void glob_step(Glob *g, const char *rest, size_t len)
{
for (;;) {
if (rest == nullptr) {
struct stat st;
if (sys_stat(g->path, &st) != 0) {
if (errno != ENOENT && errno != ENOTDIR) (void)glob_fail(g, "look at", g->path);
return;
}
if (!S_ISREG(st.st_mode)) return;
size_t n = strlen(g->path) + 1;
if (!field_ok(g->path, n - 1)) {
g->skipped++;
return;
}
if (nfent == lim.files || npool_used + fpool_used + n > lim.pool) {
say(STDERR_FILENO, "suit: more than %zu session files (or %zu bytes of their names)\n", lim.files, lim.pool);
g->rc = 1;
return;
}
memcpy(fpool + fpool_used, g->path, n);
fent[nfent++] = (FileEnt){fpool + fpool_used, st.st_size, platform_mtime_sec(&st)};
fpool_used += n;
return;
}
const char *slash = strchr(rest, '/');
size_t plen = slash != nullptr ? (size_t)(slash - rest) : strlen(rest);
const char *next = slash != nullptr ? slash + 1 : nullptr;
bool wild = memchr(rest, '*', plen) != nullptr;
if (wild) {
Visit v = {g, len, rest, plen, next};
int rc = sys_listdir(len == 0 ? "/" : g->path, glob_entry, &v);
if (rc < 0 && errno != ENOENT && errno != ENOTDIR) (void)glob_fail(g, "read", len == 0 ? "/" : g->path);
return;
}
if (len + 1 + plen >= GLOB_PATH_MAX) {
g->skipped++;
return;
}
g->path[len] = '/';
memcpy(g->path + len + 1, rest, plen);
len += 1 + plen;
g->path[len] = '\0';
rest = next;
}
}
static int fent_cmp(const void *pa, const void *pb)
{
return strcmp(((const FileEnt *)pa)->path, ((const FileEnt *)pb)->path);
}
// The files the patterns match, sorted and without repeats, in fent. SKIPPED counts names that cannot be kept.
static int list_files(const char *const *patterns, uint32_t n, uint32_t *skipped)
{
static Glob g;
nfent = 0;
fpool_used = 0;
for (uint32_t i = 0; i < n; i++) {
g.path[0] = '\0';
g.rc = 0;
g.skipped = 0;
glob_step(&g, patterns[i] + 1, 0);
*skipped += g.skipped;
if (g.rc != 0) return 1;
}
qsort(fent, nfent, sizeof fent[0], fent_cmp);
uint32_t w = 0;
for (uint32_t i = 0; i < nfent; i++)
if (w == 0 || strcmp(fent[w - 1].path, fent[i].path) != 0) fent[w++] = fent[i];
nfent = w;
return 0;
}
// ---- reading one session file -------------------------------------------------------
static size_t new_bytes; // bytes of events this scan has added, over every harness
typedef struct {
const char *harness;
const char *home;
size_t home_len;
const Projects *projects;
uint32_t added;
uint32_t skipped;
bool full;
char last_dir[USAGE_PROJECT_MAX + 1]; // the last folder looked up, and what it came to
char last_project[USAGE_PROJECT_MAX + 1];
bool have_last;
} Reader;
// The longest project folder that holds DIR, or null.
static const ProjectEntry *project_of(const Projects *p, const char *dir)
{
const ProjectEntry *best = nullptr;
size_t best_len = 0;
for (uint32_t i = 0; i < p->n; i++) {
size_t len = strlen(p->e[i].path);
bool inside = strncmp(dir, p->e[i].path, len) == 0 && (dir[len] == '\0' || dir[len] == '/');
if (inside && len >= best_len) {
best = &p->e[i];
best_len = len;
}
}
return best;
}
// What the event says about the folder DIR: its project's key, else the folder with the home folder as "~".
static const char *project_name(Reader *r, const char *dir)
{
if (r->have_last && strcmp(r->last_dir, dir) == 0) return r->last_project;
const ProjectEntry *p = project_of(r->projects, dir);
if (p != nullptr && p->key[0] != '\0') {
memcpy(r->last_project, p->key, strlen(p->key) + 1);
} else if (dir[0] == '\0') {
memcpy(r->last_project, "-", 2);
} else if (strncmp(dir, r->home, r->home_len) == 0 && (dir[r->home_len] == '\0' || dir[r->home_len] == '/')) {
snprintf(r->last_project, sizeof r->last_project, "~%s", dir + r->home_len);
} else {
memcpy(r->last_project, dir, strlen(dir) + 1);
}
memcpy(r->last_dir, dir, strlen(dir) + 1);
r->have_last = true;
return r->last_project;
}
static void on_event(void *state, const UsageEvent *ev)
{
Reader *r = state;
const char *project = project_name(r, ev->project);
bool ok = tally_time_ok(ev->time, strlen(ev->time)) && field_ok(project, strlen(project)) &&
strlen(project) <= USAGE_PROJECT_MAX;
if (!ok) {
r->skipped++;
return;
}
char line[2 * USAGE_PROJECT_MAX + 1024];
int n = snprintf(line, sizeof line, "%s\t%s\t%s\t%s\t%s\t%s\n", ev->time, r->harness, kind_words[ev->kind], ev->name,
project, ev->id[0] != '\0' ? ev->id : "-");
ensure(n > 0 && (size_t)n < sizeof line);
EvLine e;
[[maybe_unused]] bool parsed = ev_parse(line, (size_t)n - 1, &e);
ensure(parsed);
if (!key_add(ev_key(&e))) return;
if (new_bytes + (size_t)n > lim.new_bytes) {
r->full = true;
return;
}
ensure(ev_len + (size_t)n <= EV_BUF - 1);
memcpy(ev_buf + ev_len, line, (size_t)n);
ev_len += (size_t)n;
new_bytes += (size_t)n;
r->added++;
}
static uint64_t head_hash(const char *buf, size_t n)
{
return fnv(14695981039346656037ull, buf, n);
}
// Read what is new in F for HARNESS and put its record in the new table.
static int read_file(Usage *u, UsageSource *src, Reader *r, const FileEnt *f, uint32_t *files)
{
const Off *old = off_find(r->harness, f->path);
if (old != nullptr && old->size == f->size && old->mtime == f->mtime) {
new_recs[nnew++] = *old;
ncarried++;
return 0;
}
if (old == nullptr && !off_existed && f->mtime < now_sec - TALLY_FIRST_SCAN_DAYS * DAY) {
// Too old for a first scan: noted as read up to nothing, so a later scan reads it only if it grows.
new_recs[nnew++] = (Off){r->harness, pool_keep(f->path), f->size, f->mtime, 0, 0, head_hash("", 0)};
return 0;
}
int fd = sys_open(f->path, O_RDONLY, 0);
if (fd < 0 && errno == ENOENT) return 0; // gone since it was listed
if (fd < 0) {
say(STDERR_FILENO, "suit: cannot open %s: %s\n", f->path, strerror(errno));
return 1;
}
(*files)++;
char head[HEAD_MAX];
size_t hn = 0;
ssize_t got = 1;
while (got > 0 && hn < sizeof head) {
got = sys_read(fd, head + hn, sizeof head - hn);
hn += got > 0 ? (size_t)got : 0;
}
if (got < 0 || sys_lseek(fd, 0, SEEK_SET) < 0) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", f->path, strerror(errno));
(void)sys_close(fd);
return 1;
}
uint64_t start = 0;
bool same = old != nullptr && old->size <= f->size && hn >= old->headlen &&
head_hash(head, old->headlen) == old->head;
if (same) start = old->offset;
usage_source_fd(src, fd);
uint64_t end;
bool read_ok = usage_read(u, src, start, &end, on_event, r);
int err = src->err;
(void)sys_close(fd);
if (!read_ok) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", f->path, strerror(err));
return 1;
}
new_recs[nnew++] = (Off){r->harness, pool_keep(f->path), f->size, f->mtime, end, (uint32_t)hn, head_hash(head, hn)};
return 0;
}
// ---- the harnesses --------------------------------------------------------------------
typedef struct {
char home[PATH_CAP];
char suit_home[PATH_CAP];
char lock[PATH_CAP];
char dir[PATH_CAP];
char events[PATH_CAP];
char offsets[PATH_CAP];
char projects[PATH_CAP];
} Paths;
static int find_paths(Paths *p)
{
size_t len = suit_home_path(p->suit_home, sizeof p->suit_home, "usage");
if (len == 0) return 1;
const char *home = sys_getenv("HOME");
if (home == nullptr || strlen(home) >= PATH_CAP - PATH_ROOM) {
say(STDERR_FILENO, "suit: HOME is not set, or too long\n");
return 1;
}
if (len + PATH_ROOM > PATH_CAP) {
say(STDERR_FILENO, "suit: SUIT_HOME is longer than %zu bytes\n", PATH_CAP - PATH_ROOM);
return 1;
}
snprintf(p->home, sizeof p->home, "%s", home);
p->suit_home[len] = '\0';
// The home folder left PATH_ROOM bytes for the names below.
[[maybe_unused]] int a = snprintf(p->lock, sizeof p->lock, "%s/lock", p->suit_home);
[[maybe_unused]] int b = snprintf(p->dir, sizeof p->dir, "%s/usage", p->suit_home);
[[maybe_unused]] int c = snprintf(p->events, sizeof p->events, "%s/usage/events", p->suit_home);
[[maybe_unused]] int d = snprintf(p->offsets, sizeof p->offsets, "%s/usage/offsets", p->suit_home);
[[maybe_unused]] int e = snprintf(p->projects, sizeof p->projects, "%s/projects", p->suit_home);
ensure(a > 0 && b > 0 && c > 0 && d > 0 && e > 0 && (size_t)c < sizeof p->events && (size_t)d < sizeof p->offsets);
return 0;
}
static Conf conf;
static Wards wards;
static Projects found;
static UsageRule rules[CONF_USE_MAX];
static UsagePath time_path;
static UsagePath project_path;
static Usage usage;
static UsageSource source;
static char glob_text[CONF_SESSIONS_MAX][GLOB_PATH_MAX];
static const char *globs[CONF_SESSIONS_MAX];
typedef struct {
uint32_t files;
uint32_t added;
uint32_t skipped;
bool any; // some harness has sessions
} Scan;
static bool key_is(const Entry *e, const char *key)
{
return strcmp(e->key, key) == 0;
}
// Read the new bytes of every session file of the harness at section SEC.
static int scan_harness(const Section *sec, const Paths *p, Scan *out)
{
uint32_t ng = 0;
uint32_t nr = 0;
bool has_time = false;
bool has_project = false;
for (uint32_t i = 0; i < sec->count; i++) {
const Entry *e = &conf.entries[sec->first + i];
if (key_is(e, "sessions")) {
bool tilde = e->val[0] == '~';
if ((tilde ? strlen(p->home) : 0) + strlen(e->val) >= GLOB_PATH_MAX) {
say(STDERR_FILENO, "suit: harness %s: a sessions path is longer than %zu bytes\n", sec->arg[0], GLOB_PATH_MAX - 1);
return 2;
}
// The length was checked above, so both parts fit.
const char *rest = tilde ? e->val + 1 : e->val;
size_t hl = tilde ? strlen(p->home) : 0;
memcpy(glob_text[ng], p->home, hl);
memcpy(glob_text[ng] + hl, rest, strlen(rest) + 1);
globs[ng] = glob_text[ng];
ng++;
} else if (key_is(e, "session time")) {
has_time = conf_path_parse(&time_path, e->val, false, false);
} else if (key_is(e, "session project")) {
has_project = conf_path_parse(&project_path, e->val, false, false);
} else if (strncmp(e->key, "use ", 4) == 0) {
char msg[256];
UseKind kind = e->key[4] == 's' ? USE_SKILL : e->key[4] == 'a' ? USE_AGENT : USE_COMMAND;
[[maybe_unused]] bool ok = conf_rule_parse(&rules[nr++], kind, e->val, msg, sizeof msg);
ensure(ok); // the config was parsed already
}
}
if (!has_time) {
say(STDERR_FILENO, "suit: harness %s: sessions needs a session time\n", sec->arg[0]);
return 2;
}
usage_init(&usage, rules, nr, &time_path, has_project ? &project_path : nullptr);
uint32_t skipped = 0;
if (list_files(globs, ng, &skipped) != 0) return 1;
out->skipped += skipped;
Reader r = {.harness = sec->arg[0], .home = p->home, .home_len = strlen(p->home), .projects = &found};
uint32_t files = 0;
for (uint32_t i = 0; i < nfent; i++) {
if (nnew == lim.files) {
say(STDERR_FILENO, "suit: more than %zu session files\n", lim.files);
return 1;
}
if (read_file(&usage, &source, &r, &fent[i], &files) != 0) return 1;
if (r.full) {
say(STDERR_FILENO, "suit: more than %zu bytes of new events in one scan\n", lim.new_bytes);
return 1;
}
}
out->files += files;
out->added += r.added;
out->skipped += r.skipped + (uint32_t)usage.skipped;
return 0;
}
static int write_failed(const char *path, int err)
{
say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
return 1;
}
// Write what the scan found. The events first: if the offsets then fail, the
// next scan reads the same bytes again and finds every event there already.
static int scan_write(const Paths *p, const Scan *s, size_t old_events_len)
{
size_t olen = 0;
if (!offsets_text(&olen)) {
say(STDERR_FILENO, "suit: the offsets would be over %zu bytes\n", lim.text);
return 1;
}
char cutoff[20];
tally_civil(now_sec - TALLY_DAYS_KEPT * DAY, cutoff);
ev_len = tally_trim(ev_buf, ev_len, cutoff, (uint32_t)lim.events, lim.bytes);
bool events_changed = s->added > 0 || ev_len != old_events_len;
bool offsets_changed = !off_existed || nnew != nold || ncarried != nnew;
if (!events_changed && !offsets_changed) return 0;
if (sys_mkdir(p->dir, 0755) != 0 && errno != EEXIST) {
say(STDERR_FILENO, "suit: cannot create %s: %s\n", p->dir, strerror(errno));
return 1;
}
int err = events_changed ? sys_write_atomic(p->events, ev_buf, ev_len) : 0;
if (err != 0) return write_failed(p->events, err);
err = offsets_changed ? sys_write_atomic(p->offsets, out_text, olen) : 0;
return err == 0 ? 0 : write_failed(p->offsets, err);
}
static int load_projects(const Paths *p)
{
ProjectError err;
if (projects_load(&found, p->projects, true, &err)) return 0;
say(STDERR_FILENO, "%s:%d: %s\n", p->projects, err.line, err.msg);
return 1;
}
// Whether the harness at SEC has anything to scan: a `sessions` and a `use`.
static bool scannable(const Section *sec)
{
bool sessions = false;
bool use = false;
for (uint32_t i = 0; i < sec->count; i++) {
const Entry *e = &conf.entries[sec->first + i];
sessions |= key_is(e, "sessions");
use |= strncmp(e->key, "use ", 4) == 0;
}
return sessions && use;
}
// The scan, with the lock held. OUT gets the figures.
static int scan_locked(const Paths *p, Scan *out)
{
for (uint32_t i = 0; i < conf.nsections; i++)
out->any |= conf.sections[i].kind == KIND_HARNESS && scannable(&conf.sections[i]);
if (!out->any) return 0;
limits_init();
ensure(nkeys == 0); // a process scans once, and the keys start empty
int rc = load_projects(p);
rc = rc != 0 ? rc : events_load(p->events, true);
rc = rc != 0 ? rc : offsets_load(p->offsets);
if (rc != 0) return rc;
size_t old_events_len = ev_len;
for (uint32_t i = 0; i < conf.nsections; i++) {
const Section *sec = &conf.sections[i];
if (sec->kind != KIND_HARNESS || !scannable(sec)) continue;
rc = scan_harness(sec, p, out);
if (rc != 0) return rc;
}
return scan_write(p, out, old_events_len);
}
// QUIET: say nothing when there is nothing to scan (the timer's scan). Returns the exit status.
static int scan(bool quiet, Scan *out, Paths *p)
{
*out = (Scan){};
int rc = find_paths(p);
if (rc != 0) return rc;
if (!sys_wall_sec(&now_sec)) {
say(STDERR_FILENO, "suit: cannot read the clock: %s\n", strerror(errno));
return 1;
}
rc = wardrobes_look(&wards, p->suit_home, !quiet);
if (rc == 2 && wards.n == 0 && quiet) return 0;
if (rc != 0) return rc;
if (wardrobes_load(&wards, &conf) != 0) return 2;
rc = place_lock(p->lock, false);
if (rc != 0) return rc;
rc = scan_locked(p, out);
place_unlock(p->lock);
return rc;
}
int cmd_usage_scan(void)
{
Scan s;
Paths p;
int rc = scan(false, &s, &p);
if (rc != 0) return rc;
if (!s.any) say(STDOUT_FILENO, "usage: no harness has sessions\n");
else say(STDOUT_FILENO, "usage: %u files read, %u invocations added, %u records skipped\n", s.files, s.added, s.skipped);
return 0;
}
int cmd_tend_all(void)
{
int worst = store_tend_all();
int up = upstream_tend_local();
worst = up > worst ? up : worst;
Scan s;
Paths p;
int rc = scan(true, &s, &p);
if (rc != 0) say(STDERR_FILENO, "suit: tend: the usage scan did not finish, exit %d\n", rc);
else if (s.any) say(STDOUT_FILENO, "usage: %u files read, %u invocations added, %u records skipped\n", s.files, s.added, s.skipped);
return worst;
}
// ---- the report ---------------------------------------------------------------------------
typedef struct {
int since;
bool have_kind;
UseKind kind;
const char *harness;
const char *project;
bool tsv;
} Query;
static uint32_t sel[TALLY_EVENTS_MAX + 1];
static uint32_t nsel;
static EvLine at_line(uint32_t off)
{
EvLine e;
const char *nl = memchr(ev_buf + off, '\n', ev_len - off);
[[maybe_unused]] bool ok = ev_parse(ev_buf + off, (size_t)(nl - (ev_buf + off)), &e);
ensure(ok);
return e;
}
static int cmp_field(const EvLine *a, const EvLine *b, size_t i)
{
size_t n = a->n[i] < b->n[i] ? a->n[i] : b->n[i];
int c = memcmp(a->f[i], b->f[i], n);
if (c != 0) return c;
return (a->n[i] > b->n[i]) - (a->n[i] < b->n[i]);
}
static int sel_cmp(const void *pa, const void *pb)
{
EvLine a = at_line(*(const uint32_t *)pa);
EvLine b = at_line(*(const uint32_t *)pb);
int c = (a.kind > b.kind) - (a.kind < b.kind);
c = c != 0 ? c : cmp_field(&a, &b, 3);
return c != 0 ? c : cmp_field(&a, &b, 4);
}
typedef struct {
uint32_t first;
uint32_t end;
uint64_t uses;
uint32_t projects;
const char *last; // the newest time
} Row;
static Row rows[TALLY_ROWS_MAX];
static uint32_t nrows;
static int row_cmp(const void *pa, const void *pb)
{
const Row *a = pa;
const Row *b = pb;
int c = (a->uses < b->uses) - (a->uses > b->uses);
if (c != 0) return c;
EvLine x = at_line(sel[a->first]);
EvLine y = at_line(sel[b->first]);
c = cmp_field(&x, &y, 3);
return c != 0 ? c : (x.kind > y.kind) - (x.kind < y.kind);
}
// Whether event E is in the report.
static bool wanted(const Query *q, const EvLine *e, const char *cutoff)
{
if (memcmp(e->f[0], cutoff, TIME_LEN) < 0) return false;
if (q->have_kind && e->kind != q->kind) return false;
if (q->harness != nullptr && !(strlen(q->harness) == e->n[1] && memcmp(q->harness, e->f[1], e->n[1]) == 0)) return false;
return q->project == nullptr || (strlen(q->project) == e->n[4] && memcmp(q->project, e->f[4], e->n[4]) == 0);
}
// Group the selected events, which are sorted, into rows.
static int make_rows(void)
{
nrows = 0;
for (uint32_t i = 0; i < nsel;) {
EvLine first = at_line(sel[i]);
Row r = {.first = i, .last = first.f[0]};
uint32_t j = i;
EvLine prev = {};
while (j < nsel) {
EvLine e = at_line(sel[j]);
if (e.kind != first.kind || cmp_field(&e, &first, 3) != 0) break;
if (j == i || cmp_field(&e, &prev, 4) != 0) r.projects++;
if (memcmp(e.f[0], r.last, TIME_LEN) > 0) r.last = e.f[0];
prev = e;
j++;
}
r.end = j;
r.uses = j - i;
if (nrows == lim.rows) {
say(STDERR_FILENO, "suit: more than %zu names in the window\n", lim.rows);
return 1;
}
rows[nrows++] = r;
i = j;
}
qsort(rows, nrows, sizeof rows[0], row_cmp);
return 0;
}
// The project of an event, as the last column of --tsv writes it: "," and "%" are written %2C and %25.
static void out_project(Out *o, const EvLine *e)
{
for (size_t i = 0; i < e->n[4]; i++) {
char c = e->f[4][i];
char piece[4] = {c, '\0'};
if (c == ',') memcpy(piece, "%2C", 4);
if (c == '%') memcpy(piece, "%25", 4);
out_str(o, piece);
}
}
static void print_rows(Out *o, const Query *q)
{
size_t name_w = 4;
for (uint32_t i = 0; i < nrows; i++) {
EvLine e = at_line(sel[rows[i].first]);
if (e.n[3] > name_w) name_w = e.n[3];
}
if (!q->tsv) {
char head[128];
snprintf(head, sizeof head, "%-7s %-*s %6s %-10s %s\n", "KIND", (int)name_w, "NAME", "USES", "LAST", "PROJECTS");
out_str(o, head);
}
for (uint32_t i = 0; i < nrows; i++) {
const Row *r = &rows[i];
EvLine e = at_line(sel[r->first]);
char line[PATH_CAP];
if (q->tsv) {
snprintf(line, sizeof line, "%s\t%.*s\t%llu\t%.10s\t", kind_words[e.kind], (int)e.n[3], e.f[3],
(unsigned long long)r->uses, r->last);
} else {
snprintf(line, sizeof line, "%-7s %-*.*s %6llu %-10.10s %u\n", kind_words[e.kind], (int)name_w, (int)e.n[3], e.f[3],
(unsigned long long)r->uses, r->last, r->projects);
}
out_str(o, line);
if (!q->tsv) continue;
for (uint32_t j = r->first; j < r->end;) {
EvLine a = at_line(sel[j]);
uint32_t k = j;
while (k < r->end) {
EvLine b = at_line(sel[k]);
if (cmp_field(&a, &b, 4) != 0) break;
k++;
}
if (j > r->first) out_str(o, ",");
out_project(o, &a);
char count[32];
snprintf(count, sizeof count, "=%u", k - j);
out_str(o, count);
j = k;
}
out_str(o, "\n");
}
}
static int report(const Query *q, const Paths *p)
{
if (!sys_wall_sec(&now_sec)) {
say(STDERR_FILENO, "suit: cannot read the clock: %s\n", strerror(errno));
return 1;
}
limits_init();
ev_len = 0;
int rc = events_load(p->events, false);
if (rc != 0) return rc;
char cutoff[20];
tally_civil(now_sec - q->since * DAY, cutoff);
uint64_t total = 0;
const char *oldest = nullptr;
nsel = 0;
for (size_t at = 0; at < ev_len;) {
const char *nl = memchr(ev_buf + at, '\n', ev_len - at);
EvLine e;
[[maybe_unused]] bool ok = ev_parse(ev_buf + at, (size_t)(nl - (ev_buf + at)), &e);
ensure(ok);
if (oldest == nullptr || memcmp(e.f[0], oldest, TIME_LEN) < 0) oldest = e.f[0];
if (wanted(q, &e, cutoff)) {
sel[nsel++] = (uint32_t)at;
total++;
}
at = (size_t)(nl - ev_buf) + 1;
}
qsort(sel, nsel, sizeof sel[0], sel_cmp);
rc = make_rows();
if (rc != 0) return rc;
Out o;
out_init(&o, STDOUT_FILENO);
print_rows(&o, q);
if (!q->tsv) {
char line[160];
if (oldest != nullptr)
snprintf(line, sizeof line, "%llu invocations, %u names, last %d days, oldest event kept %.10s\n",
(unsigned long long)total, nrows, q->since, oldest);
else
snprintf(line, sizeof line, "%llu invocations, %u names, last %d days, no events kept\n",
(unsigned long long)total, nrows, q->since);
out_str(&o, line);
}
if (!out_finish(&o)) {
say(STDERR_FILENO, "suit: cannot write the report: %s\n", strerror(errno));
return 1;
}
return 0;
}
static int usage_error(const char *why)
{
say(STDERR_FILENO, "suit: usage: %s\nusage: suit usage scan\n suit usage [--since DAYS] [--kind skill|agent|command] "
"[--harness NAME] [--project KEY] [--tsv]\n", why);
return 2;
}
int cmd_usage(int argc, char **argv)
{
if (argc == 1 && strcmp(argv[0], "scan") == 0) return cmd_usage_scan();
Query q = {.since = TALLY_WINDOW_DEFAULT};
for (int i = 0; i < argc; i++) {
const char *a = argv[i];
if (strcmp(a, "--tsv") == 0) {
q.tsv = true;
continue;
}
if (i + 1 == argc) return usage_error("an option needs a value, or is not one");
const char *v = argv[++i];
if (strcmp(a, "--since") == 0) {
char *end;
long days = strtol(v, &end, 10);
if (*v == '\0' || *end != '\0' || days < 1 || days > TALLY_DAYS_KEPT)
return usage_error("--since takes a number of days from 1 to 400");
q.since = (int)days;
} else if (strcmp(a, "--kind") == 0) {
q.kind = USE_SKILL;
while (q.kind < USE_KIND_COUNT && strcmp(kind_words[q.kind], v) != 0) q.kind++;
if (q.kind == USE_KIND_COUNT) return usage_error("--kind takes skill, agent or command");
q.have_kind = true;
} else if (strcmp(a, "--harness") == 0) {
q.harness = v;
} else if (strcmp(a, "--project") == 0) {
q.project = v;
} else {
return usage_error("an option needs a value, or is not one");
}
}
Scan s;
Paths p;
int rc = scan(false, &s, &p);
return rc != 0 ? rc : report(&q, &p);
}
// ---- for `suit curate` ---------------------------------------------------------------------
bool tally_scannable(const Section *sec)
{
return scannable(sec);
}
const Conf *tally_conf(void)
{
return &conf;
}
const Wards *tally_wards(void)
{
return &wards;
}
int64_t tally_now(void)
{
return now_sec;
}
int tally_open(void)
{
Scan s;
Paths p;
int rc = scan(false, &s, &p);
if (rc != 0) return rc;
limits_init();
ev_len = 0;
return events_load(p.events, false);
}
void tally_each(TallyEventSink sink, void *state)
{
for (size_t at = 0; at < ev_len;) {
const char *nl = memchr(ev_buf + at, '\n', ev_len - at);
EvLine e;
[[maybe_unused]] bool ok = ev_parse(ev_buf + at, (size_t)(nl - (ev_buf + at)), &e);
ensure(ok);
TallyEvent ev = {.time = e.f[0], .kind = e.kind, .name = e.f[3], .name_len = e.n[3], .project = e.f[4],
.project_len = e.n[4]};
sink(state, &ev);
at = (size_t)(nl - ev_buf) + 1;
}
}