4
0

update.sh 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #!/bin/bash
  2. # NetPulse — script de actualización (lo lanza el updater del backend, corre
  3. # como netpulse). Único flujo soportado: Go.
  4. # - Go (/opt/netpulse/server-go/netpulse): git pull → binario precompilado
  5. # de CI (go-latest) → verificación sha256 → swap atómico → reinicio
  6. # diferido.
  7. # Progreso (issue #280): cada paso emite STEP:<nombre> y los hitos largos
  8. # PROGRESS:<0-100>; el updater los reenvía al frontend vía SSE.
  9. #
  10. # Safeguards (issue #425):
  11. # - Backup de .ssh/ y de la BD antes de tocar nada.
  12. # - Restauración automática de .ssh/ si git lo borró o regeneró.
  13. # - El binario anterior se conserva como .prev hasta que el post-update
  14. # healthcheck pase.
  15. # - Si tras el reinicio no se ven routers, se hace rollback al binario,
  16. # claves y BD anteriores y se reinicia de nuevo.
  17. set -e
  18. REPO_ROOT="${REPO_ROOT:-/opt/netpulse}"
  19. DATA_DIR="${DATA_DIR:-/opt/netpulse/server/data}"
  20. RESTART_DIR="${RESTART_DIR:-/opt/netpulse/server-go/data}"
  21. SERVER_BIN="${SERVER_BIN:-/opt/netpulse/server-go/netpulse}"
  22. PORT="${PORT:-3000}"
  23. HEALTH_URL="http://127.0.0.1:${PORT}/api/health"
  24. cd "$REPO_ROOT"
  25. SSH_DIR="$DATA_DIR/.ssh"
  26. DB_FILE="${DB_DIR:-$DATA_DIR}/netpulse.db"
  27. BACKUP_DIR="$DATA_DIR/.update-backup-$(date +%Y%m%d-%H%M%S)"
  28. PREV_BIN="$SERVER_BIN.prev"
  29. mkdir -p "$BACKUP_DIR"
  30. echo "STEP:backup"
  31. # Respaldo de las claves SSH (si no existe, no hay nada que proteger).
  32. if [ -d "$SSH_DIR" ]; then
  33. cp -a "$SSH_DIR" "$BACKUP_DIR/"
  34. echo "copia de seguridad de .ssh en $BACKUP_DIR/.ssh"
  35. fi
  36. # Respaldo consistente de la BD. Preferimos sqlite3 VACUUM INTO; si no está
  37. # disponible, usamos Python; como último recurso cp (a riesgo del admin).
  38. if [ -f "$DB_FILE" ]; then
  39. if command -v sqlite3 >/dev/null 2>&1; then
  40. sqlite3 "$DB_FILE" ".backup '$BACKUP_DIR/netpulse.db'" || cp -a "$DB_FILE" "$BACKUP_DIR/netpulse.db"
  41. elif python3 -c "import sqlite3" >/dev/null 2>&1; then
  42. python3 - <<PYEOF
  43. import sqlite3, sys
  44. src, dst = "$DB_FILE", "$BACKUP_DIR/netpulse.db"
  45. try:
  46. c = sqlite3.connect(src)
  47. c.execute("VACUUM INTO ?", (dst,))
  48. c.close()
  49. except Exception as e:
  50. print(e, file=sys.stderr)
  51. sys.exit(1)
  52. PYEOF
  53. else
  54. cp -a "$DB_FILE" "$BACKUP_DIR/netpulse.db"
  55. fi
  56. # La BD con las series comprime a un tercio y con KEEP=3 son cientos de MB
  57. # en un disco pequeño (#1862). Sin gzip se queda sin comprimir.
  58. if command -v gzip >/dev/null 2>&1 && gzip -9 "$BACKUP_DIR/netpulse.db" 2>/dev/null; then
  59. echo "copia de seguridad de BD comprimida en $BACKUP_DIR/netpulse.db.gz"
  60. else
  61. rm -f "$BACKUP_DIR/netpulse.db.gz"
  62. echo "copia de seguridad de BD en $BACKUP_DIR/netpulse.db"
  63. fi
  64. fi
  65. echo "STEP:fetch"
  66. # Dos layouts soportados:
  67. # - rolling (dev): REPO_ROOT es un clone git → fetch + reset al main.
  68. # - estable (install.sh / CT): REPO_ROOT es solo el árbol de fuentes, sin
  69. # .git (el fetch moría aquí y el update abortaba). El único dato que
  70. # necesita el flujo Go es el SHA de main, que se resuelve vía ls-remote
  71. # anónimo (repo público).
  72. if git -C "$REPO_ROOT" rev-parse --git-dir >/dev/null 2>&1; then
  73. timeout 60 git -C "$REPO_ROOT" fetch origin main
  74. git -C "$REPO_ROOT" reset --hard origin/main
  75. SHA=$(git -C "$REPO_ROOT" rev-parse HEAD)
  76. else
  77. echo "aviso: $REPO_ROOT no es un clone git (layout estable); resolviendo HEAD de main vía ls-remote"
  78. SHA=$(timeout 60 git ls-remote https://github.com/gnacho/netpulse.git refs/heads/main | awk '{print $1}')
  79. if [ -z "$SHA" ]; then
  80. echo "ERROR: no se pudo resolver el HEAD de main (red o git ausente)"
  81. exit 1
  82. fi
  83. fi
  84. # Si git reset --hard (o git clean) eliminó .ssh, lo restauramos desde el
  85. # backup. Esto es lo que pasó en issue #425.
  86. if [ -d "$BACKUP_DIR/.ssh" ]; then
  87. if [ ! -d "$SSH_DIR" ] || [ ! -f "$SSH_DIR/id_ed25519" ] || [ ! -f "$SSH_DIR/id_ed25519.pub" ]; then
  88. rm -rf "$SSH_DIR"
  89. cp -a "$BACKUP_DIR/.ssh" "$DATA_DIR/"
  90. chmod 700 "$SSH_DIR" 2>/dev/null || true
  91. chmod 600 "$SSH_DIR/id_ed25519" 2>/dev/null || true
  92. chmod 644 "$SSH_DIR/id_ed25519.pub" "$SSH_DIR/known_hosts" 2>/dev/null || true
  93. echo "restaurada .ssh desde copia de seguridad"
  94. fi
  95. fi
  96. if [ -f "$SERVER_BIN" ]; then
  97. # ---------------- Flujo Go ----------------
  98. echo "STEP:download"
  99. ARCH=$(uname -m)
  100. case "$ARCH" in
  101. x86_64) ARCH=amd64 ;;
  102. aarch64) ARCH=arm64 ;;
  103. *) echo "arquitectura no soportada: $ARCH"; exit 1 ;;
  104. esac
  105. ASSET="netpulse-server-$SHA-linux-$ARCH.tar.gz"
  106. rm -rf /opt/netpulse/server-go/pkg.new
  107. mkdir -p /opt/netpulse/server-go/pkg.new
  108. # Metadatos de la prerelease go-latest: fallback de asset + digest sha256
  109. # para el paso verify. Si la llamada falla, el flujo sigue (fallback solo
  110. # con el asset exacto del commit).
  111. RELEASE_JSON=/tmp/netpulse-go-release.json
  112. curl -fsSL -m 30 "https://api.github.com/repos/gnacho/netpulse/releases/tags/go-latest" -o "$RELEASE_JSON" || rm -f "$RELEASE_JSON"
  113. # 1) asset exacto del commit; 2) si no existe (commit sin cambios en
  114. # server-go/ ni app/), el asset más reciente de esta arquitectura.
  115. if ! curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz; then
  116. ASSET=$(grep -oP '"name":\s*"\Knetpulse-server-[0-9a-f]+-linux-'"$ARCH"'\.tar\.gz' "$RELEASE_JSON" 2>/dev/null | head -1)
  117. if [ -n "$ASSET" ] && curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz; then
  118. echo "aviso (#471): sin asset para el commit $SHA; instalando el más reciente ($ASSET). El updater seguirá ofreciendo actualización hasta que main publique un asset propio de su SHA."
  119. else
  120. echo "ERROR: sin binario en CI para $ARCH (el CT no puede compilar Go)"
  121. exit 1
  122. fi
  123. fi
  124. echo "PROGRESS:55"
  125. echo "STEP:verify"
  126. # Digest sha256 del asset publicado por la API de GitHub. Si el campo no
  127. # viene (release sin digest), se avisa y continúa; si viene y NO coincide,
  128. # aborta (el tarball no es el publicado por CI).
  129. DIGEST=""
  130. if [ -s "$RELEASE_JSON" ]; then
  131. DIGEST=$(awk -v want="\"$ASSET\"" '$0 ~ "\"name\": *" want {f=1} f && /"digest"/ {print; exit}' "$RELEASE_JSON" | grep -oE 'sha256:[0-9a-f]+')
  132. fi
  133. if [ -n "$DIGEST" ]; then
  134. echo "verificando $ASSET contra $DIGEST"
  135. echo "${DIGEST#sha256:} /tmp/netpulse-go.tgz" | sha256sum -c - || { echo "ERROR: sha256 del asset no coincide"; exit 1; }
  136. else
  137. echo "aviso: la API no publicó digest para $ASSET; verificación omitida"
  138. fi
  139. tar xzf /tmp/netpulse-go.tgz -C /opt/netpulse/server-go/pkg.new
  140. echo "PROGRESS:75"
  141. echo "STEP:install"
  142. # Swap atómico: conservamos el anterior como .prev hasta pasar el healthcheck.
  143. chmod +x /opt/netpulse/server-go/pkg.new/netpulse
  144. mv "$SERVER_BIN" "$PREV_BIN"
  145. if ! mv /opt/netpulse/server-go/pkg.new/netpulse "$SERVER_BIN"; then
  146. # Swap falló: intentar devolver el anterior y abortar.
  147. mv "$PREV_BIN" "$SERVER_BIN"
  148. rm -rf /opt/netpulse/server-go/pkg.new /tmp/netpulse-go.tgz "$RELEASE_JSON"
  149. echo "ERROR: swap del binario falló"
  150. exit 1
  151. fi
  152. rm -rf /opt/netpulse/server-go/pkg.new /tmp/netpulse-go.tgz "$RELEASE_JSON"
  153. echo "STEP:restart"
  154. # Marcador de éxito pre-reinicio (#444): el reinicio vía systemd.path mata
  155. # este script (hijo del servidor) y sin este fichero el updater registra
  156. # "update_exit_-1" aunque el swap haya ido bien. El updater lo interpreta
  157. # como el camino de éxito esperado y mantiene el pendingApply (#161).
  158. echo "$SHA" > "$REPO_ROOT/.update-applied"
  159. # Reinicio vía unidad systemd.path del CT (netpulse-go-restart.path vigila
  160. # este flag y ejecuta systemctl restart netpulse-go.service como root).
  161. # El dir puede no existir (DATA_DIR real vive en /opt/netpulse/server-go/data):
  162. # crearlo antes de tocar el flag (bug visto 1-Ago-2026: touch fallaba y el
  163. # binario nuevo quedaba instalado sin reiniciar).
  164. mkdir -p "$RESTART_DIR"
  165. touch "$RESTART_DIR/.restart-me"
  166. echo "STEP:verify"
  167. # Esperamos a que el servidor vuelva y haya sondeado al menos un router.
  168. # /api/health es público; devicesTotal > 0 indica que SSH/known_hosts/BD funcionan.
  169. HEALTHY=0
  170. DEVICES=0
  171. for i in $(seq 1 60); do
  172. HEALTH_JSON=$(curl -fsS --max-time 5 "$HEALTH_URL" 2>/dev/null || true)
  173. if [ -n "$HEALTH_JSON" ]; then
  174. DEVICES=$(echo "$HEALTH_JSON" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("devicesTotal",0))' 2>/dev/null || echo 0)
  175. AGENTS=$(echo "$HEALTH_JSON" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("agentsConnected",0))' 2>/dev/null || echo 0)
  176. if [ "$DEVICES" -gt 0 ] || [ "$AGENTS" -gt 0 ]; then
  177. HEALTHY=1
  178. break
  179. fi
  180. fi
  181. sleep 2
  182. done
  183. if [ "$HEALTHY" -eq 0 ]; then
  184. echo "ERROR: el servidor no respondió o no ve routers/agentes tras el reinicio (devices=$DEVICES)"
  185. DO_ROLLBACK=1
  186. else
  187. echo "healthcheck OK: devices=$DEVICES agents=$AGENTS"
  188. fi
  189. if [ "${DO_ROLLBACK:-0}" -eq 1 ]; then
  190. if [ -f "$PREV_BIN" ]; then
  191. mv "$PREV_BIN" "$SERVER_BIN"
  192. fi
  193. if [ -d "$BACKUP_DIR/.ssh" ]; then
  194. rm -rf "$SSH_DIR"
  195. cp -a "$BACKUP_DIR/.ssh" "$DATA_DIR/"
  196. chmod 700 "$SSH_DIR" 2>/dev/null || true
  197. chmod 600 "$SSH_DIR/id_ed25519" 2>/dev/null || true
  198. chmod 644 "$SSH_DIR/id_ed25519.pub" "$SSH_DIR/known_hosts" 2>/dev/null || true
  199. fi
  200. if [ -f "$BACKUP_DIR/netpulse.db.gz" ]; then
  201. # Se descomprime a un temporal y se renombra, para no dejar la BD a
  202. # medias si el disco se llena. Los -wal/-shm viejos se tiran: aplicarían
  203. # escrituras de la versión anterior sobre la BD restaurada (#1862).
  204. if gunzip -c "$BACKUP_DIR/netpulse.db.gz" > "$DB_FILE.restore" 2>/dev/null; then
  205. rm -f "$DB_FILE-wal" "$DB_FILE-shm"
  206. mv -f "$DB_FILE.restore" "$DB_FILE"
  207. echo "BD restaurada desde $BACKUP_DIR/netpulse.db.gz"
  208. else
  209. rm -f "$DB_FILE.restore"
  210. echo "ERROR: no pude restaurar la BD desde $BACKUP_DIR/netpulse.db.gz" >&2
  211. fi
  212. elif [ -f "$BACKUP_DIR/netpulse.db" ]; then
  213. rm -f "$DB_FILE-wal" "$DB_FILE-shm"
  214. cp -a "$BACKUP_DIR/netpulse.db" "$DB_FILE"
  215. fi
  216. # Forzamos un nuevo reinicio para levantar con la versión anterior.
  217. touch "$RESTART_DIR/.restart-me"
  218. echo "ERROR: rollback completado; versión anterior restaurada"
  219. exit 1
  220. fi
  221. # Todo OK: ya podemos descartar el binario anterior.
  222. rm -f "$PREV_BIN"
  223. # Purga de snapshots del updater (issue #809). Solo en el camino de éxito:
  224. # durante un rollback el snapshot en curso es la red de seguridad. Ruta
  225. # absoluta porque este script se ejecuta copiado en /tmp (no hay dirname).
  226. if [ -f "$REPO_ROOT/deploy/prune-update-backups.sh" ]; then
  227. DATA_DIR="$DATA_DIR" KEEP="${NETPULSE_UPDATE_BACKUPS_KEEP:-3}" \
  228. bash "$REPO_ROOT/deploy/prune-update-backups.sh" || true
  229. fi
  230. fi
  231. echo "STEP:done"