File post_start_cleanup.sh of Package venv-salt-minion

#!/bin/bash
#
# This script performs a cleanup of the prev_env Salt Bundle environment
# that is created during a Salt Bundle upgrade.
#
# In case the script is triggered having WAIT_IF_SALT_JOBS env defined
# then it will wait until there is no active Salt jobs running on the system
# to perform the cleanup of the old environment.
#
# The script is triggered automatically via different ways:
#
#   1. As part of the Salt Highstate (via services.salt-minion).
#   2. By venv-salt-minion-postinstall.service, 60 seconds after a Salt Bundle upgrade.
#   3. By spec file during package installation/upgrade/removal.
#
# Expected execution behavior:
#
# - If there is no old environment detected -> Do nothing.
# - If an old environment is found:
#   a) If WAIT_IF_SALT_JOBS env is NOT present -> Perform the cleanup.
#   b) If WAIT_IF_SALT_JOBS env is present -> Wait until there are no
#      other Salt jobs running to perform the cleanup.
#
# NOTE: In transactional systems, nothing is done when not running in a transaction.
#
# CAUTION: Do not call this script within a Salt execution and passing
#          the WAIT_IF_SALT_JOBS env, as it will produce the script to
#          go into an infinite loop.
#

if builtin type -P transactional-update &> /dev/null && [ "$TRANSACTIONAL_UPDATE" != "true" ]; then
  # Do not clean previous environment on T-U systems when not in transaction
  exit 0
fi

if [ -d "VENV_LOCATION_PLACEHOLDER/lib/prev_env" ] || [ -L "VENV_LOCATION_PLACEHOLDER/lib/PLACEHOLDER" ]; then
    while [ "${WAIT_IF_SALT_JOBS}" ]; do
        echo "Checking for active Salt jobs..."
        JOBS_RUNNING=$(venv-salt-call --local --output=json saltutil.running | grep '"jid":' | wc -l)
        if [ $JOBS_RUNNING -gt 0 ]; then
            echo "Found active Salt jobs! Waiting 10 seconds..."
            sleep 10
        else
            echo "No active Salt Jobs! Cleaning up the old environment..."
            break
        fi
    done
fi

if [ -d "VENV_LOCATION_PLACEHOLDER/lib/prev_env" ]; then
    echo "Removing VENV_LOCATION_PLACEHOLDER/lib/prev_env"
    rm -r "VENV_LOCATION_PLACEHOLDER/lib/prev_env" || :
fi
if [ -L "VENV_LOCATION_PLACEHOLDER/lib/PLACEHOLDER" ]; then
    echo "Unlinking VENV_LOCATION_PLACEHOLDER/lib/PLACEHOLDER"
    unlink "VENV_LOCATION_PLACEHOLDER/lib/PLACEHOLDER" || :
fi
openSUSE Build Service is sponsored by