Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b30cc1a294 | ||
|
|
a7a6680cf8 | ||
|
|
44570ad457 | ||
|
|
8caed06362 | ||
|
|
e3db3d6cd7 | ||
|
|
fb7b29cd94 | ||
|
|
0a11a452b5 | ||
|
|
1d661e2e48 | ||
|
|
2ee956665f | ||
|
|
0d5db42c77 | ||
|
|
21127b8cff | ||
|
|
50a9dc5183 | ||
|
|
a69df1d2d6 |
+1
-2
@@ -9,11 +9,10 @@
|
|||||||
"start:dev": "nest start --watch",
|
"start:dev": "nest start --watch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "tsc -p tsconfig.test.json --noEmit && node --import tsx --test test/**/*.test.ts",
|
"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 --preview",
|
"migration:run": "node dist/database/migration-cli.js run",
|
||||||
"migration:show": "node dist/database/migration-cli.js show",
|
"migration:show": "node dist/database/migration-cli.js show",
|
||||||
"migration:revert": "node dist/database/migration-cli.js revert",
|
"migration:revert": "node dist/database/migration-cli.js revert",
|
||||||
"bootstrap:admin": "node dist/cli/bootstrap-admin.js",
|
"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"
|
"dev:seed:mendoza-demo": "node dist/cli/dev-seed-mendoza-demo.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -1,247 +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_asset_types',
|
|
||||||
'finding_catalog_asset_type_profiles',
|
|
||||||
]);
|
|
||||||
|
|
||||||
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('\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) => {
|
|
||||||
await manager.query(`SET LOCAL session_replication_role = replica`);
|
|
||||||
|
|
||||||
for (const table of tablesToClear) {
|
|
||||||
await manager.query(`DELETE FROM public.${quoteIdentifier(table)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
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álogos estructurales: conservados\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
-256
@@ -3,301 +3,112 @@ set -Eeuo pipefail
|
|||||||
|
|
||||||
APP="/var/www/dhv2.korexlabs.com"
|
APP="/var/www/dhv2.korexlabs.com"
|
||||||
KEY="/root/.ssh/dhv2_github"
|
KEY="/root/.ssh/dhv2_github"
|
||||||
BACKUP_ROOT="/root/DH_V2_BACKUPS"
|
|
||||||
DEPLOY_REF="${DHV2_DEPLOY_REF:-deploy}"
|
DEPLOY_REF="${DHV2_DEPLOY_REF:-deploy}"
|
||||||
STAMP="$(date +%Y%m%d_%H%M%S)"
|
LOG="$(mktemp /tmp/dhv2-android-discovery.XXXXXX.log)"
|
||||||
BACKUP="$BACKUP_ROOT/GITHUB_DEPLOY_${STAMP}"
|
STATUS="$(mktemp /tmp/dhv2-android-discovery-status.XXXXXX)"
|
||||||
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
|
|
||||||
|
|
||||||
cd "$APP"
|
cd "$APP"
|
||||||
export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
|
export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
|
||||||
exec > >(tee -a "$LOG") 2>&1
|
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() {
|
publish_status() {
|
||||||
local rc="${1:-1}"
|
local rc="${1:-1}"
|
||||||
set +e
|
set +e
|
||||||
|
|
||||||
local outcome="failure"
|
local outcome="failure"
|
||||||
[ "$rc" -eq 0 ] && outcome="success"
|
[ "$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)"
|
current="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
|
||||||
local status_file log_file status_blob log_blob tree commit
|
target="$(git rev-parse origin/$DEPLOY_REF 2>/dev/null || echo unknown)"
|
||||||
|
|
||||||
status_file="$(mktemp /tmp/dhv2-status.XXXXXX)"
|
|
||||||
log_file="$(mktemp /tmp/dhv2-log.XXXXXX)"
|
|
||||||
|
|
||||||
{
|
{
|
||||||
echo "status=$outcome"
|
echo "status=$outcome"
|
||||||
echo "exit_code=$rc"
|
echo "exit_code=$rc"
|
||||||
echo "phase=$PHASE"
|
echo "phase=android-source-discovery"
|
||||||
echo "timestamp=$(date --iso-8601=seconds)"
|
echo "timestamp=$(date --iso-8601=seconds)"
|
||||||
echo "deploy_ref=$DEPLOY_REF"
|
echo "deploy_ref=$DEPLOY_REF"
|
||||||
echo "previous_sha=${PREV_SHA:-unknown}"
|
echo "target_sha=$target"
|
||||||
echo "target_sha=${TARGET_SHA:-unknown}"
|
|
||||||
echo "current_sha=$current"
|
echo "current_sha=$current"
|
||||||
echo "api_version=${EXPECTED_API_VERSION:-unknown}"
|
echo "app_touched=0"
|
||||||
echo "web_version=${EXPECTED_WEB_VERSION:-unknown}"
|
echo "backup=not-required-read-only"
|
||||||
echo "app_touched=$APP_TOUCHED"
|
} > "$STATUS"
|
||||||
echo "backup=${BACKUP:-unknown}"
|
status_blob="$(git hash-object -w "$STATUS" 2>/dev/null || true)"
|
||||||
} > "$status_file"
|
log_blob="$(git hash-object -w "$LOG" 2>/dev/null || true)"
|
||||||
|
|
||||||
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)"
|
|
||||||
|
|
||||||
if [ -n "$status_blob" ] && [ -n "$log_blob" ]; then
|
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)"
|
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
|
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
|
[ -z "$commit" ] || git push --force origin "$commit:refs/heads/deploy-status" >/dev/null 2>&1 || true
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
rm -f "$STATUS" "$LOG"
|
||||||
rm -f "$status_file" "$log_file"
|
|
||||||
}
|
}
|
||||||
|
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 "Las migraciones son forward-only; database-before.dump queda disponible para restauración manual 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 "============================================================"
|
||||||
echo " DH V2 · DEPLOY DESDE GITHUB · $DEPLOY_REF"
|
echo " DH V2 · ANDROID SOURCE DISCOVERY · SOLO LECTURA"
|
||||||
echo "============================================================"
|
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"
|
git fetch origin "$DEPLOY_REF"
|
||||||
TARGET_SHA="$(git rev-parse "origin/$DEPLOY_REF")"
|
TARGET="$(git rev-parse "origin/$DEPLOY_REF")"
|
||||||
|
CURRENT="$(git rev-parse HEAD)"
|
||||||
echo "Actual: $PREV_SHA"
|
echo "Current: $CURRENT"
|
||||||
echo "Objetivo: $TARGET_SHA"
|
echo "Target: $TARGET"
|
||||||
|
git merge-base --is-ancestor "$CURRENT" "$TARGET"
|
||||||
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)
|
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "========== TEST API CANDIDATA =========="
|
echo "========== PROYECTOS GRADLE / ANDROID =========="
|
||||||
docker build --target builder -t "$API_TEST_IMAGE" "$STAGE/api-v3" </dev/null
|
for root in /root /var/www /home /tmp; do
|
||||||
docker run --rm \
|
[ -d "$root" ] || continue
|
||||||
-v "$STAGE/api-v3/test:/app/test:ro" \
|
find "$root" -maxdepth 9 -type f \
|
||||||
-v "$STAGE/api-v3/tsconfig.test.json:/app/tsconfig.test.json:ro" \
|
\( -name gradlew -o -name settings.gradle -o -name settings.gradle.kts -o -name build.gradle -o -name build.gradle.kts \) \
|
||||||
"$API_TEST_IMAGE" npm test </dev/null
|
-printf '%TY-%Tm-%Td %TH:%TM %10s %p\n' 2>/dev/null || true
|
||||||
|
done | sort -r | head -300
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "========== BUILD WEB CANDIDATA =========="
|
echo "========== ZIP / APK / AAB RELACIONADOS =========="
|
||||||
docker build -t "$WEB_TEST_IMAGE" "$STAGE/web-v2" </dev/null
|
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
|
||||||
echo "========== BACKUP PRE =========="
|
echo "========== VERSIONES ANDROID =========="
|
||||||
install -d -m 700 "$BACKUP"
|
for root in /root /var/www /home /tmp; do
|
||||||
docker compose exec -T db sh -lc 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' </dev/null > "$BACKUP/database-before.dump"
|
[ -d "$root" ] || continue
|
||||||
tar \
|
find "$root" -maxdepth 10 -type f \( -name build.gradle -o -name build.gradle.kts \) -print0 2>/dev/null || true
|
||||||
--exclude='./.git' \
|
done | while IFS= read -r -d '' f; do
|
||||||
--exclude='./.env' \
|
if grep -Eq 'applicationId|versionCode|versionName|namespace' "$f" 2>/dev/null; then
|
||||||
--exclude='*/node_modules' \
|
echo "----- $f -----"
|
||||||
--exclude='*/dist' \
|
grep -nE 'applicationId|namespace|versionCode|versionName' "$f" 2>/dev/null | head -30 || true
|
||||||
--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"
|
|
||||||
(
|
|
||||||
cd "$BACKUP"
|
|
||||||
sha256sum database-before.dump source-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 =========="
|
|
||||||
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="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
|
|
||||||
fi
|
fi
|
||||||
sleep 2
|
|
||||||
done
|
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
|
echo
|
||||||
|
echo "========== GIT REPOS CON GRADLE =========="
|
||||||
grep -Fq "\"version\":\"$EXPECTED_API_VERSION\"" "$BACKUP/health.json"
|
for root in /root /var/www /home /tmp; do
|
||||||
grep -Fq '"database":"ok"' "$BACKUP/health.json"
|
[ -d "$root" ] || continue
|
||||||
|
find "$root" -maxdepth 9 -type d -name .git -print 2>/dev/null || true
|
||||||
WEB_CODE="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 10 http://127.0.0.1:8182/)"
|
done | while read -r gitdir; do
|
||||||
[ "$WEB_CODE" = "200" ] || { echo "ERROR: WEB HTTP $WEB_CODE"; false; }
|
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
|
||||||
PHASE="verify"
|
echo "----- $dir -----"
|
||||||
echo
|
git -C "$dir" status --short --branch 2>/dev/null || true
|
||||||
echo "========== VERIFICACIÓN FINAL =========="
|
git -C "$dir" log -8 --oneline 2>/dev/null || true
|
||||||
docker compose ps -a | tee "$BACKUP/docker-after.txt"
|
fi
|
||||||
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
|
done
|
||||||
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 docker-after.txt >> SHA256SUMS.txt
|
|
||||||
sha256sum -c SHA256SUMS.txt
|
|
||||||
)
|
|
||||||
chmod 600 "$BACKUP"/* "$BACKUP/.env" 2>/dev/null || true
|
|
||||||
|
|
||||||
PHASE="complete"
|
|
||||||
trap - ERR
|
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "============================================================"
|
echo "========== HUELLA KOTLIN / COMPOSE =========="
|
||||||
echo " DH V2 · DEPLOY OK"
|
for root in /root /var/www /home /tmp; do
|
||||||
echo "============================================================"
|
[ -d "$root" ] || continue
|
||||||
echo "Commit: $TARGET_SHA"
|
find "$root" -maxdepth 10 -type f -name '*.kt' -printf '%h\n' 2>/dev/null || true
|
||||||
echo "API: $EXPECTED_API_VERSION"
|
done | grep -Ei 'dh|inspe|android|mobile|app' | sort -u | head -300
|
||||||
echo "WEB: $EXPECTED_WEB_VERSION"
|
|
||||||
echo "Backup: $BACKUP"
|
echo
|
||||||
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)"
|
||||||
|
|||||||
Reference in New Issue
Block a user