/* `pic ps`: the processes pic started (picu_proc in ~/.pic/pic.sqlite). The
* liveness and signalling code is the only OS-specific part and lives here. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include "procs.h"
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef __APPLE__
#include <sys/sysctl.h>
#include <sys/types.h>
#endif
#include "platform.h"
#include "userdb.h"
#define CMD_MAX 200
#define KEEP_MS (7ll * 24 * 3600 * 1000)
#define NOTICE_EVERY_MS (3600ll * 1000)
#define NOTICE_KEY "ps.noticed_ms"
static char scope_workspace[4096], scope_conversation[128];
static long owner_pid;
static int logged;
static long long wall_ms(void) {
return (long long)(pic_platform_get()->wall_ns() / 1000000);
}
/* ---- the OS-specific part --------------------------------------------------- */
long long pic_proc_start_token(long pid) {
#ifdef __APPLE__
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)pid};
struct kinfo_proc kp;
size_t n = sizeof kp;
memset(&kp, 0, sizeof kp);
if (sysctl(mib, 4, &kp, &n, NULL, 0) != 0 || n == 0 || kp.kp_proc.p_pid != (pid_t)pid) {
return 0;
}
return (long long)kp.kp_proc.p_starttime.tv_sec * 1000000 + (long long)kp.kp_proc.p_starttime.tv_usec;
#elif defined(__linux__)
char path[64], line[1024], *p;
FILE *f;
long long tok = 0;
(void)snprintf(path, sizeof path, "/proc/%ld/stat", pid);
f = fopen(path, "r");
if (!f) {
return 0;
}
if (fgets(line, sizeof line, f) && (p = strrchr(line, ')'))) {
/* After the command's ")": state is field 3, starttime field 22. */
p++;
for (int field = 3; field < 22 && p; field++) {
p = strchr(p + 1, ' ');
}
tok = p ? strtoll(p + 1, NULL, 10) : 0;
}
(void)fclose(f);
return tok;
#else
(void)pid;
return 0;
#endif
}
int pic_proc_alive(long pid, long long token) {
long long now;
if (pid <= 0 || (kill((pid_t)pid, 0) != 0 && errno != EPERM)) {
return 0;
}
now = pic_proc_start_token(pid);
return !(token != 0 && now != 0 && now != token);
}
/* Signals the process's own group when it leads one, else the process. */
static void signal_proc(const pic_proc *p, int sig) {
if (p->pgid > 1 && p->pgid == p->pid) {
(void)killpg((pid_t)p->pgid, sig);
} else {
(void)kill((pid_t)p->pid, sig);
}
}
int pic_proc_running(const pic_proc *p) {
return p->ended_ms == 0 && pic_proc_alive((long)p->pid, p->start_token);
}
int pic_proc_kill(const pic_proc *p, int grace_ms) {
if (!pic_proc_running(p)) {
return -1;
}
signal_proc(p, SIGTERM);
for (int waited = 0; waited < grace_ms; waited += 50) {
struct timespec ts = {0, 50 * 1000000L};
if (!pic_proc_alive((long)p->pid, p->start_token)) {
return 0;
}
(void)nanosleep(&ts, NULL);
}
if (pic_proc_alive((long)p->pid, p->start_token)) {
signal_proc(p, SIGKILL);
}
return 0;
}
/* ---- recording -------------------------------------------------------------- */
void pic_proc_scope(const char *workspace, const char *conversation) {
(void)snprintf(scope_workspace, sizeof scope_workspace, "%s", workspace ? workspace : "");
(void)snprintf(scope_conversation, sizeof scope_conversation, "%s", conversation ? conversation : "");
}
/* COMMAND cut to what a row keeps, at a character boundary. */
static void short_command(const char *command, char *out, size_t cap) {
size_t n = strlen(command);
if (n > CMD_MAX) {
n = CMD_MAX;
while (n > 0 && ((unsigned char)command[n] & 0xC0) == 0x80) { /* not inside a UTF-8 sequence */
n--;
}
(void)snprintf(out, cap, "%.*s...", (int)n, command);
} else {
(void)snprintf(out, cap, "%s", command);
}
}
static long long record(const pic_proc *p) {
long long id = pic_proc_add(p);
if (id < 0 && !logged && !isatty(STDERR_FILENO)) {
logged = 1;
(void)fputs("pic: ps: could not record a process (~/.pic/pic.sqlite busy or unwritable)\n", stderr);
}
return id;
}
long long pic_proc_start(const char *kind, const char *command, long pid, long pgid) {
char cmd[CMD_MAX + 4];
pic_proc p;
short_command(command, cmd, sizeof cmd);
memset(&p, 0, sizeof p);
p.kind = kind;
p.command = cmd;
p.workspace = scope_workspace;
p.conversation = scope_conversation;
p.pid = pid;
p.pgid = pgid;
p.start_token = pic_proc_start_token(pid);
p.owner_pid = owner_pid ? owner_pid : (long)getpid();
return record(&p);
}
void pic_proc_end(long long id, int exit_code, int sig) {
if (id >= 0) {
(void)pic_proc_finish(id, exit_code, sig);
}
}
const pic_proc_sink pic_procs_sink = {pic_proc_start, pic_proc_end};
/* ---- startup ---------------------------------------------------------------- */
static int count_orphans(void *ctx, const pic_proc *p) {
if (p->owner_pid != (long long)getpid() && !pic_proc_alive((long)p->owner_pid, 0) && pic_proc_running(p)) {
(*(int *)ctx)++;
}
return 0;
}
void pic_procs_init(int notice) {
long long now = wall_ms();
owner_pid = (long)getpid();
(void)pic_procs_prune(now - KEEP_MS);
if (notice) {
int n = 0;
char *last = pic_setting(NOTICE_KEY);
long long then = last ? strtoll(last, NULL, 10) : 0;
free(last);
if (now - then >= NOTICE_EVERY_MS && pic_procs_each(0, count_orphans, &n) == 0 && n > 0) {
char stamp[32];
(void)snprintf(stamp, sizeof stamp, "%lld", now);
(void)pic_setting_set(NOTICE_KEY, stamp);
(void)fprintf(stderr, "pic: %d process%s from earlier runs still running; see pic ps\n", n, n == 1 ? "" : "es");
}
}
}
/* ---- pic ps ------------------------------------------------------------------ */
static const char *const ps_usage =
"usage: pic ps [--all] [--json]\n"
" pic ps --kill ID | --all\n"
" Lists the processes pic started that are still running: hooks (sync and async), bash tool and\n"
" \"!\" commands, and the terminal interface's request children. --all adds those finished in the\n"
" last 7 days. --json prints them as a JSON array.\n"
" --kill sends SIGTERM to the process group of a running one (SIGKILL after 3 seconds); --all\n"
" kills every running one.\n"
" Limits: processes a hook script starts on its own are not tracked, and an async hook shows as ended\n"
" (no exit status) once its process is gone.\n";
typedef struct {
int all, json, shown;
long long reconcile[64];
int nreconcile;
} list_ctx;
static const char *state_of(const pic_proc *p, int running, char *buf, size_t cap) {
if (running) {
return "running";
}
if (p->ended_ms == 0) {
return "ended";
}
if (p->signal > 0) {
(void)snprintf(buf, cap, "signal %d", p->signal);
} else if (p->exit_code >= 0) {
(void)snprintf(buf, cap, "exit %d", p->exit_code);
} else {
return "ended";
}
return buf;
}
static void json_str(const char *s) {
if (!s) {
fputs("null", stdout);
return;
}
putchar('"');
for (; *s; s++) {
unsigned char c = (unsigned char)*s;
if (c == '"' || c == '\\') {
printf("\\%c", c);
} else if (c < 0x20) {
printf("\\u%04x", c);
} else {
putchar(c);
}
}
putchar('"');
}
static int list_row(void *vctx, const pic_proc *p) {
list_ctx *c = vctx;
int running = pic_proc_running(p);
char buf[24], when[32];
time_t t = (time_t)(p->started_ms / 1000);
struct tm tm;
if (!running && p->ended_ms == 0 && !pic_proc_alive((long)p->owner_pid, 0) && c->nreconcile < 64) {
c->reconcile[c->nreconcile++] = p->id; /* nobody is left to say how it ended */
}
if (!running && !c->all) {
return 0;
}
(void)localtime_r(&t, &tm);
(void)strftime(when, sizeof when, "%m-%d %H:%M:%S", &tm);
if (c->json) {
printf("%s{\"id\":%lld,\"kind\":", c->shown ? ",\n " : "[", p->id);
json_str(p->kind);
printf(",\"command\":");
json_str(p->command);
printf(",\"workspace\":");
json_str(p->workspace && *p->workspace ? p->workspace : NULL);
printf(",\"conversation\":");
json_str(p->conversation && *p->conversation ? p->conversation : NULL);
printf(",\"pid\":%lld,\"pgid\":%lld,\"owner_pid\":%lld,\"started_ms\":%lld,\"ended_ms\":", p->pid, p->pgid,
p->owner_pid, p->started_ms);
if (p->ended_ms) {
printf("%lld", p->ended_ms);
} else {
printf("null");
}
printf(",\"exit_code\":");
if (p->exit_code >= 0) {
printf("%d", p->exit_code);
} else {
printf("null");
}
printf(",\"signal\":");
if (p->signal > 0) {
printf("%d", p->signal);
} else {
printf("null");
}
printf(",\"running\":%s}", running ? "true" : "false");
} else {
char cmd[80];
size_t n = 0;
for (const char *s = p->command; *s && n + 1 < sizeof cmd; s++) {
cmd[n++] = (unsigned char)*s < 0x20 ? ' ' : *s;
}
cmd[n] = '\0';
if (!c->shown) {
printf("%-5s %-11s %-7s %-14s %-10s %s\n", "ID", "KIND", "PID", "STARTED", "STATE", "COMMAND");
}
printf("%-5lld %-11s %-7lld %-14s %-10s %s\n", p->id, p->kind, p->pid, when, state_of(p, running, buf, sizeof buf),
cmd);
}
c->shown++;
return 0;
}
typedef struct {
long long id; /* 0: every running one */
int found, killed;
} kill_ctx;
static int kill_row(void *vctx, const pic_proc *p) {
kill_ctx *k = vctx;
if (k->id && p->id != k->id) {
return 0;
}
k->found = 1;
if (pic_proc_kill(p, 3000) == 0) {
printf("killed %lld (pid %lld, %s)\n", p->id, p->pid, p->kind);
k->killed++;
} else if (k->id) {
printf("%lld is not running\n", p->id);
}
return 0;
}
int pic_ps_command(int argc, char **argv) {
int all = 0, json = 0, kill_it = 0;
long long id = 0;
for (int i = 0; i < argc; i++) {
char *end = NULL;
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
fputs(ps_usage, stdout);
return 0;
} else if (strcmp(argv[i], "--all") == 0) {
all = 1;
} else if (strcmp(argv[i], "--json") == 0) {
json = 1;
} else if (strcmp(argv[i], "--kill") == 0) {
kill_it = 1;
} else if (argv[i][0] != '-' && (id = strtoll(argv[i], &end, 10)) > 0 && !*end) {
continue;
} else {
fputs(ps_usage, stderr);
return 2;
}
}
if (kill_it) {
kill_ctx k = {id, 0, 0};
if ((!id && !all) || (id && all) || json) {
fputs(ps_usage, stderr);
return 2;
}
if (pic_procs_each(0, kill_row, &k) != 0) {
fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
return 1;
}
if (id && !k.found) {
printf("%lld is not running\n", id);
}
if (!id && !k.killed) {
puts("nothing running");
}
return id ? (k.killed ? 0 : 1) : 0;
}
if (id) {
fputs(ps_usage, stderr);
return 2;
}
{
list_ctx c;
memset(&c, 0, sizeof c);
c.all = all;
c.json = json;
if (pic_procs_each(1, list_row, &c) != 0) {
fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
return 1;
}
for (int i = 0; i < c.nreconcile; i++) {
(void)pic_proc_finish(c.reconcile[i], -1, 0);
}
if (json) {
puts(c.shown ? "\n]" : "[]");
} else if (!c.shown) {
puts(all ? "no processes recorded" : "no processes running");
}
}
return 0;
}