Skip to content
12 min read

Cold restore: retries, fences and cutover

Cold restore and disaster recovery is the core path. This page is what to add when the restore has to survive failures, because a restore that is wrong on the second attempt is worse than one that is slow on the first. It adds three things: a state directory that retries read from, two fences that keep the restored forge from acting before it is verified, and a defined boundary after which a full reload is no longer safe.

Read the core page first. The step numbers here are its step numbers.

The two phases

The whole page rests on one distinction.

PhaseWhat is trueIs a full reload safe?
A. FencedNo customer can reach the forge, and mail, Actions, mirrors and webhooks cannot act. Nothing the forge has done can have left the machine.Yes. Fix the cause and re-run from the top.
B. OpenAt least one fence has been lifted. Pushes, mail or webhook deliveries may have happened.No. A reload throws away accepted work and can repeat effects that already left.

The boundary is lifting either fence, not repointing DNS. A DNS update that fails after the fences are down is still phase B. Record the phase in a file, as below, so that a tired operator at 3 a.m. does not have to remember it.

The state directory

The core page keeps one file for retries. Keep four, in the same private directory ($KEEP, mode 0700, outside both destinations and never touched by the cleanup trap):

FileWrittenWhy it exists
database-section.iniOnce, in step 3, never overwrittenThe replacement’s own database settings. The only copy of the credentials its database accepts.
restored-app.iniCopied from the unpacked dump on every runThe restored configuration, saved so that cutover can rebuild it after staging is gone.
overrides.iniBy you, only when a check failsYour corrections. Never regenerated, so no retry and no cutover discards them.
phaseBy you, at the boundaryA or B.

Cutover runs after the step 3 to 7 script has exited, in a different shell, so the variables and the function must not live only in that script. Save them in the state directory at the end of step 3 and source them wherever you need them:

set -euo pipefail
{
  echo 'set -euo pipefail'
  for v in COMPOSE SVC_DB SVC_FORGEJO REPOS_DIR DATA_DIR KEEP; do
    printf '%s=%q\n' "$v" "${!v}"
  done
} > "$KEEP/env.sh"
# lib.sh holds build_config, below. Later shells enter strict mode before sourcing either file.

Add the phase marker to step 3:

set -euo pipefail
if [ ! -e "$KEEP/phase" ]; then
  printf 'A\n' > "$KEEP/phase.tmp" && mv "$KEEP/phase.tmp" "$KEEP/phase" || exit 1
fi
[ "$(cat "$KEEP/phase")" = "A" ] || { echo "phase B: do not reload, see the recovery section below"; exit 1; }

Put that guard right after the install -d line that creates $KEEP, before the first destructive command. A re-run in phase B then stops before it can do harm. An empty or invalid marker also stops the restore; never reset it to A to bypass the guard.

One function builds the configuration, always

Save the function below as $KEEP/lib.sh, and source it in step 6 and at cutover.

Two code paths install an app.ini: step 6 at restore time, and cutover when the fences come down. If they build it differently, a correction made for one is lost in the other. Build it in one place, from the saved files only:

set -euo pipefail

# build_config FENCE OUT: the restored config without its [database] and, when FENCE=1,
# without [mailer], [actions] and [mirror]; then the saved [database]; then your
# overrides; then the disabled fence sections.
build_config() {
  local fence=$1 out=$2 tmp="$2.tmp"
  # Every step returns failure explicitly: a function called in a list or condition
  # does not stop under set -e, so a failed step must not reach the final mv.
  # Headers are compared without spaces, tabs or a carriage return, so a CRLF file or
  # "[ database ]" still matches. Output is written with plain line endings.
  tr -d '\r' < "$KEEP/restored-app.ini" \
    | awk -v fence="$fence" '/^[ \t]*\[/{h=$0; gsub(/[ \t]/,"",h); skip = (h=="[database]") || (fence=="1" && (h=="[mailer]" || h=="[actions]" || h=="[mirror]"))} !skip' > "$tmp" || return 1
  { echo; tr -d '\r' < "$KEEP/database-section.ini"; } >> "$tmp" || return 1
  if [ -s "$KEEP/overrides.ini" ]; then
    awk 'FNR==NR{ if($0 ~ /^\[/){sec=$0} else if($0 ~ /=/){k=$0; sub(/[ \t]*=.*/,"",k); ov[sec SUBSEP k]=$0} next }
         /^\[/{sec=$0; print; next}
         { if($0 ~ /=/){k=$0; sub(/[ \t]*=.*/,"",k); if((sec SUBSEP k) in ov){print ov[sec SUBSEP k]; next}} print }' \
      "$KEEP/overrides.ini" "$tmp" > "$tmp.2" || return 1
    mv "$tmp.2" "$tmp" || return 1
  fi
  if [ "$fence" = "1" ]; then
    printf '\n[mailer]\nENABLED = false\n\n[actions]\nENABLED = false\n\n[mirror]\nENABLED = false\n' >> "$tmp" || return 1
  fi
  mv "$tmp" "$out"
}

An override replaces a key that already exists in the saved [database] section. Use it for the thing the TCP login check in step 6 usually finds: a wrong host or password. It does not add new keys.

In step 6, replace the inline merge with:

cp "$STAGE/unpacked/app.ini" "$KEEP/restored-app.ini"
build_config 1 "$KEEP/merged-app.ini" || { echo "could not build the configuration"; exit 1; }
cp "$KEEP/merged-app.ini" "$DATA_DIR/conf/app.ini" || { echo "could not install the configuration"; exit 1; }
chown -R 1000:1000 "$REPOS_DIR" "$DATA_DIR"   # the whole restored trees, as in the core step

Call it with || and exit as shown, because a function that fails inside a list does not stop the script under set -e.

Then run the TCP login check against $KEEP/merged-app.ini, the file just installed, before step 7. If it fails, write the correction into $KEEP/overrides.ini and re-run from the top. Never edit the installed app.ini or merged-app.ini by hand: the next run rebuilds both and your edit is gone.

Fence both directions before the first start

Both fences must be in place, and verified, before the first up. Starting Forgejo and blocking afterwards is too late: a restored backup can hold queued webhook deliveries and push mirrors that act in the first seconds, and a retry loads them again.

Inbound. A published port such as 0.0.0.0:3000 or the SSH port is reachable by address whatever DNS says. Bind both to loopback in a recovery override file, or allow only your own addresses at the firewall. With Docker Compose 2.24 or newer, !override replaces the published ports instead of adding to them:

services:
  forgejo:
    ports: !override
      - "127.0.0.1:3000:3000"
      - "127.0.0.1:2222:22"

Add -f for that file to COMPOSE. Check with ss -ltn that nothing is listening on a public address before you start.

Outbound. The configuration built with FENCE=1 turns off mail, Actions and mirrors. Webhooks have no switch, so block the Forgejo container’s egress at the network instead, while keeping its path to the database. The mechanism depends on your network (a firewall rule on the container’s subnet, or a network that has no route out), so prove it rather than trust it:

# Probe from a disposable container on the same network as Forgejo, before any start.
# NET is the compose network name (docker network ls). nc comes from the image's busybox.
NET=REPLACE_WITH_COMPOSE_NETWORK
IMG=$($COMPOSE config --format json | jq -er --arg s "$SVC_FORGEJO" '.services[$s].image')
probe() { docker run --rm --network "$NET" --entrypoint nc "$IMG" -z -w 5 "$1" "$2"; }
probe "$SVC_DB" 5432 || { echo "positive control failed: the probe or the database path is broken"; exit 1; }
# PROBE_HOST is an address you operate or know answers on PROBE_PORT. It must be
# reachable from the host, or a failed probe from the container proves nothing.
PROBE_HOST=REPLACE_WITH_REACHABLE_HOST; PROBE_PORT=443
nc -z -w 5 "$PROBE_HOST" "$PROBE_PORT" || { echo "the probe target does not answer from the host"; exit 1; }
if probe "$PROBE_HOST" "$PROBE_PORT"; then echo "egress is open: do not start"; exit 1; fi

The first probe is the control: the same tool, from the same network, must reach the database. If it cannot, the probe itself is broken (no nc, wrong network) and the second result means nothing. These probes are smoke checks, not certification. One closed port does not show that SMTP, SSH push mirrors or LAN webhook targets are blocked. The fence itself must be a default-deny policy that covers every network the container is attached to and both address families, with only the database allowed. Use the probes to catch a policy that is plainly not applied: the container reaches the database, the host reaches the probe target, and the container does not. A target that never answers from anywhere proves nothing, so do not use an unused or reserved address.

Run the database TCP check from step 6 in the same sitting, and use set -euo pipefail; . "$KEEP/env.sh" if you are in a new shell. A fence that also cuts the database is not a fence, it is an outage.

Verify, then cross the boundary deliberately

Step 8 runs against the fenced forge. Two backups matter here, and they are not the same thing.

  1. Interim backup, still fenced. Run the normal backup after the checks pass. It is useful protection, but it records the temporary settings: mail, Actions and mirrors are disabled in it. Write that into the incident record next to the snapshot id. Before taking the dump, save a private companion archive alongside it, using a unique path in the backup destination:

    set -euo pipefail
    . "$KEEP/env.sh"
    # Set CONFIG_ARCHIVE to a new path alongside this interim dump, outside $KEEP.
    CONFIG_ARCHIVE=/REPLACE_WITH_BACKUP_DIRECTORY/interim-config.tar
    umask 077
    files=(restored-app.ini database-section.ini)
    if [ -e "$KEEP/overrides.ini" ]; then files+=(overrides.ini); fi
    tar -cf "$CONFIG_ARCHIVE" -C "$KEEP" "${files[@]}"

    Keep the archive with the dump under the same secret-storage protections. It contains credentials and the original integration settings, plus any overrides. Confirm both artifacts are stored successfully before proceeding. When restoring this snapshot, keep both fences in place. After step 6 copies the dump’s fenced app.ini, replace $KEEP/restored-app.ini with the corresponding archive file, and restore overrides.ini if present (remove a stale local override if absent). Retain the current phase guard, replacement paths and replacement database section. The archived database section is reference only; correct database overrides for the new replacement’s credentials. Rebuild with FENCE=1, install and verify as usual; only build with FENCE=0 at cutover.

  2. Final backup, after the fences are down. It is the one that counts as recovery complete.

Review mirrors before anything leaves the machine. A mirror restored from an older backup pushes stale refs, and can overwrite newer history at the destination, the moment its sync is due and the network is open. While both fences still hold, list every push mirror, and disable or correct each one that no longer matches its destination.

In every new shell, enable strict mode before sourcing saved state: set -euo pipefail; . "$KEEP/env.sh"; . "$KEEP/lib.sh". The cutover, in order. Recreating the service is what applies a changed port mapping; restart does not:

set -euo pipefail
. "$KEEP/env.sh"
. "$KEEP/lib.sh"
# Persist B before any fence can open. A failed write leaves the old marker intact.
printf 'B\n' > "$KEEP/phase.tmp" && mv "$KEEP/phase.tmp" "$KEEP/phase" || { echo "could not persist phase B; keep both fences closed"; exit 1; }
# From here, no full reload.
build_config 0 "$KEEP/final-app.ini" || { echo "could not build the configuration"; exit 1; }
cp "$KEEP/final-app.ini" "$DATA_DIR/conf/app.ini" || { echo "could not install the configuration; keep both fences closed"; exit 1; }
chown 1000:1000 "$DATA_DIR/conf/app.ini" || exit 1
# Mail, Actions and mirrors are now on, but egress is still blocked and the ports are
# still loopback: watch the logs and the mirror list for a few minutes.
$COMPOSE restart "$SVC_FORGEJO" || { echo "restart failed; keep both fences closed"; exit 1; }

Then lift the network fences. Remove the egress block, then drop the recovery override file from COMPOSE and recreate the service, and read back the bindings:

$COMPOSE up -d --force-recreate "$SVC_FORGEJO"
$COMPOSE port "$SVC_FORGEJO" 3000
$COMPOSE port "$SVC_FORGEJO" 22

Then:

  • repoint the records and confirm they converged, as in step 9,
  • sign in and clone through the real name,
  • check that mail, one webhook delivery and one Actions run actually happen,
  • run the normal backup again, and confirm its new snapshot and success evidence as in step 8. Only then record recovery complete.

Delete $KEEP last, as in step 9.

Retrying

PhaseFailed atWhat to do
AAny of steps 3 to 7Fix the cause and re-run the script from the top. The destinations, database and staging are rebuilt; $KEEP is not. Corrections go in overrides.ini.
AThe TCP login checkWrite the correction to overrides.ini, rebuild, and repeat the check against the rebuilt file.
AA full disk during the copyFree space and re-run. The configuration source is in $KEEP, not in the destinations.
BAnything after the fences came downDo not reload. See below.

Recovering in phase B. Treat the second fence you lift as a failure boundary of its own. Stop first, then:

  1. Put the fences back: build_config 1, install, restore the egress block, add the loopback override file to COMPOSE and recreate the service with up -d --force-recreate, then read back the bindings, so nothing further leaves the machine.
  2. Take a fresh dump of the forge as it is now and keep it.
  3. List what has already left or been accepted: pushes, issues, deliveries, mail, mirror pushes. A reload would replay the external ones.
  4. Get an explicit, recorded data-loss decision from the incident owner before reloading anything.

What has and has not been run

The build_config function was run against sample configuration files: with FENCE=1 and FENCE=0, with and without an override, and with CRLF line endings and a [ database ] header. The old database password did not appear in either output, the instance secrets were kept, the override replaced the saved host, and a build that could not read its inputs returned failure without publishing a file. Local shell checks also exercised failed phase writes, configuration installation and restart, plus companion-archive recovery of the original integration settings and overrides. These used temporary fixtures and substituted service commands, not Docker. The egress block and the loopback override remain untested, and the whole procedure has not been run against a real destroyed forge. Until it is, treat the page as reviewed, not drilled.

Contributors
  • Stephen Way