Skip to content
pi-c Artifact [917cba7122]
Login

Artifact [917cba7122]

Artifact 917cba71221b648f1e35bd219ea0e3264e10a77f68cca6a88eefdd83d995d6f2:


#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#include "doctor.h"
#include "folder.h"
#include "pic.h"
#include "platform.h"

#define DOC_MAX 32

typedef struct {
    char text[4096];
    size_t len;
} doc_say;

static void doc_line(doc_say *d, const char *fmt, ...) {
    va_list ap;
    if (d->len >= sizeof d->text - 1) {
        return;
    }
    va_start(ap, fmt);
    (void)vsnprintf(d->text + d->len, sizeof d->text - d->len, fmt, ap);
    va_end(ap);
    d->len += strlen(d->text + d->len);
    if (d->len < sizeof d->text - 1) {
        d->text[d->len++] = '\n';
        d->text[d->len] = '\0';
    }
}

/* The schema the journal at DB says it has, or -1 when it is no journal. */
static long doc_schema(const char *db) {
    sqlite3 *h = NULL;
    sqlite3_stmt *q = NULL;
    long v = -1;
    if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, pic_platform_get()->vfs) == SQLITE_OK &&
        sqlite3_prepare_v2(h, "SELECT CAST(value AS INTEGER) FROM pic_meta WHERE key = 'schema_version'", -1, &q, NULL) ==
            SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW) {
        v = sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    sqlite3_close(h);
    return v;
}

static void doc_sleep_ms(int ms) {
    struct timespec ts = {ms / 1000, (long)(ms % 1000) * 1000000L};
    (void)nanosleep(&ts, NULL);
}

/* Waits up to MS for the journal to be held by no one. 1 when it is. */
static int doc_wait_unheld(const char *db, int ms) {
    for (int waited = 0;; waited += 50) {
        if (pic_journal_unheld(db)) {
            return 1;
        }
        if (waited >= ms) {
            return 0;
        }
        doc_sleep_ms(50);
    }
}

/* Opens the journal as pic does, which migrates it: 0, or -1 with ERR. */
static int doc_open(const char *db, char *err, size_t cap) {
    pic_store s;
    int rc = pic_open(&s, db);
    if (rc != 0) {
        (void)snprintf(err, cap, "%s", s.err);
    }
    pic_close(&s);
    return rc == 0 ? 0 : -1;
}

typedef struct {
    long pid;
    char what[64];
    int remote, signalled;
} doc_target;

/* Every process that holds the journal but this one and its parent: those that say what they are,
 * then those the platform sees with a pic's command name. Others are reported and left alone. */
static int doc_targets(const char *db, doc_target *t, int cap, doc_say *d) {
    pic_holder h[DOC_MAX];
    long pids[DOC_MAX];
    char names[DOC_MAX][32];
    int n = 0, nh = pic_holders(db, h, DOC_MAX), nu = pic_journal_users(db, pids, names, DOC_MAX);
    for (int i = 0; i < nh && i < DOC_MAX && n < cap; i++) {
        int seen = nu < 0; /* where the platform can tell, the pid must have the lock open: never a reused one */
        for (int k = 0; k < nu && k < DOC_MAX && !seen; k++) {
            seen = pids[k] == h[i].pid;
        }
        if (h[i].pid <= 1 || h[i].pid == (long)getpid() || h[i].pid == (long)getppid() || !seen) {
            continue;
        }
        t[n].pid = h[i].pid;
        t[n].remote = strcmp(h[i].role, "pic remote") == 0;
        t[n].signalled = 0;
        (void)snprintf(t[n].what, sizeof t[n].what, "%s%s", h[i].role,
                       h[i].schema > 0 && h[i].schema < atol(PIC_SCHEMA_VERSION) ? ", an older pic" : "");
        n++;
    }
    for (int i = 0; i < nu && i < DOC_MAX && n < cap; i++) {
        int known = pids[i] <= 1 || pids[i] == (long)getpid() || pids[i] == (long)getppid();
        for (int k = 0; k < n && !known; k++) {
            known = t[k].pid == pids[i];
        }
        if (known) {
            continue;
        }
        if (strncmp(names[i], "pic", 3) != 0) {
            doc_line(d, "pid %ld (%s) has the journal open and is not a pic: left alone", pids[i], names[i]);
            continue;
        }
        t[n].pid = pids[i];
        t[n].remote = 0;
        t[n].signalled = 0;
        (void)snprintf(t[n].what, sizeof t[n].what, "an older pic that does not say what it is");
        n++;
    }
    return n;
}

static int doc_alive(long pid) { return kill((pid_t)pid, 0) == 0 || errno == EPERM; }

static void doc_report(int json, int ok, const char *state, doc_say *d, const char *db) {
    char warn[2048], dir[4096];
    const char *slash = strrchr(db, '/');
    size_t n = slash ? (size_t)(slash - db) : 0;
    if (n && n < sizeof dir && n >= 5 && strncmp(slash - 5, "/.pic", 5) == 0) { /* WORKSPACE/.pic/journal.sqlite */
        memcpy(dir, db, n);
        dir[n] = '\0';
        if (pic_folder_report(dir, warn, sizeof warn)) {
            for (char *l = strtok(warn, "\n"); l; l = strtok(NULL, "\n")) {
                doc_line(d, "%s", l);
            }
        }
    }
    if (d->len && d->text[d->len - 1] == '\n') {
        d->text[--d->len] = '\0';
    }
    if (json) {
        sqlite3 *h = NULL;
        sqlite3_stmt *q = NULL;
        if (sqlite3_open(":memory:", &h) == SQLITE_OK &&
            sqlite3_prepare_v2(h, "SELECT json_object('type', 'doctor', 'ok', json(?1), 'state', ?2, 'message', ?3)", -1, &q,
                               NULL) == SQLITE_OK) {
            (void)sqlite3_bind_text(q, 1, ok ? "true" : "false", -1, SQLITE_STATIC);
            (void)sqlite3_bind_text(q, 2, state, -1, SQLITE_STATIC);
            (void)sqlite3_bind_text(q, 3, d->text, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                puts((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        sqlite3_close(h);
    } else if (d->len) {
        puts(d->text);
    }
    (void)fflush(stdout);
}

int pic_doctor(const char *db, int json) {
    doc_say d = {"", 0};
    doc_target t[DOC_MAX];
    char err[PIC_ERR_CAP];
    struct stat sb;
    long v, own = atol(PIC_SCHEMA_VERSION);
    int n, remote = 0;
    pic_store_role("pic doctor", 0);
    if (stat(db, &sb) != 0) {
        doc_line(&d, "There is no journal at %s, so there is nothing to fix.", db);
        doc_report(json, 1, "none", &d, db);
        return 0;
    }
    if ((v = doc_schema(db)) < 0) {
        doc_line(&d, "%s is not a pic journal, or it is damaged; pic doctor leaves it as it is.", db);
        doc_report(json, 0, "damaged", &d, db);
        return 1;
    }
    if (v > own) {
        doc_line(&d, "This workspace's journal was written by a newer pic; update pic (in pic's source: make install-pic).");
        doc_report(json, 0, "newer", &d, db);
        return 1;
    }
    if (v == own) {
        if (doc_open(db, err, sizeof err) != 0) {
            doc_line(&d, "The journal is up to date, but it does not open: %s", err);
            doc_report(json, 0, "damaged", &d, db);
            return 1;
        }
        doc_line(&d, "The journal is up to date; nothing to fix.");
        doc_report(json, 1, "current", &d, db);
        return 0;
    }
    doc_line(&d, "This workspace's journal is from an older pic; updating it.");
    if (doc_open(db, err, sizeof err) == 0) { /* nobody in the way, or they stepped aside */
        doc_line(&d, "Updated the journal; pic works in this workspace again.");
        doc_report(json, 1, "updated", &d, db);
        return 0;
    }
    if (pic_journal_unheld(db)) { /* not a holder: the migration itself failed */
        doc_line(&d, "The journal could not be updated: %s", err);
        doc_report(json, 0, "damaged", &d, db);
        return 1;
    }
    if (!(n = doc_targets(db, t, DOC_MAX, &d))) {
        doc_line(&d, "Something keeps the journal open that pic doctor cannot find or stop: %s", err);
        doc_report(json, 0, "blocked", &d, db);
        return 1;
    }
    for (int i = 0; i < n; i++) { /* the polite signal first */
        if (kill((pid_t)t[i].pid, SIGTERM) == 0) {
            t[i].signalled = 1;
            remote |= t[i].remote;
        } else {
            doc_line(&d, "Could not stop pid %ld (%s): %s.", t[i].pid, t[i].what, strerror(errno));
        }
    }
    if (!doc_wait_unheld(db, 5000)) {
        for (int i = 0; i < n; i++) {
            if (t[i].signalled && doc_alive(t[i].pid)) {
                (void)kill((pid_t)t[i].pid, SIGKILL);
            }
        }
        (void)doc_wait_unheld(db, 2000);
    }
    for (int i = 0; i < n; i++) {
        if (t[i].signalled) {
            doc_line(&d, "Stopped pid %ld (%s), which had the journal open.", t[i].pid, t[i].what);
        }
    }
    if (doc_open(db, err, sizeof err) != 0) {
        doc_line(&d, "The journal is still not updated: %s", err);
        doc_report(json, 0, "blocked", &d, db);
        return 1;
    }
    doc_line(&d, "Updated the journal; pic works in this workspace again.");
    if (remote) {
        doc_line(&d, "pic remote was one of them: if it does not start again by itself, turn it on with /rc or pic remote.");
    }
    doc_report(json, 1, "updated", &d, db);
    return 0;
}