#!/usr/bin/bash

# nginx-upgrade - Upgrade all running nginx instances with zero downtime

# Upgrade all running nginx instances by sending the USR2 signal to the
# master process of each instance, then gracefully stopping the old master.
# This allows for zero-downtime upgrades of nginx.

# Last updated: 2026-11-24

# Seconds to wait for the old master to rename its PID file, for the old
# master to exit and for systemd to follow the new master.
TIMEOUT=10
# Seconds to wait for the new master to parse its configuration and write its
# PID file. Failures are detected early, so this only bounds a slow start
# (e.g. resolving upstream hostnames). Matches systemd's default
# TimeoutStartSec.
START_TIMEOUT=90

err() {
	# Errors go to stderr and to the journal: the RPM file trigger discards
	# stdout, and a failed upgrade leaves the old binary running.
	echo "ERROR: $*" >&2
	echo "$*" | systemd-cat -t nginx-upgrade -p err 2>/dev/null
}

valid_pid() {
	# usage: valid_pid <pid> <cgroup>
	# PID file contents are not trusted: only accept a PID that belongs to
	# the unit's cgroup, as systemd does for PID files not owned by root.
	local pid=$1 cgroup=$2
	[[ $pid =~ ^[0-9]+$ ]] && (( pid > 1 )) &&
		grep -qxF "0::$cgroup" "/proc/$pid/cgroup" 2>/dev/null
}

wait_for_file() {
	# usage: wait_for_file <present|absent> <file> <label>
	local mode=$1 file=$2 label=$3
	local i

	# Poll often: if the new master fails quickly, the old master renames
	# .oldbin back to the PID file and a slow poll would never see it.
	for ((i=0; i<TIMEOUT*10; i++)); do
		[[ $mode == present && -f $file ]] && return 0
		[[ $mode == absent  && ! -f $file ]] && return 0
		sleep 0.1
	done

	err "$label - file never ${mode}ed: $file"
	return 1
}

wait_for_new_master() {
	# usage: wait_for_new_master <pid-file> <old-pid-file> <old-pid> <cgroup> <label>
	# Prints the new master's PID on success.
	#
	# The old master renames its PID file to .oldbin before it executes the
	# new binary, but the new master only writes its PID file after it has
	# parsed its configuration. The old master must not be stopped before
	# that: systemd (Type=forking) would find no PID to follow, consider the
	# unit stopped and kill the new master (rhbz#2582004).
	local file=$1 old_file=$2 old_pid=$3 cgroup=$4 label=$5
	local i pid

	for ((i=0; i<START_TIMEOUT*10; i++)); do
		pid=
		{ read -r pid < "$file"; } 2>/dev/null
		if [[ $pid != "$old_pid" ]] && valid_pid "$pid" "$cgroup"; then
			echo "$pid"
			return 0
		fi
		# If the new master exits (e.g. invalid configuration), the old
		# master renames .oldbin back to the PID file. It is also removed
		# if the old master itself exits.
		if [[ ! -f $old_file ]]; then
			if kill -0 "$old_pid" 2>/dev/null; then
				err "$label - upgrade aborted: the new master exited, the old master ($old_pid) keeps running the old binary. Check the configuration and restart the service."
			else
				err "$label - upgrade aborted: the old master ($old_pid) exited."
			fi
			return 1
		fi
		sleep 0.1
	done

	err "$label - upgrade aborted: no new master PID in $file after ${START_TIMEOUT}s, the old master ($old_pid) keeps running the old binary. Restart the service."
	return 1
}

wait_for_main_pid() {
	# usage: wait_for_main_pid <service-unit> <pid> <label>
	# Check that systemd follows the new master once the old one is gone.
	local unit=$1 pid=$2 label=$3
	local i

	for ((i=0; i<TIMEOUT*10; i++)); do
		if ! /bin/systemctl is-active -q "$unit"; then
			err "$label - $unit is no longer active after the upgrade."
			return 1
		fi
		[[ $(/bin/systemctl show -p MainPID --value "$unit") == "$pid" ]] && return 0
		sleep 0.1
	done

	err "$label - systemd does not track the new master ($pid) as the main process of $unit."
	return 1
}

upgrade_instance() {
	# usage: upgrade_instance <service-unit> <pid-file>
	local unit="$1" pid_file="$2"
	local old_pid_file="${pid_file}.oldbin"
	local old_pid new_pid cgroup

	if [ ! -f "$pid_file" ]; then
		echo "[$unit] No PID file at $pid_file - skipping."
		return 0
	fi

	# Take the old master's PID from systemd rather than from a PID file.
	old_pid=$(/bin/systemctl show -p MainPID --value "$unit")
	cgroup=$(/bin/systemctl show -p ControlGroup --value "$unit")
	if [[ -z $cgroup ]] || ! valid_pid "$old_pid" "$cgroup"; then
		err "[$unit] Could not determine the main PID - skipping."
		return 1
	fi

	echo "[$unit] Starting new master process..."
	/bin/systemctl kill --signal=SIGUSR2 --kill-who=main "$unit"

	wait_for_file present "$old_pid_file" "[$unit] new master start" || return 1

	new_pid=$(wait_for_new_master "$pid_file" "$old_pid_file" "$old_pid" "$cgroup" "[$unit] new master start") || return 1

	echo "[$unit] New master ($new_pid) is up. Gracefully stopping old master ($old_pid)..."
	if ! valid_pid "$old_pid" "$cgroup"; then
		err "[$unit] Old master ($old_pid) is gone before it could be stopped."
		return 1
	fi
	/bin/kill -s QUIT "$old_pid" 2>/dev/null

	wait_for_file absent "$old_pid_file" "[$unit] old master stop" || return 1

	wait_for_main_pid "$unit" "$new_pid" "[$unit] new master takeover" || return 1

	echo "[$unit] Done."
	return 0
}

overall_rc=0

# Discover every active nginx instance via systemctl
# Instance names may contain the characters systemd allows in unit names,
# including "\" from escaping (e.g. nginx@foo\x2dbar.service).
instances=$(systemctl list-units --type=service --state=running --no-legend --plain "nginx*" |
	awk '{print $1}' |
	grep -E '^nginx(@[-[:alnum:]:_.\\]+)?\.service$')

for unit in $instances; do
	pid_file=$(systemctl show "$unit" -p PIDFile --value)

	if [ -z "$pid_file" ]; then
		echo "[$unit] Could not determine PID file - skipping." >&2
		continue
	fi

	upgrade_instance "$unit" "$pid_file"
	rc=$?
	[ $rc -ne 0 ] && overall_rc=$rc
done

exit $overall_rc

# Man page source for pod2man (see nginx.spec), never executed.
# shellcheck disable=SC2317
: <<'POD'
=pod

=head1 NAME

nginx-upgrade - tool to upgrade nginx without any downtime

=head1 SYNOPSIS

nginx-upgrade

=head1 DESCRIPTION

This downstream shell script updates nginx without any downtime. After
upgrading nginx via the package manager, running this script will create
a new nginx master. This master takes over all new requests. The old
masters and workers are then gracefully shutdown without breaking any
existing connections.

For further information, see: L<http://nginx.org/en/docs/control.html>

=head1 BUGS

If you find any bugs, please send an email to the author.

=head1 AUTHORS

Felix Kaechele E<lt>felix@kaechele.caE<gt>

Originally written by
Jamie Nguyen E<lt>jamielinux@fedoraproject.orgE<gt>

=cut
POD
