Files
sam f92c5b4536
ci/woodpecker/pr/quality Pipeline was successful
Quality / check (pull_request) Canceled after 7m39s
chore(runtime): delete Kit and external agent harness support (#1877)
Archie runs its own agent loop only. Removes Kit resolution and launch,
the harness runner and adapters, the setup terminal and sandbox view,
harness secrets and OAuth capture (table dropped in migration 0075), the
task-tools contract that only Kit containers reached, and the
sandbox-kit-spec dependency. Agent profiles carry image and tools only.
The egress proxy keeps the model-session path; the sandbox relay code
stays for #1867.
2026-11-12 21:29:05 +11:00

592 lines
26 KiB
Bash
Executable File

#!/usr/bin/env bash
# install.sh - installs Archie Core for the current user.
#
# curl -fsSL https://offloaded.dev/install.sh | bash
#
# Downloads a release from its OCI registry, verifies the release key signed
# it and that the zip is the one signed, installs the
# five services to ${XDG_BIN_HOME:-~/.local/bin}, runs `archied setup`, starts
# the bundled PostgreSQL and installs systemd user units.
# Config: ${XDG_CONFIG_HOME:-~/.config}/archie Data: ${XDG_DATA_HOME:-~/.local/share}/archie
set -euo pipefail
MODULE="github.com/samcharles93/archie-core"
SOURCE_GIT="https://git.catlow.cloud/sam/archie.git"
# Where releases come from: an OCI repository and the base64 ed25519 key that
# must have signed them. A self-hosted source sets both.
DEFAULT_RELEASES="git.catlow.cloud/sam/archie"
DEFAULT_RELEASE_KEY="gIBqoQMwy+8WXmGfiuHtnUa50W0IqfzkTR6iF5q3dSM="
ARCHIE_RELEASES="${ARCHIE_RELEASES:-${DEFAULT_RELEASES}}"
ARCHIE_RELEASE_KEY="${ARCHIE_RELEASE_KEY:-${DEFAULT_RELEASE_KEY}}"
ARCHIE_CHANNEL="${ARCHIE_CHANNEL:-stable}"
XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-${HOME}/.config}"
XDG_DATA_HOME="${XDG_DATA_HOME:-${HOME}/.local/share}"
XDG_BIN_HOME="${XDG_BIN_HOME:-${HOME}/.local/bin}"
ARCHIE_BIN_DIR="${XDG_BIN_HOME}"
INSTANCE=archie
PORT_BASE=""
INSTALL_SYSTEMD=true
ENABLE_LINGER=true
AUTO_START=true
FROM_SOURCE=false
# Piped into bash, stdin is the script; setup reads its answers from the
# terminal instead, so a pipe can still be interactive.
INTERACTIVE=false
if (: </dev/tty) 2>/dev/null; then INTERACTIVE=true; fi
usage() {
cat <<EOF
Usage: install.sh [options]
or: curl -fsSL https://offloaded.dev/install.sh | bash -s -- [options]
Environment:
ARCHIE_RELEASES OCI repository to install from (default ${DEFAULT_RELEASES})
ARCHIE_RELEASE_KEY base64 ed25519 key that source signs with
ARCHIE_CHANNEL stable (default) or next
Options:
--version X.Y.Z Install this release instead of the latest
--from-source Build from a checkout (this one, or a fresh clone) instead
of a release; needs Go, git and jq
--instance NAME Install a named instance beside others: archie (default)
or archie-X; its dirs are <xdg>/NAME and its units end in -X
--port-base N Use ports N..N+6 for web, health, gateway, state store,
state store readiness, messaging and daemon
--no-systemd Skip systemd user units
--no-linger Skip loginctl enable-linger
--no-start Install the units but do not start them
--non-interactive Write an unattended config (no forge, Ollama)
--help, -h Show this help
EOF
}
VERSION=""
while [ $# -gt 0 ]; do
case "$1" in
--version) VERSION="${2:?--version needs a value}"; shift ;;
--instance) INSTANCE="${2:?--instance needs a value}"; shift ;;
--port-base) PORT_BASE="${2:?--port-base needs a value}"; shift ;;
--from-source) FROM_SOURCE=true ;;
--no-systemd) INSTALL_SYSTEMD=false; AUTO_START=false ;;
--no-linger) ENABLE_LINGER=false ;;
--no-start) AUTO_START=false ;;
--non-interactive|--batch) INTERACTIVE=false ;;
--help|-h) usage; exit 0 ;;
*) echo "Error: unknown option '$1'" >&2; usage >&2; exit 1 ;;
esac
shift
done
if ! [[ "${INSTANCE}" =~ ^archie(-[a-z0-9][a-z0-9-]{0,23})?$ ]]; then
echo "Error: --instance '${INSTANCE}' must be archie or archie-<name>, e.g. archie-dev" >&2; exit 1
fi
if [ -n "${PORT_BASE}" ] && ! { [[ "${PORT_BASE}" =~ ^[0-9]+$ ]] && [ "${PORT_BASE}" -ge 1024 ] && [ "${PORT_BASE}" -le 65529 ]; }; then
echo "Error: --port-base must be a number from 1024 to 65529" >&2; exit 1
fi
export ARCHIE_INSTANCE="${INSTANCE}"
ARCHIE_CONFIG_DIR="${XDG_CONFIG_HOME}/${INSTANCE}"
ARCHIE_DATA_DIR="${XDG_DATA_HOME}/${INSTANCE}"
ENV_FILE="${ARCHIE_CONFIG_DIR}/env"
# The database roles a bundled install serves from: the least-privilege role
# the services connect as, and the role that owns the schema and runs
# migrations. The names mirror postgres.RuntimeRole/MigrationRole, which setup
# writes into the bundled configuration.
RUNTIME_ROLE=archie_runtime
MIGRATION_ROLE=archie_migrator
# The credential the bundled PostgreSQL is created with and the installer uses
# once, to create the two roles. It lives in this Compose-only file, which the
# systemd units never load, so no service holds a credential that owns the
# cluster.
PG_ADMIN_ENV="${ARCHIE_DATA_DIR}/postgres.env"
# unit maps a base unit name to this instance's: unchanged for the default
# instance, suffixed with the name after archie- otherwise.
unit() {
if [ "${INSTANCE}" = archie ]; then echo "$1"; else echo "$1-${INSTANCE#archie-}"; fi
}
U_DAEMON="$(unit archied)"
U_STATE="$(unit archie-state-store)"
U_GATEWAY="$(unit archie-gateway)"
U_UI="$(unit archie-ui)"
U_MESSAGING="$(unit archie-messaging)"
# Ports in --port-base order; without it, today's defaults.
if [ -n "${PORT_BASE}" ]; then
P_WEB=${PORT_BASE}; P_HEALTH=$((PORT_BASE + 1)); P_GATEWAY=$((PORT_BASE + 2))
P_STATE=$((PORT_BASE + 3)); P_READY=$((PORT_BASE + 4)); P_MESSAGING=$((PORT_BASE + 5)); P_DAEMON=$((PORT_BASE + 6))
else
P_WEB=8484; P_HEALTH=8485; P_GATEWAY=8585; P_STATE=9090; P_READY=9091; P_MESSAGING=8586; P_DAEMON=8587
fi
need() {
for cmd in "$@"; do
command -v "$cmd" &>/dev/null || { echo "Error: '$cmd' is required but not installed." >&2; exit 1; }
done
}
# install_release fetches the release on ARCHIE_CHANNEL (or VERSION) from
# ARCHIE_RELEASES and unpacks it into TMP: the statement must verify against
# ARCHIE_RELEASE_KEY and the zip must hash to the digest the statement names.
install_release() {
local registry="${ARCHIE_RELEASES%%/*}" repo="${ARCHIE_RELEASES#*/}" scheme=https tag="${ARCHIE_CHANNEL}"
case "${registry}" in localhost | localhost:* | 127.* | "[::1]"*) scheme=http ;; esac
[ -n "${VERSION}" ] && tag="v${VERSION#v}"
local base="${scheme}://${registry}/v2/${repo}" auth=()
# Registries hand anonymous readers a pull token named by the challenge.
local challenge
challenge="$(curl -fsS -o /dev/null -D - "${base}/manifests/${tag}" 2>/dev/null | tr -d '\r' | sed -n 's/^[Ww][Ww][Ww]-[Aa]uthenticate: *Bearer *//p')" || true
if [ -n "${challenge}" ]; then
local realm service token
realm="$(sed -n 's/.*realm="\([^"]*\)".*/\1/p' <<<"${challenge}")"
service="$(sed -n 's/.*service="\([^"]*\)".*/\1/p' <<<"${challenge}")"
token="$(curl -fsSL -G "${realm}" --data-urlencode "service=${service}" --data-urlencode "scope=repository:${repo}:pull" | jq -r '.token // .access_token')"
auth=(-H "Authorization: Bearer ${token}")
fi
echo "==> Fetching ${ARCHIE_RELEASES}:${tag}..."
curl -fsSL "${auth[@]}" -H "Accept: application/vnd.oci.image.manifest.v1+json" "${base}/manifests/${tag}" -o "${TMP}/manifest.json"
blob() { curl -fsSL "${auth[@]}" "${base}/blobs/$1" -o "$2" && [ "sha256:$(sha256sum "$2" | cut -d' ' -f1)" = "$1" ]; }
local statement_digest
statement_digest="$(jq -er '.layers[0].digest' "${TMP}/manifest.json")"
blob "${statement_digest}" "${TMP}/statement.json" || { echo "Error: the release statement does not match its digest." >&2; exit 1; }
jq -er '.annotations["dev.archie.release.signature.v1"]' "${TMP}/manifest.json" | base64 -d >"${TMP}/statement.sig"
# An ed25519 public key is its 32 bytes behind a fixed SubjectPublicKeyInfo header.
{ printf '\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00'; base64 -d <<<"${ARCHIE_RELEASE_KEY}"; } >"${TMP}/key.der"
openssl pkeyutl -verify -pubin -inkey "${TMP}/key.der" -keyform DER -rawin \
-in "${TMP}/statement.json" -sigfile "${TMP}/statement.sig" >/dev/null 2>&1 ||
{ echo "Error: ${ARCHIE_RELEASES}:${tag} is not signed by the release key." >&2; exit 1; }
local zip_name zip_digest
VERSION="$(jq -er .version "${TMP}/statement.json")"
[ "$(jq -r .platform "${TMP}/statement.json")" = linux-amd64 ] || { echo "Error: the release is not built for linux-amd64." >&2; exit 1; }
[ -z "${VERSION}" ] || [ "${tag}" = "${ARCHIE_CHANNEL}" ] || [ "v${VERSION}" = "${tag}" ] ||
{ echo "Error: ${tag} carries the statement for ${VERSION}." >&2; exit 1; }
zip_name="$(jq -er .zip.name "${TMP}/statement.json")"
zip_digest="$(jq -er .zip.digest "${TMP}/statement.json")"
RELEASE_NAME="${zip_name%.zip}"
case "${RELEASE_NAME}" in archie-core-archied-v*-linux-amd64) ;; *) echo "Error: unexpected release zip ${zip_name}." >&2; exit 1 ;; esac
echo "==> Downloading Archie ${VERSION}..."
blob "${zip_digest}" "${TMP}/${zip_name}" || { echo "Error: ${zip_name} does not match the signed digest." >&2; exit 1; }
unzip -q "${TMP}/${zip_name}" -d "${TMP}"
}
# 1. Prerequisites
echo "==> Checking prerequisites..."
# The installer depends on systemd user units and GNU tools.
if [ "$(uname -s)" != "Linux" ]; then
echo "Error: the installer supports Linux only. Detected: $(uname -s)" >&2
exit 1
fi
if [ "${FROM_SOURCE}" = true ]; then
need git go jq
else
[ "$(uname -m)" = x86_64 ] || { echo "Error: releases are built for x86_64 only; use --from-source." >&2; exit 1; }
need curl unzip sha256sum openssl jq base64
fi
if command -v docker &>/dev/null; then
echo " [OK] $(docker --version)"
else
echo " [WARN] Docker not found. Agents run in containers and the bundled PostgreSQL needs it."
fi
mkdir -p "${ARCHIE_CONFIG_DIR}" "${ARCHIE_DATA_DIR}" "${ARCHIE_BIN_DIR}"
# 2. Binaries. STAGE ends up holding the binaries and release.json, whichever
# way they were obtained.
TMP="$(mktemp -d)"
trap 'rm -rf "${TMP}"' EXIT
if [ "${FROM_SOURCE}" = true ]; then
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
if [ -f "${SCRIPT_DIR}/go.mod" ] && grep -q "${MODULE}" "${SCRIPT_DIR}/go.mod"; then
SRC_DIR="${SCRIPT_DIR}"
else
SRC_DIR="${TMP}/src"
git clone --quiet --depth=1 "${SOURCE_GIT}" "${SRC_DIR}"
fi
echo "==> Building from ${SRC_DIR}..."
# Selects (and under the default GOTOOLCHAIN=auto, downloads) the toolchain
# go.mod requires, so a missing one fails here rather than mid-build.
required="$(sed -n 's/^go //p' "${SRC_DIR}/go.mod")"
if ! out="$(cd "${SRC_DIR}" && go list -m 2>&1)"; then
echo "Error: Archie needs Go ${required}, which is not available: ${out}" >&2
echo "Install Go ${required} from https://go.dev/dl, or allow the download with GOTOOLCHAIN=auto and network access to proxy.golang.org." >&2
exit 1
fi
STAGE="${TMP}/stage"
mkdir -p "${STAGE}"
# A source build is not a release: it says `dev`, and buildType=binary lets
# it self-update. The agentworker stamp only lands in archie-agent.
LDFLAGS="-X ${MODULE}/internal/buildinfo.Version=dev -X ${MODULE}/internal/buildinfo.Runtime=dev -X ${MODULE}/internal/installtype.buildType=binary -X ${MODULE}/internal/app/agentworker.version=dev"
for cmd in $(jq -er '[.required_topology.units[], .required_topology.binaries[]?] | join(" ")' "${SRC_DIR}/release.json"); do
(cd "${SRC_DIR}" && go build -ldflags "${LDFLAGS}" -o "${STAGE}/${cmd}" "./cmd/${cmd}")
done
cp "${SRC_DIR}/release.json" "${STAGE}/"
else
install_release
STAGE="${TMP}/${RELEASE_NAME}"
fi
TOPOLOGY_UNITS="$(tr -d '\n' <"${STAGE}/release.json" | sed -n 's/.*"units": *\[\([^]]*\)\].*/\1/p' | tr -d '" ' | tr , ' ')"
# Binaries that run beside the units without a service of their own are
# installed and replaced with them.
TOPOLOGY_BINARIES="$(tr -d '\n' <"${STAGE}/release.json" | sed -n 's/.*"binaries": *\[\([^]]*\)\].*/\1/p' | tr -d '" ' | tr , ' ')"
for cmd in ${TOPOLOGY_UNITS} ${TOPOLOGY_BINARIES}; do
install -m755 "${STAGE}/${cmd}" "${ARCHIE_BIN_DIR}/${cmd}"
done
echo " Installed ${TOPOLOGY_UNITS} ${TOPOLOGY_BINARIES} to ${ARCHIE_BIN_DIR}/"
# 3. Configuration. archied setup asks every question and writes config.toml
# plus any secrets to the env file beside it; this script asks nothing itself.
if [ ! -f "${ARCHIE_CONFIG_DIR}/config.toml" ]; then
echo "==> Generating config.toml (archied setup)..."
if [ "${INTERACTIVE}" = true ]; then
setup_args=(-config "${ARCHIE_CONFIG_DIR}/config.toml")
else
# Unattended: no forge and keyless Ollama, so the services boot without a secret.
setup_args=(--defaults -config "${ARCHIE_CONFIG_DIR}/config.toml" -forge-type none)
fi
setup_in=/dev/null
[ "${INTERACTIVE}" = true ] && setup_in=/dev/tty
if ! "${ARCHIE_BIN_DIR}/archied" setup "${setup_args[@]}" <"${setup_in}"; then
echo "ERROR: archied setup could not generate ${ARCHIE_CONFIG_DIR}/config.toml" >&2
exit 1
fi
if [ "${ARCHIE_RELEASES}" != "${DEFAULT_RELEASES}" ] || [ "${ARCHIE_RELEASE_KEY}" != "${DEFAULT_RELEASE_KEY}" ]; then
# The instance keeps updating from the source it was installed from.
printf '\n[distribution]\nreleases = "%s"\nreleases_key = "%s"\n' "${ARCHIE_RELEASES}" "${ARCHIE_RELEASE_KEY}" >>"${ARCHIE_CONFIG_DIR}/config.toml"
fi
if [ -n "${PORT_BASE}" ]; then
# The generated config names the default addresses; move them to this
# instance's ports and pin the services the template leaves commented.
sed -i -e "s/127\.0\.0\.1:8484/127.0.0.1:${P_WEB}/g" -e "s/127\.0\.0\.1:8485/127.0.0.1:${P_HEALTH}/g" \
-e "s/127\.0\.0\.1:8585/127.0.0.1:${P_GATEWAY}/g" -e "s/127\.0\.0\.1:9090/127.0.0.1:${P_STATE}/g" \
-e "s/127\.0\.0\.1:8586/127.0.0.1:${P_MESSAGING}/g" -e "s/127\.0\.0\.1:8587/127.0.0.1:${P_DAEMON}/g" \
"${ARCHIE_CONFIG_DIR}/config.toml"
for section in messaging:${P_MESSAGING} daemon:${P_DAEMON}; do
name="${section%%:*}" port="${section#*:}"
grep -q "^\[services\.${name}\]" "${ARCHIE_CONFIG_DIR}/config.toml" ||
printf '\n[services.%s]\ntarget = "127.0.0.1:%s"\nlisten = "127.0.0.1:%s"\n' "${name}" "${port}" "${port}" >>"${ARCHIE_CONFIG_DIR}/config.toml"
done
fi
else
[ -n "${PORT_BASE}" ] && echo " [WARN] --port-base only applies to a new config; ${ARCHIE_CONFIG_DIR}/config.toml keeps its addresses." >&2
echo " [SKIP] ${ARCHIE_CONFIG_DIR}/config.toml already exists. Re-run 'archied setup' to change it."
fi
# provision_database reconciles the two database roles a bundled install
# serves from: an archie_migrator that owns the schema and runs goose, and an
# archie_runtime with row access only. It also moves the superuser password out
# of the env file the units load: a config written before the split connects as
# the bundled superuser, so its password is rotated to the Compose-only one
# once the roles exist. Idempotent, so re-running the installer reconciles an
# already-split install.
provision_database() {
local role_pw admin_pw connect_pw split=false
role_pw="$(sed -n "s/^PGPASSWORD='\([^']*\)'$/\1/p" "${ENV_FILE}" | tail -n1)"
admin_pw="$(sed -n "s/^POSTGRES_PASSWORD='\([^']*\)'$/\1/p" "${PG_ADMIN_ENV}" | tail -n1)"
if [ -z "${role_pw}" ] || [ -z "${admin_pw}" ]; then
echo " [WARN] Cannot provision database roles: ${ENV_FILE} needs PGPASSWORD and ${PG_ADMIN_ENV} needs POSTGRES_PASSWORD." >&2
return
fi
if ! grep -q '^migration_database_url' "${ARCHIE_CONFIG_DIR}/config.toml"; then
split=true
fi
# A pre-split install authenticates as the superuser with the env file's
# PGPASSWORD; a split one authenticates with the Compose-only password.
if [ "${split}" = true ]; then connect_pw="${role_pw}"; else connect_pw="${admin_pw}"; fi
echo "==> Provisioning the database roles..."
if ! PGPASSWORD="${connect_pw}" ARCHIE_NEW_ADMIN_PASSWORD="${admin_pw}" \
"${ARCHIE_BIN_DIR}/archie-state-store" provision \
-admin-url "postgres://archie@/archie?host=${PG_SOCKET_DIR}" \
-runtime-url "postgres://${RUNTIME_ROLE}:${role_pw}@/archie?host=${PG_SOCKET_DIR}" \
-migration-url "postgres://${MIGRATION_ROLE}:${role_pw}@/archie?host=${PG_SOCKET_DIR}" \
-rotate-admin-password-env ARCHIE_NEW_ADMIN_PASSWORD; then
echo " [WARN] Database role provisioning failed; not restarting the services until it succeeds. Re-run the installer once the database accepts the admin credential." >&2
AUTO_START=false
return
fi
if [ "${split}" = true ]; then
if grep -q '^database_url = "postgres://archie@' "${ARCHIE_CONFIG_DIR}/config.toml"; then
sed -i "s#^database_url = \"postgres://archie@#database_url = \"postgres://${RUNTIME_ROLE}@#" "${ARCHIE_CONFIG_DIR}/config.toml"
sed -i "/^database_url = /a migration_database_url = \"postgres://${MIGRATION_ROLE}@/archie?host=${PG_SOCKET_DIR}\"" "${ARCHIE_CONFIG_DIR}/config.toml"
echo " [OK] config.toml now connects as ${RUNTIME_ROLE} and migrates as ${MIGRATION_ROLE}."
else
echo " [WARN] Could not move database_url to ${RUNTIME_ROLE}; set database_url and migration_database_url by hand." >&2
fi
fi
}
# 4. PostgreSQL. Every service fails closed without it. The bundled database
# has no network at all: the services reach it through its Unix socket,
# mounted at PG_SOCKET_DIR, so it publishes no port and cannot collide with
# another PostgreSQL. The superuser it is created with is only the installer's
# bootstrap credential; the services connect as the two provisioned roles and
# read their password from the env file's PGPASSWORD as before.
PG_SOCKET_DIR="${ARCHIE_DATA_DIR}/postgres"
PG_COMPOSE="${ARCHIE_DATA_DIR}/postgres.yml"
if ! grep -qF "host=${PG_SOCKET_DIR}" "${ARCHIE_CONFIG_DIR}/config.toml"; then
echo " [OK] Using the PostgreSQL server named by database_url."
elif ! command -v docker &>/dev/null; then
echo " [WARN] Docker not found: the bundled PostgreSQL needs it. Install Docker, or run 'archied setup' with your own PostgreSQL 18 URL." >&2
AUTO_START=false
else
echo "==> Starting the bundled PostgreSQL 18..."
mkdir -p "${PG_SOCKET_DIR}"
# The superuser password is generated here rather than reused from setup: it
# is the one credential that must never be in the env file the units load.
# Written before the first start so a failed run can be retried with it.
if [ ! -f "${PG_ADMIN_ENV}" ]; then
previous_umask="$(umask)"
umask 077
printf "POSTGRES_PASSWORD='%s'\n" "$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')" >"${PG_ADMIN_ENV}"
umask "${previous_umask}"
fi
cat >"${PG_COMPOSE}" <<'EOF'
services:
postgres:
image: postgres:18
network_mode: none
environment:
POSTGRES_USER: archie
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-}
POSTGRES_DB: archie
POSTGRES_INITDB_ARGS: --auth-local=scram-sha-256
PGDATA: /var/lib/postgresql/data/pgdata
volumes:
- pg_data:/var/lib/postgresql/data
# :z relabels the directory for SELinux hosts.
- ./postgres:/var/run/postgresql:z
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U archie -d archie"]
interval: 5s
timeout: 5s
retries: 10
volumes:
pg_data:
EOF
if ! docker compose -p "${INSTANCE}" --env-file "${PG_ADMIN_ENV}" -f "${PG_COMPOSE}" up -d --wait; then
echo " [WARN] The bundled PostgreSQL did not start, so the services are installed but not started." >&2
echo " Check: docker compose -p "${INSTANCE}" -f ${PG_COMPOSE} logs" >&2
AUTO_START=false
else
provision_database
fi
fi
# Extensions run in an unprivileged user namespace. Ubuntu 23.10+ forbids
# those unless an AppArmor profile allows them, and only root can add one, so
# print the profile that allows it for these binaries alone.
if [ "$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null)" = 1 ]; then
echo " [WARN] This host restricts user namespaces, so extensions will not start until you run:" >&2
cat >&2 <<EOF
sudo tee /etc/apparmor.d/archie >/dev/null <<'PROFILE'
abi <abi/4.0>,
include <tunables/global>
profile archie ${ARCHIE_BIN_DIR}/archie{d,-*} flags=(unconfined) {
userns,
}
PROFILE
sudo apparmor_parser -r /etc/apparmor.d/archie
EOF
fi
# 5. Systemd user service setup & linger configuration
SERVICE_INSTALLED=false
if [ "${INSTALL_SYSTEMD}" = true ] && command -v systemctl &>/dev/null && [ -d "${XDG_CONFIG_HOME}" ]; then
SYSTEMD_USER_DIR="${XDG_CONFIG_HOME}/systemd/user"
echo "==> Configuring systemd user services..."
mkdir -p "${SYSTEMD_USER_DIR}"
# Every service this installer builds gets a unit, with the contents the
# runbook used to tell an operator to paste by hand. The runbook is a
# description now, not the mechanism: a fresh install must not need four
# hand-written units before its own updater will run, and
# the contents must not live in two places to drift apart.
cat <<EOF > "${SYSTEMD_USER_DIR}/${U_DAEMON}.service"
[Unit]
Description=Archie Core Orchestrator Daemon
After=network.target
# Give up after 5 failures in 5 minutes rather than restarting forever. A
# genuinely broken install otherwise loops every RestartSec indefinitely,
# burying the real error in the journal instead of surfacing a failed unit.
StartLimitIntervalSec=300
StartLimitBurst=5
[Service]
Type=notify
NotifyAccess=main
# Beats only while the run loop is polling, so a wedged loop is restarted.
WatchdogSec=30s
ExecStart=${ARCHIE_BIN_DIR}/archied -config ${ARCHIE_CONFIG_DIR}/config.toml
EnvironmentFile=-${ENV_FILE}
Environment=ARCHIE_INSTANCE=${INSTANCE}
# archied reloads its configuration on SIGHUP. Without ExecReload,
# 'systemctl --user reload archied' fails and the operator has to know
# to run 'systemctl --user kill -s HUP' instead.
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
EOF
# The State Store owns the task data and is the process everything else dials, so
# its unit is the first dependency the others name.
cat <<EOF > "${SYSTEMD_USER_DIR}/${U_STATE}.service"
[Unit]
Description=Archie State Store Service
After=network.target
[Service]
Type=notify
NotifyAccess=main
ExecStart=${ARCHIE_BIN_DIR}/archie-state-store -config ${ARCHIE_CONFIG_DIR}/config.toml -listen 127.0.0.1:${P_STATE} -ready-addr 127.0.0.1:${P_READY}
EnvironmentFile=-${ENV_FILE}
Environment=ARCHIE_INSTANCE=${INSTANCE}
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
EOF
cat <<EOF > "${SYSTEMD_USER_DIR}/${U_GATEWAY}.service"
[Unit]
Description=Archie Gateway Service
After=network.target
[Service]
Type=notify
NotifyAccess=main
ExecStart=${ARCHIE_BIN_DIR}/archie-gateway -config ${ARCHIE_CONFIG_DIR}/config.toml -listen 127.0.0.1:${P_GATEWAY}
EnvironmentFile=-${ENV_FILE}
Environment=ARCHIE_INSTANCE=${INSTANCE}
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
EOF
cat <<EOF > "${SYSTEMD_USER_DIR}/${U_UI}.service"
[Unit]
Description=Archie UI Service
After=network.target ${U_STATE}.service
Wants=${U_STATE}.service
[Service]
Type=simple
ExecStart=${ARCHIE_BIN_DIR}/archie-ui -config ${ARCHIE_CONFIG_DIR}/config.toml
EnvironmentFile=-${ENV_FILE}
Environment=ARCHIE_INSTANCE=${INSTANCE}
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
EOF
# The Telegram, email and webhook channels run here, not in archied: without
# this unit a host looks healthy while its channels are dead.
cat <<EOF > "${SYSTEMD_USER_DIR}/${U_MESSAGING}.service"
[Unit]
Description=Archie Messaging Service
After=network.target ${U_GATEWAY}.service ${U_STATE}.service
Wants=${U_GATEWAY}.service ${U_STATE}.service
[Service]
Type=notify
NotifyAccess=main
ExecStart=${ARCHIE_BIN_DIR}/archie-messaging -config ${ARCHIE_CONFIG_DIR}/config.toml
EnvironmentFile=-${ENV_FILE}
Environment=ARCHIE_INSTANCE=${INSTANCE}
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
EOF
INSTANCE_UNITS=""
for base in $TOPOLOGY_UNITS; do INSTANCE_UNITS="${INSTANCE_UNITS:+${INSTANCE_UNITS} }$(unit "${base}")"; done
systemctl --user daemon-reload || true
SERVICE_INSTALLED=true
for unit in $INSTANCE_UNITS; do
test -f "${SYSTEMD_USER_DIR}/${unit}.service" || { echo "missing required unit: $unit" >&2; exit 1; }
echo " Installed ${SYSTEMD_USER_DIR}/${unit}.service"
done
# Enable linger so systemd --user runs continuously without an active login
# session. $(id -un) is used rather than $USER, which is unset in some
# container and cron contexts and would abort under `set -u`. Only a
# positive "Linger=yes" counts as already enabled -- a failed or empty
# `loginctl show-user` (no logind session, a container) falls through to
# enable-linger rather than being reported as already OK, since nothing
# was actually observed. enable-linger is idempotent, so a redundant call
# here is harmless.
if [ "${ENABLE_LINGER}" = true ] && command -v loginctl &>/dev/null; then
LINGER_USER="$(id -un)"
if loginctl show-user "${LINGER_USER}" 2>/dev/null | grep -q "Linger=yes"; then
echo " [OK] User linger is already enabled."
else
echo "==> Enabling systemd user linger (loginctl enable-linger ${LINGER_USER})..."
loginctl enable-linger "${LINGER_USER}" || echo " Notice: Could not enable linger automatically. Run 'loginctl enable-linger ${LINGER_USER}' manually if needed."
fi
fi
# Auto-enable and start the services, the store first so a fresh boot does
# not race a dial it depends on. Restart rather than start, because a
# reinstall over running services would otherwise leave the old binaries
# running.
if [ "${AUTO_START}" = true ]; then
echo "==> Enabling and starting Archie services..."
{ systemctl --user enable $INSTANCE_UNITS && systemctl --user restart $INSTANCE_UNITS; } ||
echo " Notice: Could not start every service automatically. Check: systemctl --user status ${INSTANCE_UNITS}"
fi
fi
# 6. Post-installation summary & instructions
echo ""
echo "============================================================"
echo " ✓ Archie Core Installation Complete!"
echo "============================================================"
echo ""
echo "Installation Details:"
echo " - Binaries : ${ARCHIE_BIN_DIR}/{archied,archie-state-store,archie-gateway,archie-ui,archie-messaging}"
echo " - Config : ${ARCHIE_CONFIG_DIR}/config.toml"
echo " - Secrets : ${ENV_FILE}"
if [ -f "${PG_ADMIN_ENV}" ]; then
echo " - DB admin : ${PG_ADMIN_ENV} # compose-only, never loaded by the units"
fi
echo " - Data : ${ARCHIE_DATA_DIR}/"
echo ""
# Check PATH
if [[ ":$PATH:" != *":${ARCHIE_BIN_DIR}:"* ]]; then
echo "NOTE: ${ARCHIE_BIN_DIR} is not in your current PATH."
echo "Add it to your shell configuration file (~/.bashrc or ~/.zshrc):"
echo " export PATH=\"${ARCHIE_BIN_DIR}:\$PATH\""
echo ""
fi
if [ "${SERVICE_INSTALLED}" = true ] && [ "${AUTO_START}" = true ]; then
echo "Service Management:"
echo " - Units installed : ${INSTANCE_UNITS}"
echo " - View live logs : journalctl --user -u ${U_DAEMON} -f"
echo " - Service status : systemctl --user status ${INSTANCE_UNITS}"
echo " - Restart daemon : systemctl --user restart ${U_DAEMON}"
else
echo "Manual Startup: start the five services as in https://offloaded.dev"
fi
echo ""
SETUP_HINT="archied setup"
[ "${INSTANCE}" = archie ] || SETUP_HINT="ARCHIE_INSTANCE=${INSTANCE} archied setup"
echo "Dashboard: http://127.0.0.1:${P_WEB} Change the config: ${SETUP_HINT}"
echo ""