Compare commits
4 Commits
f79f2e757c
...
28ff9c3f79
| Author | SHA1 | Date | |
|---|---|---|---|
| 28ff9c3f79 | |||
| ab226d7137 | |||
| 8a96ebe412 | |||
| a402192e73 |
@@ -109,6 +109,125 @@ metabase_update_dashboard(client, dash["id"], dashcards=[
|
|||||||
|
|
||||||
**Filtros de list_dashboards:** `all`, `mine`, `archived`
|
**Filtros de list_dashboards:** `all`, `mine`, `archived`
|
||||||
|
|
||||||
|
### Documents (ProseMirror)
|
||||||
|
|
||||||
|
Los "documents" son páginas narrativas editables con texto rico y cards embebidas. **No hay helpers en fn_registry todavía** — usa el endpoint REST directamente a través de `client._http`.
|
||||||
|
|
||||||
|
**Endpoints:**
|
||||||
|
|
||||||
|
| Método | Ruta | Qué hace |
|
||||||
|
|--------|------|---------|
|
||||||
|
| GET | `/api/document` | Lista documents (`{items: [...]}`) |
|
||||||
|
| GET | `/api/document/{id}` | Lee un document (incluye `document` con árbol ProseMirror) |
|
||||||
|
| POST | `/api/document` | Crea. Payload: `{name, collection_id, document}` |
|
||||||
|
| PUT | `/api/document/{id}` | Actualiza. Mismo payload que POST |
|
||||||
|
| PUT | `/api/document/{id}` con `{archived: true}` | Soft-delete |
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Crear documento
|
||||||
|
resp = client._http.request("POST", "/api/document", json={
|
||||||
|
"name": "Mi análisis",
|
||||||
|
"collection_id": 583, # obligatorio — raíz no se acepta desde API
|
||||||
|
"document": {"type": "doc", "content": [
|
||||||
|
{"type": "heading", "attrs": {"level": 1}, "content": [{"type": "text", "text": "Título"}]},
|
||||||
|
{"type": "paragraph", "content": [{"type": "text", "text": "Cuerpo."}]},
|
||||||
|
]},
|
||||||
|
})
|
||||||
|
doc_id = resp.json()["id"]
|
||||||
|
print(f"https://reports.autingo.es/document/{doc_id}")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Tipos de nodo SOPORTADOS en Metabase v0.59.x
|
||||||
|
|
||||||
|
Solo estos tipos renderizan. **Cualquier tipo fuera de esta lista hace que el documento se vea vacío al abrirlo.**
|
||||||
|
|
||||||
|
```python
|
||||||
|
ALLOWED_DOC_NODES = {
|
||||||
|
"doc", "heading", "paragraph", "text",
|
||||||
|
"horizontalRule", "blockquote",
|
||||||
|
"bulletList", "listItem",
|
||||||
|
"codeBlock", # attrs.language ej: "sql"
|
||||||
|
"resizeNode", # envuelve SIEMPRE a cardEmbed
|
||||||
|
"cardEmbed", # solo dentro de resizeNode
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Marcas inline válidas en nodos `text`: `bold`, `italic`, `code`, `strike` (se aplican con `"marks": [{"type": "bold"}, ...]`).
|
||||||
|
|
||||||
|
#### Tipos PROHIBIDOS (rompen el render)
|
||||||
|
|
||||||
|
- `table`, `tableRow`, `tableHeader`, `tableCell` → en v0.59.x no están registrados en el schema del editor y el doc entero se vuelve invisible.
|
||||||
|
- `callout` → idem (documentado en memoria `feedback_metabase_prosemirror.md`).
|
||||||
|
- `image`, `video`, `iframe`, `mention`, cualquier embed de terceros → no registrados.
|
||||||
|
|
||||||
|
Si necesitas una tabla, **emúlala con una `bulletList` de `**clave:** valor`**:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def kv_list(pairs):
|
||||||
|
return {"type": "bulletList", "content": [
|
||||||
|
{"type": "listItem", "content": [
|
||||||
|
{"type": "paragraph", "content": [
|
||||||
|
{"type": "text", "text": k, "marks": [{"type": "bold"}]},
|
||||||
|
{"type": "text", "text": f": {v}"},
|
||||||
|
]},
|
||||||
|
]}
|
||||||
|
for k, v in pairs
|
||||||
|
]}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### cardEmbed SIEMPRE dentro de resizeNode
|
||||||
|
|
||||||
|
Un `cardEmbed` suelto no renderiza. Patrón obligatorio:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def card_embed(card_id, height=420):
|
||||||
|
import uuid
|
||||||
|
return {
|
||||||
|
"type": "resizeNode",
|
||||||
|
"attrs": {"height": height, "minHeight": 280},
|
||||||
|
"content": [{
|
||||||
|
"type": "cardEmbed",
|
||||||
|
"attrs": {"id": card_id, "name": None, "_id": str(uuid.uuid4())},
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Validación OBLIGATORIA antes de POST/PUT
|
||||||
|
|
||||||
|
Nunca envíes un document a Metabase sin validar primero. Un solo nodo prohibido lo deja invisible sin devolver error HTTP:
|
||||||
|
|
||||||
|
```python
|
||||||
|
ALLOWED = {"doc","heading","paragraph","text","horizontalRule","blockquote",
|
||||||
|
"bulletList","listItem","codeBlock","resizeNode","cardEmbed"}
|
||||||
|
|
||||||
|
def validate_doc(node, path=""):
|
||||||
|
errs = []
|
||||||
|
if isinstance(node, dict):
|
||||||
|
typ = node.get("type", "?")
|
||||||
|
if typ not in ALLOWED:
|
||||||
|
errs.append(f"{path}: tipo no permitido '{typ}'")
|
||||||
|
if typ == "resizeNode":
|
||||||
|
inner = node.get("content", [])
|
||||||
|
if not (len(inner) == 1 and inner[0].get("type") == "cardEmbed"):
|
||||||
|
errs.append(f"{path}: resizeNode debe contener exactamente un cardEmbed")
|
||||||
|
return errs # no re-descender al cardEmbed interno
|
||||||
|
for i, c in enumerate(node.get("content", []) or []):
|
||||||
|
errs += validate_doc(c, f"{path}/{typ}[{i}]")
|
||||||
|
return errs
|
||||||
|
|
||||||
|
errs = validate_doc(my_doc)
|
||||||
|
assert not errs, f"Doc inválido:\n" + "\n".join(f" - {e}" for e in errs)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Aprender estructura de un doc que ya funciona
|
||||||
|
|
||||||
|
Si dudas sobre un nodo, **clónalo de un doc existente que renderice**:
|
||||||
|
|
||||||
|
```python
|
||||||
|
d = client._http.request("GET", "/api/document/2").json()
|
||||||
|
# d["document"] contiene el árbol completo en ProseMirror
|
||||||
|
```
|
||||||
|
|
||||||
### Databases
|
### Databases
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|||||||
@@ -19,3 +19,4 @@ Reglas operativas del proyecto. Cada archivo es una regla independiente.
|
|||||||
| 13 | [frontend_theming.md](frontend_theming.md) | Componentes propios y sistema de temas en frontends |
|
| 13 | [frontend_theming.md](frontend_theming.md) | Componentes propios y sistema de temas en frontends |
|
||||||
| 14 | [deploy.md](deploy.md) | Deploy de apps a VPS remotos via SSH + systemd + rsync |
|
| 14 | [deploy.md](deploy.md) | Deploy de apps a VPS remotos via SSH + systemd + rsync |
|
||||||
| 15 | [projects.md](projects.md) | Projects: agrupar apps, analysis y vaults bajo un tema |
|
| 15 | [projects.md](projects.md) | Projects: agrupar apps, analysis y vaults bajo un tema |
|
||||||
|
| 16 | [kiss.md](kiss.md) | KISS en proyectos y apps: cuestionar herramientas externas, sin abstracciones especulativas |
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
## KISS en proyectos y apps
|
||||||
|
|
||||||
|
**Mantener proyectos (`projects/`) y apps (`apps/`, `projects/*/apps/`) simples**. La complejidad no solicitada es deuda — cada línea, cada dependencia y cada herramienta externa se justifican o no entran.
|
||||||
|
|
||||||
|
### Reglas
|
||||||
|
|
||||||
|
1. **Preferir herramientas ya presentes en el sistema o en el registry** antes que paquetes/CLI externos.
|
||||||
|
- ¿Lo hace `git` / `bash` / una función del registry? Úsalo.
|
||||||
|
- Antes de añadir una dependencia nueva, buscar en `registry.db` (FTS5) si ya existe algo similar.
|
||||||
|
|
||||||
|
2. **Cuestionar cada nueva herramienta externa**. Antes de instalarla preguntar:
|
||||||
|
- ¿Qué problema concreto resuelve que NO podemos resolver con lo que ya tenemos?
|
||||||
|
- ¿El coste (instalar, mantener, aprender, conflictos con nuestro flujo) compensa el beneficio real?
|
||||||
|
- ¿Qué pasa si el proyecto upstream se abandona / rompe compatibilidad?
|
||||||
|
|
||||||
|
3. **Sin abstracciones ni features especulativas**. No generalizar "por si acaso". Tres líneas similares son mejores que una abstracción prematura.
|
||||||
|
|
||||||
|
4. **Ser consciente del flujo de trabajo actual**. Si algo funciona bien con `git` / submódulos / `fn` CLI, no lo sustituyas por una herramienta que prometa "mejorarlo" sin evidencia de mejora concreta en tu contexto.
|
||||||
|
|
||||||
|
5. **Escritura de apps**: una responsabilidad clara, layout mínimo (`main.*`, `app.md`, y lo estrictamente necesario), sin config ni estructuras que no se usen hoy.
|
||||||
|
|
||||||
|
### Caso aprendido (GitButler)
|
||||||
|
|
||||||
|
Se probó GitButler (virtual branches) pensando en paralelizar trabajo. Resultado:
|
||||||
|
- Bugs con submódulos (git submodule add + gitlinks) — commits vacíos o contenido cruzado.
|
||||||
|
- Auto-commits con el texto del chat como commit message.
|
||||||
|
- Pre-commit hook que bloquea `git commit` directo y exige otro CLI (`but`).
|
||||||
|
- Un binario externo de 37 MB + un plugin en Claude Code + skill propio + hooks en `settings.json`.
|
||||||
|
|
||||||
|
Al volver a `git` + ramas normales + `fn` CLI: cero fricción, commits limpios, submódulos funcionan. **Lección**: antes de adoptar una capa nueva, medir la fricción real actual. Si no la hay, no vale la pena añadir complejidad.
|
||||||
+3
-1
@@ -1,6 +1,8 @@
|
|||||||
# SQLite index — journal/wal temporales
|
# SQLite index — regenerable con `fn index` + completable con `fn sync`
|
||||||
|
registry.db
|
||||||
registry.db-journal
|
registry.db-journal
|
||||||
registry.db-wal
|
registry.db-wal
|
||||||
|
registry.db-shm
|
||||||
|
|
||||||
# operations.db — datos vivos, cada app genera el suyo con fn ops init
|
# operations.db — datos vivos, cada app genera el suyo con fn ops init
|
||||||
**/operations.db
|
**/operations.db
|
||||||
|
|||||||
+2
-2
@@ -8,6 +8,6 @@
|
|||||||
[submodule "cpp/vendor/tracy"]
|
[submodule "cpp/vendor/tracy"]
|
||||||
path = cpp/vendor/tracy
|
path = cpp/vendor/tracy
|
||||||
url = https://github.com/wolfpld/tracy.git
|
url = https://github.com/wolfpld/tracy.git
|
||||||
[submodule "/home/lucas/fn_registry/cpp/vendor/glfw"]
|
[submodule "cpp/vendor/glfw"]
|
||||||
path = /home/lucas/fn_registry/cpp/vendor/glfw
|
path = cpp/vendor/glfw
|
||||||
url = https://github.com/glfw/glfw.git
|
url = https://github.com/glfw/glfw.git
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
name: systemd_local_enable
|
||||||
|
kind: function
|
||||||
|
lang: bash
|
||||||
|
domain: infra
|
||||||
|
version: "1.0.0"
|
||||||
|
purity: impure
|
||||||
|
signature: "systemd_local_enable(name: string) -> json"
|
||||||
|
description: "Habilita un servicio systemd local con systemctl enable para que arranque automáticamente al boot. Requiere sudo."
|
||||||
|
tags: [systemd, service, local, infra, enable]
|
||||||
|
uses_functions: []
|
||||||
|
uses_types: []
|
||||||
|
returns: []
|
||||||
|
returns_optional: false
|
||||||
|
error_type: "error_go_core"
|
||||||
|
imports: []
|
||||||
|
params:
|
||||||
|
- name: name
|
||||||
|
desc: "nombre del servicio sin sufijo .service"
|
||||||
|
output: "JSON {name, enabled:true}. Errores a stderr, exit 1."
|
||||||
|
tested: false
|
||||||
|
tests: []
|
||||||
|
test_file_path: ""
|
||||||
|
file_path: "bash/functions/infra/systemd_local_enable.sh"
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejemplo
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source bash/functions/infra/systemd_local_enable.sh
|
||||||
|
systemd_local_enable "sqlite_api"
|
||||||
|
# {"name":"sqlite_api","enabled":true}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notas
|
||||||
|
|
||||||
|
- El unit debe existir en `/etc/systemd/system/` (usar `systemd_local_install_unit` primero).
|
||||||
|
- No arranca el servicio — solo lo habilita para el próximo boot. Usar `systemd_local_start` para lanzarlo ahora.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# systemd_local_enable — Habilita un servicio systemd local (arranque automático).
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
systemd_local_enable() {
|
||||||
|
local name="$1"
|
||||||
|
|
||||||
|
if [[ -z "$name" ]]; then
|
||||||
|
echo "systemd_local_enable: se requiere name" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# systemctl enable imprime "Created symlink ..." en stdout — redirigir a stderr
|
||||||
|
# para que $(systemd_local_enable ...) capture sólo el JSON final.
|
||||||
|
if ! sudo systemctl enable "${name}.service" >&2; then
|
||||||
|
echo "systemd_local_enable: enable falló para '$name'" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '{"name":"%s","enabled":true}\n' "$name"
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
---
|
||||||
|
name: systemd_local_install_unit
|
||||||
|
kind: function
|
||||||
|
lang: bash
|
||||||
|
domain: infra
|
||||||
|
version: "1.0.0"
|
||||||
|
purity: impure
|
||||||
|
signature: "systemd_local_install_unit(name: string, unit_content: string) -> json"
|
||||||
|
description: "Instala un unit file de systemd en /etc/systemd/system/<name>.service y ejecuta daemon-reload. Requiere sudo sin password para install y systemctl. Sobrescribe si el unit ya existe."
|
||||||
|
tags: [systemd, service, local, infra, wsl]
|
||||||
|
uses_functions: []
|
||||||
|
uses_types: []
|
||||||
|
returns: []
|
||||||
|
returns_optional: false
|
||||||
|
error_type: "error_go_core"
|
||||||
|
imports: []
|
||||||
|
params:
|
||||||
|
- name: name
|
||||||
|
desc: "nombre del servicio sin sufijo (se añade .service automáticamente)"
|
||||||
|
- name: unit_content
|
||||||
|
desc: "contenido completo del archivo unit como texto (con secciones [Unit], [Service], [Install])"
|
||||||
|
output: "JSON {name, path, installed:true}. Errores a stderr, exit 1."
|
||||||
|
tested: false
|
||||||
|
tests: []
|
||||||
|
test_file_path: ""
|
||||||
|
file_path: "bash/functions/infra/systemd_local_install_unit.sh"
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejemplo
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source bash/functions/infra/systemd_local_install_unit.sh
|
||||||
|
|
||||||
|
unit=$(cat <<'EOF'
|
||||||
|
[Unit]
|
||||||
|
Description=my service
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/usr/local/bin/my_service
|
||||||
|
Restart=on-failure
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
)
|
||||||
|
|
||||||
|
systemd_local_install_unit "my_service" "$unit"
|
||||||
|
# {"name":"my_service","path":"/etc/systemd/system/my_service.service","installed":true}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notas
|
||||||
|
|
||||||
|
- Usa `install -m 0644 -o root -g root` para escribir el unit con permisos correctos.
|
||||||
|
- Llama a `sudo systemctl daemon-reload` al final — imprescindible para que systemd vea el unit.
|
||||||
|
- No hace `enable` ni `start` — esas son funciones separadas (principio de composabilidad).
|
||||||
|
- En WSL requiere `systemd=true` en `/etc/wsl.conf`.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# systemd_local_install_unit — Instala un unit file en /etc/systemd/system y recarga systemd.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
systemd_local_install_unit() {
|
||||||
|
local name="$1"
|
||||||
|
local unit_content="$2"
|
||||||
|
|
||||||
|
if [[ -z "$name" || -z "$unit_content" ]]; then
|
||||||
|
echo "systemd_local_install_unit: se requieren name y unit_content" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
local unit_path="/etc/systemd/system/${name}.service"
|
||||||
|
local tmp
|
||||||
|
tmp="$(mktemp)"
|
||||||
|
printf '%s' "$unit_content" > "$tmp"
|
||||||
|
|
||||||
|
if ! sudo install -m 0644 -o root -g root "$tmp" "$unit_path"; then
|
||||||
|
rm -f "$tmp"
|
||||||
|
echo "systemd_local_install_unit: no se pudo instalar '$unit_path'" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
rm -f "$tmp"
|
||||||
|
|
||||||
|
if ! sudo systemctl daemon-reload; then
|
||||||
|
echo "systemd_local_install_unit: daemon-reload falló" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '{"name":"%s","path":"%s","installed":true}\n' "$name" "$unit_path"
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
name: systemd_local_restart
|
||||||
|
kind: function
|
||||||
|
lang: bash
|
||||||
|
domain: infra
|
||||||
|
version: "1.0.0"
|
||||||
|
purity: impure
|
||||||
|
signature: "systemd_local_restart(name: string) -> json"
|
||||||
|
description: "Reinicia un servicio systemd local con systemctl restart. Útil tras actualizar el binario o cambiar el unit. Requiere sudo."
|
||||||
|
tags: [systemd, service, local, infra, restart]
|
||||||
|
uses_functions: []
|
||||||
|
uses_types: []
|
||||||
|
returns: []
|
||||||
|
returns_optional: false
|
||||||
|
error_type: "error_go_core"
|
||||||
|
imports: []
|
||||||
|
params:
|
||||||
|
- name: name
|
||||||
|
desc: "nombre del servicio sin sufijo .service"
|
||||||
|
output: "JSON {name, restarted:true, pid:int}. Errores a stderr, exit 1."
|
||||||
|
tested: false
|
||||||
|
tests: []
|
||||||
|
test_file_path: ""
|
||||||
|
file_path: "bash/functions/infra/systemd_local_restart.sh"
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejemplo
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source bash/functions/infra/systemd_local_restart.sh
|
||||||
|
systemd_local_restart "sqlite_api"
|
||||||
|
# {"name":"sqlite_api","restarted":true,"pid":54321}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notas
|
||||||
|
|
||||||
|
- Si modificaste el unit, primero ejecuta `sudo systemctl daemon-reload` (o llama a `systemd_local_install_unit` que ya lo hace).
|
||||||
|
- Equivalente a stop+start pero systemd lo gestiona atómicamente.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# systemd_local_restart — Reinicia un servicio systemd local.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
systemd_local_restart() {
|
||||||
|
local name="$1"
|
||||||
|
|
||||||
|
if [[ -z "$name" ]]; then
|
||||||
|
echo "systemd_local_restart: se requiere name" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! sudo systemctl restart "${name}.service" >&2; then
|
||||||
|
echo "systemd_local_restart: restart falló para '$name'" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
local pid
|
||||||
|
pid=$(systemctl show -p MainPID --value "${name}.service" 2>/dev/null || echo 0)
|
||||||
|
|
||||||
|
printf '{"name":"%s","restarted":true,"pid":%s}\n' "$name" "${pid:-0}"
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
name: systemd_local_start
|
||||||
|
kind: function
|
||||||
|
lang: bash
|
||||||
|
domain: infra
|
||||||
|
version: "1.0.0"
|
||||||
|
purity: impure
|
||||||
|
signature: "systemd_local_start(name: string) -> json"
|
||||||
|
description: "Arranca un servicio systemd local con systemctl start. Devuelve el MainPID asignado. Requiere sudo."
|
||||||
|
tags: [systemd, service, local, infra, start]
|
||||||
|
uses_functions: []
|
||||||
|
uses_types: []
|
||||||
|
returns: []
|
||||||
|
returns_optional: false
|
||||||
|
error_type: "error_go_core"
|
||||||
|
imports: []
|
||||||
|
params:
|
||||||
|
- name: name
|
||||||
|
desc: "nombre del servicio sin sufijo .service"
|
||||||
|
output: "JSON {name, started:true, pid:int}. Errores a stderr, exit 1."
|
||||||
|
tested: false
|
||||||
|
tests: []
|
||||||
|
test_file_path: ""
|
||||||
|
file_path: "bash/functions/infra/systemd_local_start.sh"
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejemplo
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source bash/functions/infra/systemd_local_start.sh
|
||||||
|
systemd_local_start "sqlite_api"
|
||||||
|
# {"name":"sqlite_api","started":true,"pid":12345}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notas
|
||||||
|
|
||||||
|
- Si el servicio ya está corriendo, `systemctl start` es idempotente (no hace nada).
|
||||||
|
- El PID devuelto es el `MainPID` según systemd. 0 si el arranque falló en silencio (usar `systemd_local_status` para diagnóstico).
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# systemd_local_start — Arranca un servicio systemd local.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
systemd_local_start() {
|
||||||
|
local name="$1"
|
||||||
|
|
||||||
|
if [[ -z "$name" ]]; then
|
||||||
|
echo "systemd_local_start: se requiere name" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! sudo systemctl start "${name}.service" >&2; then
|
||||||
|
echo "systemd_local_start: start falló para '$name'" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
local pid
|
||||||
|
pid=$(systemctl show -p MainPID --value "${name}.service" 2>/dev/null || echo 0)
|
||||||
|
|
||||||
|
printf '{"name":"%s","started":true,"pid":%s}\n' "$name" "${pid:-0}"
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
---
|
||||||
|
name: systemd_local_status
|
||||||
|
kind: function
|
||||||
|
lang: bash
|
||||||
|
domain: infra
|
||||||
|
version: "1.0.0"
|
||||||
|
purity: impure
|
||||||
|
signature: "systemd_local_status(name: string, log_lines: int = 10) -> json"
|
||||||
|
description: "Devuelve el estado de un servicio systemd local: active state, sub state, PID, enabled, y las N últimas líneas de journalctl. No requiere sudo."
|
||||||
|
tags: [systemd, service, local, infra, status, journalctl]
|
||||||
|
uses_functions: []
|
||||||
|
uses_types: []
|
||||||
|
returns: []
|
||||||
|
returns_optional: false
|
||||||
|
error_type: "error_go_core"
|
||||||
|
imports: []
|
||||||
|
params:
|
||||||
|
- name: name
|
||||||
|
desc: "nombre del servicio sin sufijo .service"
|
||||||
|
- name: log_lines
|
||||||
|
desc: "número de líneas de log a incluir en el JSON (default 10)"
|
||||||
|
output: "JSON {name, active, sub, enabled, pid, logs:[...]}. Errores a stderr, exit 1."
|
||||||
|
tested: false
|
||||||
|
tests: []
|
||||||
|
test_file_path: ""
|
||||||
|
file_path: "bash/functions/infra/systemd_local_status.sh"
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejemplo
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source bash/functions/infra/systemd_local_status.sh
|
||||||
|
systemd_local_status "sqlite_api" 5
|
||||||
|
# {"name":"sqlite_api","active":"active","sub":"running","enabled":"enabled","pid":12345,"logs":["...","..."]}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Valores típicos
|
||||||
|
|
||||||
|
- `active`: `active`, `inactive`, `failed`, `activating`, `deactivating`
|
||||||
|
- `sub`: `running`, `dead`, `exited`, `start-pre`, etc.
|
||||||
|
- `enabled`: `enabled`, `disabled`, `static`, `masked`
|
||||||
|
|
||||||
|
## Notas
|
||||||
|
|
||||||
|
- No requiere sudo (solo lectura).
|
||||||
|
- Si el unit no existe, `active` será `inactive` y `sub` será `dead`.
|
||||||
|
- Los logs vienen de `journalctl -u <name> -n N --no-pager -o cat` (sin prefijos, solo el mensaje).
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# systemd_local_status — Estado + últimos logs de un servicio systemd local.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
systemd_local_status() {
|
||||||
|
local name="$1"
|
||||||
|
local log_lines="${2:-10}"
|
||||||
|
|
||||||
|
if [[ -z "$name" ]]; then
|
||||||
|
echo "systemd_local_status: se requiere name" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
local active sub pid enabled
|
||||||
|
active=$(systemctl show -p ActiveState --value "${name}.service" 2>/dev/null || echo unknown)
|
||||||
|
sub=$(systemctl show -p SubState --value "${name}.service" 2>/dev/null || echo unknown)
|
||||||
|
pid=$(systemctl show -p MainPID --value "${name}.service" 2>/dev/null || echo 0)
|
||||||
|
enabled=$(systemctl is-enabled "${name}.service" 2>/dev/null || echo disabled)
|
||||||
|
|
||||||
|
# logs como array JSON
|
||||||
|
local logs_json
|
||||||
|
logs_json=$(journalctl -u "${name}.service" -n "$log_lines" --no-pager -o cat 2>/dev/null \
|
||||||
|
| python3 -c 'import sys, json; print(json.dumps([l.rstrip() for l in sys.stdin if l.strip()]))' \
|
||||||
|
2>/dev/null || echo "[]")
|
||||||
|
|
||||||
|
printf '{"name":"%s","active":"%s","sub":"%s","enabled":"%s","pid":%s,"logs":%s}\n' \
|
||||||
|
"$name" "$active" "$sub" "$enabled" "${pid:-0}" "$logs_json"
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
---
|
||||||
|
name: systemd_local_uninstall
|
||||||
|
kind: function
|
||||||
|
lang: bash
|
||||||
|
domain: infra
|
||||||
|
version: "1.0.0"
|
||||||
|
purity: impure
|
||||||
|
signature: "systemd_local_uninstall(name: string) -> json"
|
||||||
|
description: "Detiene, deshabilita y elimina el unit file de un servicio systemd local. Idempotente: no falla si el servicio ya está parado o el unit no existe. Requiere sudo."
|
||||||
|
tags: [systemd, service, local, infra, uninstall, cleanup]
|
||||||
|
uses_functions: []
|
||||||
|
uses_types: []
|
||||||
|
returns: []
|
||||||
|
returns_optional: false
|
||||||
|
error_type: "error_go_core"
|
||||||
|
imports: []
|
||||||
|
params:
|
||||||
|
- name: name
|
||||||
|
desc: "nombre del servicio sin sufijo .service"
|
||||||
|
output: "JSON {name, uninstalled:true}. Errores a stderr, exit 1."
|
||||||
|
tested: false
|
||||||
|
tests: []
|
||||||
|
test_file_path: ""
|
||||||
|
file_path: "bash/functions/infra/systemd_local_uninstall.sh"
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejemplo
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source bash/functions/infra/systemd_local_uninstall.sh
|
||||||
|
systemd_local_uninstall "sqlite_api"
|
||||||
|
# {"name":"sqlite_api","uninstalled":true}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notas
|
||||||
|
|
||||||
|
- Secuencia: stop → disable → rm unit → daemon-reload → reset-failed.
|
||||||
|
- `stop` y `disable` con `|| true` para idempotencia (si ya no estaba corriendo/enabled, no es error).
|
||||||
|
- `reset-failed` limpia el estado "failed" si el servicio había fallado previamente.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# systemd_local_uninstall — Detiene, deshabilita y elimina un servicio systemd local.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
systemd_local_uninstall() {
|
||||||
|
local name="$1"
|
||||||
|
|
||||||
|
if [[ -z "$name" ]]; then
|
||||||
|
echo "systemd_local_uninstall: se requiere name" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
local unit_path="/etc/systemd/system/${name}.service"
|
||||||
|
|
||||||
|
# stop (idempotente: no falla si ya parado)
|
||||||
|
sudo systemctl stop "${name}.service" 2>/dev/null || true
|
||||||
|
sudo systemctl disable "${name}.service" 2>/dev/null || true
|
||||||
|
|
||||||
|
if [[ -f "$unit_path" ]]; then
|
||||||
|
sudo rm -f "$unit_path"
|
||||||
|
fi
|
||||||
|
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl reset-failed "${name}.service" 2>/dev/null || true
|
||||||
|
|
||||||
|
printf '{"name":"%s","uninstalled":true}\n' "$name"
|
||||||
|
}
|
||||||
@@ -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
|
||||||
BIN
Binary file not shown.
Reference in New Issue
Block a user