update.sh 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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="$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. echo "copia de seguridad de BD en $BACKUP_DIR/netpulse.db"
  57. fi
  58. echo "STEP:fetch"
  59. # Dos layouts soportados:
  60. # - rolling (dev): REPO_ROOT es un clone git → fetch + reset al main.
  61. # - estable (install.sh / CT): REPO_ROOT es solo el árbol de fuentes, sin
  62. # .git (el fetch moría aquí y el update abortaba). El único dato que
  63. # necesita el flujo Go es el SHA de main, que se resuelve vía ls-remote
  64. # anónimo (repo público).
  65. if git -C "$REPO_ROOT" rev-parse --git-dir >/dev/null 2>&1; then
  66. timeout 60 git -C "$REPO_ROOT" fetch origin main
  67. git -C "$REPO_ROOT" reset --hard origin/main
  68. SHA=$(git -C "$REPO_ROOT" rev-parse HEAD)
  69. else
  70. echo "aviso: $REPO_ROOT no es un clone git (layout estable); resolviendo HEAD de main vía ls-remote"
  71. SHA=$(timeout 60 git ls-remote https://github.com/gnacho/netpulse.git refs/heads/main | awk '{print $1}')
  72. if [ -z "$SHA" ]; then
  73. echo "ERROR: no se pudo resolver el HEAD de main (red o git ausente)"
  74. exit 1
  75. fi
  76. fi
  77. # Si git reset --hard (o git clean) eliminó .ssh, lo restauramos desde el
  78. # backup. Esto es lo que pasó en issue #425.
  79. if [ -d "$BACKUP_DIR/.ssh" ]; then
  80. if [ ! -d "$SSH_DIR" ] || [ ! -f "$SSH_DIR/id_ed25519" ] || [ ! -f "$SSH_DIR/id_ed25519.pub" ]; then
  81. rm -rf "$SSH_DIR"
  82. cp -a "$BACKUP_DIR/.ssh" "$DATA_DIR/"
  83. chmod 700 "$SSH_DIR" 2>/dev/null || true
  84. chmod 600 "$SSH_DIR/id_ed25519" 2>/dev/null || true
  85. chmod 644 "$SSH_DIR/id_ed25519.pub" "$SSH_DIR/known_hosts" 2>/dev/null || true
  86. echo "restaurada .ssh desde copia de seguridad"
  87. fi
  88. fi
  89. if [ -f "$SERVER_BIN" ]; then
  90. # ---------------- Flujo Go ----------------
  91. echo "STEP:download"
  92. ARCH=$(uname -m)
  93. case "$ARCH" in
  94. x86_64) ARCH=amd64 ;;
  95. aarch64) ARCH=arm64 ;;
  96. *) echo "arquitectura no soportada: $ARCH"; exit 1 ;;
  97. esac
  98. ASSET="netpulse-server-$SHA-linux-$ARCH.tar.gz"
  99. rm -rf /opt/netpulse/server-go/pkg.new
  100. mkdir -p /opt/netpulse/server-go/pkg.new
  101. # Metadatos de la prerelease go-latest: fallback de asset + digest sha256
  102. # para el paso verify. Si la llamada falla, el flujo sigue (fallback solo
  103. # con el asset exacto del commit).
  104. RELEASE_JSON=/tmp/netpulse-go-release.json
  105. curl -fsSL -m 30 "https://api.github.com/repos/gnacho/netpulse/releases/tags/go-latest" -o "$RELEASE_JSON" || rm -f "$RELEASE_JSON"
  106. # 1) asset exacto del commit; 2) si no existe (commit sin cambios en
  107. # server-go/ ni app/), el asset más reciente de esta arquitectura.
  108. if ! curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz; then
  109. ASSET=$(grep -oP '"name":\s*"\Knetpulse-server-[0-9a-f]+-linux-'"$ARCH"'\.tar\.gz' "$RELEASE_JSON" 2>/dev/null | head -1)
  110. if [ -n "$ASSET" ] && curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz; then
  111. 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."
  112. else
  113. echo "ERROR: sin binario en CI para $ARCH (el CT no puede compilar Go)"
  114. exit 1
  115. fi
  116. fi
  117. echo "PROGRESS:55"
  118. echo "STEP:verify"
  119. # Digest sha256 del asset publicado por la API de GitHub. Si el campo no
  120. # viene (release sin digest), se avisa y continúa; si viene y NO coincide,
  121. # aborta (el tarball no es el publicado por CI).
  122. DIGEST=""
  123. if [ -s "$RELEASE_JSON" ]; then
  124. DIGEST=$(awk -v want="\"$ASSET\"" '$0 ~ "\"name\": *" want {f=1} f && /"digest"/ {print; exit}' "$RELEASE_JSON" | grep -oE 'sha256:[0-9a-f]+')
  125. fi
  126. if [ -n "$DIGEST" ]; then
  127. echo "verificando $ASSET contra $DIGEST"
  128. echo "${DIGEST#sha256:} /tmp/netpulse-go.tgz" | sha256sum -c - || { echo "ERROR: sha256 del asset no coincide"; exit 1; }
  129. else
  130. echo "aviso: la API no publicó digest para $ASSET; verificación omitida"
  131. fi
  132. tar xzf /tmp/netpulse-go.tgz -C /opt/netpulse/server-go/pkg.new
  133. echo "PROGRESS:75"
  134. echo "STEP:install"
  135. # Swap atómico: conservamos el anterior como .prev hasta pasar el healthcheck.
  136. chmod +x /opt/netpulse/server-go/pkg.new/netpulse
  137. mv "$SERVER_BIN" "$PREV_BIN"
  138. if ! mv /opt/netpulse/server-go/pkg.new/netpulse "$SERVER_BIN"; then
  139. # Swap falló: intentar devolver el anterior y abortar.
  140. mv "$PREV_BIN" "$SERVER_BIN"
  141. rm -rf /opt/netpulse/server-go/pkg.new /tmp/netpulse-go.tgz "$RELEASE_JSON"
  142. echo "ERROR: swap del binario falló"
  143. exit 1
  144. fi
  145. rm -rf /opt/netpulse/server-go/pkg.new /tmp/netpulse-go.tgz "$RELEASE_JSON"
  146. echo "STEP:restart"
  147. # Marcador de éxito pre-reinicio (#444): el reinicio vía systemd.path mata
  148. # este script (hijo del servidor) y sin este fichero el updater registra
  149. # "update_exit_-1" aunque el swap haya ido bien. El updater lo interpreta
  150. # como el camino de éxito esperado y mantiene el pendingApply (#161).
  151. echo "$SHA" > "$REPO_ROOT/.update-applied"
  152. # Reinicio vía unidad systemd.path del CT (netpulse-go-restart.path vigila
  153. # este flag y ejecuta systemctl restart netpulse-go.service como root).
  154. # El dir puede no existir (DATA_DIR real vive en /opt/netpulse/server-go/data):
  155. # crearlo antes de tocar el flag (bug visto 1-Ago-2026: touch fallaba y el
  156. # binario nuevo quedaba instalado sin reiniciar).
  157. mkdir -p "$RESTART_DIR"
  158. touch "$RESTART_DIR/.restart-me"
  159. echo "STEP:verify"
  160. # Esperamos a que el servidor vuelva y haya sondeado al menos un router.
  161. # /api/health es público; devicesTotal > 0 indica que SSH/known_hosts/BD funcionan.
  162. HEALTHY=0
  163. DEVICES=0
  164. for i in $(seq 1 60); do
  165. HEALTH_JSON=$(curl -fsS --max-time 5 "$HEALTH_URL" 2>/dev/null || true)
  166. if [ -n "$HEALTH_JSON" ]; then
  167. DEVICES=$(echo "$HEALTH_JSON" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("devicesTotal",0))' 2>/dev/null || echo 0)
  168. AGENTS=$(echo "$HEALTH_JSON" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("agentsConnected",0))' 2>/dev/null || echo 0)
  169. if [ "$DEVICES" -gt 0 ] || [ "$AGENTS" -gt 0 ]; then
  170. HEALTHY=1
  171. break
  172. fi
  173. fi
  174. sleep 2
  175. done
  176. if [ "$HEALTHY" -eq 0 ]; then
  177. echo "ERROR: el servidor no respondió o no ve routers/agentes tras el reinicio (devices=$DEVICES)"
  178. DO_ROLLBACK=1
  179. else
  180. echo "healthcheck OK: devices=$DEVICES agents=$AGENTS"
  181. fi
  182. if [ "${DO_ROLLBACK:-0}" -eq 1 ]; then
  183. if [ -f "$PREV_BIN" ]; then
  184. mv "$PREV_BIN" "$SERVER_BIN"
  185. fi
  186. if [ -d "$BACKUP_DIR/.ssh" ]; then
  187. rm -rf "$SSH_DIR"
  188. cp -a "$BACKUP_DIR/.ssh" "$DATA_DIR/"
  189. chmod 700 "$SSH_DIR" 2>/dev/null || true
  190. chmod 600 "$SSH_DIR/id_ed25519" 2>/dev/null || true
  191. chmod 644 "$SSH_DIR/id_ed25519.pub" "$SSH_DIR/known_hosts" 2>/dev/null || true
  192. fi
  193. if [ -f "$BACKUP_DIR/netpulse.db" ]; then
  194. cp -a "$BACKUP_DIR/netpulse.db" "$DB_FILE"
  195. fi
  196. # Forzamos un nuevo reinicio para levantar con la versión anterior.
  197. touch "$RESTART_DIR/.restart-me"
  198. echo "ERROR: rollback completado; versión anterior restaurada"
  199. exit 1
  200. fi
  201. # Todo OK: ya podemos descartar el binario anterior.
  202. rm -f "$PREV_BIN"
  203. # Purga de snapshots del updater (issue #809). Solo en el camino de éxito:
  204. # durante un rollback el snapshot en curso es la red de seguridad. Ruta
  205. # absoluta porque este script se ejecuta copiado en /tmp (no hay dirname).
  206. if [ -f "$REPO_ROOT/deploy/prune-update-backups.sh" ]; then
  207. DATA_DIR="$DATA_DIR" KEEP="${NETPULSE_UPDATE_BACKUPS_KEEP:-3}" \
  208. bash "$REPO_ROOT/deploy/prune-update-backups.sh" || true
  209. fi
  210. fi
  211. echo "STEP:done"