Replace flag-based upgrade.sh with named migrate/hotfix-code modes

upgrade.sh's old -f/-w/-s flags let you skip a backup or the DB
migration independently of each other, with nothing to stop a
combination that didn't actually make sense for the change being
shipped. Replace them with two named modes:

- migrate: for a change that touches the DB. Full SQL+WAR+logs
  backup, both the existing short-lived tier and a new, never-pruned
  backup/migrations/<tag>/ tier (before/after snapshot plus the full
  DB migration transcript, tee'd from manager-exec.sh). The tag comes
  from build.xml's migrate(@host) target: the git version already
  embedded in sportrum.war's WEB-INF/VERSION (see README for the
  webapp project's own build.xml snippet this needs), plus an
  optional interactive label via Ant's <input> task.

- hotfix-code: for a Java/resource change with no DB migration. WAR
  backup only (no SQL dump, no indefinite copy), no manager-exec.sh
  at all. Only reached after check-schema-diff.sh - a new script that
  runs ICPManager's diff-meta against a staged, not-yet-installed
  copy of manager.zip, entirely independent of the live webapp/Tomcat
  - has already confirmed there's no pending schema change, hard
  gating build.xml's hotfix-code(@host) target before Tomcat is ever
  touched.

A third scenario (template-only hotfix, no Tomcat restart at all) is
intentionally not implemented yet - which files count as "templates"
and how they'd sync into the live webapp directory is still an open
question.

Dropped without replacement: the old storeonly (-s) mode and the
"leave Tomcat stopped" action argument - undocumented, flag-only
behaviors nothing here exercised, easy to reintroduce as an explicit
mode later if actually needed.

Also fixes a real gap found while testing this: a failed migration
left upgrade-cmds.sh exiting 0, which would have made upgrade.sh (and
an Ant sshexec with failonerror) report success on a failed DB
migration. And build.xml's deploy.key.passphrase had no default,
which (confirmed by testing) left the literal string
"${deploy.key.passphrase}" as the passphrase for anyone not setting
it in build.local.properties.

Verified with a full fake fixture (fake pg_dump, fake manager.zip/
manager-exec.sh, fake sportrum.war): migrate success, migrate
collision-refusal on a reused tag, migrate failure preserving the
before-snapshot without pruning, hotfix-code skipping the SQL/DB
steps, and check-schema-diff.sh's three exit codes (clean/
differences/broken) all behave as designed. Ant-side tag assembly
(<input> skip-when-preset, blank-label fallback, unsafe-character
rejection) verified the same way.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tj4SF2BGFxgoRYrCAzNpDb
This commit is contained in:
Claude 2026-09-30 20:00:35 +00:00
parent 3fd244a5be
commit 8c5c0fa3a0
No known key found for this signature in database
5 changed files with 555 additions and 126 deletions

76
README.md Normal file
View file

@ -0,0 +1,76 @@
# sportrum-deploy
Deploy tooling for the sportrum webapp — the actual server-side upgrade
(stop Tomcat, back up, install the new build, migrate the DB, restart),
run either by hand or via this repo's `build.xml`.
This project deliberately does NOT build or upload `sportrum.war`/
`manager.zip` itself. That's the sportrum webapp project's own `build.xml`
(its `release-all` target) — see the next section for the one change that
project needs to make so `ant "migrate(@host)"` here can tag a deploy by
the exact commit it shipped.
## Required: embedding WEB-INF/VERSION in the webapp build
`ant "migrate(@host)"` (see `build.xml`) tags every migration with the git
version of whatever `sportrum.war` is already sitting on the server —
read back off the WAR itself, not derived from this repo's git history
(there isn't a relationship between the two repos to derive it from).
That means the sportrum webapp project's own `build.xml` needs to embed a
`WEB-INF/VERSION` file into the WAR, containing a single line:
```
<build-timestamp>-<git-short-hash>
```
e.g. `20260930-184512-a3f9c21`. Timestamp first so tagged migration
folders on the server sort chronologically; build time (not commit time),
so the value stays unique even if the same commit is ever rebuilt and
redeployed again; `WEB-INF/`, not the WAR root, since anything outside
`WEB-INF/` is directly servable over HTTP by Tomcat and a commit hash
shouldn't be publicly fetchable.
Add this near the top of the webapp project's `war` target, before the
`<war>` task itself runs:
```xml
<tstamp>
<format property="build.timestamp" pattern="yyyyMMdd-HHmmss"/>
</tstamp>
<exec executable="git" outputproperty="build.gitrev" failonerror="true">
<arg value="rev-parse"/>
<arg value="--short"/>
<arg value="HEAD"/>
</exec>
<property name="build.version" value="${build.timestamp}-${build.gitrev}"/>
<echo message="Building version ${build.version}"/>
<mkdir dir="${build}/version-stage"/>
<echo file="${build}/version-stage/VERSION" message="${build.version}"/>
```
Then add a `<webinf>` fileset to the existing `<war destfile="${build}/sportrum.war" ...>`
task call, alongside whatever filesets are already there:
```xml
<webinf dir="${build}/version-stage">
<include name="VERSION"/>
</webinf>
```
Until that's in place, `ant "migrate(@host)"` here will fail its own
pre-flight check with a message pointing back here, rather than silently
tagging every migration `unknown` or similar — see `resolve-migration-tag`
in `build.xml`.
## Deploy targets
See `ant help` (or just `ant`, since `help` is the default target) for the
full, current usage text — it's kept there rather than duplicated here so
it can't drift out of sync with the actual `build.xml`. Short version:
`install-scripts(@host)` syncs this repo's scripts to the server without
running anything; `hotfix-code(@host)` is for a change with no DB
migration (hard-gated on `check-schema-diff.sh` confirming that's actually
true); `migrate(@host)` is for a change that does migrate the DB (tagged,
indefinitely-kept before/after backup and migration transcript under
`backup/migrations/<tag>/` on the server).

248
build.xml
View file

@ -35,6 +35,17 @@
file is fine; Ant just skips it. --> file is fine; Ant just skips it. -->
<property file="${basedir}/build.local.properties"/> <property file="${basedir}/build.local.properties"/>
<!-- Default so an unencrypted key doesn't get passed the LITERAL
string "${deploy.key.passphrase}" as its passphrase - an unset
Ant property is left as its own ${...} text rather than becoming
empty, which is exactly the kind of thing that fails silently
confusingly deep in a JSch stack trace. Confirmed this is a real
gotcha, not a hypothetical one, by testing an unset reference
directly. Set the real value in build.local.properties if your
key needs one; this default only applies when nothing overrides
it. -->
<property name="deploy.key.passphrase" value=""/>
<!-- Same Windows-vs-WSL ${user.home} gotcha documented at length in <!-- Same Windows-vs-WSL ${user.home} gotcha documented at length in
xzpect-timer/build.xml: which home directory this resolves to xzpect-timer/build.xml: which home directory this resolves to
depends entirely on what actually runs the JVM invoking Ant depends entirely on what actually runs the JVM invoking Ant
@ -158,6 +169,7 @@ Preferences -> Ant -> Runtime -> Classpath -> Ant Home Entries — same fix.
<include name="upgrade-funs.sh"/> <include name="upgrade-funs.sh"/>
<include name="tomcat_ctl.sh"/> <include name="tomcat_ctl.sh"/>
<include name="restart.sh"/> <include name="restart.sh"/>
<include name="check-schema-diff.sh"/>
</fileset> </fileset>
</scp> </scp>
@ -173,15 +185,9 @@ Preferences -> Ant -> Runtime -> Classpath -> Ant Home Entries — same fix.
</sequential> </sequential>
</macrodef> </macrodef>
<!-- The actual upgrade — sshexecs upgrade.sh on the server, which: <!-- Both deploy modes below deliberately do NOT build or upload
calls storeall and stops Tomcat, backs up the current SQL/webapp sportrum.war/manager.zip themselves — they assume those are
(the short-lived tier — see upgrade-cmds.sh), unzips the NEW ALREADY sitting at /home/sportrum/webapp/sportrum.war and
sportrum.war/manager.zip, runs manager-exec.sh's DB migrations,
then restarts Tomcat.
This target deliberately does NOT build or upload
sportrum.war/manager.zip itself — it assumes they're ALREADY
sitting at /home/sportrum/webapp/sportrum.war and
/home/sportrum/manager.zip from a prior run of the sportrum webapp /home/sportrum/manager.zip from a prior run of the sportrum webapp
project's own "ant release-all" (its release-all target scps them project's own "ant release-all" (its release-all target scps them
there). That's the split the two projects deliberately keep: the there). That's the split the two projects deliberately keep: the
@ -189,23 +195,155 @@ Preferences -> Ant -> Runtime -> Classpath -> Ant Home Entries — same fix.
project's build.xml does the actual deploy. Forgetting to run project's build.xml does the actual deploy. Forgetting to run
release-all first isn't silent, though — upgrade-cmds.sh's own release-all first isn't silent, though — upgrade-cmds.sh's own
"unzip -q sportrum.war -d sportrum" fails loudly if the file isn't "unzip -q sportrum.war -d sportrum" fails loudly if the file isn't
there, and failonerror below makes that failure fail this Ant there, and failonerror below makes that failure fail the Ant
target too, not just get logged and ignored. --> target too, not just get logged and ignored. -->
<macrodef name="run-upgrade">
<!-- Verifies the "no pending DB schema change" assumption BEFORE
anything live is touched - see check-schema-diff.sh's own header
comment for why this is safe to run standalone (it only reads a
staged, not-yet-installed copy of manager.zip and the live DB,
never the running webapp/Tomcat). haltonerror="true" (the
default, for hotfix-code) fails the whole Ant build the moment
the remote check comes back non-clean, before Tomcat is ever
stopped - a wrong assumption there costs zero downtime.
haltonerror="false" (used by migrate) logs the same diff for
visibility without blocking, since migrate is exactly the mode
where a schema difference is expected, not a sign anything is
wrong. Either way, sshexec streams the remote command's output as
it runs, so the diff is visible in the build log regardless of
whether it ends up blocking anything. -->
<macrodef name="run-schema-check">
<attribute name="host"/> <attribute name="host"/>
<attribute name="haltonerror" default="true"/>
<sequential> <sequential>
<echo message="Running upgrade.sh on @{host} — this stops Tomcat, backs up the current SQL dump/webapp/logs, installs the new sportrum.war/manager.zip, runs DB migrations, then restarts Tomcat..."/> <echo message="Checking for pending schema differences against @{host} (not touching the live webapp or Tomcat)..."/>
<sshexec host="@{host}" <sshexec host="@{host}"
port="${deploy.ssh.port}" port="${deploy.ssh.port}"
username="${deploy.user}" username="${deploy.user}"
keyfile="${deploy.keyfile}" keyfile="${deploy.keyfile}"
passphrase="${deploy.key.passphrase}" passphrase="${deploy.key.passphrase}"
knownhosts="${deploy.knownhosts}" knownhosts="${deploy.knownhosts}"
command="cd ${deploy.remotepath} &amp;&amp; ./upgrade.sh" command="${deploy.remotepath}check-schema-diff.sh /home/sportrum/manager.zip"
failonerror="@{haltonerror}"/>
</sequential>
</macrodef>
<!-- hotfix-code: no SQL backup, no DB migration - see upgrade.sh's own
header comment for the full rationale. Only ever reached after
run-schema-check above has already confirmed there's nothing
pending, so upgrade-cmds.sh isn't guessing when it skips the DB
step. -->
<macrodef name="run-hotfix-code">
<attribute name="host"/>
<sequential>
<echo message="Running upgrade.sh hotfix-code on @{host} — stops Tomcat, backs up the current webapp/logs (no SQL dump - no schema change to protect against), installs the new sportrum.war, restarts Tomcat. No DB migration runs..."/>
<sshexec host="@{host}"
port="${deploy.ssh.port}"
username="${deploy.user}"
keyfile="${deploy.keyfile}"
passphrase="${deploy.key.passphrase}"
knownhosts="${deploy.knownhosts}"
command="cd ${deploy.remotepath} &amp;&amp; ./upgrade.sh hotfix-code"
failonerror="true"/> failonerror="true"/>
</sequential> </sequential>
</macrodef> </macrodef>
<!-- migrate: full careful path, including the tagged, never-pruned
before/after backup and DB migration transcript under
backup/migrations/<tag>/ on the server - see upgrade-cmds.sh's own
comments for exactly what gets captured. -->
<macrodef name="run-migrate">
<attribute name="host"/>
<attribute name="tag"/>
<sequential>
<echo message="Running upgrade.sh migrate on @{host} (tag: @{tag}) — stops Tomcat, takes a tagged before-snapshot (kept indefinitely) plus the regular short-lived backup, installs the new sportrum.war/manager.zip, runs the DB migration with its transcript saved under the tag, takes a tagged after-snapshot, restarts Tomcat..."/>
<sshexec host="@{host}"
port="${deploy.ssh.port}"
username="${deploy.user}"
keyfile="${deploy.keyfile}"
passphrase="${deploy.key.passphrase}"
knownhosts="${deploy.knownhosts}"
command="cd ${deploy.remotepath} &amp;&amp; ./upgrade.sh migrate '@{tag}'"
failonerror="true"/>
</sequential>
</macrodef>
<!-- Resolves deploy.tag for migrate(@host): <git-version>[-<label>].
The git-version half is read back off the sportrum.war ALREADY
uploaded by the webapp project's own release-all - see this
project's README for the WEB-INF/VERSION snippet that project's
build.xml needs for this to work. WEB-INF/, not the WAR root,
since anything outside WEB-INF/ is directly servable over HTTP by
Tomcat and a commit hash shouldn't be publicly fetchable.
The label half is optional and interactive by design (Ant's
<input> task, confirmed empirically: it skips prompting entirely
if deploy.label is already set, e.g. via -Ddeploy.label=... for a
scripted run - and confirmed working from a plain piped/typed
stdin). Hit enter to skip it; the git version alone is already a
complete, unique, non-blank tag on its own. -->
<macrodef name="resolve-migration-tag">
<attribute name="host"/>
<sequential>
<sshexec host="@{host}"
port="${deploy.ssh.port}"
username="${deploy.user}"
keyfile="${deploy.keyfile}"
passphrase="${deploy.key.passphrase}"
knownhosts="${deploy.knownhosts}"
command="unzip -p /home/sportrum/webapp/sportrum.war WEB-INF/VERSION | tr -d '\n'"
outputproperty="deploy.gitversion"
failonerror="true"/>
<!-- tr -d strips any trailing newline the webapp build's echo/
file-write may have left in WEB-INF/VERSION - whether or
not it did isn't this project's business to assume either
way, and a stray newline landing in a directory name would
be a much stranger failure to debug than this one-liner is
to write. -->
<condition property="deploy.gitversion.blank">
<equals arg1="${deploy.gitversion}" arg2=""/>
</condition>
<fail if="deploy.gitversion.blank">
Couldn't read WEB-INF/VERSION out of the sportrum.war on @{host}. Either
"ant release-all" hasn't been run against this server yet, or the webapp
project's build.xml doesn't embed WEB-INF/VERSION yet - see this project's
README for the snippet it needs.
</fail>
<input message="Optional short label for this migration (e.g. 'invoice-table') - press Enter to skip:" addproperty="deploy.label"/>
<condition property="deploy.label.unsafe">
<and>
<not><equals arg1="${deploy.label}" arg2=""/></not>
<not><matches pattern="^[A-Za-z0-9._-]*$" string="${deploy.label}"/></not>
</and>
</condition>
<fail if="deploy.label.unsafe">
The migration label can only contain letters, digits, dots, dashes, and
underscores (got: "${deploy.label}") - it becomes part of a directory name
on the server. Run again without spaces or other punctuation.
</fail>
<!-- Set-once semantics do the branching here: this only takes
effect (and only when deploy.tag isn't already set, e.g.
via -Ddeploy.tag=... for a fully scripted run) when the
label is non-blank; the plain <property> right after it
is the fallback for a blank label, since it won't
override a value the condition above already set.
Confirmed both branches empirically before relying on
this. -->
<condition property="deploy.tag" value="${deploy.gitversion}-${deploy.label}">
<not><equals arg1="${deploy.label}" arg2=""/></not>
</condition>
<property name="deploy.tag" value="${deploy.gitversion}"/>
<echo message="Migration tag: ${deploy.tag}"/>
</sequential>
</macrodef>
<!-- Post-deploy check, same idea as xzpect-timer's verify-pwa — the app <!-- Post-deploy check, same idea as xzpect-timer's verify-pwa — the app
itself is reverse-proxied at the domain root by Caddy (see itself is reverse-proxied at the domain root by Caddy (see
sportrum-ansible's templates/Caddyfile.j2), so @{host} IS the URL sportrum-ansible's templates/Caddyfile.j2), so @{host} IS the URL
@ -224,8 +362,9 @@ Preferences -> Ant -> Runtime -> Classpath -> Ant Home Entries — same fix.
<!-- No-op default so running plain "ant" never touches a live server by accident. --> <!-- No-op default so running plain "ant" never touches a live server by accident. -->
<target name="help"> <target name="help">
<echo>Available targets: <echo>Available targets:
ant "install-scripts(@local.sportrum.se)" - sync upgrade.sh and friends to the server (does NOT run an upgrade) ant "install-scripts(@local.sportrum.se)" - sync this repo's control scripts to the server (does NOT run anything)
ant "deploy(@local.sportrum.se)" - install-scripts(@local.sportrum.se), then run upgrade.sh, then verify the site responds ant "hotfix-code(@local.sportrum.se)" - for a Java/resource change with NO DB migration
ant "migrate(@local.sportrum.se)" - for a change that DOES migrate the DB schema/data
Before the FIRST run against any given server: ssh -p ${deploy.ssh.port} ${deploy.user}@&lt;that server&gt; Before the FIRST run against any given server: ssh -p ${deploy.ssh.port} ${deploy.user}@&lt;that server&gt;
once, interactively (accept the host key, then Ctrl+D) so ${deploy.knownhosts} once, interactively (accept the host key, then Ctrl+D) so ${deploy.knownhosts}
@ -233,34 +372,60 @@ already has it — these targets do not auto-trust unknown host keys.
Also run the sportrum webapp project's own "ant release-all" FIRST, against Also run the sportrum webapp project's own "ant release-all" FIRST, against
the same server — it builds and uploads sportrum.war/manager.zip, which the same server — it builds and uploads sportrum.war/manager.zip, which
upgrade.sh (run by the deploy target here) expects to already be sitting at upgrade.sh (run by both deploy targets here) expects to already be sitting
/home/sportrum/webapp/sportrum.war and /home/sportrum/manager.zip. This at /home/sportrum/webapp/sportrum.war and /home/sportrum/manager.zip. This
project's build.xml never builds or uploads those itself. project's build.xml never builds or uploads those itself.
install-scripts/deploy are deliberately separate steps, not one big Two deploy targets, not one, because the two scenarios genuinely need
"deploy" that both syncs scripts and upgrades: different handling - see upgrade.sh's own header comment for the full
- install-scripts(@server) only uploads this repo's control scripts rationale:
(upgrade.sh, upgrade-cmds.sh, upgrade-funs.sh, tomcat_ctl.sh, - hotfix-code(@server): for a change with no DB migration. First runs
restart.sh) to ${deploy.remotepath} on the server. Nothing on the check-schema-diff.sh against the server and HARD-FAILS if it finds any
server is touched otherwise — no Tomcat stop, no backup, no DB pending schema difference, before Tomcat is ever touched - a wrong
migration. assumption here costs zero downtime instead of a broken mid-upgrade
- deploy(@server) runs install-scripts(@server) first (so the server is state. Then: WAR+logs backup only (no SQL dump - nothing to protect
always running this repo's current scripts, never a stale hand-copied against), install the new sportrum.war, restart Tomcat (still needed;
version), then sshexecs upgrade.sh itself, then checks the site class files may have changed). No manager-exec.sh runs at all.
responds afterwards. - migrate(@server): for a change that DOES touch the DB. Prompts for a
tag - the git version already embedded in sportrum.war's
WEB-INF/VERSION (see this project's README for the webapp project's
own build.xml needs), plus an optional short label - then runs the
same schema check as above but only logs the result rather than
blocking (a diff here is expected, not a sign anything's wrong). Then:
full SQL+WAR+logs backup (the regular short-lived tier AND an
indefinitely-kept copy under backup/migrations/&lt;tag&gt;/ on the
server), install the new sportrum.war/manager.zip, run the DB
migration (its full transcript saved next to the tagged backup),
take a matching post-migration snapshot, restart Tomcat.
Because the upgrade is just upgrade.sh living on the server (at Both depend on install-scripts(@server) first, so the server is always
running this repo's current scripts, never a stale hand-copied version.
A third scenario - a template-only hotfix needing no Tomcat restart at all
- is intentionally not implemented as a target yet; see upgrade.sh's
header comment for why.
Because each deploy is just upgrade.sh living on the server (at
${deploy.remotepath}), you don't need ant for it at all if you'd rather ${deploy.remotepath}), you don't need ant for it at all if you'd rather
not: run "ant install-scripts(@server)" whenever you like, then SSH in as not: run "ant install-scripts(@server)" whenever you like, then SSH in as
${deploy.user} and run "./upgrade.sh" (or "./restart.sh", for a plain ${deploy.user} and run "./upgrade.sh hotfix-code", "./upgrade.sh migrate
restart with no upgrade) yourself, at whatever moment you choose. &lt;tag&gt;", or "./restart.sh" (a plain restart, no upgrade) yourself, at
whatever moment you choose - check-schema-diff.sh is there too, if you
want to run that check by hand first.
Adding a new server: add Adding a new server: add
&lt;target name="install-scripts(@new-server-hostname)" description="..."&gt; &lt;target name="install-scripts(@new-server-hostname)" description="..."&gt;
&lt;upload-scripts host="new-server-hostname"/&gt; &lt;upload-scripts host="new-server-hostname"/&gt;
&lt;/target&gt; &lt;/target&gt;
&lt;target name="deploy(@new-server-hostname)" depends="install-scripts(@new-server-hostname)" description="..."&gt; &lt;target name="hotfix-code(@new-server-hostname)" depends="install-scripts(@new-server-hostname)" description="..."&gt;
&lt;run-upgrade host="new-server-hostname"/&gt; &lt;run-schema-check host="new-server-hostname"/&gt;
&lt;run-hotfix-code host="new-server-hostname"/&gt;
&lt;verify-upgrade host="new-server-hostname"/&gt;
&lt;/target&gt;
&lt;target name="migrate(@new-server-hostname)" depends="install-scripts(@new-server-hostname)" description="..."&gt;
&lt;resolve-migration-tag host="new-server-hostname"/&gt;
&lt;run-schema-check host="new-server-hostname" haltonerror="false"/&gt;
&lt;run-migrate host="new-server-hostname" tag="${deploy.tag}"/&gt;
&lt;verify-upgrade host="new-server-hostname"/&gt; &lt;verify-upgrade host="new-server-hostname"/&gt;
&lt;/target&gt; &lt;/target&gt;
below — the shared sportrum user/key/port above cover it already, nothing below — the shared sportrum user/key/port above cover it already, nothing
@ -268,13 +433,22 @@ else to configure here.</echo>
</target> </target>
<target name="install-scripts(@local.sportrum.se)" <target name="install-scripts(@local.sportrum.se)"
description="Upload upgrade.sh, upgrade-cmds.sh, upgrade-funs.sh, tomcat_ctl.sh, and restart.sh to local.sportrum.se. Does NOT run an upgrade — see deploy(@local.sportrum.se)."> description="Upload upgrade.sh, upgrade-cmds.sh, upgrade-funs.sh, tomcat_ctl.sh, restart.sh, and check-schema-diff.sh to local.sportrum.se. Does NOT run anything.">
<upload-scripts host="local.sportrum.se"/> <upload-scripts host="local.sportrum.se"/>
</target> </target>
<target name="deploy(@local.sportrum.se)" depends="install-scripts(@local.sportrum.se)" <target name="hotfix-code(@local.sportrum.se)" depends="install-scripts(@local.sportrum.se)"
description="install-scripts(@local.sportrum.se), then run upgrade.sh on local.sportrum.se (stop Tomcat, back up, install the new sportrum.war/manager.zip, migrate the DB, restart Tomcat), then confirm https://local.sportrum.se/ responds."> description="For a Java/resource change with NO DB migration. Verifies no schema change is pending (hard fail if one is, before Tomcat is touched), then runs upgrade.sh hotfix-code on local.sportrum.se, then confirms https://local.sportrum.se/ responds.">
<run-upgrade host="local.sportrum.se"/> <run-schema-check host="local.sportrum.se"/>
<run-hotfix-code host="local.sportrum.se"/>
<verify-upgrade host="local.sportrum.se"/>
</target>
<target name="migrate(@local.sportrum.se)" depends="install-scripts(@local.sportrum.se)"
description="For a change that DOES migrate the DB. Resolves a tag (git version from sportrum.war's WEB-INF/VERSION + optional label), logs the pending schema diff, then runs upgrade.sh migrate on local.sportrum.se (tagged before/after backup kept indefinitely, DB migration with saved transcript), then confirms https://local.sportrum.se/ responds.">
<resolve-migration-tag host="local.sportrum.se"/>
<run-schema-check host="local.sportrum.se" haltonerror="false"/>
<run-migrate host="local.sportrum.se" tag="${deploy.tag}"/>
<verify-upgrade host="local.sportrum.se"/> <verify-upgrade host="local.sportrum.se"/>
</target> </target>

65
check-schema-diff.sh Executable file
View file

@ -0,0 +1,65 @@
#!/bin/bash
# check-schema-diff.sh <path-to-manager.zip>
#
# Runs ICPManager's diff-meta against the live DB, using a staged copy of
# manager.zip that is NOT yet installed anywhere live. Per ICPManager.java
# (getAppMeta/getDbMeta): dump-appmeta just scans a directory of compiled
# classes already on the classpath (the "model" dir bundled inside
# manager.zip), and dump-dbmeta just opens a JDBC connection - neither one
# touches the running webapp or Tomcat at all. That means this check can
# run BEFORE anything live is touched, so a deploy mode that assumes "no
# DB changes" (hotfix-code) can verify that assumption first - a wrong
# assumption costs zero downtime instead of a broken mid-upgrade state.
#
# diff-meta itself has no dedicated exit code for "differences found" vs
# "none" (see ICPManager.doDiffMeta - there's no System.exit tied to the
# diff result at all) - the only signal is the literal stdout line
# "No differences detected". This script imposes the contract callers
# actually need:
# exit 0 - clean, no schema differences
# exit 1 - the check itself failed to run (bad manager.conf, DB
# unreachable, manager.zip missing/incomplete, etc.) - treat
# this as at least as serious as differences found, not as
# "probably fine"
# exit 2 - differences were detected (see stdout for the diff)
#
# Deliberately reuses manager-exec.sh's own classpath/invocation instead
# of duplicating the "java -cp model:libs/...jar icp.ICPManager manager.conf
# -exec ..." line here - if the app's dependency jars ever change version,
# this script never needs to be updated to match.
set -u
manager_zip="${1:?Usage: check-schema-diff.sh <path-to-manager.zip>}"
stage_dir="/home/sportrum/schema-check-staging"
if [ ! -f "$manager_zip" ]; then
echo "ERROR: $manager_zip not found - has this project's webapp counterpart's \"ant release-all\" been run against this server yet?" >&2
exit 1
fi
rm -rf "$stage_dir"
mkdir -p "$stage_dir"
if ! unzip -q "$manager_zip" -d "$stage_dir"; then
echo "ERROR: failed to unzip $manager_zip into $stage_dir" >&2
rm -rf "$stage_dir"
exit 1
fi
output=$(cd "$stage_dir" && bash manager-exec.sh diff-meta 2>&1)
status=$?
echo "$output"
rm -rf "$stage_dir"
if [ $status -ne 0 ]; then
echo "SCHEMA-CHECK: FAILED - manager-exec.sh exited ${status}, treat as unsafe (same as differences found)" >&2
exit 1
fi
if echo "$output" | grep -qF "No differences detected"; then
echo "SCHEMA-CHECK: no differences detected"
exit 0
else
echo "SCHEMA-CHECK: differences detected - see the diff above" >&2
exit 2
fi

View file

@ -1,26 +1,34 @@
# Short-lived tier: this is the per-upgrade safety net, not the nightly # Runs as the sportrum user (see upgrade.sh's "sudo su - sportrum -c"),
# backup. Every run pairs a SQL dump and a webapp/WAR snapshot under the # with $mode and $tag already set in scope by the caller.
# SAME $timestamp so a revert always restores both together, never one #
# without the other. It's deliberately aggressive about pruning: old # Short-lived tier: the per-upgrade safety net, not the nightly backup.
# pairs older than RETENTION_DAYS get deleted right after a new upgrade # Every run pairs a SQL dump and a webapp/WAR snapshot under the SAME
# succeeds, since these exist for tactical "undo the last upgrade" use, # $timestamp so a revert always restores both together, never one without
# not long-term retention - disk size matters less here than it does for # the other. Deliberately aggressive about pruning - old pairs older than
# the nightly tier. # RETENTION_DAYS get deleted right after a successful upgrade, since these
# exist for tactical "undo the last upgrade" use, not long-term retention.
#
# Migrations tier (migrate mode only): a SEPARATE, NEVER-pruned directory
# per tag (migrations/<tag>/) holding a before/after SQL+WAR+logs snapshot
# plus the full DB migration transcript. Kept indefinitely on purpose -
# these are the record of exactly what a given schema change did, not a
# rolling safety net - so they live under their own top-level directory
# rather than any naming convention prune_upgrade_backups would need to
# know to skip.
backupdir="/home/sportrum/backup" backupdir="/home/sportrum/backup"
RETENTION_DAYS=14 RETENTION_DAYS=14
timestamp=$(date +'%Y%m%d-%H%M%S') timestamp=$(date +'%Y%m%d-%H%M%S')
sqlbackup="sportrum-upgrade-backup-${timestamp}.sqldump"
webappbackup="sportrum-upgrade-backup-${timestamp}.war"
logsbackup="sportrum-log-backup-${timestamp}"
# Deletes every backup artifact (sql dump, war snapshot, log dir) whose # Deletes every SHORT-LIVED-TIER backup artifact (sql dump, war snapshot,
# embedded timestamp is older than RETENTION_DAYS. Works from the union of # log dir) whose embedded timestamp is older than RETENTION_DAYS. Never
# timestamps found across all three backup dirs - not each dir's own # touches migrations/ - that lives under a different top-level directory
# listing - so a timestamp only disappears entirely once every artifact # entirely, not just a different filename pattern, so there's no risk of
# that shares it is old enough. rm -f/-rf are used throughout since a # this ever pruning something meant to be kept forever. Works from the
# given timestamp may legitimately be missing one artifact (e.g. this # union of timestamps found across all three backup dirs - not each dir's
# upgrade was run with -f or -w and skipped a backup), and that's not an # own listing - so a timestamp only disappears entirely once every
# error here. # artifact that shares it is old enough. rm -f/-rf are used throughout
# since a given timestamp may legitimately be missing one artifact (e.g.
# hotfix-code mode never takes a SQL dump), and that's not an error here.
prune_upgrade_backups() { prune_upgrade_backups() {
local cutoff_epoch local cutoff_epoch
cutoff_epoch=$(date -d "-${RETENTION_DAYS} days" +%s) cutoff_epoch=$(date -d "-${RETENTION_DAYS} days" +%s)
@ -44,39 +52,110 @@ prune_upgrade_backups() {
done done
} }
if [ "$backup_sql" == "true" ]; then # Dumps the DB, zips the current webapp, and copies current logs to the
echo "Backup database to ${sqlbackup}..."; sleep 2 # three given destinations. Shared by the short-lived tier and, for
pg_dump sportrum > ${backupdir}/sql/${sqlbackup} # migrate mode, the migrations/<tag>/ tier - one dump/zip per instant,
else # written wherever it's needed, rather than dumping the same DB twice
echo "Backup of database skipped!" # (nothing else can write to it while Tomcat is stopped, so a second dump
fi # would just be redundant load, not a more accurate snapshot). mkdir -p on
if [ "$backup_war" == "true" ]; then # the destination directories defensively - sportrum_backups is a fresh
echo "Backup webapp to ${webappbackup}..."; sleep 2 # named Docker volume (see sportrum-ansible's docker-compose.yml.j2), so
# sql/webapp/logs/migrations don't necessarily already exist on it the way
# they did on the old server's plain filesystem.
take_snapshot() {
local sql_dest="$1" war_dest="$2" logs_dest="$3"
mkdir -p "$(dirname "$sql_dest")" "$(dirname "$war_dest")"
echo "Backing up database to ${sql_dest}..."
pg_dump sportrum > "${sql_dest}"
echo "Backing up webapp to ${war_dest}..."
( cd /home/sportrum/webapp && zip -q -r sportrum sportrum && mv sportrum.zip "${war_dest}" )
echo "Backing up logs to ${logs_dest}..."
mkdir -p "${logs_dest}"
cp /home/sportrum/webapp/sportrum/logs/* "${logs_dest}"
}
case "$mode" in
migrate)
migdir="${backupdir}/migrations/${tag}"
if [ -e "$migdir" ]; then
echo "ERROR: ${migdir} already exists - refusing to overwrite an indefinitely-kept migration record. Re-run with a different tag." >&2
exit 1
fi
mkdir -p "$migdir"
sql_file="${backupdir}/sql/sportrum-upgrade-backup-${timestamp}.sqldump"
war_file="${backupdir}/webapp/sportrum-upgrade-backup-${timestamp}.war"
logs_dir="${backupdir}/logs/sportrum-log-backup-${timestamp}"
take_snapshot "$sql_file" "$war_file" "$logs_dir"
# Same instant as the short-lived-tier backup just taken above, also
# preserved indefinitely under the tag - copied, not re-dumped (see
# take_snapshot's comment).
cp "$sql_file" "${migdir}/before.sqldump"
cp "$war_file" "${migdir}/before.war"
cp -r "$logs_dir" "${migdir}/before-logs"
echo "Installing new sportrum.war and manager.zip..."
cd /home/sportrum/webapp cd /home/sportrum/webapp
zip -q -r sportrum sportrum rm -rf sportrum/* ; unzip -q sportrum.war -d sportrum
mv sportrum.zip ${backupdir}/webapp/${webappbackup} chmod -R o+w sportrum/WEB-INF/storage
else chmod -R o+w sportrum/logs
echo "Backup webapp skipped!"
fi
cd /home/sportrum/webapp cd /home/sportrum/
echo "Keep logs in ${backupdir}/logs/${logbackup}..."; sleep 1 rm -rf manager ; unzip -q manager.zip ; cd manager
mkdir -p ${backupdir}/logs/${logsbackup} echo "Running DB migration (transcript saved to ${migdir}/upgrade-output.log)..."
cp sportrum/logs/* ${backupdir}/logs/${logsbackup} bash manager-exec.sh upgrade 2>&1 | tee "${migdir}/upgrade-output.log"
# A pipe's own exit status is tee's, not manager-exec.sh's -
# PIPESTATUS[0] is the first command in the pipe, i.e. the actual
# migration.
upgrade_status=${PIPESTATUS[0]}
cd /home/sportrum/
echo "Remove webapp at $(pwd) and unzip new war..."; sleep 2 if [ $upgrade_status -eq 0 ]; then
rm -rf sportrum/* ; unzip -q sportrum.war -d sportrum echo "Taking post-migration snapshot..."
chmod -R o+w sportrum/WEB-INF/storage take_snapshot "${migdir}/after.sqldump" "${migdir}/after.war" "${migdir}/after-logs"
chmod -R o+w sportrum/logs
cd /home/sportrum/
echo "Upgrade DB using manager at $(pwd)/manager..."; sleep 2
rm -rf manager ; unzip -q manager.zip ; cd manager
bash -x manager-exec.sh upgrade
upgrade_status=$?
cd /home/sportrum/
if [ $upgrade_status -eq 0 ]; then
prune_upgrade_backups prune_upgrade_backups
else else
echo "manager-exec.sh upgrade failed (exit ${upgrade_status}) - skipping backup pruning so nothing is discarded until this is investigated." echo "manager-exec.sh upgrade failed (exit ${upgrade_status}) - skipping the post-migration snapshot and short-lived-tier pruning so nothing is discarded until this is investigated." >&2
fi exit "$upgrade_status"
fi
;;
hotfix-code)
war_file="${backupdir}/webapp/sportrum-upgrade-backup-${timestamp}.war"
logs_dir="${backupdir}/logs/sportrum-log-backup-${timestamp}"
mkdir -p "$(dirname "$war_file")"
echo "Backing up webapp to ${war_file}..."
( cd /home/sportrum/webapp && zip -q -r sportrum sportrum && mv sportrum.zip "${war_file}" )
echo "Backing up logs to ${logs_dir}..."
mkdir -p "${logs_dir}"
cp /home/sportrum/webapp/sportrum/logs/* "${logs_dir}"
# No SQL backup - hotfix-code is only ever reached after
# check-schema-diff.sh has already confirmed there's no pending schema
# change, so there's nothing here a SQL dump would protect against
# that the short-lived tier's existing history doesn't already cover.
echo "Installing new sportrum.war..."
cd /home/sportrum/webapp
rm -rf sportrum/* ; unzip -q sportrum.war -d sportrum
chmod -R o+w sportrum/WEB-INF/storage
chmod -R o+w sportrum/logs
# No manager-exec.sh upgrade - hotfix-code is specifically for changes
# with no DB migration to run.
prune_upgrade_backups
;;
*)
echo "ERROR: unknown mode '$mode'" >&2
exit 1
;;
esac

View file

@ -1,33 +1,73 @@
#!/bin/bash #!/bin/bash
# upgrade.sh <migrate|hotfix-code> [tag]
#
# Replaces the old "-f/-w/-s flags + optional action argument" interface
# with named modes - a flag combination was too easy to get subtly wrong
# (nothing stopped you from skipping the SQL backup on a deploy that
# actually needed a DB migration), whereas a named mode says up front what
# kind of change this is and only allows the combination that actually
# makes sense for it:
#
# migrate Full careful path, for a deploy that changes the DB
# schema or data. Takes a SQL+WAR+logs backup (both the
# short-lived tier AND an indefinitely-kept copy tagged
# with the required <tag>), installs the new
# sportrum.war/manager.zip, runs the DB migration via
# manager-exec.sh (its full transcript saved next to the
# tagged backup - see upgrade-cmds.sh), takes a matching
# post-migration snapshot, restarts Tomcat.
#
# hotfix-code For a Java/resource change with NO DB migration. Takes a
# WAR+logs backup (short-lived tier only - no SQL dump, no
# indefinite copy: there's no schema change to protect
# against that the short-lived tier's existing history
# doesn't already cover), installs the new sportrum.war,
# restarts Tomcat (still needed - class files may have
# changed and the JVM can't hot-swap those). Does NOT run
# manager-exec.sh at all: the caller (sportrum-deploy's
# build.xml, via check-schema-diff.sh) is expected to have
# already confirmed there's no pending schema change
# BEFORE ever invoking this, so skipping the DB step here
# isn't a guess made by this script.
#
# hotfix-templates (a zero-downtime template-only sync with no Tomcat
# stop/restart, no storeall, no backup at all) is intentionally NOT
# implemented yet - which files count as "templates" and how they get
# synced into the live, already-running webapp directory is still an open
# design question, not something to guess at here.
#
# Also dropped in this refactor, neither carried forward nor replaced:
# the old storeonly ("-s") mode and the "leave Tomcat stopped instead of
# restarting" action argument. Both were undocumented, flag-only
# behaviors nobody had asked about when this was redesigned around named
# modes - easy to reintroduce as an explicit mode later if actually
# needed, rather than silently keep flag combinations nothing here
# exercises or tests.
. ./upgrade-funs.sh . ./upgrade-funs.sh
action="reboot"
pid=$$ pid=$$
backup_sql="true"
backup_war="true" mode="${1:?Usage: upgrade.sh <migrate|hotfix-code> [tag]}"
storeonly="false" tag="${2:-}"
while getopts "fsw" option
do case "$mode" in
case $option in migrate)
f) if [ -z "$tag" ]; then
backup_sql="false" echo "ERROR: migrate mode requires a tag (second argument) - it's how the indefinitely-kept before/after backup gets named. See sportrum-deploy's build.xml migrate(@host) target, which resolves one for you." >&2
backup_war="false" exit 1
fi
if [[ ! "$tag" =~ ^[A-Za-z0-9._-]+$ ]]; then
echo "ERROR: tag '$tag' contains characters other than letters, digits, dots, dashes, and underscores - it becomes a directory name on the server." >&2
exit 1
fi
;; ;;
w) hotfix-code)
backup_sql="false"
;; ;;
s) *)
storeonly="true" echo "ERROR: unknown mode '$mode' - expected 'migrate' or 'hotfix-code'." >&2
exit 1
;; ;;
?) esac
usage
exit
;;
esac
done
shift $(($OPTIND - 1))
if [ "x$1" != "x" ]; then
action=$1;
fi
running=$(./tomcat_ctl.sh status | grep "tomcat8 is stopped") running=$(./tomcat_ctl.sh status | grep "tomcat8 is stopped")
if [ "x$running" == "x" ]; then if [ "x$running" == "x" ]; then
printf "Call server command storeall.."; sleep 2 printf "Call server command storeall.."; sleep 2
@ -44,14 +84,9 @@ if [ "x$running" == "x" ]; then
else else
echo "Tomcat is not running!" echo "Tomcat is not running!"
fi fi
if [ $storeonly != "true" ]; then
runcmds=$(cat upgrade-cmds.sh)
sudo su - sportrum -c "backup_sql=$backup_sql; backup_war=$backup_war; ${runcmds}"
else
echo "Skipping upgrade commands, store only mode"
fi
if [ $action == "reboot" ]; then
echo "Starting tomcat..."; sleep 2
./tomcat_ctl.sh start
fi
runcmds=$(cat upgrade-cmds.sh)
sudo su - sportrum -c "mode='$mode'; tag='$tag'; ${runcmds}"
echo "Starting tomcat..."; sleep 2
./tomcat_ctl.sh start