upgrade.sh #47

  • //
  • guest/
  • perforce_software/
  • sdp/
  • dev/
  • Server/
  • Unix/
  • p4/
  • common/
  • bin/
  • upgrade.sh
  • View
  • Commits
  • Open Download .zip Download (55 KB)
#!/bin/bash
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
#------------------------------------------------------------------------------
set -u

#==============================================================================
# Declarations and Environment

declare ThisScript="${0##*/}"
declare ThisHost=
declare ThisUser=
declare CmdLine="$0 $*"
declare SDPInstance=UnsetSDPInstance
declare Version=4.9.1
declare -i Debug=0
declare -i NoOp=1
declare -i ErrorCount=0
declare -i WarningCount=0
declare -i IgnorePreflightErrors=0
declare -i ManualUpgrade=0
declare -i PreflightOnly=0
declare -i DoProtectionsCommentStyleUpgrade=0
declare -i DoP4DMajorVersionUpgrade=0
declare -i P4D2019_1_StorageUpgrades=0
declare -i P4D2019_1_Plus=0
declare -i P4D2020_2_Plus=0
declare -i SilentMode=0
declare -i RestartP4D=0
declare -i RestartBroker=0
declare -i RestartProxy=0
declare -i OnlineUpgrade=1
declare -i OverrideDowngradePrevention=0
declare PreUpgradeScript=/p4/common/site/upgrade/pre-upgrade.sh
declare PreUpgradeCmd=
declare PostUpgradeScript=/p4/common/site/upgrade/post-upgrade.sh
declare PostUpgradeCmd=
declare UpgradeJournal=
declare VOpts=
declare BinariesDir="/p4/sdp/helix_binaries"
declare HelixBinaries="p4 p4d p4broker p4p"
declare UpgradeHelixBinaries=
declare UpgradeServiceList=
declare RestartCandidates=
declare Bin=
declare BinPath=
declare NewVersionNamedBin=
declare InstanceLinkPath=
declare VersionLinkPath=
declare OldMajorVersion=
declare OldBuildCL=
declare OldVersion=
declare NewMajorVersion=
declare NewBuildCL=
declare NewVersion=
declare VersionInfo=
declare LiveMajorVersion=
declare LiveBuildCL=
declare LiveVersion=
declare VerifyCmd=
declare Log=
declare TmpFile_1=
declare TmpFile_2=

#==============================================================================
# Local Functions
function msg () { echo -e "$*"; }
function dbg () { [[ "$Debug" -eq 1 ]] && msg "DEBUG: $*"; }
function errmsg () { msg "\\nError: (line: ${BASH_LINENO[0]}) $*" >&2; ErrorCount+=1; }
function warnmsg () { msg "\\nWarning: (line: ${BASH_LINENO[0]}) $*"; WarningCount+=1; }
function bail() { errmsg "(line: ${BASH_LINENO[0]}) ${1:-Unknown Error}\\n" >&2; exit "${2:-1}"; }

#------------------------------------------------------------------------------
# This function takes as input an SDP version string, and returns a version
# id of the form YYYY.N.CL, where YYYY is the year, N is an incrementing
# release ID with a given year, and CL is a changelist identifier. The
# YYYY.N together comprise the major version, often shortened to YY.N, e.g.
# r20.1 for the 2020.1 release.
#
# The full SDP Version string looks something like this:
# Rev. SDP/MultiArch/2019.3/26494 (2020/04/23).
#
# This function parses that full string and returns a value like: 2019.3.26494
function get_sdp_version_from_string () {
   local versionString="${1:-}"
   local version=
   version="20${versionString##*/20}"
   version="${version%% *}"
   version="${version/\//.}"
   echo "$version"
}

#------------------------------------------------------------------------------
# Function: run ($cmd, $desc, $honorNoOp)
#
# Input:
#
# $cmd  - Command to execute, including arguments.?
#
# $desc - Description of command to run. Optional; default is no description.
#
# $honorNoOp - If set to 1, command is always executed; NoOp setting is ignored.
#    Optional, default is 0.
#------------------------------------------------------------------------------
function run () { 
   declare cmd="${1:-echo}"
   declare desc="${2:-}"
   declare honorNoOp="${3:-1}"

   [[ -n "$desc" ]] && msg "$desc"
   msg "Running: $cmd"

   if [[ "$NoOp" -eq 1 && "$honorNoOp" -eq 1 ]]; then
      msg "NO_OP: Would run $cmd"
      return 0
   else
      if $cmd; then
         return 0
      else
         return 1
      fi
   fi
}

#------------------------------------------------------------------------------
# Function: usage (required function)
#
# Input:
# $1 - style, either -h (for short form) or -man (for man-page like format).
# The default is -h.
#
# $2 - error message (optional).  Specify this if usage() is called due to
# user error, in which case the given message displayed first, followed by the
# standard usage message (short or long depending on $1).  If displaying an
# error, usually $1 should be -h so that the longer usage message doesn't
# obscure the error message.
#
# Sample Usage:
# usage
# usage -h
# usage -man
# usage -h "Incorrect command line usage."
#------------------------------------------------------------------------------
function usage
{
   declare style=${1:--h}
   declare usageErrorMessage=${2:-Unset}

   if [[ "$usageErrorMessage" != Unset ]]; then
      echo -e "\\n\\nUsage Error:\\n\\n$usageErrorMessage\\n\\n"
   fi

   echo "USAGE for $ThisScript v$Version:

$ThisScript <instance> [-p|-I] [-M] [-Od] [-c] [-y] [-L <log>] [-d|-D]

or

$ThisScript [-h|-man]
"
   if [[ $style == -man ]]; then
      echo -e "
DESCRIPTION:

This script upgrades the following Helix Core software:

* p4d, the Perforce Helix Core server
* p4broker, the Helix Broker server
* p4p, the Helix Proxy server
* p4, the command line client

Details of each upgrade are described below. Prior to executing any upgrades, a
preflight check is done to help ensure upgrades will go smoothly.  Also, checks
are done to determine what (if any) of the above software products need to be
updated.

To prepare for an upgrade, new binaries must be update in the $BinariesDir
directory.  This is generally done using the get_helix_binaries.sh script in
that directory.  Binaries in this directory are not referenced by live running
servers, and so it is safe to upgrade files in this directory to stage for a
future upgrade at any time. Also, the SDP standard PATH does not include this
directory, as verified by the verify_sdp.sh script.

THE INSTANCE BIN DIR

The 'instance bin' directory, /p4/<instance>/bin, (e.g. /p4/1/bin for instance
1), is expected to contain *_init scripts for services that operate on the
given machine.

For example, a typical master machine for instance 1 might have the following
in /p4/1/bin:

* p4broker_1_init script
* p4broker_1 symlink
* p4d_1_init script
* p4d_1 symlink or script
* p4_1 symlink (a reference to the 'p4' command line client)

A server machine for instance 1 that runs only the proxy server would have the
following in /p4/1/bin:

* p4p_1_init script
* p4p_1 symlink
* p4_1 symlink

The instance bin directory is never modified by the 'upgrade.sh' script.
The addition of new binaries and update of symlinks occur in $P4CBIN.

The existence of *_init scripts for any given binary determines whether this
script attempts to manage the service on a given machine, stopping it before
upgrades, restarting it afterward, and other processing in the case of p4d.

Note that Phase 2, adding new binaries and updating symlinks, will occur for
all binaries for which new staged versions are available, regardless of
whether they are operational on the given machine.

THE COMMON DIR

This script performs it operations in the SDP common bin dir, $P4CBIN.

Unlike the instance bin directory, the $P4CBIN directory is expected
to be identical across all machines in a topology.  Scripts and symlinks
should always be the same, with only temporary differences while global
topology upgrades are in progress.

Thus, all binaries available to be upgraded will be upgraded in Phase 2, even
if the binary does not operate on the current machine. For example, if a new
version of 'p4p' binary is available, a new version will be copied to
$P4CBIN and symlink references updated there. However, the p4p binary will
not be stopped/started.

GENERAL UPGRADE PROCESS

This script determines what binaries need to be upgraded, based on what new
binaries are available in the $BinariesDir directory compared to what binaries
the current instance uses.

There are 5 potential phases. Which phases execute depend on the set of binaries
being upgraded.  The phases are:

* PHASE 1 - Establish a clean rollback point.
This phase executes on the master if p4d is upgraded.

* PHASE 2 - Install new binaries and update SDP symlinks in $P4CBIN.
This phase executes for all upgrades.

* PHASE 3 - Stop services to be upgraded.
This phase executes for all upgrades involving p4d, p4p, p4broker.
Only a 'p4' client only upgrade skips this phase.

* PHASE 4 - Perforce p4d schema upgrades
This step involves the 'p4d -xu' processing. It executes if p4d is upgraded
to a new major version, and occurs on the master as well as all replicas/edge
servers. The behavior of 'p4d -xu' differs depending on whether the server is
the master or a replica.

This phase is skipped if upgrading to a patch of the same major version, as
patches do not require 'p4d -xu' processing.

* PHASE 5 - Start upgraded services.
This phase executes for all upgrades involving p4d, p4p, p4broker.
Only a 'p4' client only upgrade skips this phase.

SPECIAL CASE - To OR THRU P4D 2019.1

If you are upgrading from a version that is older than 2019.1, services
are NOT restarted after the upgrade in Phase 5, except on the master.
Services must be restarted manually on all other servers.

For these 'to-or-thru' 2019.1 upgrades, after ensuring all replicas/edges
are caught up (per 'p4 pull -lj'), shutdown all servers other than the
master.

Proceeding outer-to-inner, execute this script like so on all machines
except the master:
   1. Deploy new executables in $BinariesDir
   2. Stop p4d.
   3. Run 'verify_sdp.sh -skip cron,version'; fix problems if needed until it reports clean.
   4. Run 'upgrade.sh -M' to update symlinks.
   5. Do the upgrade manually with:  p4d -xu
   6. Leave the server offline.

On the master, execute like this:
   1. Deploy new executables in $BinariesDir
   2. Run 'verify_sdp.sh -skip cron,version'; fix problems if needed until it reports clean.
   3. upgrade.sh

When the script completes (it will wait for 'p4 storage' upgrades),
restart services manually after the upgrade in the 'inner-to-outer'
direction.  Restart services on replicas/edges going inner-to-outer

This procedure requiring extra steps is specific to 'to-or-thru' P4D 2019.1
upgrades.  For upgrades starting from P4D 2019.1 or later, things are simpler.

UPGRADES FOR P4D 2019.1+

For upgrades where the P4D start version is 2019.1 and going to any subsequent
version, run this script going outer-to-inner. On each machine, it leaves the
services online and running.  Going in the outer-to-inner direction an all
servers, do:
   1. Deploy new executables in $BinariesDir
   2. Run 'verify_sdp.sh -skip cron,version'; fix problems if needed until it reports clean.
   3. upgrade.sh

UPGRADE PREPARATION

The steps for deploying new binaries to server machines and running verify_sdp.sh
(and potentially correcting any issues it discovers) can and should be done before
the time or even day of any planned upgrade.

UPGRADING HELIX CORE - P4D

The p4d process, the Perforce Helix Core Server, is the center of the Perforce
Helix universe, and the only server with a significant database component.
Most of the upgrade phases above are about performing the p4d upgrade.

This 'upgrade.sh' script requires that the 'p4d' service be running at the
beginning of processing if p4d is to be upgraded, and will abort if p4d is
not running.

ORDER OF UPGRADES

Any given Perforce Helix installation will have least one p4d master server, and
may have several other p4d servers deployed on different machines as replicas and
edge servers.  When upgrading multiple p4d servers for any given instance (i.e.
any given data set, with a unique set of changelist numbers and users), the order
in which upgrades are performed matters.  Upgrades must be done in \"outer to
inner\" order.

The master server, at the center of the topology, is the innermost server and
must be upgraded last. Any replicas or edge servers connected directly to the
master constitute the next outer circle.  These can be upgraded in any order
relative to each other, but must be done before the master and after any
replicas farther out from the master in the topology.  So this 'upgrade.sh'
script should be run first on the server machines that are \"outermost\" from
the master from a replication perspective, and moving inward. The last run is
done on the master server machine.

Server machines running only proxies and brokers do not have a strict order
dependency for upgrades. These are commonly done in the same \"outer to inner\"
methodology as p4d for process consistency rather than strict technical need.

See the SDP_Guide.Unix.html for more information related to performing global
topology upgrades.

MASTER JOURNAL ROTATIONS

This script helps minimize downtime for upgrades by taking advantage of the SDP
offline checkpoint mechanism.  Rather than wait for a full checkpoint, a journal
is rotated and replayed to the offline_db.  This typically takes very little
time compared to a checkpoint, reducing downtime needed for the overall upgrade.

When the master server is upgraded, two rotations of the master server's journal
occur during processing.  The first journal rotation occurs before any upgrade
processing occurs, i.e. before the new binaries are added and symlinks are
updated. This gives a clean rollback point.

Later, after the p4d has started and p4d performs its journaled upgrade
processing, a second journal rotation occurs in Phase 5. This second journal
rotation captures all upgrade-related processing in a separately numbered journal.

UPGRADING HELIX BROKER

Helix Broker (p4broker) servers are commonly deployed on the same machine as a
Helix Core server, and can also be deployed on stand-alone machines (e.g.
deployed to a DMZ host to provide secure access outside a corporate firewall).

Helix Brokers configured in the SDP environment can use a default configuration
file, and may have other configurations. The default configuration is the done
defined in /p4/common/config/p4_N.broker.cfg (or a host-specific override file
if it exists named /p4/common/config/p4_N.broker.<short_hostname>.cfg).  Other
broker configurations may exist, such as a DFM (Down for Maintenance) broker
config /p4/common/config/p4_N.broker.dfm.cfg.

During upgrade processing, this 'upgrade.sh' script only stops and restarts the
broker with the default configuration. Thus, if coordinating DFM brokers, first
manually shutdown the default broker and start the DFM brokers before calling
this script. This script will leave the DFM brokers running while adding the
new binaries and updating the symlinks.  (Note: Depending on how services
are configured, this DFM configuration might not survive a machine reboot.
typically the default broker will come online after a machine reboot).

This 'upgrade.sh' script will stop the p4broker service if it is running at the
beginning of processing.  If it was stopped, it will be restarted after the new
binaries are in place and symlinks are updated. If p4broker was not running at the
start of processing, new binaries are added and symlinks updated, but the
p4broker server will not be started.

UPGRADING HELIX PROXY

Helix Proxy (p4p) are commonly deployed on a machine by themselves, with no p4d
and no broker. It may also be run on the same machine as p4d.

This 'upgrade.sh' script will stop the p4p service if it is running at the
beginning of processing.  If it was stopped, it will be restarted after the new
binaries are in place and symlinks are updated. If p4p was not running at the
start of processing, new binaries are added and symlinks updated, but the p4p
server will not be started.

UPGRADING HELIX P4 COMMAND LINE CLIENT

The command line client, 'p4', is upgraded in Phase 2 by addition of new
binaries and updating of symlinks.

STAGING HELIX BINARIES

If your server can reach the Perforce FTP server over the public internet, a
script can be used from the $BinariesDir directory to get the latest
binaries:
	
	\$ cd $BinariesDir
	\$ ./get_helix_binaries.sh

If your server cannot reach the Perforce FTP server, perhaps due to outbound
network firewall restrictions or operating on an \"air gapped\" network,
use the '-n' option to see where Helix binaries can be acquired from:

	\$ cd $BinariesDir
	\$ ./get_helix_binaries.sh -n

OPTIONS:
 <instance>
	Specify the SDP instance name to add.  This is a reference to the Perforce
	Helix Core data set. This defaults to the current instance based on the
	\$SDP_INSTANCE shell environment variable. If the SDP shell environment is
	not loaded, this option is required.

 -p	Specify '-p' to halt processing after preflight checks are complete,
	and before actual processing starts. By default, processing starts
	immediately upon successful completion of preflight checks.

 -Od	Specify '-Od' to override the rule preventing downgrades.

	WARNING: This is an advanced option intended for use by or with the
	guidance of Perforce Support or Perforce Consulting.

 -I	Specify '-I' to ignore preflight errors. Use of this flag is STRONGLY
	DISCOURAGED, as the preflight checks are essential to ensure a safe
	and smooth migration. If used, preflight checks are still done so
	their errors are recorded in the upgrade log, and then the migration
	will attempt to proceed.

	WARNING: This is an advanced option intended for use by or with the
	guidance of Perforce Support or Perforce Consulting.

 -M	Specify '-M' if you plan to do a manual upgrade. With this option,
	only Phase 2 processing, adding new staged binaries and updating
	symlinks, is done by this script.

	WARNING: This is an advanced option intended for use by or with the
	guidance of Perforce Support or Perforce Consulting.

 -c	Specify '-c' to execute a command to upgrade the Protections table
	comment format after the p4d upgrade, by using a command like:

        p4 protect --convert-p4admin-comments -o | p4 -s protect -i

	By default, this Protections table conversion is not performed.  In some
	environments with custom policies related to update of the protections
	table, this command may not work.

	The new style of comments and the '--convert-p4admin-comments' option
	was introduced in P4D 2016.1.

 -L <log>
	Specify the path to a log file, or the special value 'off' to disable
	logging.  By default, all output (stdout and stderr) goes to this file
	in the /p4/N/logs directory (where N is the SDP instance name):

	upgrade.p4_N.<datestamp>.log

	NOTE: This script is self-logging.  That is, output displayed on the
	screen is simultaneously captured in the log file.  Do not run this
	script with redirection operators like '> log' or '2>&1', and do not
	use 'tee.'

	Logging can only be disabled with '-L off' if the '-n' or '-p' flags
	are used. Disabling logging for actual upgrades is not allowed.

 -y	Specify the '-y' option to confirm that the upgrade should be done.

	By default, this script operates in No-Op mode, meaning no actions
	that affect data or structures are taken.  Instead, commands that would
	be run are displayed.  This mode can be educational, showing various
	steps that will occur during an actual upgrade.

DEBUGGING OPTIONS:
 -d     Increase verbosity for debugging.

 -D     Set extreme debugging verbosity, using bash '-x' mode. Also implies -d.

HELP OPTIONS:
 -h	Display short help message
 -man	Display man-style help message

EXAMPLES:
	EXAMPLE 1: Preflight Only

	To see if an upgrade is needed for this instance, based on binaries
	staged in $BinariesDir, use the '-p' flag to execute only the preflight
	checks, and disable logging, as in this example:

	\$ cd /p4/common/bin
	\$ ./upgrade.sh 1 -p -L off

	EXAMPLE 2: Typical Usage

	Typical usage is with just the SDP instance name as an argument, e.g.
	instance '1', and no other parameters, as in this example:

	\$ cd /p4/common/bin
	\$ ./upgrade.sh 1

	This first runs preflight checks, and aborts if preflight checks
	detected any issues. The it gives a preview of the upgrade. A
	successful preview completes with a line near the end that looks like
	this sample:

	Success: Finished p4_1 Upgrade.

	If the preview is successful, then proceed with the real upgrade using
	the -y flag:

	\$ ./upgrade.sh 1 -y

	EXAMPLE 3: Simplified

	If the standard SDP shell environment is loaded, upgrade.sh will be in
	the path, so the 'cd' command to /p4/common/bin is not needed. Also,
	the SDP_INSTANCE shell environment variable will be defined, so the
	'instance' parameter can be dropped, with simply a call to the script
	needed.  First do a preview:

	\$ upgrade.sh

	Review the output of the preview, looking for the 'Success: Finished'
	message near the end of the output. If that exists, then execute again
	with the '-y' flag to execute the actual migration:

	\$ upgrade.sh -y

CUSTOM PRE- AND POST- UPGRADE AUTOMATION HOOKS:
	This script can execute custom pre- and post- upgrade scripts. This
	can be useful to incorporate site-specifc elements of an upgrade.

	If the file /p4/common/site/upgrade/pre-upgrade.sh exists and is
	executable, it will be executed as a pre-upgrade script. If the file
	/p4/common/site/upgrade/post-upgrade.sh exists and is executable,
	it will be executed as a post-ugprade script.
	
	Pre- and post- upgrade scripts are called with an SDP instance
	parameter, and an optional '-y' flag to confirm actual processing is
	to be done.  Custom scripts are expected to operate in preview mode
	by default, taking no actions that affect data (just as this script
	behaves).  If this upgrade.sh script is given the '-y' flag, that
	option is passed to the custom script as well, indicating active
	processing should occur.

	Pre- and post- upgrade scripts are expected to exit with a zero exit
	code to indicate success, and non-zero to indicate failure.

	The custom pre-upgrade script is executed after standard preflight
	checks complete successfully.  If the '-I' flag is used to ignore the
	status of preflight checks, the custom pre-upgrade script is
	executed regardless of the status of preflight checks. Preflight
	checks are executed before actual upgrade processing commences. If a
	custom pre-upgrade script indicates a failure, the overall upgrade
	process aborts.

	The post-upgrade custom script is executed after the main upgrade
	is successful.

	Success or failure of pre- and post- upgrade scripts is repored in
	the log.  These scripts do not require independent logging, as all
	standard and error output is captured in the log of this upgrade.sh
	script.

	TIP: Be sure to fully test custom scripts in a test environment
	before incorporating them into an upgrade on production systems.

SEE ALSO:
	The $P4CBIN/verify_sdp.sh script is used for preflight checks.

	The $BinariesDir/get_helix_binaries.sh script acquires new binaries
	for upgrades.

	Both scripts sport the same '-h' (short help) and '-man' (full manual)
	usage options as this script.

LIMITATIONS:
	This script does not handle upgrades of 'p4dtg', Helix Swarm,
	Helix4Git, or any other software. It only handles upgrades of
	p4d, p4p, p4broker, and the p4 client binary on the SDP-managed
	server machine on which it is executed.
"
   fi

   exit 1
}

#------------------------------------------------------------------------------
# Function: terminate
function terminate
{
   # Disable signal trapping.
   trap - EXIT SIGINT SIGTERM

   # Ensure a non-zero exit code if the trap was triggered by anything other
   # than the 'exit 0' at the end of the Main Program.
   [[ "$BASH_COMMAND" == *"exit 0"* ]] || ErrorCount+=1

   msg "\\n$ThisScript: EXITCODE: $ErrorCount\\n"
   [[ "$Log" != "off" ]] && msg "Log is: $Log"

   # With the trap removed, exit.
   exit "$ErrorCount"
}

#==============================================================================
# Command Line Processing

declare -i shiftArgs=0

set +u
while [[ $# -gt 0 ]]; do
   case $1 in
      (-c) DoProtectionsCommentStyleUpgrade=1;;
      (-p) PreflightOnly=1;;
      (-M) ManualUpgrade=1;;
      (-I) IgnorePreflightErrors=1;;
      (-Od) OverrideDowngradePrevention=1;;
      (-h) usage -h;;
      (-man) usage -man;;
      (-y) NoOp=0;;
      (-d) Debug=1;;
      (-si) SilentMode=1;;
      (-L) Log="$2"; shiftArgs=1;;
      (-D) Debug=1; set -x;; # Debug; use bash 'set -x' high verbosity debugging mode.
      (-n) usage -h "The '-n' option (preview mode) is now default behavior, so '-n' is no longer needed.\\nA new '-y' confirmation flag is required to perform an actual ugprade.  See EXAMPLES in 'ugprades.sh -man'.";;
      (*)
         if [[ "$SDPInstance" == "UnsetSDPInstance" ]]; then
            SDPInstance="$1"
	 else
            usage -h "Instance $1 specified after already being specified as $SDPInstance. Only one instance can be specified."
	 fi
      ;;
   esac

   # Shift (modify $#) the appropriate number of times.
   shift; while [[ $shiftArgs -gt 0 ]]; do
      [[ $# -eq 0 ]] && usage -h "Incorrect number of arguments."
      shiftArgs=$shiftArgs-1
      shift
   done
done
set -u

# Default SDPInstance to the SDP_INSTANCE shell environment variable
# if no value was specified on the command line.
if [[ "$SDPInstance" == "UnsetSDPInstance" ]]; then
   if [[ -n "${SDP_INSTANCE:-}" ]]; then
      SDPInstance="$SDP_INSTANCE"
   else
      usage -h "No instance specified and SDP shell environment is not loaded."
   fi
fi

if [[ "$Log" == "off" ]]; then
   if [[ "$NoOp" -eq 0 && "$PreflightOnly" -eq 0 ]]; then
      usage -h "Disabling logging with '-L off' is only allowed with '-p' and/or '-n' flags."
   fi
fi

[[ "$SilentMode" -eq 1 && "$Log" == "off" ]] && \
   usage -h "Cannot use '-si' with '-L off'."

[[ "$PreflightOnly" -eq 1 && "$IgnorePreflightErrors" -eq 1 ]] && \
   usage -h "Cannot use '-p' with '-I'."

#==============================================================================
# Main Program

# Pre-Preflight checks occur before logging starts, to ensure essential utils
# (including those needed for logging) are available in the PATH.
for util in awk date id sed tee touch; do
   if ! command -v $util > /dev/null; then
      errmsg "Cannot find this essential util in PATH: $util"
   fi
done

if [[ "$ErrorCount" -ne 0 ]]; then
   bail "Aborting due to essential tools not available in directories listed in the PATH."
fi

[[ -n "$Log" ]] ||\
   Log="${LOGS:-/tmp}/upgrade.p4_${SDPInstance}.$(date +'%Y%m%d-%H%M%S').log"

# Set LOGFILE to be compatible with functions like log() in backup_functions.sh.
export LOGFILE="${Log}"

if [[ "$Log" != off ]]; then
   touch "$Log" || bail "Couldn't touch log file [$Log]."
fi

trap terminate EXIT SIGINT SIGTERM

# Redirect stdout and stderr to the log file.
if [[ "$Log" != "off" ]]; then
   # Redirect stdout and stderr to a log file.
   if [[ "$SilentMode" -eq 0 ]]; then
      exec > >(tee "$Log")
      exec 2>&1
   else
      exec >"$Log"
      exec 2>&1
   fi
fi

ThisUser=$(whoami)
ThisHost=$(hostname -s)

msg "Started $ThisScript v$Version as $ThisUser@$ThisHost on $(date) as:\\n$CmdLine\\n"

[[ "$ManualUpgrade" -eq 1 ]] && warnmsg "Expert option '-M' (manual upgrade) specified."
[[ "$IgnorePreflightErrors" -eq 1 ]] && warnmsg "Expert option '-I' (ignore preflight errors)."

TmpFile_1=$(mktemp)
TmpFile_2="${TmpFile_1}.2"

# Standard Preflight checks after logging has started.

# Load SDP controlled shell environment.
# shellcheck disable=SC1091
source /p4/common/bin/p4_vars "$SDPInstance" ||\
   errmsg "Failed to load SDP environment."

# shellcheck disable=SC1090 disable=SC1091
source "$P4CBIN/backup_functions.sh" ||\
   errmsg "Failed to load SDP backup_functions.sh lib.\\n"

set_vars

cd "$P4CBIN" || errmsg "Failed to cd to $P4CBIN."
msg "Operating in: $PWD"

# P4DInitScript is defined with set_vars() from backup_functions.sh.
# shellcheck disable=SC2154
if [[ -x "$P4DInitScript" && "$ManualUpgrade" -eq 0 ]]; then
   VerifyCmd="$P4CBIN/verify_sdp.sh $SDPInstance -skip ${VERIFY_SDP_SKIP_TEST_LIST:-},crontab,version -L off -online"
else
   VerifyCmd="$P4CBIN/verify_sdp.sh $SDPInstance -skip ${VERIFY_SDP_SKIP_TEST_LIST:-},crontab,version -L off"
fi

msg "Running verify_sdp.sh as part of preflight checks."
# Call verify_sdp.sh with honorNoOp=0 so it is called even in NoOp mode.
if run "$VerifyCmd" \
   "Verifying SDP instance $SDPInstance:" 0; then
   msg "\\nVerified: verify_sdp.sh is OK."
else
   errmsg "The verify_sdp.sh script reported preflight errors. Correct these and try again."
fi

for Bin in $HelixBinaries; do
   BinPath="$BinariesDir/$Bin"
   if [[ -e "$BinPath" ]]; then
      VOpts="-V"
      # For p4d, we must supply an existing dir with '-r' to suppress ugly
      # error messages related to P4ROOT not existing, e.g. if run on a
      # proxy-only or broker-only host.
      [[ "$Bin" == p4d ]] && VOpts="-V -r /tmp"

      if [[ -x "$BinPath" ]]; then
         if [[ "$Bin" == "p4" ]]; then
            InstanceLinkPath="${Bin}_bin"
         else
            InstanceLinkPath="${Bin}_${SDPInstance}_bin"
         fi

         if [[ -L "$InstanceLinkPath" ]]; then
            # shellcheck disable=SC2086
            OldMajorVersion=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
            # shellcheck disable=SC2086
            OldBuildCL=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
            OldVersion="${OldMajorVersion}.${OldBuildCL}"
            case "$Bin" in
               (p4)
                  LiveMajorVersion="$OldMajorVersion"
                  LiveBuildCL="$OldBuildCL"
                  LiveVersion="$OldVersion"
               ;;
               (p4d)
                  # shellcheck disable=SC2154
                  if [[ -x "$P4DInitScript" ]]; then
                     VersionInfo=$("$P4BIN" -p "$P4PORT" -ztag -F %serverVersion% info -s 2>/dev/null)
                     if [[ -n "$VersionInfo" ]]; then
                        # Trim off the date string, e.g. " (2020/09/08)"
                        VersionInfo=${VersionInfo%% (*}
                        LiveMajorVersion=$(echo "$VersionInfo" | awk -F / '{print $3}')
                        LiveBuildCL=$(echo "$VersionInfo" | awk -F / '{print $4}')
                        LiveVersion="${LiveMajorVersion}.${LiveBuildCL}"
                     else
                        LiveVersion="NoLiveP4D"
                     fi
                  else
                     LiveVersion="NoLiveP4D"
                  fi
               ;;
               (p4broker)
                  # shellcheck disable=SC2154
                  if [[ -x "$P4BrokerInitScript" ]]; then
                     VersionInfo=$("$P4BIN" -p "$P4BROKERPORT" -ztag -F %brokerVersion% info -s 2>/dev/null)

                     if [[ -n "$VersionInfo" ]]; then
                        # Trim off the date string, e.g. " (2020/09/08)"
                        VersionInfo=${VersionInfo%% (*}
                        LiveMajorVersion=$(echo "$VersionInfo" | awk -F / '{print $3}')
                        LiveBuildCL=$(echo "$VersionInfo" | awk -F / '{print $4}')
                        LiveVersion="${LiveMajorVersion}.${LiveBuildCL}"
                     else
                        LiveVersion="NoLiveP4Broker"
                     fi
                  else
                     LiveVersion="NoLiveP4Broker"
                  fi
               ;;
               (p4p)
                  # shellcheck disable=SC2154
                  if [[ -x "$P4ProxyInitScript" ]]; then
                  VersionInfo=$("$P4BIN" -p "$PROXY_PORT" -ztag -F %proxyVersion% info -s 2>/dev/null)

                     if [[ -n "$VersionInfo" ]]; then
                        # Trim off the date string, e.g. " (2020/09/08)"
                        VersionInfo=${VersionInfo%% (*}
                        LiveMajorVersion=$(echo "$VersionInfo" | awk -F / '{print $3}')
                        LiveBuildCL=$(echo "$VersionInfo" | awk -F / '{print $4}')
                        LiveVersion="${LiveMajorVersion}.${LiveBuildCL}"
                     else
                        LiveVersion="NoLiveP4Proxy"
                     fi
                  else
                     LiveVersion="NoLiveP4Proxy"
                  fi
               ;;
            esac
         else
            msg "Skipping $Bin upgrade as there is no current symlink: $InstanceLinkPath"
            continue
         fi

         # shellcheck disable=SC2086
         NewMajorVersion=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
         # shellcheck disable=SC2086
         NewBuildCL=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
         NewVersion="${NewMajorVersion}.${NewBuildCL}"

         if [[ "$OldVersion" != "$NewVersion" ]]; then
            # A lexigraphical comparison is good for our needs here.
            if [[ "$OldVersion" < "$NewVersion" ]]; then
               msg "The $Bin binary will be upgraded from $OldVersion to $NewVersion."
               UpgradeHelixBinaries+="$Bin "
               [[ "$Bin" != "p4" ]] && UpgradeServiceList+="$Bin "
            else
               if [[ "$OverrideDowngradePrevention" -eq 0 ]]; then
                  errmsg "The staged $Bin binary in $BinariesDir [$NewVersion] is an older version than what what is in place [$OldVersion]. Downgrades are not supported."
                  continue
               else
                  warnmsg "Downgrade detected. Downgrade will be attempted due to '-Od'."
                  UpgradeHelixBinaries+="$Bin "
                  [[ "$Bin" != "p4" ]] && UpgradeServiceList+="$Bin "
               fi
            fi
         else
            # If there are multiple instances to be upgraded, the upgrade of the first
            # instance will upgrade the major version symlink (e.g. p4d_2020.1_bin or
            # similar) to point to the latest patch binary, e.g. p4d_2020.1.2007551.
            # Live running binaries for other instances will still be on the older version,
            # and will need just a service bounce to update them to the latest patch.
            if [[ "$Bin" == "p4" || "$LiveVersion" == "NoLive"* || "$OldVersion" == "$LiveVersion" ]]; then
               msg "The $Bin v$NewVersion binary does not need to be upgraded."
               continue
            else
               if [[ "$LiveVersion" < "$OldVersion" ]]; then
                  msg "The live running $Bin binary will be restarted to update from $LiveVersion to $NewVersion."
                  UpgradeServiceList+="$Bin "
               else
                  if [[ "$OverrideDowngradePrevention" -eq 0 ]]; then
                     errmsg "The live running $Bin binary version [$LiveVersion] is newer than what is is in place [$OldVersion]. Downgrades are not supported."
                     continue
                  else
                     warnmsg "Downgrade detected. Downgrade will be attempted due to '-Od'."
                     UpgradeServiceList+="$Bin "
                  fi
               fi
            fi
         fi

         if [[ "$Bin" == "p4d" ]]; then
            if [[ "$OldMajorVersion" != "$NewMajorVersion" ]]; then
               msg "A major version upgrade for p4d is needed. A schema upgrade will be performed."
               DoP4DMajorVersionUpgrade=1
            else
               msg "P4D patch upgrade is needed, but not a major version upgrade. No schema upgrade will be performed."
            fi

            # A lexigraphical comparison is good for our needs here.
            # shellcheck disable=SC2072
            if [[ "$NewMajorVersion" > "2020.1" ]]; then
               msg "New P4D version is 2020.2+. Modern upgrade logic applies, and 'p4 upgrades' will be used."
               P4D2019_1_Plus=1
               P4D2020_2_Plus=1
            elif [[ "$NewMajorVersion" > "2019.0" ]]; then
               msg "New P4D version is 2019.1+. Modern upgrade logic applies."
               P4D2019_1_Plus=1
            else
               msg "P4D version pre-2019.1, so legacy upgrade logic will be applied."
            fi

            # A lexigraphical comparison is good for our needs here.
            # shellcheck disable=SC2072
            if [[ "$OldMajorVersion" < "2019.0" && "$NewMajorVersion" > "2019.0" ]]; then
               msg "This upgrade goes 'to or thru' P4D 2019.1. Upgrades to db.storage will be done."

               # Even if the user did not specify '-M', we still implicitly
               # disable online upgrade for 'to-or-thru' P4D 2019.1 upgrade,
               # except on the master server itself.
               if [[ "$OnlineUpgrade" -eq 1 ]]; then
                  msg "For any server other than the master, services will be stopped at the start of"
                  msg "processing for 'to-or-thru' P4D 2019.1 upgrades, and will not be restarted"
                  msg "automatically.  For the master, services will be restarted after the upgrade"
                  msg "so that online processing completes and the second journal rotation occurs."
                  msg "After the upgrade.sh completes entirely done on the master (including the"
                  msg "online portion of upgrades, which this script will wait for), a manual of"
                  msg "services on all other machines is required in the 'inner-to-outer' direction"
                  msg "relative to the master."
                  msg "\\nThis applies to 'to-or-thru' P4D 2019.1 upgrades only. This script will"
                  msg "behave differently when the starting P4D version is P4D 2019.1+, such that"
                  msg "upgrades will be simpler, and follow 'outer-to-inner' order."
               fi
               P4D2019_1_StorageUpgrades=1
               [[ "$SERVERID" == "$P4MASTER_ID" ]] || OnlineUpgrade=0
            fi
         fi

      else
         errmsg "The staged $BinPath is not binary."
      fi
   else
      msg "There is no staged $BinPath binary; skipping $Bin."
   fi
done

#------------------------------------------------------------------------------
if [[ -x "$PreUpgradeScript" ]]; then
   PreUpgradeCmd="$PreUpgradeScript $SDPInstance"
   [[ "$NoOp" -eq 0 ]] && PreUpgradeCmd+=" -y"

   if [[ "$IgnorePreflightErrors" -eq 0 ]]; then
      msg "\\nA custom pre-upgrade script exists and will be executed if preflight checks\\nare successful. The pre-upgrade command line will be:\\n\\t$PreUpgradeCmd\\n"
   else
      msg "\\nA custom pre-upgrade script exists and will be executed after preflight checks\\nare attempted. The pre-upgrade command line will be:\\n\\t$PreUpgradeCmd\\n"
   fi
fi

if [[ -x "$PostUpgradeScript" ]]; then
   PostUpgradeCmd="$PostUpgradeScript $SDPInstance"
   [[ "$NoOp" -eq 0 ]] && PostUpgradeCmd+=" -y"

   msg "\\nA custom post-upgrade script exists and will be executed if the upgrade is\\nsuccessful. The post-upgrade command line will be:\\n\\t$PostUpgradeCmd\\n"
fi

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "Verified: Preflight checks passed ($WarningCount warnings)."
else
   if [[ "$IgnorePreflightErrors" -eq 1 ]]; then
      warnmsg "Preflight checks FAILED. Proceeding and resetting error count to 0 after preflight checks due to '-I' flag."
      ErrorCount=0
   else
      bail "Aborting due to failed preflight checks."
   fi
fi

if [[ -z "$UpgradeHelixBinaries" ]]; then
   if [[ -z "$UpgradeServiceList" ]]; then
      msg "No upgrades are needed based on binaries staged in $BinariesDir."
   else
      msg "No upgrades are needed based on binaries staged in $BinariesDir, but service restarts are needed for these $UpgradeServiceList."
   fi
fi

if [[ "$PreflightOnly" -eq 1 ]]; then
   msg "\\nExiting early after successful preflight checks due to '-p'."
   exit 0
fi

if [[ -z "$UpgradeHelixBinaries" && -z "$UpgradeServiceList" ]]; then
   msg "\\nExiting because no upgrades are needed."
   exit 0
fi

#------------------------------------------------------------------------------
# Preflight checks completed. Continue on!

msg "Start $P4SERVER Upgrade as $ThisUser@${HOSTNAME%%.*} at $(date)."

if [[ "$ErrorCount" -eq 0 || "$IgnorePreflightErrors" -eq 1 ]]; then
   if [[ -n "$PreUpgradeCmd" ]]; then
      msg "\\nExecuting custom pre-upgrade command:\\n\\t$PreUpgradeCmd"

      if $PreUpgradeCmd; then
         msg "\\nThe custom pre-upgrade command indicated success."
      else
         bail "\\nAlthough the standard preflight checks were successful, the custom pre-upgrade command indicated failure. Aborting the ugprade."
      fi
   fi
fi

#------------------------------------------------------------------------------
# Phase 1 - Establish a clean rollback point.
if [[ "$ManualUpgrade" -eq 0 ]]; then
   if [[ "$UpgradeHelixBinaries" == *"p4d"* || "$UpgradeServiceList" == *"p4d"* ]]; then
      if [[ "$SERVERID" == "$P4MASTER_ID" ]]; then
         msg "\\nPhase 1: Establish a clean rollback point for p4d upgrades."
         run "$P4CBIN/rotate_journal.sh $SDPInstance" \
            "Rotating journal to provide a clean rollback point." ||\
            bail "Journal rotation failed. No upgrade processing has been done. Aborting upgrade."

         if [[ "$NoOp" -eq 0 ]]; then
            if grep -q "End $P4SERVER journal rotation" "$LOGS/checkpoint.log"; then
               msg "Verified: Journal rotation completed OK."
            else
               bail "Could not verify journal rotation completed OK. No upgrade processing has been done. Aborting upgrade."
            fi
         else
            msg "NO_OP: Journal rotation completed OK."
         fi
      else
         # P4DInitScript is defined with set_vars() from backup_functions.sh.
         # shellcheck disable=SC2154
         if [[ -x "$P4DInitScript" ]]; then
            msg "Skipping Phase 1 (p4d journal rotation) on replica as this is only needed on master server."
         else
            msg "Skipping Phase 1 (p4d journal rotation) as p4d does not run on this machine."
            fi
      fi
   else
      msg "Skipping Phase 1 (p4d journal rotation) as p4d does not need to be upgraded."
   fi
else
   msg "Skipping Phase 1 (p4d journal rotation) due to '-M'."
fi

#------------------------------------------------------------------------------
# Phase 2 - Install new binaries and update SDP symlinks.
msg "\\nPhase 2: Install new binaries and update SDP symlinks in $PWD."

for Bin in $UpgradeHelixBinaries; do
   BinPath="$BinariesDir/$Bin"
   VOpts="-V"
   # For p4d, we must supply an existing dir with '-r' to suppress ugly
   # error messages related to P4ROOT not existing, e.g. if run on a
   # proxy-only or broker-only host.
   [[ "$Bin" == p4d ]] && VOpts="-V -r /tmp"
   # shellcheck disable=SC2086
   NewMajorVersion=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
   # shellcheck disable=SC2086
   NewBuildCL=$("$BinPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
   NewVersion="${NewMajorVersion}.${NewBuildCL}"
   VersionLinkPath="${Bin}_${NewMajorVersion}_bin"
   if [[ "$Bin" == "p4" ]]; then
      InstanceLinkPath="${Bin}_bin"
   else
      InstanceLinkPath="${Bin}_${SDPInstance}_bin"
   fi

   # shellcheck disable=SC2086
   OldMajorVersion=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $3}')
   # shellcheck disable=SC2086
   OldBuildCL=$("./$InstanceLinkPath" $VOpts | grep -i Rev. | awk -F / '{print $4}' | awk '{print $1}')
   OldVersion="${OldMajorVersion}.${OldBuildCL}"

   NewVersionNamedBin="${Bin}_$NewVersion"
   if [[ ! -f "$NewVersionNamedBin" ]]; then
      run "cp $BinariesDir/$Bin $NewVersionNamedBin" ||\
         errmsg "Failed to copy $BinariesDir/$Bin to $NewVersionNamedBin"
   fi
   run "ln -f -s $NewVersionNamedBin $VersionLinkPath" \
      "Updating major version symlink $VersionLinkPath" ||\
      errmsg "Failed to updated major version symlink."
   run "ln -f -s $VersionLinkPath $InstanceLinkPath" \
      "Updating instance symlink $InstanceLinkPath" ||\
      errmsg "Failed to updated major version symlink."
done

if [[ "$ManualUpgrade" -eq 1 ]]; then
   if [[ "$ErrorCount" -eq 0 ]]; then
      msg "\\nDone with no errors. Stopping after Phase 2 (adding binaries and updating symlinks) due to '-M'."
      exit 0
   else
      bail "\\nPhase 2 done with $ErrorCount errors. Stopping after Phase 2 (adding binaries and updating symlinks) due to '-M'."
   fi
fi

#------------------------------------------------------------------------------
# Phase 3 - Stop services to be upgraded.

# Phase 2 will add binaries and update symlinks to keep /p4/common/bin in
# sync everywhere, even though services aren't operational on all machines.
# Here in Phase 3, we only stop/restart services active on this machine.
for Bin in $UpgradeServiceList; do
   if [[ "$Bin" == "p4broker" ]]; then
      # shellcheck disable=SC2154
      [[ -x "$P4BrokerInitScript" ]] && RestartCandidates+="p4broker "
   fi

   if [[ "$Bin" == "p4p" ]]; then
      # shellcheck disable=SC2154
      [[ -x "$P4ProxyInitScript" ]] && RestartCandidates+="p4p "
   fi

   if [[ "$Bin" == "p4d" ]]; then
      # shellcheck disable=SC2154
      [[ -x "$P4DInitScript" ]] && RestartCandidates+="p4d "
   fi
done

if [[ -n "$RestartCandidates" ]]; then
   msg "\\nPhase 3: Stop services to be upgraded (if operating): $RestartCandidates."

   # Stop services to be upgraded if they have an init script and are up.
   # In the case of a p4broker, only interact with the default p4broker config;
   # do not manage other broker configurations, such as 'dfm' (Down for
   # Maintenance) configs.
   for Bin in $RestartCandidates; do
      if [[ "$Bin" == "p4broker" ]]; then
         if is_server_up p4broker; then
            RestartBroker=1
            if [[ "$NoOp" -eq 0 ]]; then
               stop_p4broker
            else
               msg "NO_OP: Would stop p4broker now."
            fi
         else
            msg "Broker (p4broker) with default config was not running, and will not be started after the upgrade."
         fi
      fi

      if [[ "$Bin" == "p4p" ]]; then
         if is_server_up p4p; then
            RestartProxy=1
            if [[ "$NoOp" -eq 0 ]]; then
               stop_p4p
            else
               msg "NO_OP: Would stop p4p now."
            fi
         else
            msg "Proxy (p4p) was not running, and will not be started after the upgrade."
         fi
      fi

      if [[ "$Bin" == "p4d" ]]; then
         # P4DInitScript is defined with set_vars() from backup_functions.sh.
         # shellcheck disable=SC2154
         if [[ -x "$P4DInitScript" ]]; then
            RestartP4D=1
            if [[ "$NoOp" -eq 0 ]]; then
               stop_p4d
            else
               msg "NO_OP: Would stop p4d now."
            fi
         fi
      fi
   done
else
   msg "Skipping Phase 3 (stop services) because no running services were upgraded."
fi

#------------------------------------------------------------------------------
# Phase 4 - Perforce p4d schema upgrades
if [[ "$UpgradeHelixBinaries" == *"p4d"* && -x "$P4DInitScript" ]]; then
   if [[ "$DoP4DMajorVersionUpgrade" -eq 1 ]]; then
      msg "\\nPhase 4: Perform p4d schema upgrades."

      # For P4D versions >= 19.1, schema upgrades are journaled, and thus are
      # applied to the offline_db through the journal rotation process.
      # For older versions of p4d, we run the 'p4d -xu' separately in the offline_db.
      if [[ "$P4D2019_1_Plus" -eq 1 ]]; then
         UpgradeJournal="$P4JOURNAL"
      else
         UpgradeJournal=off
      fi

      run "$P4DBIN -r $P4ROOT -J $UpgradeJournal -xu" \
         "Upgrading databases in $P4ROOT." ||\
         bail "Failed to upgrade root database."

      # Upgrade the offline database on the master and on edge servers.
      # This only applies to pre-2019.1 upgrades.
      if [[ "$P4REPLICA" == "FALSE" ]] || [[ "$EDGESERVER" -eq 1 ]]; then
         if [[ "$P4D2019_1_Plus" -eq 0 ]]; then
            msg "Upgrading databases in $OFFLINE_DB as this is a pre-19.1 server upgrade."

            # The value of '-t localhost:0000' is necessary for syntax reasons;
            # it is ignored. This allows upgrade of offline databases without needing
            # a license file; there isn't one in offline_db, only P4ROOT.  A valid
            # license file is required to actually start the server process and have
            # it listen on a port.

            run "$P4DBIN -r $OFFLINE_DB -J $UpgradeJournal -xu -t localhost:0000" \
               "Upgrading databases in $OFFLINE_DB." ||\
               bail "Failed to upgrade offline_db"
         fi
      else
         msg "Skipping '-xu' update of offline_db; not on master or edge."
      fi
   else
      msg "Skipping Phase 4 (schema upgrade) as p4d upgrade is a patch rather than a major version upgrade." 
   fi
else
   # Display a message indicating that we're skipping the schema upgrade only if
   # we're on a machine with p4d operating.  Otherwise, no message is needed.
   if [[ -x "$P4DInitScript" ]]; then
      msg "Skipping Phase 4 (schema upgrade) as p4d does not need to be upgraded."
   fi
fi

#------------------------------------------------------------------------------
# Phase 5 - Start upgraded services.
if [[ -n "$RestartCandidates" ]]; then
   msg "\\nPhase 5: Restart upgraded services: $RestartCandidates."

   # Start upgraded services if they have an init script. In the case of a
   # broker, also check that it has a default configuration file, as brokers are
   # often configured but run only on demand with a non-default configuration file
   # (e.g. in maintenance mode with a 'dfm' (Down for Maintenance) config.
   for Bin in $RestartCandidates; do
      if [[ "$Bin" == "p4d" ]]; then
         if [[ "$RestartP4D" -eq 1 ]]; then
            if [[ "$NoOp" -eq 0 ]]; then
               if [[ "$OnlineUpgrade" -eq 1 ]]; then
                  msg "Starting Helix Core (p4d)."
                  start_p4d
               else
                  msg "Skipping restart of Helix Core (p4d). Start it manually when ready."
               fi
            else
               msg "NO_OP: Would start p4d now."
            fi
         fi

         # For p4d 2019.1+ upgrades, do an extra journal rotation post-upgrade
         # to apply journal changes to the offline_db (if on the master).
         if [[ "$P4D2019_1_Plus" -eq 1 && "$RestartP4D" -eq 1 ]]; then
            if [[ "$SERVERID" == "$P4MASTER_ID" ]]; then
               if [[ "$P4D2019_1_StorageUpgrades" -eq 1 ]]; then
                  run "$P4BIN storage -w" "Waiting for db.storage upgrades. This may take a while." ||\
                     errmsg "The 'p4 storage -w' command reported errors."
               fi

               if [[ "$DoP4DMajorVersionUpgrade" -eq 1 ]]; then
                  if [[ "$P4D2020_2_Plus" -eq 1 ]]; then
                     msg "Waiting for all upgrades per 'p4 upgrades' to complete."
                     if [[ "$NoOp" -eq 0 ]]; then
                        echo -ne "Waiting ..."

                        # In theory, this could be an infinite loop. However,
                        # the safest way to code this is to simply wait for
                        # all upgrades to complete, as they may take an
                        # arbitrarily long time.
                        # shellcheck disable=SC2078 disable=SC2161
                        while [[ 1 ]]; do
                           "$P4BIN" upgrades > "$TmpFile_1" 2>&1
                           dbg "Output of 'p4 upgrades' in $TmpFile_1:"
                           [[ "$Debug" -eq 1 ]] && cat "$TmpFile_1"
                           # If we see anything other than 'completed' or
                           # 'failed', keep waiting.
                           if grep -qiEv ' (completed|failed)' "$TmpFile_1"; then
                              echo -n "."
                              sleep 3
                           else
                              break
                           fi
                        done

                        if ! grep -qi ' failed' "$TmpFile_1"; then
                           msg "\\nProcessing of upgrades completed OK.\\n"
                        else
                           errmsg "The 'p4 upgrades' command reported failed steps:"
                           cat "$TmpFile_1"
                           msg "\\n\\n"
                        fi
                        rm -f "$TmpFile_1"
                     else
                        msg "NO_OP: Would have waited for 'p4 upgrades'."
                     fi
                  fi

                  run "$P4CBIN/rotate_journal.sh $SDPInstance" \
                     "Upgrade offline_db via journal rotation on master/commit server." ||\
                     bail "Journal rotation failed during offline_db upgrade phase."
               fi
            else
               msg "Skipping second journal rotation as this is only a patch upgrade."
            fi
         fi
      fi

      if [[ "$Bin" == "p4broker" ]]; then
         if [[ "$RestartBroker" -eq 1 ]]; then
            if [[ "$OnlineUpgrade" -eq 1 ]]; then
               if [[ "$NoOp" -eq 0 ]]; then
                  msg "Starting Broker (p4broker)."
                  start_p4broker
               else
                  msg "NO_OP: Would start p4broker now."
               fi
            else
               msg "Skipping restart of p4broker with default config. Start it manually when ready."
            fi
         else
            msg "Skipping start of p4broker with default config (not online at start of upgrade)."
         fi
      fi

      if [[ "$Bin" == "p4p" ]]; then
         if [[ "$RestartProxy" -eq 1 ]]; then
            if [[ "$OnlineUpgrade" -eq 1 ]]; then
               if [[ "$NoOp" -eq 0 ]]; then
                  msg "Starting Proxy (p4p)."
                  start_p4p
               else
                  msg "NO_OP: Would start p4p now."
               fi
            else
               msg "Skipping start of p4p. Start it manually when ready."
            fi
         else
            msg "Skipping start of p4p (not online at start of upgrade)."
         fi
      fi
   done
else
   msg "Skipping Phase 5 (restart services) because no running services were upgraded."
fi

# Upgrade protections on master if '-c' was specified.
if [[ "$DoProtectionsCommentStyleUpgrade" -eq 1 ]]; then
   if [[ "$SERVERID" == "$P4MASTER_ID" ]]; then
      msg "Upgrading protections table comment format."
      if "$P4BIN" protect -o | grep -v '^Update:' > "$TmpFile_1"; then
         if "$P4BIN" protect --convert-p4admin-comments -o | grep -v '^Update:' > "$TmpFile_2"; then
            if ! diff -q "$TmpFile_1" "$TmpFile_2"; then
               msg "Protections table comment conversion diffs are:"
               diff -q "$TmpFile_1" "$TmpFile_2"

               if [[ "$NoOp" -eq 0 ]]; then
                  if "$P4BIN" -s protect -i < "$TmpFile_2"; then
                     msg "Protections table comments updated."
                  else
                     errmsg "There was a problem updating the Protections table comments."
                  fi
               else
                  msg "NO_OP: Would update protections with comment conversion."
               fi
            else
               msg "The '-c' flag was specified, but no protections table updates are needed."
            fi
         else
            errmsg "Error capturing protections table with --convert-p4admin-comments option."
         fi
      else
         errmsg "Error capturing protections table."
      fi
      rm -f "$TmpFile_1" "$TmpFile_2"
   fi
fi

if [[ "$ErrorCount" -eq 0 ]]; then
   msg "\\nSuccess: Finished $P4SERVER Upgrade."

   if [[ -n "$PostUpgradeCmd" ]]; then
      msg "\\nExecuting custom post-upgrade command:\\n\\t$PostUpgradeCmd"

      if $PostUpgradeCmd; then
         msg "\\nThe custom post-upgrade command indicated success."
      else
         errmsg "\\nAlthough the primary upgrade was successful, the custom post-upgrade command indicated failure."
      fi
   fi
else
   errmsg "Finished $P4SERVER Upgrade, but there were errors. Review this log."
fi

if [[ "$NoOp" -ne 0 ]]; then
   msg "NO_OP: This was done in No-Op (No Operation/Preview) mode. No actual ugprade was done. Add the '-y' flag to perform the actual upgrade."
fi

# See the terminate() function, which is really where this script exits.
exit 0
# Change User Description Committed
#64 31445 C. Thomas Tyler Removed setcap handling code from upgrade.sh now that we can rely on
AmbientCapabilities in the systemd unit file to enable the OOM Killer
defense feature in p4d.

Thus, the limited sudoers no longer requires setcap/getcap commands.

Fixed various typos with aspell.

#review-31446
#63 30631 C. Thomas Tyler Corrected one message indicating why a second journal rotation was skipped.

Added a second message for a different reason that second journal rotations
can be skipped, i.e if not running on commit server.

This change does not change processing functionality or workflows; it
affects output displayed.
#62 30630 C. Thomas Tyler Added error handling for using an unknown option (starting with '-').
#61 30038 C. Thomas Tyler Enhanced upgrade.sh to better prepare for a rollback, adding
docs and skipping replay of the rotated journal to the offline_db
for the second journal rotation after a major version upgrade.
#60 30025 C. Thomas Tyler Minor doc refinements.
#59 30023 C. Thomas Tyler Doc enhancements to upgrade.sh:

* Docs make it more clear that p4d is expected to be online at the start of processing.
* Enhanced error message for scenario where a cautious admin stops p4d manually first,
causing the script to abort the upgrade.
* Verified that the call to 'verify_sdp.sh' is captured in the output; this is done by
verify_sdp.sh itself.

Fixes: SDP-845.

#review-30024
#58 29748 C. Thomas Tyler Fixed issue with 'setcap':
* Prelfight checks failed in some cases due to differing variants of 'setcap';
not all support the '-v' option the same.
* The preflight check would actually hang in some cases (even though the actual
setcap call would not) due to sudo/PAM configuration variations.

#review-29749
#57 29666 C. Thomas Tyler Added logic to avoid applying the 'setcap' (the OOM Killer defense)
in Docker environments (e.g. for testing).

Info: Using the 'setcap' command on a binary in a Docker container renders
the binary inoperable.  Attempts to execute the binary result in
an 'Operation not permitted' error. The workaround: Don't use 'setcap' on
binaries in a Docker container.

#review-29667
#56 29665 C. Thomas Tyler Tweaked logic to ensure schema upgrades are done (i.e.
'p4d -xu) even if
the live running p4d is older than the binary on the disk, even if the
binary on the disk did not need to be updated.

This completes a dev branch change started in @29659.
#55 29659 C. Thomas Tyler Fixed upgrade.sh issue with outer-to-inner upgrades with NFS on inner server.

In an environment where /hxdepots (and thus /p4/common) is shared via NFS, an
upgrade on the outer server will confuse the upgrade.sh script into thinking
that the inner server has already been upgraded, and that only a patch update
rather than a major version update (requiring p4d -xu) is needed.  So the
'p4d -xu' step is skipped, resulting in a failed service start.

This change fixes that.

In the case of a new binary being in place on disk, and linked to with the
usual SDP symlinks, but having a major version that the differs with the live
running p4d binary, a message is displayed something like:

  The live running p4d binary will be restarted to update from 2021.1.2179737 to 2021.2.2410559.
  A major version upgrade for the live running p4d is needed. A schema upgrade will be performed.

#review-29660
#54 29640 C. Thomas Tyler In upgrade.sh, refined preflight check for 'sudo setcap' ability.

#review-29641
#53 29607 C. Thomas Tyler Refined logic for applying setcap to handle a wider array scenarios
with respect to sudo access not being available or possibly not
being verifiable.
#52 29606 C. Thomas Tyler Added override to skip preflight checks to ensure sudo access.
#51 29604 C. Thomas Tyler Added support for p4d r23.1 upgrades.

This adds a call to 'sudo setcap' per the P4D 2023.1 release notes.
Several preflight checks are done to verify the needed sudo access is
available to do 'sudo setcap'. If no such access is available, an
error message is displayed, and we abort in the preflight phase.

The code for the sudo preflight checks avoids a password prompt/hang
from 'sudo'.

#review-29605 @brent_schiestl @jason_gibson
#50 28645 Domenic Updates to upgrade.sh.
1. Move sourcing of p4_vars values before $Log definition so that the instance's log path is used rather than always writing to /tmp. This aligns with the help info for the -L flag.

2. Expose the path to $TmpFile_1 as part of the 'p4 upgrades' step so users easily know where to go look if the process is taking longer than they'd expect rather.

3. Correct some misspellings.
#49 28494 Robert Cowham Fix indentation of -man comments.
#48 28473 C. Thomas Tyler Fixed typo in script docs for upgrade.sh.
Non-functional change.
#47 28228 C. Thomas Tyler Tweak to avoid erroneous error message when a service such as p4broker
is not running and its binary does not need to be updated.
#46 28199 C. Thomas Tyler Added hooks for executing custom pre- and post- upgrade scripts.

This will enable Helix Management System (HMS) centrally orchestrated
upgrades to be integrated into vanilla SDP upgrades.
#45 28158 C. Thomas Tyler Made former '-n' preview mode the default behavior.
Added new '-y' flag to execute a real upgrade.

Added a message in preview mode to clarify that no actual
upgrade is performed.

Removed the '-n' preview option, as preview mode is now the
default behavior.

#review-28159
#44 28139 C. Thomas Tyler upgrade.sh v4.7.0:
Added '-Od' option to override restriction on doing downgrades.

It is needed to upgrade from internal PREP-TEST upgrades.
#43 27750 C. Thomas Tyler upgrade.sh v4.6.9:
* Fixed issue where where patch-only upgrades of instances after the first
in a multi-instance environment are skipped.
* Corrected error message for scenario where downgrades are attempted; the
logic was correct but error message was confusing.

verify_sdp.sh v5.17.3:
* Extended '-skip version' meaning to also skip new live binary version
comparison checks.

Related updates:
* A call to verify_sdp.sh in the switch_db_files() function in backup_functions.sh
now skips the version check.
* A call to daily_checkpoint.sh now skips the version check.

#review-27743
#42 27722 C. Thomas Tyler Refinements to @27712:
* Resolved one out-of-date file (verify_sdp.sh).
* Added missing adoc file for which HTML file had a change (WorkflowEnforcementTriggers.adoc).
* Updated revdate/revnumber in *.adoc files.
* Additional content updates in Server/Unix/p4/common/etc/cron.d/ReadMe.md.
* Bumped version numbers on scripts with Version= def'n.
* Generated HTML, PDF, and doc/gen files:
  - Most HTML and all PDF are generated using Makefiles that call an AsciiDoc utility.
  - HTML for Perl scripts is generated with pod2html.
  - doc/gen/*.man.txt files are generated with .../tools/gen_script_man_pages.sh.

#review-27712
#41 27708 C. Thomas Tyler Fixed typo in output; non-functional change.
#40 27455 C. Thomas Tyler Normalized usage of calls to verify_sdp.sh from other scripts.

In some contexts, we may desire "squeaky clean," while in other
contexts we may only need assurance that core functions are
operating OK.

Fixed typo in variable name used by verify_sdp.sh in call from
upgrade.sh that prevented local VERIFY_SDP_SKIP_TEST_LIST def'n
from having any effect.
#39 27347 C. Thomas Tyler upgrade.sh v4.6.5: Refined logic and doc for 'to-or-thru' 2019.1 upgrades.

The logic to implicitly disable online upgrades for 'to-or-thru'
P4D 2019.1 upgrades now only applies if not on the master server.
The master server will still be started after unless the '-M'
option is used to specifically request a manual upgrade option.

Also added doc content re: planning for ugprades.
#38 27346 C. Thomas Tyler Accounted for VERIFY_SDP_SKIP_TEST_LIST possibly being set.
#37 27345 C. Thomas Tyler Fixed typo in message.
#36 27344 C. Thomas Tyler Tweak '-M' to skip online verify check.
Fixed bug with version identification.
#35 27343 C. Thomas Tyler Reset error count with -I.
#34 27342 C. Thomas Tyler Added '-M' option for manual processing.
#33 27341 C. Thomas Tyler Completed '-I' flag.
#32 27340 C. Thomas Tyler Added -I flag.
#31 27339 C. Thomas Tyler New upgrade.sh able to handle outer-to-inner for upgrades
starting from a pre-2019.1 start point going 'to-or-thru'
2019.1.
#30 27216 C. Thomas Tyler Non-functional change: Fixed a common doc type:
paramter -> parameter
#29 27210 C. Thomas Tyler upgrade.sh v4.3.2: Spellcheck and shellcheck.
#28 27209 C. Thomas Tyler Refined message indicating why phases 3 and 5 might be skipped.
#27 27207 C. Thomas Tyler upgrade.sh v4.3.0:
* Greatly enhanced documentation and examples.
* Before doing second journal rotation:
  - Added wait for 'p4 storage -w' (for 'to or thru' P4D 2019.1).
  - Added wait for 'p4 upgrades|grep -v completed' (for P4D 2020.2+)
* Added check for whether p4broker and p4p were online at the start
of upgrade processing. Only start those services that were running at
the beginning of processing are now started after the binaries and
symlinks are updated.  For the broker, only the broker with the default
configuration is stopped and started; DFM brokers are ignored by this
script (thus making this script compaitble with using DFM brokers).
* Fixed bug where '-c' (Protections table comment conversion) would
have failed due to 'p4d' addition of 'Update:' field to the Protections
table. Also generally enhanced logic to convert Protections table
comments.
* Added support for operation on proxy-only and broker-only hosts.
Processing of upgrades for p4d occur only if /p4/N/bin/p4d_N_init
script exists on the machine.
* Refined lexigraphical P4D version comparsion checks.

verify_sdp.sh v5.12.0:
* Added support for proxy-only and broker-only hosts.  The
existence of a *_init script in the instance bin dir for any of the
Helix server binaries p4d/p4p/p4broker indicate they are configured,
determining what tests are executed or skipped.
* Added check_file_x() function to check for execute bit on files.

In backup_functions.sh, fixed is_server_up() to avoid displaying
output.

#review-27208
#26 27022 C. Thomas Tyler Changed 'exes' to 'helix_binaries' in folder and script name, per review.
#25 26989 C. Thomas Tyler Fixed issue where initial commnad line wasn't displayed correctly.
#24 26982 C. Thomas Tyler mkdirs.sh v4.1.0:
* Accounted for directory structure change of Maintenance to Unsupported.
* Added standard command line processing with '-h' and '-man' doc flags,
and other flags (all documented).
* Added in-code docs and updated AsciiDoc.
* Enhanced '-test' mode to simulate /hx* mounts.
* Enhanced preflight testing, and fixed '-test' mode installs.
* Added support for installing to an alternate root directory.
* Added '-s <ServerID>' option to override REPLICA_ID.
* Added '-S <TargetServerID>' used for replicas of edge servers.
* Added '-t <server_type>' option to override SERVER_TYPE.
* Added '-M' option to override mount points.
* Added '-f' fast option to skip big chown/chmod commands, and
moved those commands near the end as well.

verify_sdp.sh v5.9.0:
* Added check for /p4/Version file, and checked that other legacy
SDP methods of checking version
* Added sanity check for crontab.
* Added 'test skip' mechanism to skip certain tests:
 - crontab: Skip crontab check. Use this if you do not expect crontab to be configured, perhaps if a different scheduler is used.
 - license: Skip license related checks.
 - version: Skip version checks.
 - excess: Skip checks for excess copies of p4d/p4p/p4broker in PATH.
* Added VERIFY_SDP_SKIP_TEST_LIST setting ton instance_vars.template,
to define a standard way to have verify_sdp.sh always skip certain
tests for a site.
* Extended '-online' checks to check for bogus P4MASTERPORT, a common
config error.

Update test_SDP.py:
* Adjusted test suite to account for various changes in mkdirs.sh.
* Added 'dir' parameter to run_cmd() and sudo_cmd(), to run a
command from a specified directory (as required to test new
mkdirs.sh)
* Added check_links() similar to existing check_dirs() function.

=== Upgrade Process Changes ===

Made /p4/common/bin/p4d/p4/p4broker/p4p shell script rather than binary.

This changes the way SDP new binaries are staged for upgrade.  For
safety, exes are now staged to a director outside the PATH, the
/p4/sdp/exes folder. A new 'get_latest_exes.sh' script simplifies
the task of pulling executables from the Perforce FTP server. This
can be used 'as is' for environments with outbound internet access,
and is useful in any case to describe now to acquire binaries.

This addresses an issue where a p4d binary staged for a future
upgrade might be called before the actual upgrade is performed.

upgrade.sh v4.0.0:
* All preflight checks are now done first. Added '-p' to abort after preflight.
* Added '-n' to show what would be done before anything is executed.
* Minimalist logic to start/stop only servers that are upgrade, and apply
upgrades only as needed.
* Staging of exes for upgrade is now separate from /p4/common/bin
* Improved in-code docs, added '-h' and '-man' options.
* Retained pre/post P4D 2019.1 upgrade logic.
#23 26810 C. Thomas Tyler Fixed typo in comment; non-user visible change that doesn't affect behavior.
#22 26400 C. Thomas Tyler Added refresh_P4ROOT_from_offline_db.sh.

Updated backup_functions.sh to support functionality for db refresh.

Upgrade start_p4d() and stop_p4d() to use systemd if available, else
use the underlying SysV init scripts.

Updated verify_sdp.sh to be called from other scripts (sans
its own logging).  Added many checks to verify_sdp.sh to
support P4ROOT/offline_db swap.

Logic in P4ROOT/offline_db swap is more careful about what gets
swapped.

Added start_p4broker() and stop_p4broker() that behave similarly.

More shellcheck compliance.

#review-26401
#21 25590 Robert Cowham Avoid attempting to start p4broker if not configured.
Tweak messaging
#20 25575 Robert Cowham Updates to SDP and tests for 19.1 upgrades

#review @tom_tyler
#19 25555 Robert Cowham Handle new 19.1 upgrade.sh requirements
#18 24096 C. Thomas Tyler Enhanced upgrade.sh to incorporate a call to:
p4 protect --convert-p4admin-comments

This upgrades the format of comments in the protections table to a version
compatible with newer versions of P4Admin.
#17 24092 C. Thomas Tyler Adjusted user message indicating how long the operation might take.
#16 23297 C. Thomas Tyler Added safety checks to avoid running commands that will certainly fail
in upgrade.sh.

Generally, /p4/common/bin will be the same on all hosts in a Helix topolgy.
However, on any given machine, the /p4/<N>/bin/<EXE>_<N>_init scripts
should exist only for executables that run on that machine.

This change to upgrade.sh should work on machines even where only a
proxy or broker runs.  Also, it will not generate errors in cases
where there is, say, a p4p_N_bin symlink in /p4/common/bin but no
/p4/N/bin/p4p_N_init script, which will a common situation since
/p4/common/bin will contain all executables used anywhere, while
/p4/N/bin is host-specific.

Also made cosmetic fixes and style convergence change.

In dump_edge.sh and recover_edge_dump.sh, just fixed cosmetic typos.
#15 23031 C. Thomas Tyler Simplified stop_p4d() in backup functions to just call the init
script.  Previously stop_p4d() had 'wait' logic to wait for p4d
to stop before trying to stop with a 'kill' signal, but this is
no longer needed since the modern init script (with logic in
p4d_base) now does a 'kill' anyway, and also has the 'wait' logic
and will exit only when p4d is well and truly down.

In upgrade.sh, fixed issue where start/stop of p4broker and p4p
went directly to the screen instead of the log.  Also changed to
call start/stop init scripts for p4d directly, just as for other
services.

Also enhanced upgrade.sh logging:
* Log file name to incorporate SDP instance (redundant but nice).
* Remove pesky ':' characters from the datestamp in log file name,
as ':' chars in file names wreak havoc with 'scp' commands and
require escaping on the command line.
* Added log comments indicating which databases are being upgraded
($P4ROOT and $OFFLINE_DB).

Also added common explaining use of '-t' flag in 'p4d -xu'
call for offline databases.
#14 21433 Russell C. Jackson (Rusty) Fixed a bug in upgrade.sh introduced when truncate journal was changed to use p4 admin journal.
#13 20749 C. Thomas Tyler Approved and committed, but I believe that the shared data setting is always set to false on the master and we should look at fixing that in another change.

Enhanced p4login again.

Improvements:
Default behavior with no arguments gives the desired results.
For example, if run on a master, we login on the super user P4USER to
P4PORT.  If run on a replica/edge and auth.id is set, we login P4USER
to the P4TARGET port of the replica.

All other login functionality, such as logging in the replication
service user on a replica, logging in supplemental automation users,
is now accessed via new flags.

A usage message is now available via '-h' and '-man' options.  The
new synopsys is:
p4login [<instance>] [-p <port> | -service] [-automation] [-all]

The <instance> parameter is the only non-flag positional parameter,
and can be ommitted if SDP_INSTANCE is already defined (as is typical
when called by scripts).

With this change, several other scripts calling either the 'p4login'
script or 'p4 login' commands were normalized to call p4login as
appropriate given the new usage.

Reviewer Note:  Review p4login first, then other files.  Most changes
are in p4login.

In other scripts callling p4login, calls similar to:
$P4BIN -u $P4USER -p $P4PORT login < /path/to/pwd
are replaced with: $P4CBIN/p4login

In other scritps calling p4login, calls similar to:
$P4BIN -p $P4MASTERPORT login < /path/to/pwd
are replaced with: $P4CBIN/p4login -p $P4MASTERPORT

Note that, if auth.id is set, calling 'p4login' actually has the
same behavior as 'p4login -p $P4MASTERPORT', since p4login
called on a replica with auth.id set will just login to the master
port anyway.

Depending on intent, sometimes $P4BIN/p4login -service
is used.

== Misc Cleanup ==

In doing the cleanup:
* Fixed a hard-coding-to-instance-1 bug in broker_rotate.sh.
* Fixed an inconsistency in recreate_db_sync_replica.sh, where
it did just a regular login rather than a login -a as done in other
places for (for compatibility with some multi-interface NIC card
configs).

== p4login Call Normalization ==
Code cleanup was done to normalize calls to p4login, such that:
1) the call starts with $P4CBIN/p4login (not the hard-coded path),
and 2) logic to redirect sdtout/stderr to /dev/null was removed,
since it's not necessary with p4login.  (And if p4login ever
does generate any unwanted output, we only fix it in one place).

== Tweak to instance_vars.template ==
This change includes a tweak to set P4MASTERPORT dynamically
on a replica to ensure the value precisely matches P4TARGET
for the given replica.  This will reduce a source of problems
when SSL is used, as it is particularly sensitive to the precise
P4PORT values used, and will also help for environments which
have not yet set auth.id.  If the port cannot be determined
dynamically, we fall back to the old logic using the assigned
value.

== Tweak to SDP_ALWAYS_LOGIN behavior ==
This used to default to 1, now it defaults to 0.  At this
point we should no longer need to force logins, and in fact
doing so can get into a 'p4 login' hang situation with
auth.id set.  Best to avoid unnecessary logins if we
already have a valid ticket.  (I think the need to force a
login may have gone away with p4d patches).

== Obsolete Script ==
With this change, svclogin.sh is now obsolete.  All it was doing
was a few redundant 'p4 login' commands followed by a call to
p4login anyway.

== Testing ==
Our test suite doesn't fully cover this change, so additional
manual testing was done in the Battle School lab environment.
#12 20460 C. Thomas Tyler This files was supposed to go along for the ride when @20448 was submitted.
This is part of that change, and also adds p4p support.
#11 19406 Russell C. Jackson (Rusty) Add -t localhost:1666 to offline_db upgrade to avoid license check in 2016.1
#10 18587 Russell C. Jackson (Rusty) Reworked the log rotation stuff in backup_functions.sh to make it cleaner and
handle the new log from recreate_offline_db.sh.

Modified recreate_offline_db.sh to add comments about a bad checkpoint. Also
made it create its own log file since it isn't doing a checkpoint. Removed the
log rotation for the same reason.

Moved the LOGFILE setting out to all of scripts to make it more obvious for future
scripts that you need to set that variable in your script so that it doesn't just
default to checkpoint.log.

Moved the functions in weekly_backup.sh and recreate_offline_db.sh into backup_functions.sh
where they belong for consistency.

Modified backup_functions.sh to use a consistent naming convention for all the
rotated log files rather than checkpoint.log being unique.

Replaced all back ticks with the newer bash $() method.

Removed all of the line wrapping since I am pretty sure that none of us are working on an
80 character terminal these days and it is easier to read this way.
#9 16563 C. Thomas Tyler Routine Merge Down to dev from main using:
p4 merge -b perforce_software-sdp-dev
p4 resolve -as
#8 16029 C. Thomas Tyler Routine merge to dev from main using:
p4 merge -b perforce_software-sdp-dev
#7 15778 C. Thomas Tyler Routine Merge Down to dev from main.
#6 15374 adrian_waters - Ensure backup scripts are run as the OSUSER (to prevent accidental running as root); 
- in scripts where LOGFILE value is changed from the 'checkpoint.log'  set by set_vars, ensure the new assignment is before check_dirs is called, otherwise errors could be written to the 'wrong' log
- in 'die()' - detect if running from terminal & also send output to stderr
#5 13906 C. Thomas Tyler Normalized P4INSTANCE to SDP_INSTANCE to get Unix/Windows
implementations in sync.

Reasons:
1. Things that interact with SDP in both Unix and Windows
environments shoudn't have to account for this obscure
SDP difference between Unix and Windows.  (I came across
this doing CBD work).

2. The Windows and Unix scripts have different variable
names for defining the same concept, the SDP instance.
Unix uses P4INSTANCE, while Windows uses SDP_INSTANCE.

3. This instance tag, a data set identifier, is an SDP concept.
I prefer the SDP_INSTANCE name over P4INSTANCE, so I prpose
to normalize to SDP_INSTANCE.

4. The P4INSTANCE name makes it look like a setting that might be
recognized by the p4d itself, which it is not.  (There are other
such things such as P4SERVER that could perhaps be renamed as
a separate task; but I'm not sure we want to totally disallow
the P4 prefix for variable names. It looks too right to be wrong
in same cases, like P4BIN and P4DBIN.  That's a discussion for
another day, outside the scope of this task).

Meanwhile:
* Fixed a bug in the Windows 2013.3 upgrade script that
was referencing undefined P4INSTANCE, as the Windows
environment defined only SDP_INSTANCE.

* Had P4INSTANCE been removed completely, this change would
likely cause trouble for users doing updates for existing
SDP installations.  So, though it involves slight technical debt,
I opted to keep a redundant definition of P4INSTANCE
in p4_vars.template, with comments indicating SDP_INSTANCE should be
used in favor of P4INSTANCE, with a warning that P4INSTANCE
may go away in a future release.  This should avoid unnecessary
upgrade pain.

* In mkdirs.sh, the varialbe name was INSTANCE rather than
SDP_INSTANCE.  I changed that as well.  That required manual
change rather than sub/replace to avoid corrupting other similar
varialbe names (e.g.  MASTERINSTANCE).

This is a trivial change technically (a substitute/replace, plus
tweaks in p4_vars.template), but impacts many files.
#4 12169 Russell C. Jackson (Rusty) Updated copyright date to 2015

 Updated shell scripts to require an instance parameter to eliminate the need
 for calling p4master_run.    Python and Perl still need it since you have to set the
environment for them to run in.

 Incorporated comments from reviewers. Left the . instead of source as that seems
more common in the field and has the same functionality.
#3 11485 Russell C. Jackson (Rusty) Brought over changes from RCJ sdp to properly handle Edge servers
 and to properly replicate shelves when replicating from Windows to Linux
#2 11463 Russell C. Jackson (Rusty) Updated dev to prepare for Summit agreed changes.
#1 10638 C. Thomas Tyler Populate perforce_software-sdp-dev.
//guest/perforce_software/sdp/main/Server/Unix/p4/common/bin/upgrade.sh
#1 10148 C. Thomas Tyler Promoted the Perforce Server Deployment Package to The Workshop.