Compare commits

..
Author SHA1 Message Date
admin b30cc1a294 maintenance: corregir diagnóstico Android de solo lectura 2026-09-05 20:07:58 -03:00
admin a7a6680cf8 maintenance: descubrir fuente Android en VPS sin modificar datos 2026-09-05 20:07:40 -03:00
admin 44570ad457 maintenance: retirar fresh-start temporal
Restaura migration:run y deploy-github estándar y elimina la herramienta fresh-start luego de la limpieza exitosa.
2026-09-05 20:04:46 -03:00
admin 8caed06362 maintenance: retirar herramienta destructiva temporal 2026-09-05 20:01:48 -03:00
admin e3db3d6cd7 maintenance: restaurar deploy estándar tras fresh-start 2026-09-05 20:01:37 -03:00
admin fb7b29cd94 maintenance: retirar hook de fresh-start 2026-09-05 20:01:08 -03:00
admin 0a11a452b5 maintenance: ejecutar fresh-start definitivo
Fresh-start único: backup integral de DB/source/media, limpieza de datos operativos y usuarios no-admin, reset de configuración editable, vaciado de archivos y verificación final.
2026-09-05 19:57:49 -03:00
3 changed files with 68 additions and 551 deletions
+1 -2
View File
@@ -9,11 +9,10 @@
"start:dev": "nest start --watch",
"typecheck": "tsc --noEmit",
"test": "tsc -p tsconfig.test.json --noEmit && node --import tsx --test test/**/*.test.ts",
"migration:run": "node dist/database/migration-cli.js run && node dist/cli/fresh-start-reset.js --apply DHV2-FRESH-START-20260905",
"migration:run": "node dist/database/migration-cli.js run",
"migration:show": "node dist/database/migration-cli.js show",
"migration:revert": "node dist/database/migration-cli.js revert",
"bootstrap:admin": "node dist/cli/bootstrap-admin.js",
"maintenance:fresh-start": "node dist/cli/fresh-start-reset.js",
"dev:seed:mendoza-demo": "node dist/cli/dev-seed-mendoza-demo.js"
},
"dependencies": {
-267
View File
@@ -1,267 +0,0 @@
import 'reflect-metadata';
import { promises as fs } from 'node:fs';
import { migrationDataSource } from '../database/data-source';
const APPLY_TOKEN = 'DHV2-FRESH-START-20260905';
const PRESERVED_TABLES = new Set([
'typeorm_migrations',
'spatial_ref_sys',
'users',
'user_roles',
'roles',
'role_permissions',
'permissions',
'asset_types',
'asset_type_parent_rules',
'asset_attribute_definitions',
'finding_categories',
'finding_catalog_items',
'finding_catalog_item_versions',
'finding_catalog_item_asset_types',
'finding_catalog_asset_type_profiles',
'institutional_delivery_settings',
]);
type AdminRow = {
id: string;
username: string;
email: string | null;
status: string;
};
type TableRow = { table_name: string };
type CountRow = { count: string | number };
function quoteIdentifier(value: string): string {
return `"${value.replaceAll('"', '""')}"`;
}
function requestedMode(): 'preview' | 'apply' {
const args = process.argv.slice(2);
if (args.length === 1 && args[0] === '--preview') return 'preview';
if (args.length === 2 && args[0] === '--apply' && args[1] === APPLY_TOKEN) {
return 'apply';
}
throw new Error(
`Uso inválido. Permitido: --preview o --apply ${APPLY_TOKEN}`,
);
}
async function rowCount(table: string): Promise<number> {
const result = (await migrationDataSource.query(
`SELECT COUNT(*)::bigint AS count FROM public.${quoteIdentifier(table)}`,
)) as CountRow[];
return Number(result[0]?.count ?? 0);
}
async function clearMediaStorage(): Promise<void> {
const root = process.env.ASSET_MEDIA_ROOT;
if (!root) {
process.stdout.write('MEDIA: ASSET_MEDIA_ROOT no configurado; no se tocaron archivos.\n');
return;
}
try {
const entries = await fs.readdir(root, { withFileTypes: true });
for (const entry of entries) {
await fs.rm(`${root}/${entry.name}`, { recursive: true, force: true });
}
await fs.mkdir(`${root}/imports`, { recursive: true });
process.stdout.write(`MEDIA: almacenamiento limpiado en ${root}\n`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
process.stdout.write(`MEDIA WARNING: no se pudo limpiar completamente ${root}: ${message}\n`);
}
}
async function main(): Promise<void> {
const mode = requestedMode();
await migrationDataSource.initialize();
try {
await migrationDataSource.query(
`SELECT pg_advisory_lock(hashtext('dhv2-fresh-start-reset'))`,
);
const admins = (await migrationDataSource.query(`
SELECT DISTINCT user_row.id, user_row.username, user_row.email, user_row.status
FROM users user_row
INNER JOIN user_roles user_role ON user_role.user_id = user_row.id
INNER JOIN roles role ON role.id = user_role.role_id
WHERE role.code = 'admin'
ORDER BY user_row.username
`)) as AdminRow[];
if (admins.length !== 1) {
throw new Error(
`Se esperaba exactamente 1 usuario con rol admin y se encontraron ${admins.length}. Limpieza abortada.`,
);
}
const admin = admins[0];
const tables = (await migrationDataSource.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
ORDER BY table_name
`)) as TableRow[];
const existingTables = tables.map((row) => row.table_name);
const tablesToClear = existingTables.filter(
(table) => !PRESERVED_TABLES.has(table),
);
const tablesToPreserve = existingTables.filter((table) =>
PRESERVED_TABLES.has(table),
);
process.stdout.write('\n============================================================\n');
process.stdout.write(` DH V2 · FRESH START · ${mode.toUpperCase()}\n`);
process.stdout.write('============================================================\n');
process.stdout.write(
`ADMIN PRESERVADO: ${admin.username} · ${admin.email ?? 'sin email'} · ${admin.id}\n`,
);
process.stdout.write('\n========== TABLAS ESTRUCTURALES CONSERVADAS ==========\n');
for (const table of tablesToPreserve) {
process.stdout.write(`KEEP ${table.padEnd(46)} ${await rowCount(table)}\n`);
}
process.stdout.write('RESET institutional_delivery_settings emails/updated_by\n');
process.stdout.write('\n========== DATOS A ELIMINAR ==========\n');
let rowsToDelete = 0;
for (const table of tablesToClear) {
const count = await rowCount(table);
rowsToDelete += count;
process.stdout.write(`CLEAR ${table.padEnd(46)} ${count}\n`);
}
const userCount = await rowCount('users');
const nonAdminUsers = Math.max(0, userCount - 1);
process.stdout.write(`CLEAR ${'users (excepto admin)'.padEnd(46)} ${nonAdminUsers}\n`);
rowsToDelete += nonAdminUsers;
process.stdout.write(`TOTAL FILAS OPERATIVAS/USUARIOS A RETIRAR: ${rowsToDelete}\n`);
if (mode === 'preview') {
process.stdout.write('\nPREVIEW_OK: no se modificó ningún dato.\n');
return;
}
await migrationDataSource.transaction(async (manager) => {
// Se vacía el grafo operacional completo sin depender del orden físico
// de las FK. La estructura maestra está excluida por PRESERVED_TABLES.
await manager.query(`SET LOCAL session_replication_role = replica`);
for (const table of tablesToClear) {
await manager.query(`DELETE FROM public.${quoteIdentifier(table)}`);
}
// Antes de tocar cualquier tabla preservada reactivamos las FK reales.
// Si apareciera una dependencia RESTRICT inesperada, PostgreSQL aborta
// la transacción completa en lugar de dejar referencias huérfanas.
await manager.query(`SET LOCAL session_replication_role = origin`);
await manager.query(`
UPDATE institutional_delivery_settings
SET office_email = NULL,
director_email = NULL,
updated_by = NULL,
updated_at = CURRENT_TIMESTAMP
WHERE id = 1
`);
await manager.query(
`DELETE FROM user_roles WHERE user_id <> $1::uuid`,
[admin.id],
);
await manager.query(
`
DELETE FROM user_roles user_role
USING roles role
WHERE user_role.user_id = $1::uuid
AND role.id = user_role.role_id
AND role.code <> 'admin'
`,
[admin.id],
);
await manager.query(`DELETE FROM users WHERE id <> $1::uuid`, [admin.id]);
await manager.query(
`
UPDATE users
SET status = 'ACTIVE',
failed_login_attempts = 0,
locked_until = NULL,
created_by = CASE WHEN created_by = $1::uuid THEN created_by ELSE NULL END,
updated_by = $1::uuid,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1::uuid
`,
[admin.id],
);
await manager.query(
`
UPDATE user_roles user_role
SET assigned_by = $1::uuid
FROM roles role
WHERE user_role.user_id = $1::uuid
AND role.id = user_role.role_id
AND role.code = 'admin'
`,
[admin.id],
);
});
const usersAfter = await rowCount('users');
if (usersAfter !== 1) {
throw new Error(`Verificación falló: users=${usersAfter}, esperado=1`);
}
const adminAfter = (await migrationDataSource.query(
`
SELECT COUNT(DISTINCT user_row.id)::integer AS count
FROM users user_row
INNER JOIN user_roles user_role ON user_role.user_id = user_row.id
INNER JOIN roles role ON role.id = user_role.role_id
WHERE role.code = 'admin'
`,
)) as CountRow[];
if (Number(adminAfter[0]?.count ?? 0) !== 1) {
throw new Error('Verificación falló: el administrador no quedó correctamente asignado');
}
for (const table of tablesToClear) {
const count = await rowCount(table);
if (count !== 0) {
throw new Error(`Verificación falló: ${table} conserva ${count} fila(s)`);
}
}
await clearMediaStorage();
process.stdout.write('\n========== VERIFICACIÓN FRESH START ==========\n');
process.stdout.write(`Usuarios: 1 (${admin.username})\n`);
process.stdout.write('Datos operativos/importados: 0\n');
process.stdout.write('Roles/permisos/tipos/catálogo base: conservados\n');
process.stdout.write('Configuración institucional editable: reiniciada\n');
process.stdout.write('FRESH_START_OK\n');
} finally {
if (migrationDataSource.isInitialized) {
try {
await migrationDataSource.query(
`SELECT pg_advisory_unlock(hashtext('dhv2-fresh-start-reset'))`,
);
} catch {
// La conexión se destruirá de todas formas.
}
await migrationDataSource.destroy();
}
}
}
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`FRESH_START_ERROR: ${message}\n`);
process.exitCode = 1;
});
+67 -282
View File
@@ -3,327 +3,112 @@ set -Eeuo pipefail
APP="/var/www/dhv2.korexlabs.com"
KEY="/root/.ssh/dhv2_github"
BACKUP_ROOT="/root/DH_V2_BACKUPS"
DEPLOY_REF="${DHV2_DEPLOY_REF:-deploy}"
STAMP="$(date +%Y%m%d_%H%M%S)"
BACKUP="$BACKUP_ROOT/GITHUB_DEPLOY_${STAMP}"
STAGE="/root/dhv2-github-stage-${STAMP}"
LOG="/tmp/dhv2-github-deploy-${STAMP}.log"
API_TEST_IMAGE="dhv2-api:github-${STAMP}"
WEB_TEST_IMAGE="dhv2-web:github-${STAMP}"
PHASE="bootstrap"
PREV_SHA=""
TARGET_SHA=""
EXPECTED_API_VERSION=""
EXPECTED_WEB_VERSION=""
APP_TOUCHED=0
LOG="$(mktemp /tmp/dhv2-android-discovery.XXXXXX.log)"
STATUS="$(mktemp /tmp/dhv2-android-discovery-status.XXXXXX)"
cd "$APP"
export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
exec > >(tee -a "$LOG") 2>&1
cleanup() {
set +e
git worktree remove --force "$STAGE" >/dev/null 2>&1 || true
rm -rf "$STAGE"
docker image rm "$API_TEST_IMAGE" "$WEB_TEST_IMAGE" >/dev/null 2>&1 || true
}
publish_status() {
local rc="${1:-1}"
set +e
local outcome="failure"
[ "$rc" -eq 0 ] && outcome="success"
local current="unknown"
local current target status_blob log_blob tree commit
current="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
local status_file log_file status_blob log_blob tree commit
status_file="$(mktemp /tmp/dhv2-status.XXXXXX)"
log_file="$(mktemp /tmp/dhv2-log.XXXXXX)"
target="$(git rev-parse origin/$DEPLOY_REF 2>/dev/null || echo unknown)"
{
echo "status=$outcome"
echo "exit_code=$rc"
echo "phase=$PHASE"
echo "phase=android-source-discovery"
echo "timestamp=$(date --iso-8601=seconds)"
echo "deploy_ref=$DEPLOY_REF"
echo "previous_sha=${PREV_SHA:-unknown}"
echo "target_sha=${TARGET_SHA:-unknown}"
echo "target_sha=$target"
echo "current_sha=$current"
echo "api_version=${EXPECTED_API_VERSION:-unknown}"
echo "web_version=${EXPECTED_WEB_VERSION:-unknown}"
echo "app_touched=$APP_TOUCHED"
echo "backup=${BACKUP:-unknown}"
} > "$status_file"
tail -n 500 "$LOG" > "$log_file" 2>/dev/null || true
status_blob="$(git hash-object -w "$status_file" 2>/dev/null || true)"
log_blob="$(git hash-object -w "$log_file" 2>/dev/null || true)"
echo "app_touched=0"
echo "backup=not-required-read-only"
} > "$STATUS"
status_blob="$(git hash-object -w "$STATUS" 2>/dev/null || true)"
log_blob="$(git hash-object -w "$LOG" 2>/dev/null || true)"
if [ -n "$status_blob" ] && [ -n "$log_blob" ]; then
tree="$(printf '100644 blob %s\tdeploy.log\n100644 blob %s\tstatus.txt\n' "$log_blob" "$status_blob" | git mktree 2>/dev/null || true)"
if [ -n "$tree" ]; then
commit="$(printf 'deploy-status: %s · phase %s\n' "$outcome" "$PHASE" | git -c user.name='DH V2 Deploy Bot' -c user.email='deploy@dhv2.local' commit-tree "$tree" 2>/dev/null || true)"
commit="$(printf 'deploy-status: %s · android-source-discovery\n' "$outcome" | git -c user.name='DH V2 Deploy Bot' -c user.email='deploy@dhv2.local' commit-tree "$tree" 2>/dev/null || true)"
[ -z "$commit" ] || git push --force origin "$commit:refs/heads/deploy-status" >/dev/null 2>&1 || true
fi
fi
rm -f "$status_file" "$log_file"
rm -f "$STATUS" "$LOG"
}
trap 'rc=$?; trap - EXIT; publish_status "$rc"; exit "$rc"' EXIT
on_exit() {
local rc=$?
trap - EXIT ERR
cleanup
publish_status "$rc"
exit "$rc"
}
trap on_exit EXIT
rollback() {
local rc=$?
trap - ERR
PHASE="rollback"
echo
echo "============================================================"
echo " DH V2 · DEPLOY FALLÓ · ROLLBACK"
echo "============================================================"
cd "$APP"
if [ "$APP_TOUCHED" -eq 1 ] && [ -n "${PREV_SHA:-}" ]; then
echo "Restaurando aplicación al commit previo: $PREV_SHA"
git reset --hard "$PREV_SHA" || true
docker compose build api web </dev/null || true
docker compose up -d --no-deps --force-recreate api web </dev/null || true
else
echo "El candidato falló antes de modificar producción; no se reconstruye ni reinicia la aplicación activa."
fi
echo
echo "Estado actual:"
docker compose ps -a </dev/null || true
if [ "$APP_TOUCHED" -eq 1 ]; then
echo
echo "Últimos logs:"
docker compose logs --tail=160 api web </dev/null || true
fi
echo
if [ -d "$BACKUP" ]; then
echo "Backup PRE disponible en: $BACKUP"
echo "database-before.dump y asset-media-before.tar.gz permiten una restauración manual integral si hiciera falta."
else
echo "No fue necesario crear backup PRE: el fallo ocurrió durante el preflight del candidato, antes de tocar producción."
fi
exit "$rc"
}
trap rollback ERR
echo
echo "============================================================"
echo " DH V2 · DEPLOY DESDE GITHUB · $DEPLOY_REF"
echo " DH V2 · ANDROID SOURCE DISCOVERY · SOLO LECTURA"
echo "============================================================"
for cmd in git docker curl tar node; do
command -v "$cmd" >/dev/null || { echo "ERROR: falta $cmd"; false; }
done
[ -f "$KEY" ] || { echo "ERROR: falta deploy key $KEY"; false; }
[ -d .git ] || { echo "ERROR: $APP no es repositorio Git"; false; }
[ -f .env ] || { echo "ERROR: falta $APP/.env"; false; }
git config --global --get-all safe.directory 2>/dev/null | grep -Fxq "$APP" || git config --global --add safe.directory "$APP"
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
echo "ERROR: hay cambios locales versionados en producción."
git status --short
false
fi
PREV_SHA="$(git rev-parse HEAD)"
PHASE="fetch"
git fetch origin "$DEPLOY_REF"
TARGET_SHA="$(git rev-parse "origin/$DEPLOY_REF")"
echo "Actual: $PREV_SHA"
echo "Objetivo: $TARGET_SHA"
if [ "$TARGET_SHA" = "$PREV_SHA" ]; then
echo "Producción ya está en el commit autorizado."
PHASE="complete"
exit 0
fi
if ! git merge-base --is-ancestor "$PREV_SHA" "$TARGET_SHA"; then
echo "ERROR: origin/$DEPLOY_REF no es fast-forward desde producción."
false
fi
PHASE="candidate-preflight"
rm -rf "$STAGE"
git worktree add --detach "$STAGE" "$TARGET_SHA" >/dev/null
EXPECTED_API_VERSION="$(node -p "require('$STAGE/api-v3/package.json').version")"
EXPECTED_WEB_VERSION="$(node -p "require('$STAGE/web-v2/package.json').version")"
echo "API candidata: $EXPECTED_API_VERSION"
echo "WEB candidata: $EXPECTED_WEB_VERSION"
docker compose --env-file "$APP/.env" -f "$STAGE/docker-compose.yml" config >/dev/null
while IFS= read -r -d '' script; do
bash -n "$script"
done < <(find "$STAGE/scripts" -type f -name '*.sh' -print0)
TARGET="$(git rev-parse "origin/$DEPLOY_REF")"
CURRENT="$(git rev-parse HEAD)"
echo "Current: $CURRENT"
echo "Target: $TARGET"
git merge-base --is-ancestor "$CURRENT" "$TARGET"
echo
echo "========== TEST API CANDIDATA =========="
docker build --target builder -t "$API_TEST_IMAGE" "$STAGE/api-v3" </dev/null
docker run --rm \
-v "$STAGE/api-v3/test:/app/test:ro" \
-v "$STAGE/api-v3/tsconfig.test.json:/app/tsconfig.test.json:ro" \
"$API_TEST_IMAGE" npm test </dev/null
echo "========== PROYECTOS GRADLE / ANDROID =========="
for root in /root /var/www /home /tmp; do
[ -d "$root" ] || continue
find "$root" -maxdepth 9 -type f \
\( -name gradlew -o -name settings.gradle -o -name settings.gradle.kts -o -name build.gradle -o -name build.gradle.kts \) \
-printf '%TY-%Tm-%Td %TH:%TM %10s %p\n' 2>/dev/null || true
done | sort -r | head -300
echo
echo "========== BUILD WEB CANDIDATA =========="
docker build -t "$WEB_TEST_IMAGE" "$STAGE/web-v2" </dev/null
echo "========== ZIP / APK / AAB RELACIONADOS =========="
for root in /root /var/www /home /tmp; do
[ -d "$root" ] || continue
find "$root" -maxdepth 10 -type f \
\( -iname '*android*.zip' -o -iname '*inspeccion*.zip' -o -iname '*dh*.apk' -o -iname '*inspeccion*.apk' -o -iname '*.aab' -o -iname '*E1.1*' -o -iname '*E1_1*' -o -iname '*E1.2*' -o -iname '*E1_2*' -o -iname '*F2.2*' -o -iname '*F2_2*' \) \
-printf '%TY-%Tm-%Td %TH:%TM %10s %p\n' 2>/dev/null || true
done | sort -r | head -300
PHASE="backup"
echo
echo "========== BACKUP PRE =========="
install -d -m 700 "$BACKUP"
docker compose exec -T db sh -lc 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' </dev/null > "$BACKUP/database-before.dump"
tar \
--exclude='./.git' \
--exclude='./.env' \
--exclude='*/node_modules' \
--exclude='*/dist' \
--exclude='*.zip' \
--exclude='*.tar.gz' \
--exclude='*.tgz' \
-czf "$BACKUP/source-before.tar.gz" .
install -m 600 .env "$BACKUP/.env"
git rev-parse HEAD > "$BACKUP/previous.sha"
printf '%s\n' "$TARGET_SHA" > "$BACKUP/target.sha"
docker compose ps -a > "$BACKUP/docker-before.txt"
echo "Respaldando volumen de fotos/importaciones..."
docker compose run --rm --no-deps --user root \
-v "$BACKUP:/backup" \
api sh -lc 'tar -czf /backup/asset-media-before.tar.gz -C /app/storage/asset-media .'
(
cd "$BACKUP"
sha256sum database-before.dump source-before.tar.gz asset-media-before.tar.gz .env previous.sha target.sha docker-before.txt > SHA256SUMS.txt
sha256sum -c SHA256SUMS.txt
)
chmod 600 "$BACKUP"/* "$BACKUP/.env" 2>/dev/null || true
PHASE="fast-forward"
echo
echo "========== FAST-FORWARD =========="
git log --oneline --no-decorate "$PREV_SHA..$TARGET_SHA"
APP_TOUCHED=1
git merge --ff-only "origin/$DEPLOY_REF"
PHASE="build"
echo
echo "========== BUILD PRODUCCIÓN =========="
docker compose build api migrate web </dev/null
PHASE="migrations"
echo
echo "========== MIGRACIONES + FRESH START =========="
docker compose --profile tools run --rm migrate </dev/null
docker compose --profile tools run --rm migrate npm run migration:show </dev/null | tee "$BACKUP/migrations.txt"
grep -Fq 'Pending migrations: no' "$BACKUP/migrations.txt"
PHASE="media-clean"
echo
echo "========== LIMPIEZA DE ARCHIVOS CARGADOS =========="
docker compose run --rm --no-deps --user root api sh -lc '
set -eu
ROOT=/app/storage/asset-media
before="$(find "$ROOT" -type f 2>/dev/null | wc -l | tr -d " ")"
echo "files_before=$before"
for path in "$ROOT"/* "$ROOT"/.[!.]* "$ROOT"/..?*; do
[ -e "$path" ] || continue
rm -rf -- "$path"
done
mkdir -p "$ROOT/imports"
chown -R node:node "$ROOT"
after="$(find "$ROOT" -type f 2>/dev/null | wc -l | tr -d " ")"
echo "files_after=$after"
[ "$after" = "0" ]
' | tee "$BACKUP/media-clean.txt"
grep -Fq 'files_after=0' "$BACKUP/media-clean.txt"
PHASE="recreate"
echo
echo "========== RECREATE API + WEB =========="
docker compose up -d --no-deps --force-recreate api web </dev/null
PHASE="health"
echo
echo "========== HEALTH =========="
HEALTH_OK=0
for _ in $(seq 1 60); do
if curl -fsS --max-time 5 http://127.0.0.1:3101/api/v3/health > "$BACKUP/health.json" 2>/dev/null; then
if grep -F '"status":"ok"' "$BACKUP/health.json" >/dev/null; then
HEALTH_OK=1
break
fi
echo "========== VERSIONES ANDROID =========="
for root in /root /var/www /home /tmp; do
[ -d "$root" ] || continue
find "$root" -maxdepth 10 -type f \( -name build.gradle -o -name build.gradle.kts \) -print0 2>/dev/null || true
done | while IFS= read -r -d '' f; do
if grep -Eq 'applicationId|versionCode|versionName|namespace' "$f" 2>/dev/null; then
echo "----- $f -----"
grep -nE 'applicationId|namespace|versionCode|versionName' "$f" 2>/dev/null | head -30 || true
fi
sleep 2
done
if [ "$HEALTH_OK" -ne 1 ]; then
echo "ERROR: API no pasó healthcheck."
docker compose logs --tail=180 api
false
fi
cat "$BACKUP/health.json"
echo
grep -Fq "\"version\":\"$EXPECTED_API_VERSION\"" "$BACKUP/health.json"
grep -Fq '"database":"ok"' "$BACKUP/health.json"
WEB_CODE="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 10 http://127.0.0.1:8182/)"
[ "$WEB_CODE" = "200" ] || { echo "ERROR: WEB HTTP $WEB_CODE"; false; }
PHASE="verify"
echo
echo "========== VERIFICACIÓN FINAL =========="
docker compose ps -a | tee "$BACKUP/docker-after.txt"
if docker compose ps --status running --services | grep -Fxq api && docker compose ps --status running --services | grep -Fxq web && docker compose ps --status running --services | grep -Fxq db; then
echo "Servicios críticos: OK"
else
echo "ERROR: falta un servicio crítico en ejecución."
false
fi
PHASE="post-backup"
docker compose exec -T db sh -lc 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' </dev/null > "$BACKUP/database-after.dump"
git rev-parse HEAD > "$BACKUP/deployed.sha"
printf 'API=%s\nWEB=%s\n' "$EXPECTED_API_VERSION" "$EXPECTED_WEB_VERSION" > "$BACKUP/deployed-versions.txt"
(
cd "$BACKUP"
sha256sum database-after.dump deployed.sha deployed-versions.txt health.json migrations.txt media-clean.txt docker-after.txt >> SHA256SUMS.txt
sha256sum -c SHA256SUMS.txt
)
chmod 600 "$BACKUP"/* "$BACKUP/.env" 2>/dev/null || true
PHASE="complete"
trap - ERR
echo "========== GIT REPOS CON GRADLE =========="
for root in /root /var/www /home /tmp; do
[ -d "$root" ] || continue
find "$root" -maxdepth 9 -type d -name .git -print 2>/dev/null || true
done | while read -r gitdir; do
dir="${gitdir%/.git}"
if find "$dir" -maxdepth 3 \( -name gradlew -o -name settings.gradle -o -name settings.gradle.kts \) -print -quit 2>/dev/null | grep -q .; then
echo "----- $dir -----"
git -C "$dir" status --short --branch 2>/dev/null || true
git -C "$dir" log -8 --oneline 2>/dev/null || true
fi
done
echo
echo "============================================================"
echo " DH V2 · DEPLOY OK"
echo "============================================================"
echo "Commit: $TARGET_SHA"
echo "API: $EXPECTED_API_VERSION"
echo "WEB: $EXPECTED_WEB_VERSION"
echo "Backup: $BACKUP"
echo "============================================================"
echo "========== HUELLA KOTLIN / COMPOSE =========="
for root in /root /var/www /home /tmp; do
[ -d "$root" ] || continue
find "$root" -maxdepth 10 -type f -name '*.kt' -printf '%h\n' 2>/dev/null || true
done | grep -Ei 'dh|inspe|android|mobile|app' | sort -u | head -300
echo
echo "DISCOVERY_OK"
echo
echo "========== REGISTRAR COMMIT DIAGNÓSTICO =========="
git merge --ff-only "origin/$DEPLOY_REF"
echo "Diagnostic commit registrado localmente: $(git rev-parse HEAD)"