feat(bash/infra): servicios systemd locales — 6 funciones atómicas + 1 pipeline

Nuevas primitivas para gestionar servicios systemd del sistema desde
el registry (antes solo había versiones remotas via SSH para deploy VPS):

  bash/functions/infra/
    systemd_local_install_unit   — escribir unit en /etc/systemd/system + daemon-reload
    systemd_local_enable         — systemctl enable
    systemd_local_start          — systemctl start + MainPID
    systemd_local_restart        — systemctl restart + MainPID
    systemd_local_status         — ActiveState/SubState/pid/enabled + journal tail (no sudo)
    systemd_local_uninstall      — stop + disable + rm unit + daemon-reload (idempotente)

  bash/functions/pipelines/
    install_systemd_service      — pipeline que compone las anteriores; args
                                    --name --exec [--workdir --user --env KEY=VAL
                                    --after --restart --type]

Requisito: sudo sin password para systemctl + escritura en /etc/systemd/system/.
En WSL: systemd=true en /etc/wsl.conf.

Registrado sqlite_api como servicio del sistema con este pipeline, queda
vivo al arrancar WSL. Dashboard ya no necesita arrancar la API manualmente.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-24 14:02:54 +02:00
parent 350d3341f6
commit c7ae46f86c
14 changed files with 619 additions and 0 deletions
@@ -0,0 +1,80 @@
---
name: install_systemd_service
kind: pipeline
lang: bash
domain: pipelines
version: "1.0.0"
purity: impure
signature: "install_systemd_service --name <N> --exec <PATH> [opts] -> json"
description: "Pipeline que registra una app como servicio systemd del sistema: genera el unit, lo instala en /etc/systemd/system/, hace daemon-reload, enable, start y devuelve status. Requiere sudo sin password para systemctl y escritura en /etc/systemd/system/."
tags: [systemd, service, local, infra, pipeline, install]
uses_functions:
- systemd_local_install_unit_bash_infra
- systemd_local_enable_bash_infra
- systemd_local_start_bash_infra
- systemd_local_status_bash_infra
uses_types: []
returns: []
returns_optional: false
error_type: "error_go_core"
imports: []
params:
- name: --name
desc: "nombre del servicio (sin sufijo .service)"
- name: --exec
desc: "ruta absoluta al binario/script para ExecStart="
- name: --workdir
desc: "WorkingDirectory (default: dirname del --exec)"
- name: --user
desc: "User del servicio (default: usuario actual, id -un)"
- name: --description
desc: "Description del unit (default: '<name> service')"
- name: --env
desc: "Variable de entorno en formato KEY=VAL (repetible)"
- name: --after
desc: "After= del unit (default: network.target)"
- name: --restart
desc: "Restart= del unit (default: on-failure)"
- name: --type
desc: "Type= del unit (default: simple)"
output: "JSON consolidado con subkeys install, enable, start y status de cada paso del pipeline."
tested: false
tests: []
test_file_path: ""
file_path: "bash/functions/pipelines/install_systemd_service.sh"
---
## Ejemplo
```bash
source bash/functions/pipelines/install_systemd_service.sh
install_systemd_service \
--name sqlite_api \
--exec /home/egutierrez/fn_registry/projects/fn_monitoring/apps/sqlite_api/sqlite_api \
--workdir /home/egutierrez/fn_registry/projects/fn_monitoring/apps/sqlite_api \
--env FN_REGISTRY_ROOT=/home/egutierrez/fn_registry \
--description "fn_registry sqlite_api (read-only HTTP API)"
```
Salida (resumida):
```json
{
"install": {"name":"sqlite_api","path":"/etc/systemd/system/sqlite_api.service","installed":true},
"enable": {"name":"sqlite_api","enabled":true},
"start": {"name":"sqlite_api","started":true,"pid":12345},
"status": {"name":"sqlite_api","active":"active","sub":"running","enabled":"enabled","pid":12345,"logs":["..."]}
}
```
## Requisitos
- `systemd` activo en la máquina (en WSL: `systemd=true` en `/etc/wsl.conf`).
- `sudo` sin password para `systemctl` y escritura en `/etc/systemd/system/`.
## Notas
- Idempotente: si el unit ya existe, se sobrescribe y systemd se recarga.
- Para desinstalar usar `systemd_local_uninstall <name>`.
- Orden determinista de Environment= (uno por línea, en el orden pasado en CLI).
- El pipeline NO compila el binario — se asume que `--exec` apunta a un ejecutable ya listo.
@@ -0,0 +1,129 @@
#!/usr/bin/env bash
# install_systemd_service — Pipeline que registra una app como servicio systemd local.
# Compone systemd_local_{install_unit, enable, start, status}.
set -euo pipefail
# Resolver repo root (asume que este archivo vive en bash/functions/pipelines/)
PIPELINE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$PIPELINE_DIR/../../.." && pwd)"
FN_DIR="$REPO_ROOT/bash/functions/infra"
# shellcheck source=/dev/null
source "$FN_DIR/systemd_local_install_unit.sh"
# shellcheck source=/dev/null
source "$FN_DIR/systemd_local_enable.sh"
# shellcheck source=/dev/null
source "$FN_DIR/systemd_local_start.sh"
# shellcheck source=/dev/null
source "$FN_DIR/systemd_local_status.sh"
usage() {
cat <<'USAGE' >&2
install_systemd_service — registra una app como servicio systemd del sistema.
Uso:
install_systemd_service --name <N> --exec <PATH> [opciones]
Obligatorios:
--name <name> Nombre del servicio (sin .service)
--exec <path> Ruta absoluta al binario/script ExecStart
Opcionales:
--workdir <path> WorkingDirectory (default: dirname de --exec)
--user <user> User del servicio (default: usuario actual)
--description <text> Description del unit (default: "<name> service")
--env KEY=VAL Variable de entorno (repetible)
--after <units> After= (default: network.target)
--restart <policy> Restart= (default: on-failure)
--type <type> Type= (default: simple)
Salida: JSON consolidado con los resultados de install_unit, enable, start y status.
USAGE
exit 1
}
install_systemd_service() {
local name="" exec_path="" workdir="" user="" description=""
local after="network.target" restart="on-failure" type="simple"
local -a envs=()
while [[ $# -gt 0 ]]; do
case "$1" in
--name) name="$2"; shift 2 ;;
--exec) exec_path="$2"; shift 2 ;;
--workdir) workdir="$2"; shift 2 ;;
--user) user="$2"; shift 2 ;;
--description) description="$2"; shift 2 ;;
--env) envs+=("$2"); shift 2 ;;
--after) after="$2"; shift 2 ;;
--restart) restart="$2"; shift 2 ;;
--type) type="$2"; shift 2 ;;
-h|--help) usage ;;
*) echo "opción desconocida: $1" >&2; usage ;;
esac
done
if [[ -z "$name" || -z "$exec_path" ]]; then
echo "install_systemd_service: faltan --name y --exec" >&2
usage
fi
[[ -z "$user" ]] && user="$(id -un)"
[[ -z "$workdir" ]] && workdir="$(dirname "$exec_path")"
[[ -z "$description" ]] && description="$name service"
# Construir bloque Environment= (uno por línea, orden determinista)
local env_block=""
local e
for e in "${envs[@]}"; do
env_block+="Environment=\"$e\"
"
done
# Generar unit content (heredoc determinista)
local unit_content
unit_content="[Unit]
Description=$description
After=$after
[Service]
Type=$type
User=$user
WorkingDirectory=$workdir
${env_block}ExecStart=$exec_path
Restart=$restart
RestartSec=3
[Install]
WantedBy=multi-user.target
"
echo "[install_systemd_service] instalando unit $name..." >&2
local install_json enable_json start_json status_json
install_json=$(systemd_local_install_unit "$name" "$unit_content")
echo "[install_systemd_service] enable..." >&2
enable_json=$(systemd_local_enable "$name")
echo "[install_systemd_service] start..." >&2
start_json=$(systemd_local_start "$name")
# Darle un instante a systemd para estabilizar el estado
sleep 1
echo "[install_systemd_service] status..." >&2
status_json=$(systemd_local_status "$name" 15)
# JSON consolidado
python3 - "$install_json" "$enable_json" "$start_json" "$status_json" <<'PY'
import json, sys
keys = ["install", "enable", "start", "status"]
out = {k: json.loads(v) for k, v in zip(keys, sys.argv[1:])}
print(json.dumps(out, indent=2))
PY
}
# Ejecución directa
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
install_systemd_service "$@"
fi