diff --git a/README.md b/README.md index 5a6844f7b..a1bff9a1d 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,19 @@ The application is then available at http://localhost:8080. All images, settings The images run on `linux/amd64` and `linux/arm64` and are rebuilt every night, so a tag such as `8.5` gets new images daily. To pin an image, see [Platforms and updates](docs/README.md#platforms-and-updates). +Cron jobs need no image build either: set one `CRONJOB_` variable per job, with the time, the user and the command. The jobs get the environment variables of the container. This works on Debian and Alpine, see [Cron jobs](docs/customization.md#cron-jobs): + +```yaml +services: + app: + image: webdevops/php-nginx:8.5 + volumes: + - ./:/app + environment: + # every 5 minutes, as the user application + CRONJOB_CLEANUP: "*/5 * * * * application /usr/local/bin/php /app/bin/console app:cleanup" +``` + ## Communication and support Found a bug or have a question? Write an issue in our [GitHub repository](https://github.com/webdevops/Dockerfile/issues). Problems we already know about are listed in [Known issues](docs/known-issues.md). diff --git a/ci/image-tests/Checks/ContainerEnvironmentChecks.php b/ci/image-tests/Checks/ContainerEnvironmentChecks.php index 798c89a91..57e35d927 100644 --- a/ci/image-tests/Checks/ContainerEnvironmentChecks.php +++ b/ci/image-tests/Checks/ContainerEnvironmentChecks.php @@ -6,20 +6,25 @@ use DateTimeImmutable; use DateTimeZone; +use PHPUnit\Framework\Attributes\DataProvider; use Webdevops\Build\ImageTests\ImageTestCase; use function abs; use function end; +use function escapeshellarg; use function in_array; use function preg_match_all; use function sprintf; +use function strtoupper; +use function substr_count; use function time; use function trim; /** * TZ, LOG_STDOUT and LOG_STDERR in the environment container, see docs/environment-variables.md#container and * docs/customization.md#time-zone. What the web servers write to the log files is checked by NginxEnvironmentChecks - * and ApacheEnvironmentChecks. + * and ApacheEnvironmentChecks. The CRONJOB_ variables in containers of their own, see + * docs/customization.md#cron-jobs. * * @phpstan-require-extends ImageTestCase */ @@ -27,6 +32,25 @@ trait ContainerEnvironmentChecks { private const string NO_CRON = 'The image does not start cron.'; + /** The time and user of a cron job that runs every minute as nobody */ + private const string EVERY_MINUTE_AS_NOBODY = '* * * * * nobody '; + + /** + * The command of the job of CRONJOB_IMAGETEST in testCronjobVariablesAreWrittenAnewAtEveryStart(), and that of a + * job that docker-cronjob adds there, as in an image built with it. + */ + private const string CRONJOB_VARIABLE_COMMAND = 'echo image-test-variable'; + + private const string CRONJOB_BUILD_COMMAND = 'echo image-test-build'; + + /** + * The value of IMAGE_TEST_VALUE in testCronJobsGetTheVariablesOfTheContainer(), with spaces, quotes and a dollar + * sign, and the start of the names of the files its jobs write. + */ + private const string CRON_ENVIRONMENT_VALUE = 'a b "c" $d'; + + private const string CRON_ENVIRONMENT_FILE = '/tmp/image-test-cron-environment-'; + /** * TZ=Europe/Berlin: date shows the time zone, and supervisord writes local time to the container log. */ @@ -135,4 +159,124 @@ public function testLogFilesFromTheEnvironment(): void self::assertSame(static::ENVIRONMENT['LOG_STDOUT'] . "\n", $this->stdout('readlink /docker.stdout', $container)); self::assertSame(static::ENVIRONMENT['LOG_STDERR'] . "\n", $this->stdout('readlink /docker.stderr', $container)); } + + /** + * CRONJOB_: cron runs the job of the variable as its user, and its output reaches the container log: on + * Alpine from crond through supervisord, on Debian through docker-cronjob-shell and syslog-ng, where it runs. The + * job writes the line in upper case, so it differs from its command, which cron logs. + */ + public function testCronRunsTheJobOfACronjobVariableAsItsUser(): void + { + $container = $this->startTestContainer('cronjob-variable', [ + 'CRONJOB_IMAGETEST' => '* * * * * nobody id -un > /tmp/image-test-cronjob-variable; echo image-test-cronjob-output | tr a-z A-Z', + ]); + // cron runs the job at the start of the next minute + $this->waitFor(function () use ($container): void { + self::assertSame("nobody\n", $this->execute('cat /tmp/image-test-cronjob-variable 2>&1', $container)->stdout); + }, 30, 3); + if (self::image()->isAlpine() || in_array('syslog', self::services(), true)) { + $this->waitFor(function () use ($container): void { + self::assertMatchesRegularExpression('/IMAGE-TEST-CRONJOB-OUTPUT$/m', $container->logs()); + }, 5); + } + } + + /** + * CRONJOB_: the entrypoint writes the jobs of the variables anew at every start. After a restart the job is + * there once, next to a job that docker-cronjob added; without the variable it is gone, the other job stays. Cron + * switched off with docker-service disable cron is switched on again at the start, for the job. + */ + public function testCronjobVariablesAreWrittenAnewAtEveryStart(): void + { + $container = $this->startTestContainer('cronjob-restart', [ + 'CRONJOB_IMAGETEST' => self::EVERY_MINUTE_AS_NOBODY . self::CRONJOB_VARIABLE_COMMAND, + ]); + $this->assertCommandSucceeds('docker-cronjob ' . escapeshellarg(self::EVERY_MINUTE_AS_NOBODY . self::CRONJOB_BUILD_COMMAND), $container); + $this->assertCommandSucceeds('docker-service disable cron', $container); + // Debian: a file for the variables, one for docker-cronjob; Alpine: the crontab of the user + $crontabs = self::image()->isAlpine() + ? '/etc/crontabs/nobody' + : '/etc/cron.d/webdevops-environment /etc/cron.d/webdevops-docker'; + + $container->restart(); + self::assertStringContainsString('Enabling cron for the jobs of the CRONJOB_* variables', $container->logs()); + $this->waitFor(function () use ($container): void { + $result = $this->execute('docker-service check cron', $container); + self::assertStringContainsString('ok', $result->stdout, $result->describe()); + self::assertSame(0, $result->exitCode, $result->describe()); + }, 5); + + $jobs = $this->stdout('cat ' . $crontabs, $container); + self::assertSame(1, substr_count($jobs, self::CRONJOB_VARIABLE_COMMAND), $jobs); + self::assertSame(1, substr_count($jobs, self::CRONJOB_BUILD_COMMAND), $jobs); + + // as at a start without the variable + $this->assertCommandSucceeds('env -u CRONJOB_IMAGETEST docker-cronjob --environment', $container); + $jobs = $this->execute('cat ' . $crontabs . ' 2>/dev/null', $container)->stdout; + self::assertSame(0, substr_count($jobs, self::CRONJOB_VARIABLE_COMMAND), $jobs); + self::assertSame(1, substr_count($jobs, self::CRONJOB_BUILD_COMMAND), $jobs); + } + + /** + * Cron jobs get the variables of the container, with their values as set, and its PATH: the jobs of CRONJOB_ + * as nobody and, where the image has the user, as application, and a job that docker-cronjob adds, as in an image + * built with it. Cron in Debian passes none of them on by itself. + */ + public function testCronJobsGetTheVariablesOfTheContainer(): void + { + $users = $this->execute('id -u application')->exitCode === 0 ? ['nobody', 'application'] : ['nobody']; + $environment = ['IMAGE_TEST_VALUE' => self::CRON_ENVIRONMENT_VALUE]; + foreach ($users as $user) { + $environment['CRONJOB_IMAGETEST_' . strtoupper($user)] = '* * * * * ' . $user . ' ' . self::cronEnvironmentCommand($user); + } + + $container = $this->startTestContainer('cronjob-environment', $environment); + // cron starts again with the job, as in an image built with it + $this->assertCommandSucceeds('docker-cronjob ' . escapeshellarg(self::EVERY_MINUTE_AS_NOBODY . self::cronEnvironmentCommand('docker-cronjob')) . ' && docker-service restart cron', $container); + $expected = self::CRON_ENVIRONMENT_VALUE . "\n" . $this->stdout('printenv PATH', $container); + foreach ([...$users, 'docker-cronjob'] as $name) { + // cron runs the jobs at the start of the next minute + $this->waitFor(function () use ($container, $name, $expected): void { + self::assertSame($expected, $this->execute('cat ' . self::CRON_ENVIRONMENT_FILE . $name . ' 2>&1', $container)->stdout, 'the job of ' . $name); + }, 30, 3); + } + } + + /** + * The command of a job that writes the value of IMAGE_TEST_VALUE and its PATH into the file of $name. + */ + private static function cronEnvironmentCommand(string $name): string + { + return sprintf('printenv IMAGE_TEST_VALUE > %1$s; echo "$PATH" >> %1$s', self::CRON_ENVIRONMENT_FILE . $name); + } + + /** + * Values of CRONJOB_ that are not a job cron would run: not a job at all, a user that does not exist, a time + * out of range, an unknown keyword. + * + * @return array + */ + public static function invalidCronjobVariables(): array + { + return self::cases([ + 'not a job', + '* * * * * image-test-nobody true', + '0 24 * * * nobody true', + '@dayly nobody true', + ]); + } + + /** + * CRONJOB_ with a value that is not a job: the entrypoint fails with an error that names the variable, and + * the command does not run. With a command that exits, so that the test does not wait for supervisord where the + * variable has no effect. + */ + #[DataProvider('invalidCronjobVariables')] + public function testInvalidCronjobVariableStopsTheContainer(string $value): void + { + $result = $this->runContainer(['root', 'echo', 'image-test-started'], ['CRONJOB_BROKEN' => $value]); + self::assertSame(1, $result->exitCode, $result->describe()); + self::assertStringContainsString('[ERROR] CRONJOB_BROKEN: ', $result->stderr, $result->describe()); + self::assertStringNotContainsString('image-test-started', $result->stdout, $result->describe()); + } } diff --git a/ci/image-tests/Docker/Container.php b/ci/image-tests/Docker/Container.php index 2ac299d76..bfeeb3718 100644 --- a/ci/image-tests/Docker/Container.php +++ b/ci/image-tests/Docker/Container.php @@ -99,6 +99,16 @@ public static function run(string $image, array $directories, array $labels, arr } } + /** + * Restarts the container with docker restart, as Docker does after a restart of the daemon, and returns once the + * entrypoint has run its scripts again and has started the command. + */ + public function restart(): void + { + self::docker(['restart', $this->id]); + $this->waitForEntrypoint(); + } + /** * Whether the container still runs, i.e. its command has not exited. */ diff --git a/docker/php/8.2-alpine/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.2-alpine/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.2-alpine/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob b/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.2-alpine/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.2-alpine/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.2-alpine/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.2-alpine/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.2/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.2/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.2/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.2/conf/bin/usr-bin/docker-cronjob b/docker/php/8.2/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.2/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.2/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.2/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.2/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.2/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.2/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.2/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.2/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.2/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.3-alpine/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.3-alpine/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.3-alpine/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob b/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.3-alpine/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.3-alpine/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.3-alpine/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.3-alpine/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.3/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.3/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.3/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.3/conf/bin/usr-bin/docker-cronjob b/docker/php/8.3/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.3/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.3/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.3/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.3/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.3/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.3/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.3/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.3/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.3/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.4-alpine/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.4-alpine/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.4-alpine/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob b/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.4-alpine/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.4-alpine/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.4-alpine/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.4-alpine/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.4/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.4/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.4/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.4/conf/bin/usr-bin/docker-cronjob b/docker/php/8.4/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.4/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.4/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.4/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.4/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.4/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.4/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.4/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.4/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.4/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.5-alpine/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.5-alpine/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.5-alpine/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob b/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.5-alpine/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.5-alpine/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.5-alpine/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.5-alpine/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.5/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.5/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.5/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.5/conf/bin/usr-bin/docker-cronjob b/docker/php/8.5/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.5/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.5/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.5/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.5/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.5/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.5/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.5/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.5/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.5/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.6-alpine/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.6-alpine/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.6-alpine/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob b/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.6-alpine/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.6-alpine/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.6-alpine/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.6-alpine/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docker/php/8.6/conf/bin/service.d/cron.d/20-job-environment.sh b/docker/php/8.6/conf/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/docker/php/8.6/conf/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/docker/php/8.6/conf/bin/usr-bin/docker-cronjob b/docker/php/8.6/conf/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/docker/php/8.6/conf/bin/usr-bin/docker-cronjob +++ b/docker/php/8.6/conf/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/docker/php/8.6/conf/bin/usr-bin/docker-cronjob-shell b/docker/php/8.6/conf/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/docker/php/8.6/conf/bin/usr-bin/docker-cronjob-shell +++ b/docker/php/8.6/conf/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/docker/php/8.6/conf/provision/entrypoint.d/10-cronjobs.sh b/docker/php/8.6/conf/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/docker/php/8.6/conf/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi diff --git a/docs/customization.md b/docs/customization.md index c2f959ced..b311a393b 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -76,7 +76,7 @@ These commands are installed in the images. Use them in `RUN` lines of your own | `gosu ` | Runs a command as another user, for example `application` | all except `toolbox` | | `docker-service enable `, `docker-service disable `, also `docker-service-enable` and `docker-service-disable` | Enables or disables a [service](#services); enabling installs it if needed | all except `toolbox` | | `docker-healthcheck` | Checks the services of supervisord and fails when one failed, see [Healthcheck](#healthcheck) | all except `toolbox` | -| `docker-cronjob ''` | Adds a [cron job](#cron-jobs) | all except `toolbox` | +| `docker-cronjob ''` | Adds a [cron job to the image](#cron-jobs-in-the-image); without a build, use the [`CRONJOB_` variables](#cron-jobs) | all except `toolbox` | | `docker-run-bootstrap` | Runs the [build scripts](#scripts-at-image-build) once and deletes them | all except `toolbox` | `apt-install` and `apk-install` are both present in every image except `toolbox`, but each only works on its own distribution. `toolbox` only stores the commands for the other images, see [Images](README.md#images). @@ -124,6 +124,8 @@ RUN docker-service disable cron When a service is enabled for the first time, `docker-service` sources `/opt/docker/provision/service.d/.sh` once; these scripts install the service. +A [`CRONJOB_` variable](#cron-jobs) switches cron on again when the container starts `supervisord`. + ### Service hooks Before a service starts, its start script sources every `*.sh` file in `/opt/docker/bin/service.d/.d/`: @@ -145,23 +147,48 @@ Options for each service are set with environment variables, see [Services](envi ## Cron jobs -`docker-cronjob` adds a cron job for each argument. Lines use the system crontab format, including the user, and cron runs the job as that user: +Add a cron job with an environment variable `CRONJOB_`, without building an image: one variable per job, with any name after `CRONJOB_`. Its value is a line of the system crontab: the time, the user and the command. Cron runs the job as that user: -```dockerfile -FROM webdevops/php:8.5 -RUN docker-cronjob '*/5 * * * * application /usr/local/bin/php /app/bin/console app:cleanup' +```yaml +services: + app: + image: webdevops/php-nginx:8.5 + volumes: + - ./:/app + environment: + # every 5 minutes, as the user application + CRONJOB_CLEANUP: "*/5 * * * * application /usr/local/bin/php /app/bin/console app:cleanup" ``` -In the Debian-based images, `docker-cronjob` adds the lines to `/etc/cron.d/webdevops-docker`. Alpine's BusyBox `crond` does not read `/etc/cron.d`, but one crontab per user in `/etc/crontabs`, without the user column, so in the Alpine images `docker-cronjob` adds each line without its user to the crontab of that user, for example `/etc/crontabs/application`. There it fails on a line that is not a job with time, user and command, for example a comment or a variable such as `MAILTO=`, and on a user that does not exist. +This works in all PHP images, Debian and Alpine. At every start, the entrypoint writes the jobs of the `CRONJOB_*` variables, sorted by name, in place of those of the last start (`docker-cronjob --environment`), so a restart does not add them twice. A variable that is empty adds no job. Each job gets a comment line with the name of its variable. The jobs go: + +- in the Debian images to `/etc/cron.d/webdevops-environment`; +- in the Alpine images, whose BusyBox `crond` reads no `/etc/cron.d` but one crontab per user, without the user column, to the end of the crontab of the user, for example `/etc/crontabs/application`, between the lines `# webdevops environment begin` and `# webdevops environment end`. The other lines of the crontab stay, for example those of [`docker-cronjob`](#cron-jobs-in-the-image). -Cron in Debian runs jobs with `PATH=/usr/bin:/bin`, which does not contain `/usr/local/bin`, so use absolute paths such as `/usr/local/bin/php`. Absolute paths work in Alpine too, whose `crond` passes on the `PATH` of the container. +The time is five fields or one of `@reboot`, `@yearly`, `@annually`, `@monthly`, `@weekly`, `@daily`, `@midnight` and `@hourly`. A field is `*`, a value, a range such as `1-5` or a list such as `0,15,30`; `*` and a range can have a step, such as `*/10` or `8-18/2`. The values: minute `0`-`59`, hour `0`-`23`, day of month `1`-`31`, month `1`-`12` or `jan`-`dec`, day of week `0`-`7` or `sun`-`sat`, where `0` and `7` are Sunday; in the Alpine images, whose `crond` does not take `7`, `0`-`6`. -The output of a job, stdout and stderr, goes to the container log: +If a variable holds no such job, or its user does not exist, the container exits at start with exit code `1` before its command runs, and the container log names the variable, for example `[ERROR] CRONJOB_CLEANUP: '24' is not a valid hour (0-23): 0 24 * * * application /usr/local/bin/php /app/bin/console app:cleanup`. Cron would not run such a job, and cron in the Debian images would not run the other jobs of the variables either: it ignores a file in `/etc/cron.d` with an error. The check also runs for one-off commands such as `docker compose run --rm app php -v`. -- In Alpine, BusyBox `crond` passes it on: stdout to the stdout of the container, stderr to its stderr. -- Cron in Debian would mail it, and discard it where no mail server is installed. So `docker-cronjob` begins `/etc/cron.d/webdevops-docker` with `SHELL=/usr/local/bin/docker-cronjob-shell`: cron runs each job with this script, which runs the command with `/bin/sh` and sends both outputs to syslog, a message per line and per 1 KiB of a longer line. They reach the stdout of the container, or the file of `LOG_STDOUT`, as `[SYSLOG] cron-job[]: `; the exit code stays that of the command. Without syslog-ng, for example after `docker-service disable syslog`, the output stays with cron. +Where `docker-service disable cron` switched cron off, a `CRONJOB_*` variable switches it on again when the container starts `supervisord`, its default command; the container log then says `Enabling cron for the jobs of the CRONJOB_* variables`. + +The jobs of the variables and of [`docker-cronjob`](#cron-jobs-in-the-image) get the environment variables of the container, as its services get them: those of `environment` in `compose.yaml` and of `docker run -e`, and the `ENV` of the image, including its `PATH`, so `php` works without `/usr/local/bin/`. A value arrives exactly as set, also with spaces, quotes, `$`, `=` or a line break. Cron sets `HOME` and `LOGNAME` for the user of the job and `SHELL` to `/bin/sh`; `PWD`, `OLDPWD`, `SHLVL` and `_` are those of the shell of the job, not of the container. supervisord adds its own, such as `SUPERVISOR_ENABLED`. The output of the jobs, stdout and stderr, goes to the container log: + +- In the Debian images, cron itself passes no variable of the container on, and would mail the output of a job, and discard it where no mail server is installed. So `/etc/cron.d/webdevops-environment` and `/etc/cron.d/webdevops-docker` begin with `SHELL=/usr/local/bin/docker-cronjob-shell`, and cron runs each job with this script, as the user of the job. It adds the variables of the container, which the start script of cron writes each time cron starts into `/run/docker-cronjob/` for each user of a job in a crontab in `/etc/cron.d` with this `SHELL` line, a file that only this user and `root` can read. It runs the command with `/bin/sh` and sends both outputs to syslog, a message per line and per 1 KiB of a longer line; they reach the stdout of the container, or the file of `LOG_STDOUT`, as `[SYSLOG] cron-job[]: `, and the exit code stays that of the command. Without syslog-ng, the output stays with cron. A variable whose name is not valid in the shell, such as `php.memory_limit`, does not reach the command: `/bin/sh` drops it. +- In the Alpine images, BusyBox `crond` passes on its own variables, which are those of the container, also `php.memory_limit`, and adds `USER`. It passes the output on: stdout to the stdout of the container, stderr to its stderr. - To get the mail of cron instead, as before, add a `MAILTO` line before the jobs; it applies to the jobs below it. In Debian, for example `RUN docker-cronjob 'MAILTO=ops@example.com' '*/5 * * * * application /usr/local/bin/php /app/bin/console app:cleanup'`. `docker-cronjob-shell` then only runs the command, and cron mails its output. The mail needs a mail server, for example Postfix of the `-dev` images, see [Mail](images/php.md#mail). `MAILTO=""` turns the mail off, and the output goes to syslog. -- For a crontab file of your own, for example in `/etc/cron.d`, put the same `SHELL` line at its top; otherwise cron mails the output, see [Known issues](known-issues.md#output-of-cron-jobs-in-crontab-files-of-your-own). + +For a crontab file of your own in `/etc/cron.d`, put the same `SHELL` line at its top; otherwise cron mails the output of its jobs, and they get only the variables of cron, with `PATH=/usr/bin:/bin`, see [Known issues](known-issues.md#output-and-variables-of-cron-jobs-in-crontab-files-of-your-own). + +### Cron jobs in the image + +For jobs that belong in the image, `docker-cronjob` adds a cron job for each argument at build time, in the same format: + +```dockerfile +FROM webdevops/php:8.5 +RUN docker-cronjob '*/5 * * * * application /usr/local/bin/php /app/bin/console app:cleanup' +``` + +In the Debian-based images, `docker-cronjob` adds the lines as they are to `/etc/cron.d/webdevops-docker`, which it begins with the line `SHELL=/usr/local/bin/docker-cronjob-shell` for the [variables of the container and the output](#cron-jobs). In the Alpine images, it adds each line without its user to the crontab of that user, for example `/etc/crontabs/application`. There it fails on a line that is not a job with time, user and command, for example a comment or a variable such as `MAILTO=`, on a time that cron does not take, as above, and on a user that does not exist. ### Time zone diff --git a/docs/environment-variables.md b/docs/environment-variables.md index 2a2efbcb4..555f614b8 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -1,6 +1,6 @@ # Environment variables -The container entrypoint applies these variables every time a container starts. That includes the default `supervisord` command and one-off commands such as `docker compose run --rm app php -v`. Recreate the container after changing a value. +The container entrypoint applies these variables every time a container starts. That includes the default `supervisord` command and one-off commands such as `docker compose run --rm app php -v`. Recreate the container after changing a value. [Cron jobs](customization.md#cron-jobs) get the variables of the container too. Each section names the images it applies to. Image names are given without tag; `php-*` means `php`, `php-dev`, `php-nginx`, `php-nginx-dev`, `php-apache` and `php-apache-dev`. @@ -35,7 +35,8 @@ Images: `php-*`. | Variable | Default | Effect | | --- | --- | --- | | `CLI_SCRIPT` | not set | Command the `cli` entrypoint runs as `APPLICATION_USER`. See [Customization](customization.md#commands). | -| `LOG_STDOUT` | container stdout | File that `/docker.stdout` points to. Nginx, Apache and PHP-FPM write their access logs there, syslog-ng the messages of the services, for example of cron and Postfix, and in Debian the output of the cron jobs of `docker-cronjob`, see [Cron jobs](customization.md#cron-jobs). | +| `CRONJOB_` | not set | A cron job, one variable per job with any name after `CRONJOB_`: the time, the user and the command, for example `*/5 * * * * application /usr/local/bin/php /app/bin/console app:cleanup`. A value that is not such a job, or a user that does not exist, makes the container exit at start. Where `docker-service disable cron` switched cron off, the variable switches it on again when the container starts `supervisord`. See [Cron jobs](customization.md#cron-jobs). | +| `LOG_STDOUT` | container stdout | File that `/docker.stdout` points to. Nginx, Apache and PHP-FPM write their access logs there, syslog-ng the messages of the services, for example of cron and Postfix, and in Debian the output of the cron jobs of `docker-cronjob` and of the `CRONJOB_` variables, see [Cron jobs](customization.md#cron-jobs). | | `LOG_STDERR` | container stderr | File that `/docker.stderr` points to. Nginx and Apache write their error logs there, PHP-FPM its own messages and the errors of the PHP scripts it runs. `php.error_log` gives the PHP errors of PHP-FPM and the PHP CLI a file of their own instead, in a directory that `application` may write to, for example `/app`. | | `TZ` | not set (UTC) | Time zone of the container, for example `Europe/Berlin`. It applies to `date`, cron and the time stamps supervisord writes to the container log. PHP uses `PHP_DATE_TIMEZONE` instead, see [Time zone](customization.md#time-zone). | diff --git a/docs/images/php-apache.md b/docs/images/php-apache.md index 07bed0a71..3b743d988 100644 --- a/docs/images/php-apache.md +++ b/docs/images/php-apache.md @@ -24,7 +24,7 @@ Ports: `80` (HTTP) and `443` (HTTPS). HTTPS uses a self-signed certificate for ` ## Services -Started by default: `apache`, `php-fpm`, `cron`, `syslog`. The `-dev` variant also starts `postfix` and `ssh`. +Started by default: `apache`, `php-fpm`, `cron`, `syslog`. The `-dev` variant also starts `postfix` and `ssh`. Add cron jobs with [`CRONJOB_` variables](../customization.md#cron-jobs). ## Configuration diff --git a/docs/images/php-nginx.md b/docs/images/php-nginx.md index 5f670b4f5..30e6bb12c 100644 --- a/docs/images/php-nginx.md +++ b/docs/images/php-nginx.md @@ -24,7 +24,7 @@ Ports: `80` (HTTP) and `443` (HTTPS). HTTPS uses a self-signed certificate for ` ## Services -Started by default: `nginx`, `php-fpm`, `cron`, `syslog`. The `-dev` variant also starts `postfix` and `ssh`. +Started by default: `nginx`, `php-fpm`, `cron`, `syslog`. The `-dev` variant also starts `postfix` and `ssh`. Add cron jobs with [`CRONJOB_` variables](../customization.md#cron-jobs). ## Configuration diff --git a/docs/images/php.md b/docs/images/php.md index 6b1ea04bb..790f8ae8f 100644 --- a/docs/images/php.md +++ b/docs/images/php.md @@ -30,7 +30,7 @@ PHP-FPM listens on port `9000`. For a web server in the same container use [`php ## Services -Started by default: `php-fpm`, `cron`, `syslog`. The `-dev` variant also starts `postfix` and `ssh`. See [Customization](../customization.md#services). PHP-FPM listens on port `9000` of all IPv6 and IPv4 addresses; if the container has no IPv6, of all IPv4 addresses. +Started by default: `php-fpm`, `cron`, `syslog`. The `-dev` variant also starts `postfix` and `ssh`. See [Customization](../customization.md#services). Add cron jobs with [`CRONJOB_` variables](../customization.md#cron-jobs). PHP-FPM listens on port `9000` of all IPv6 and IPv4 addresses; if the container has no IPv6, of all IPv4 addresses. ## PHP configuration @@ -128,7 +128,7 @@ Every PHP version comes as a Debian tag (`8.5`) and an Alpine tag (`8.5-alpine`) | [Build tools for extensions](#installing-more-extensions) | included | installed by `docker-php-ext-install`; for PIE install `$PHPIZE_DEPS` | | [Locales](../customization.md#locales) | several hundred, for example `de_DE.utf8` | none | | [Installing packages](../customization.md#tools-for-your-dockerfile) | `apt-install`, from the Debian components `main`, `contrib` and `non-free` | `apk-install` | -| [`docker-cronjob`](../customization.md#cron-jobs) | adds the lines to `/etc/cron.d/webdevops-docker`; jobs run with `PATH=/usr/bin:/bin`; their output goes through syslog to the stdout of the container, or with `MAILTO` by mail | adds each line without its user to `/etc/crontabs/`; jobs run with the `PATH` of the container; their output goes to the stdout and stderr of the container | +| [Cron jobs](../customization.md#cron-jobs) | the `CRONJOB_` variables go to `/etc/cron.d/webdevops-environment`, the lines of `docker-cronjob` to `/etc/cron.d/webdevops-docker`; day of week `0`-`7`; `/usr/local/bin/docker-cronjob-shell` adds the variables of the container to the jobs, not those whose names are not valid in the shell, and sends their output through syslog to the stdout of the container, or with `MAILTO` by mail | both go without the user to `/etc/crontabs/`; day of week `0`-`6`; `crond` passes the variables of the container on, and the output to the stdout and stderr of the container | | [`docker-image-cleanup`](../customization.md#tools-for-your-dockerfile) | works | works | | [Apache index files](../environment-variables.md#web-server) in `php-apache` | `index.html`, `index.cgi`, `index.pl`, `index.php`, `index.xhtml`, `index.htm` come before `WEB_DOCUMENT_INDEX` | `index.html` comes before `WEB_DOCUMENT_INDEX` | | [`mail()` without Postfix](#mail) | fails: there is no `sendmail` command | fails: BusyBox `sendmail` finds no mail server | diff --git a/docs/known-issues.md b/docs/known-issues.md index cdb0f4877..5bba9506b 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -22,11 +22,11 @@ These options and tools are part of the images but do not work, or work only in - **Images:** `php-*` with the Debian tag `8.6`. - **Instead:** Write the repository to a file in `/etc/apt/sources.list.d/`, for example `RUN echo "deb http://deb.debian.org/debian trixie-backports main" > /etc/apt/sources.list.d/backports.list`. -### Output of cron jobs in crontab files of your own +### Output and variables of cron jobs in crontab files of your own -- **Effect:** Cron in Debian mails the output of a job. Where no mail server runs, it discards it and logs `(CRON) info (No MTA installed, discarding output)`; where Postfix runs, as in the `-dev` images, the output lands in the mailbox of the user, for example `/var/mail/application`. Only the jobs that `docker-cronjob` adds send their output to the container log, see [Cron jobs](customization.md#cron-jobs). +- **Effect:** Cron in Debian mails the output of a job. Where no mail server runs, it discards it and logs `(CRON) info (No MTA installed, discarding output)`; where Postfix runs, as in the `-dev` images, the output lands in the mailbox of the user, for example `/var/mail/application`. It also passes none of the variables of the container on: a job gets only `HOME`, `LOGNAME`, `SHELL` and `PATH=/usr/bin:/bin`. Only the jobs of `docker-cronjob` and of the `CRONJOB_` variables send their output to the container log and get the variables of the container, see [Cron jobs](customization.md#cron-jobs). - **Images:** the Debian images: `php-*` without `-alpine`. -- **Instead:** Add the jobs with `docker-cronjob`, or put `SHELL=/usr/local/bin/docker-cronjob-shell` at the top of your crontab file in `/etc/cron.d`. +- **Instead:** Add the jobs with `CRONJOB_` variables or `docker-cronjob`, or put `SHELL=/usr/local/bin/docker-cronjob-shell` at the top of your crontab file in `/etc/cron.d`. Its jobs then get the variables of the container from the next start of cron on, for example after `docker compose restart`. ### Composer 1 on PHP 8.4 to 8.6 diff --git a/provisioning/base/general/bin/service.d/cron.d/20-job-environment.sh b/provisioning/base/general/bin/service.d/cron.d/20-job-environment.sh new file mode 100644 index 000000000..e770e49c9 --- /dev/null +++ b/provisioning/base/general/bin/service.d/cron.d/20-job-environment.sh @@ -0,0 +1,4 @@ +# Debian: the variables of the container for the jobs that docker-cronjob-shell runs, written anew at every +# start of cron, after 10-init.sh has copied the crontabs of /opt/docker/etc/cron; see docs/customization.md#cron-jobs. +# BusyBox crond on Alpine passes them on by itself. +docker-cronjob --job-environment diff --git a/provisioning/base/general/bin/usr-bin/docker-cronjob b/provisioning/base/general/bin/usr-bin/docker-cronjob index 5a0a3a233..df862c31e 100644 --- a/provisioning/base/general/bin/usr-bin/docker-cronjob +++ b/provisioning/base/general/bin/usr-bin/docker-cronjob @@ -9,46 +9,325 @@ source /opt/docker/bin/config.sh rootCheck "$0" -if [[ "$#" -eq 0 ]]; then - echo "Usage: $0 ''" +function usage() { + echo "Usage: $0 '' ..." + echo " adds the jobs, e.g. in a RUN line of a Dockerfile" + echo " $0 --environment [--enable-cron]" + echo " writes the jobs of the CRONJOB_* variables in place of those of its last run; with --enable-cron," + echo " also enables cron for them where it is not enabled" + echo " $0 --job-environment" + echo " Debian: writes the variables of the container anew for the jobs, see docker-cronjob-shell" exit 1 +} + +if [[ "$#" -eq 0 ]]; then + usage fi -if [[ "$(docker-image-info family)" == "Alpine" ]]; then - # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column - for CRONJOB_LINE in "$@"; do - # time (five fields or one such as @daily), user, command - if [[ ! "$CRONJOB_LINE" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then - echo "[ERROR] Not a cron job line with the time, the user and the command: $CRONJOB_LINE" - exit 1 +IMAGE_FAMILY="$(docker-image-info family)" + +# The jobs of the CRONJOB_* variables: Debian, a file of their own; Alpine, a block in the crontab of each user +ENVIRONMENT_CRONTAB=/etc/cron.d/webdevops-environment +ENVIRONMENT_BEGIN='# webdevops environment begin' +ENVIRONMENT_END='# webdevops environment end' + +# Debian: the crontab of the jobs of docker-cronjob, and the shell of the crontabs of docker-cronjob and of +# the CRONJOB_* variables, docker-cronjob-shell: it adds the variables of the container from the file of the user of the +# job in JOB_ENVIRONMENT_DIRECTORY, which the start script of cron writes with --job-environment, and sends the output of +# the job to syslog-ng. BusyBox crond on Alpine passes its own variables on, which are those of the container, and the +# output of the jobs. +DOCKER_CRONTAB=/etc/cron.d/webdevops-docker +CRON_SHELL=/usr/local/bin/docker-cronjob-shell +JOB_ENVIRONMENT_DIRECTORY=/run/docker-cronjob + +# The five time fields: their names, lowest and highest values, and the names of their values. BusyBox crond on Alpine +# takes 0 to 6 for the day of week, cron in Debian also 7 for Sunday. +TIME_FIELDS=('minute' 'hour' 'day of month' 'month' 'day of week') +TIME_MIN=(0 0 1 1 0) +TIME_MAX=(59 23 31 12 7) +TIME_NAMES=('' '' '' 'jan feb mar apr may jun jul aug sep oct nov dec' 'sun mon tue wed thu fri sat') +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + TIME_MAX[4]=6 +fi + +### + # Whether $1 is a value of the time field with the index $2: a number in its range or, for the month and the day of + # week, a name of three letters + ## +function isTimeValue() { + local value="${1,,}" + + if [[ "$value" =~ ^[0-9]{1,2}$ ]]; then + (( 10#$value >= TIME_MIN[$2] && 10#$value <= TIME_MAX[$2] )) + else + [[ "$value" =~ ^[a-z]{3}$ && " ${TIME_NAMES[$2]} " == *" $value "* ]] + fi +} + +### + # Whether $1 is the time field with the index $2: a list of items, each *, a value or a range of values; * and a range + # may have a step, e.g. */5 or 1-30/10 + ## +function isTimeField() { + local item first last step + local -a items + + # read drops an empty last item + if [[ "$1" == *, ]]; then + return 1 + fi + + IFS=, read -r -a items <<< "$1" + for item in "${items[@]}"; do + if [[ ! "$item" =~ ^(\*|([[:alnum:]]+)(-([[:alnum:]]+))?)(/([0-9]{1,2}))?$ ]]; then + return 1 fi - CRONJOB_USER="${BASH_REMATCH[3]}" - if ! id -u "$CRONJOB_USER" > /dev/null 2>&1; then - echo "[ERROR] User '${CRONJOB_USER}' does not exist: $CRONJOB_LINE" + first="${BASH_REMATCH[2]}" + last="${BASH_REMATCH[4]}" + step="${BASH_REMATCH[6]}" + if [[ -n "$first" ]] && ! isTimeValue "$first" "$2"; then + return 1 + fi + + if [[ -n "$last" ]] && ! isTimeValue "$last" "$2"; then + return 1 + fi + + # cron in Debian takes no step of 0, nor one after a single value + if [[ -n "$step" ]] && [[ "$step" =~ ^0+$ || ( -n "$first" && -z "$last" ) ]]; then + return 1 + fi + done +} + +### + # Splits the cron job line $1 into JOB_TIME, JOB_USER and JOB_COMMAND. Fails with an error that starts with $2, e.g. + # the name of a variable, on a line that is not a job, with the time (five fields or a keyword such as @daily), the + # user and the command, on a time that cron would not take, and on a user that does not exist. + ## +function parseJob() { + local line="$1" prefix="$2" index + local -a fields + + if [[ "$line" == *$'\n'* ]] || [[ ! "$line" =~ ^[[:space:]]*(@[[:alpha:]]+|[^@#[:space:]]+([[:space:]]+[^[:space:]]+){4})[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]].*)$ ]]; then + echo "[ERROR] ${prefix}Not a cron job line with the time, the user and the command: $line" >&2 + exit 1 + fi + + JOB_TIME="${BASH_REMATCH[1]}" + JOB_USER="${BASH_REMATCH[3]}" + JOB_COMMAND="${BASH_REMATCH[4]}" + + if [[ "$JOB_TIME" == @* ]]; then + if [[ ! "$JOB_TIME" =~ ^@(reboot|yearly|annually|monthly|weekly|daily|midnight|hourly)$ ]]; then + echo "[ERROR] ${prefix}'${JOB_TIME}' is not one of @reboot, @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly: $line" >&2 exit 1 fi + else + read -r -a fields <<< "$JOB_TIME" + for index in "${!fields[@]}"; do + if ! isTimeField "${fields[index]}" "$index"; then + echo "[ERROR] ${prefix}'${fields[index]}' is not a valid ${TIME_FIELDS[index]} (${TIME_MIN[index]}-${TIME_MAX[index]}): $line" >&2 + exit 1 + fi + done + fi + + if ! id -u "$JOB_USER" > /dev/null 2>&1; then + echo "[ERROR] ${prefix}User '${JOB_USER}' does not exist: $line" >&2 + exit 1 + fi +} + +### + # Prints the variables of the container for the jobs, NUL-separated, as supervisord passes them on to cron: all but + # those that cron sets for the user of a job (HOME, LOGNAME, USER, SHELL) and those of the shell that runs this script + # (PWD, OLDPWD, SHLVL, _) + ## +function printJobEnvironment() { + local variable + + while IFS= read -r -d '' variable; do + case "${variable%%=*}" in + HOME|LOGNAME|USER|SHELL|PWD|OLDPWD|SHLVL|_) + ;; + *) + printf '%s\0' "$variable" + ;; + esac + done < <(env -0) +} + +### + # Debian: writes the variables of the container anew into a file for each user of a job in a crontab in + # /etc/cron.d whose shell is CRON_SHELL, as those of docker-cronjob and of the CRONJOB_* variables. Only that user and + # root may read it; the jobs of the user get the variables anyway. + ## +function writeJobEnvironment() { + local user crontab + local -a crontabs=() - echo "${BASH_REMATCH[1]} ${BASH_REMATCH[4]}" >> "/etc/crontabs/${CRONJOB_USER}" - chmod 0600 "/etc/crontabs/${CRONJOB_USER}" + mkdir -p "$JOB_ENVIRONMENT_DIRECTORY" + chmod 0711 "$JOB_ENVIRONMENT_DIRECTORY" + rm -f -- "$JOB_ENVIRONMENT_DIRECTORY"/* + + for crontab in /etc/cron.d/*; do + if [[ -f "$crontab" ]] && grep -qxF "SHELL=${CRON_SHELL}" "$crontab"; then + crontabs+=("$crontab") + fi + done + + if [[ "${#crontabs[@]}" -eq 0 ]]; then + return 0 + fi + + # the user of each job line: the sixth field, or the second after a keyword such as @daily; not of a comment or of + # a variable such as MAILTO="" + while IFS= read -r user; do + if id -u "$user" > /dev/null 2>&1; then + ( umask 0077 && printJobEnvironment > "${JOB_ENVIRONMENT_DIRECTORY}/${user}" ) + chown "$user" "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + chmod 0400 "${JOB_ENVIRONMENT_DIRECTORY}/${user}" + fi + done < <(awk '/^[[:space:]]*(#|$)/ || $1 ~ /=/ || $2 ~ /^=/ { next } { print ($1 ~ /^@/) ? $2 : $6 }' "${crontabs[@]}" \ + | LC_ALL=C sort -u) +} + +### + # Writes the jobs of the CRONJOB_* variables, sorted by name, in place of those of the last run. Checks all of them + # before it writes, so that an error changes nothing. A variable that is empty adds no job. $1 is 1 if cron is to be + # enabled for the jobs. + ## +function writeEnvironmentJobs() { + local enableCron="$1" name value index user crontab content + local -a names=() times=() users=() commands=() + local -A written=() + + while IFS= read -r name; do + value="$(envGetValue "$name")" + if [[ -z "$value" ]]; then + continue + fi + + parseJob "$value" "${name}: " + names+=("$name") + times+=("$JOB_TIME") + users+=("$JOB_USER") + commands+=("$JOB_COMMAND") + done < <(envListVars "CRONJOB_" | LC_ALL=C sort) + + if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond: the block of the last run out of every crontab; a crontab with nothing else goes + for crontab in /etc/crontabs/*; do + if grep -qxF "$ENVIRONMENT_BEGIN" "$crontab"; then + content="$(awk -v begin="$ENVIRONMENT_BEGIN" -v end="$ENVIRONMENT_END" '$0 == begin { skip = 1 } !skip { print } $0 == end { skip = 0 }' "$crontab")" + if [[ -n "$content" ]]; then + printf '%s\n' "$content" > "$crontab" + else + rm -f -- "$crontab" + fi + fi + done + + # a block at the end of the crontab of each user, with the jobs in the order of their variables + for user in "${users[@]}"; do + if [[ -n "${written[$user]:-}" ]]; then + continue + fi + + written[$user]=1 + crontab="/etc/crontabs/${user}" + # a last line without its newline would run into the block + if [[ -s "$crontab" && -n "$(tail -c 1 "$crontab")" ]]; then + echo >> "$crontab" + fi + + { + echo "$ENVIRONMENT_BEGIN" + for index in "${!names[@]}"; do + if [[ "${users[index]}" == "$user" ]]; then + echo "# ${names[index]}" + echo "${times[index]} ${commands[index]}" + fi + done + echo "$ENVIRONMENT_END" + } >> "$crontab" + chmod 0600 "$crontab" + done + else + if [[ "${#names[@]}" -eq 0 ]]; then + rm -f -- "$ENVIRONMENT_CRONTAB" + else + { + echo "# The jobs of the CRONJOB_* variables, written anew at every start of the container; their shell adds" + echo "# the variables of the container and sends their output to the container log" + echo "SHELL=${CRON_SHELL}" + for index in "${!names[@]}"; do + echo "# ${names[index]}" + echo "${times[index]} ${users[index]} ${commands[index]}" + done + } > "$ENVIRONMENT_CRONTAB" + chmod 0644 "$ENVIRONMENT_CRONTAB" + fi + fi + + # supervisord starts cron only where it is enabled, e.g. not after docker-service disable cron + if [[ "$enableCron" == "1" && "${#names[@]}" -gt 0 ]] && ! grep -Eq '^[[:space:]]*autostart[[:space:]]*=[[:space:]]*true' /opt/docker/etc/supervisor.d/cron.conf; then + echo "Enabling cron for the jobs of the CRONJOB_* variables" + docker-service enable cron + fi +} + +if [[ "$1" == "--job-environment" ]]; then + if [[ "$#" -ne 1 ]]; then + usage + fi + + if [[ "$IMAGE_FAMILY" != "Alpine" ]]; then + writeJobEnvironment + fi + + exit 0 +fi + +if [[ "$1" == "--environment" ]]; then + if [[ "$#" -eq 1 ]]; then + writeEnvironmentJobs 0 + elif [[ "$#" -eq 2 && "$2" == "--enable-cron" ]]; then + writeEnvironmentJobs 1 + else + usage + fi + + exit 0 +fi + +if [[ "$IMAGE_FAMILY" == "Alpine" ]]; then + # BusyBox crond reads no /etc/cron.d, but one crontab per user in /etc/crontabs, without the user column + for JOB_LINE in "$@"; do + parseJob "$JOB_LINE" "" + echo "${JOB_TIME} ${JOB_COMMAND}" >> "/etc/crontabs/${JOB_USER}" + chmod 0600 "/etc/crontabs/${JOB_USER}" done exit 0 fi # create crontab file -touch /etc/cron.d/webdevops-docker -chmod 0644 /etc/cron.d/webdevops-docker +touch "$DOCKER_CRONTAB" +chmod 0644 "$DOCKER_CRONTAB" -# Cron in Debian mails the output of a job: the jobs of this file run with docker-cronjob-shell instead, which -# sends their output to syslog-ng and with it to the container log, unless a MAILTO line asks for the mail -if [[ ! -s /etc/cron.d/webdevops-docker ]]; then - echo 'SHELL=/usr/local/bin/docker-cronjob-shell' >> /etc/cron.d/webdevops-docker +# Cron in Debian mails the output of a job and passes none of the variables of the container on: the jobs of +# this file run with docker-cronjob-shell instead, which adds the variables and sends the output to syslog-ng and with it +# to the container log, unless a MAILTO line asks for the mail +if [[ ! -s "$DOCKER_CRONTAB" ]]; then + echo "SHELL=${CRON_SHELL}" >> "$DOCKER_CRONTAB" fi for CRONJOB_LINES in "$@"; do - echo "$CRONJOB_LINES" >> /etc/cron.d/webdevops-docker + echo "$CRONJOB_LINES" >> "$DOCKER_CRONTAB" done # Add required newline at end -echo >> /etc/cron.d/webdevops-docker +echo >> "$DOCKER_CRONTAB" diff --git a/provisioning/base/general/bin/usr-bin/docker-cronjob-shell b/provisioning/base/general/bin/usr-bin/docker-cronjob-shell index 4ded7cab2..9f00fd534 100644 --- a/provisioning/base/general/bin/usr-bin/docker-cronjob-shell +++ b/provisioning/base/general/bin/usr-bin/docker-cronjob-shell @@ -1,17 +1,28 @@ #!/usr/bin/env bash -# The shell of the cron jobs that docker-cronjob adds in Debian: docker-cronjob sets SHELL to this script in -# /etc/cron.d/webdevops-docker, so cron runs each job as "docker-cronjob-shell -c ". Cron in Debian -# mails the output of a job, and discards it where no mail server is installed. This script runs the command with -# /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng writes it to the -# container log. The exit code stays that of the command. +# The shell of the cron jobs that docker-cronjob and the CRONJOB_* variables add in Debian: docker-cronjob +# sets SHELL to this script in /etc/cron.d/webdevops-docker and /etc/cron.d/webdevops-environment, so cron runs each job +# as "docker-cronjob-shell -c ", as the user of the job. Cron in Debian passes none of the variables +# of the container on to a job, and mails its output, or discards it where no mail server is installed. This script +# adds the variables of the container, which docker-cronjob --environment wrote at the start into the file of the user, +# runs the command with /bin/sh, as cron would, and sends its output, stdout and stderr, to syslog, from where syslog-ng +# writes it to the container log. The exit code stays that of the command. # With MAILTO set in the crontab file, cron mails the output as before: the script then only runs the command. +# the variables of the container, NUL-separated; without the file of the user, the job gets those of cron only +ENVIRONMENT_FILE="/run/docker-cronjob/$(id -un)" +VARIABLES=() +if [[ -r "$ENVIRONMENT_FILE" ]]; then + while IFS= read -r -d '' VARIABLE; do + VARIABLES+=("$VARIABLE") + done < "$ENVIRONMENT_FILE" +fi + # the command runs with the shell that cron would use export SHELL=/bin/sh # MAILTO asks for the mail of cron; an empty MAILTO turns it off, so the output goes to syslog if [[ -n "${MAILTO:-}" ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # Cron runs @reboot jobs as soon as it starts, at the same time as syslog-ng: wait up to 10 seconds for the socket of @@ -25,10 +36,10 @@ fi # without syslog-ng, the output goes to cron as before if [[ ! -S /dev/log ]]; then - exec /bin/sh "$@" + exec env -- "${VARIABLES[@]}" /bin/sh "$@" fi # each line, and each KiB of a longer line, as a message of its own, tagged with the process id of the job; should # logger end early, cat reads the rest, so the command does not end on a broken pipe -/bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } +env -- "${VARIABLES[@]}" /bin/sh "$@" 2>&1 | { logger -t "cron-job[$$]" -p cron.info || cat > /dev/null; } exit "${PIPESTATUS[0]}" diff --git a/provisioning/base/general/provision/entrypoint.d/10-cronjobs.sh b/provisioning/base/general/provision/entrypoint.d/10-cronjobs.sh new file mode 100644 index 000000000..4831a3a57 --- /dev/null +++ b/provisioning/base/general/provision/entrypoint.d/10-cronjobs.sh @@ -0,0 +1,7 @@ +# The cron jobs of the CRONJOB_* variables, see docs/customization.md#cron-jobs. A container that starts supervisord +# also enables cron for them where it is not enabled. +if [[ "$TASK" == "supervisord" ]]; then + docker-cronjob --environment --enable-cron +else + docker-cronjob --environment +fi