From c88f9abb38f0a17db2aaa71030756276cc23e404 Mon Sep 17 00:00:00 2001
From: Valery Kharseko <vharseko@3a-systems.ru>
Date: Sat, 21 Nov 2026 13:52:14 +0000
Subject: [PATCH] [#1318] Wait for Unix startup and shutdown in the shell (#1319)

---
 opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java |   27 ++
 .github/scripts/selftest-detached-start.sh                                     |  330 ++++++++++++++++++++++++++++++
 .github/workflows/build.yml                                                    |    4 
 opendj-server-legacy/resource/bin/_script-util.sh                              |   64 +++++
 opendj-server-legacy/resource/bin/start-ds                                     |  106 ++++++++-
 opendj-server-legacy/resource/bin/stop-ds                                      |   88 ++++++-
 6 files changed, 574 insertions(+), 45 deletions(-)

diff --git a/.github/scripts/selftest-detached-start.sh b/.github/scripts/selftest-detached-start.sh
new file mode 100755
index 0000000..73f621d
--- /dev/null
+++ b/.github/scripts/selftest-detached-start.sh
@@ -0,0 +1,330 @@
+#!/usr/bin/env bash
+# The contents of this file are subject to the terms of the Common Development and
+# Distribution License (the License). You may not use this file except in compliance with the
+# License.
+#
+# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
+# specific language governing permission and limitations under the License.
+#
+# When distributing Covered Software, include this CDDL Header Notice in each file and include
+# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
+# Header, with the fields enclosed by brackets [] replaced by your own identifying
+# information: "Portions copyright [year] [name of copyright owner]".
+#
+# Copyright 2026 3A Systems, LLC.
+
+set -eu
+REPO=$(cd "$(dirname "$0")/../.." && pwd)
+SHELL_UNDER_TEST=${1:-/bin/sh}
+FIXTURES=$(mktemp -d)
+LIVE_PID=
+trap 'if [ -n "$LIVE_PID" ]; then
+        kill -KILL "$LIVE_PID" 2>/dev/null || :
+        wait "$LIVE_PID" 2>/dev/null || :
+      fi
+      rm -rf "$FIXTURES"' EXIT
+export TMPDIR="$FIXTURES"
+
+mkdir -p "$FIXTURES/bin" "$FIXTURES/lib"
+cp "$REPO/opendj-server-legacy/resource/bin/start-ds" \
+   "$REPO/opendj-server-legacy/resource/bin/stop-ds" "$FIXTURES/bin/"
+cp "$REPO/opendj-server-legacy/resource/bin/_script-util.sh" "$FIXTURES/lib/script-util-real.sh"
+cat > "$FIXTURES/lib/_script-util.sh" <<'UTIL'
+# Load the launcher helpers while using fixture Java and a shorter shutdown timer.
+SCRIPT_UTIL_CMD=
+. "$INSTALL_ROOT/lib/script-util-real.sh"
+OPENDJ_JAVA_BIN="$INSTALL_ROOT/java"
+dd() {
+  if [ "${FIXTURE_CASE:-}" = stop-sparse ]; then
+    case " $* " in
+      *' count='*) ;;
+      *)
+        touch "$INSTANCE_ROOT/unbounded-log-read"
+        return 1
+        ;;
+    esac
+  fi
+  command dd "$@"
+}
+stat() {
+  [ "${FIXTURE_CASE:-}" != stop-no-stat ] || return 1
+  command stat "$@"
+}
+sleep() {
+  case "${FIXTURE_CASE:-}:$1" in
+    stop-timeout:200) command sleep 1 ;;
+    stop-rotate:0.1)
+      touch "$INSTANCE_ROOT/waiting-for-shutdown"
+      while [ -e "$INSTANCE_ROOT/logs/server.pid" ]; do command sleep 0.05; done
+      ;;
+    *) command sleep "$@" ;;
+  esac
+}
+UTIL
+cat > "$FIXTURES/java" <<'JAVA'
+#!/bin/sh
+case " $* " in
+  *' --help '*)
+    printf 'fixture help\n'
+    exit 0
+    ;;
+  *' --checkStartability '*)
+    if [ -f "$INSTANCE_ROOT/checked" ]; then
+      touch "$INSTANCE_ROOT/final-check"
+      printf 'probe output\n' >&2
+      exit "${FIXTURE_PROBE_STATUS:-98}"
+    fi
+    if [ -n "${FIXTURE_TIMEOUT_ARG:-}" ]; then
+      found_timeout=false
+      for arg do
+        if [ "$arg" = "$FIXTURE_TIMEOUT_ARG" ]; then
+          found_timeout=true
+          break
+        fi
+      done
+      if [ "$found_timeout" = false ]; then
+        printf 'Expected preflight argument %s\n' "$FIXTURE_TIMEOUT_ARG" >&2
+        exit 1
+      fi
+    fi
+    touch "$INSTANCE_ROOT/checked"
+    while [ "$#" -gt 0 ]; do
+      case "$1" in
+        --startupTimeoutFile)
+          shift
+          printf '%s\n' "$FIXTURE_TIMEOUT" > "$1"
+          ;;
+      esac
+      shift
+    done
+    exit "$FIXTURE_START_CODE"
+    ;;
+  *org.opends.server.tools.WaitForFileDelete*)
+    touch "$INSTANCE_ROOT/waiter-jvm"
+    if [ "${FIXTURE_CASE#stop-}" != "$FIXTURE_CASE" ]; then
+      exit 2
+    fi
+    exec sleep 30
+    ;;
+  *' --checkStoppability '*)
+    exit "$FIXTURE_STOP_CODE"
+    ;;
+  *org.opends.server.tools.StopDS*)
+    touch "$INSTANCE_ROOT/ldap-stop"
+    exit 7
+    ;;
+esac
+printf 'first line\n'
+case "$FIXTURE_CASE" in
+  early|quiet-failure|write-only-early)
+    printf 'startup failed\n' >&2
+    exit 42
+    ;;
+  timeout|write-only-timeout)
+    exec sleep 30
+    ;;
+  *)
+    sleep 0.2
+    printf 'last message'
+    rm "$INSTANCE_ROOT/logs/server.starting"
+    exec sleep 30
+    ;;
+esac
+JAVA
+chmod +x "$FIXTURES/java"
+
+run_case() {
+  export FIXTURE_CASE=$1 FIXTURE_TIMEOUT=$2 FIXTURE_START_CODE=$3
+  expected=$4
+  shift 4
+  export INSTANCE_ROOT="$FIXTURES/$FIXTURE_CASE instance"
+  mkdir -p "$INSTANCE_ROOT/logs" "$INSTANCE_ROOT/tmp"
+  printf 'stale log\n' > "$INSTANCE_ROOT/logs/server.out"
+  if [[ "$FIXTURE_CASE" == write-only-* ]]; then
+    chmod 200 "$INSTANCE_ROOT/logs/server.out"
+  fi
+  status=0
+  timeout 8 "$SHELL_UNDER_TEST" "$FIXTURES/bin/start-ds" "$@" \
+    > "$INSTANCE_ROOT/stdout" 2> "$INSTANCE_ROOT/stderr" || status=$?
+  if [ -f "$INSTANCE_ROOT/logs/server.pid" ]; then
+    read -r LIVE_PID < "$INSTANCE_ROOT/logs/server.pid"
+  fi
+  if [ "$status" -ne "$expected" ] || [ -e "$INSTANCE_ROOT/waiter-jvm" ]; then
+    echo "$FIXTURE_CASE: expected exit $expected with no waiter JVM, got $status" >&2
+    cat "$INSTANCE_ROOT/stderr" >&2
+    exit 1
+  fi
+  [ -z "$(ls -A "$INSTANCE_ROOT/tmp")" ]
+}
+
+help=$(TMPDIR="$FIXTURES/unavailable" INSTANCE_ROOT="$FIXTURES/missing instance" \
+  "$SHELL_UNDER_TEST" "$FIXTURES/bin/start-ds" --help)
+[ "$help" = "fixture help" ]
+
+run_case early 0 99 1 --timeout 0
+[ -e "$INSTANCE_ROOT/logs/server.starting" ]
+[ ! -e "$INSTANCE_ROOT/final-check" ]
+grep -Fxq 'startup failed' "$INSTANCE_ROOT/stdout"
+grep -Eq 'server pid [0-9]+, status 42' "$INSTANCE_ROOT/stderr"
+grep -Fq 'status 42' "$INSTANCE_ROOT/logs/start-ds.log"
+LIVE_PID=
+
+run_case success 200 99 0
+[ -e "$INSTANCE_ROOT/final-check" ]
+printf 'first line\nlast message' | cmp - "$INSTANCE_ROOT/stdout"
+kill "$LIVE_PID"
+LIVE_PID=
+
+run_case quiet 0 103 0 --quiet --timeout=0
+[ -e "$INSTANCE_ROOT/final-check" ]
+[ ! -s "$INSTANCE_ROOT/stdout" ]
+kill "$LIVE_PID"
+LIVE_PID=
+
+run_case quiet-failure 60 103 1 --quiet --timeout=60
+[ ! -e "$INSTANCE_ROOT/final-check" ]
+[ ! -s "$INSTANCE_ROOT/stdout" ]
+grep -Fxq 'startup failed' "$INSTANCE_ROOT/logs/server.out"
+grep -Fq 'status 42' "$INSTANCE_ROOT/stderr"
+LIVE_PID=
+
+FIXTURE_TIMEOUT_ARG=-t1 run_case timeout 1 99 2 -t1
+[ ! -e "$INSTANCE_ROOT/final-check" ]
+[ -e "$INSTANCE_ROOT/logs/server.starting" ]
+kill -0 "$LIVE_PID"
+grep -Fq 'timed out after 1' "$INSTANCE_ROOT/stderr"
+kill "$LIVE_PID"
+LIVE_PID=
+
+touch "$FIXTURES/write-only"
+chmod 200 "$FIXTURES/write-only"
+if [ -r "$FIXTURES/write-only" ]; then
+  echo 'Skipping write-only log scenarios because the test user can read mode 0200 files'
+else
+  run_case write-only-success 200 99 0
+  [ -e "$INSTANCE_ROOT/final-check" ]
+  [ ! -e "$INSTANCE_ROOT/logs/server.starting" ]
+  [ ! -s "$INSTANCE_ROOT/stdout" ]
+  kill "$LIVE_PID"
+  LIVE_PID=
+
+  run_case write-only-early 0 99 1 --timeout 0
+  [ ! -e "$INSTANCE_ROOT/final-check" ]
+  [ -e "$INSTANCE_ROOT/logs/server.starting" ]
+  grep -Eq 'server pid [0-9]+, status 42' "$INSTANCE_ROOT/stderr"
+  LIVE_PID=
+
+  FIXTURE_TIMEOUT_ARG=-t1 run_case write-only-timeout 1 99 2 -t1
+  [ ! -e "$INSTANCE_ROOT/final-check" ]
+  [ -e "$INSTANCE_ROOT/logs/server.starting" ]
+  kill -0 "$LIVE_PID"
+  grep -Fq 'timed out after 1' "$INSTANCE_ROOT/stderr"
+  kill "$LIVE_PID"
+  LIVE_PID=
+fi
+
+export FIXTURE_PROBE_STATUS=99
+run_case failed-probe 3 99 1 --timeout 3
+[ -e "$INSTANCE_ROOT/final-check" ]
+grep -Fq 'checkStartability exited with status 99' "$INSTANCE_ROOT/stderr"
+grep -Fxq 'probe output' "$INSTANCE_ROOT/logs/start-ds.log"
+kill "$LIVE_PID"
+LIVE_PID=
+
+cat > "$FIXTURES/bin/start-ds" <<'START'
+#!/bin/sh
+[ ! -e "$INSTANCE_ROOT/logs/server.pid" ] || exit 1
+printf '%s\n' "$@" > "$INSTANCE_ROOT/restart-args"
+START
+chmod +x "$FIXTURES/bin/start-ds"
+
+run_stop_case() {
+  export FIXTURE_CASE=$1 FIXTURE_STOP_CODE=$2
+  expected=$3
+  shift 3
+  export INSTANCE_ROOT="$FIXTURES/$FIXTURE_CASE instance"
+  mkdir -p "$INSTANCE_ROOT/logs"
+  if [ "$FIXTURE_CASE" = stop-sparse ]; then
+    # Model a 64 GiB log without allocating or reading 64 GiB in the fixture.
+    printf x | dd of="$INSTANCE_ROOT/logs/errors" bs=1 seek=68719476742 count=1 2>/dev/null
+  else
+    awk 'BEGIN { for (i = 0; i < 8250; i++) printf "x"; print ""; }' > "$INSTANCE_ROOT/logs/errors"
+  fi
+  if [ "$FIXTURE_CASE" = stop-write-only ]; then
+    chmod 200 "$INSTANCE_ROOT/logs/errors"
+  fi
+  (
+    trap 'printf "shutdown in progress\n" >> "$INSTANCE_ROOT/logs/errors"
+          if [ "$FIXTURE_CASE" != stop-timeout ]; then
+            if [ "$FIXTURE_CASE" = stop-rotate ]; then
+              while [ ! -e "$INSTANCE_ROOT/waiting-for-shutdown" ]; do sleep 0.05; done
+            else
+              sleep 0.2
+            fi
+            printf "shutdown complete" >> "$INSTANCE_ROOT/logs/errors"
+            if [ "$FIXTURE_CASE" = stop-rotate ]; then
+              mv "$INSTANCE_ROOT/logs/errors" "$INSTANCE_ROOT/logs/errors.1"
+              : > "$INSTANCE_ROOT/logs/errors"
+            fi
+            touch "$INSTANCE_ROOT/shutdown-complete"
+            rm "$INSTANCE_ROOT/logs/server.pid"
+            exit 0
+          fi' TERM
+    touch "$INSTANCE_ROOT/ready"
+    while :; do sleep 0.1; done
+  ) &
+  LIVE_PID=$!
+  printf '%s\n' "$LIVE_PID" > "$INSTANCE_ROOT/logs/server.pid"
+  timeout 5 sh -c 'while [ ! -e "$INSTANCE_ROOT/ready" ]; do sleep 0.1; done'
+
+  status=0
+  timeout 8 "$SHELL_UNDER_TEST" "$FIXTURES/bin/stop-ds" "$@" \
+    > "$INSTANCE_ROOT/stdout" 2> "$INSTANCE_ROOT/stderr" || status=$?
+  if [ "$status" -ne "$expected" ] || [ -e "$INSTANCE_ROOT/waiter-jvm" ]; then
+    echo "$FIXTURE_CASE: expected exit $expected with no waiter JVM, got $status" >&2
+    cat "$INSTANCE_ROOT/stderr" >&2
+    exit 1
+  fi
+  if [ -e "$INSTANCE_ROOT/unbounded-log-read" ]; then
+    echo "$FIXTURE_CASE: stop-ds attempted a full scan of the existing log" >&2
+    exit 1
+  fi
+  if [ "$FIXTURE_CASE" = stop-timeout ]; then
+    kill -KILL "$LIVE_PID"
+    wait "$LIVE_PID" 2>/dev/null || :
+  else
+    [ ! -e "$INSTANCE_ROOT/logs/server.pid" ]
+    [ -e "$INSTANCE_ROOT/shutdown-complete" ]
+    wait "$LIVE_PID"
+    [ ! -e "$INSTANCE_ROOT/ldap-stop" ]
+  fi
+  LIVE_PID=
+}
+
+run_stop_case stop-success 100 0
+printf 'shutdown in progress\nshutdown complete' | cmp - "$INSTANCE_ROOT/stdout"
+
+run_stop_case stop-rotate 100 0
+printf 'shutdown in progress\nshutdown complete' | cmp - "$INSTANCE_ROOT/stdout"
+
+run_stop_case stop-sparse 100 0
+printf 'shutdown in progress\nshutdown complete' | cmp - "$INSTANCE_ROOT/stdout"
+
+run_stop_case stop-no-stat 100 0
+[ ! -s "$INSTANCE_ROOT/stdout" ]
+
+run_stop_case stop-restart 106 0 --restart --quiet
+[ ! -s "$INSTANCE_ROOT/stdout" ]
+grep -Fxq -- '--quiet' "$INSTANCE_ROOT/restart-args"
+
+run_stop_case stop-timeout 100 7
+[ -e "$INSTANCE_ROOT/ldap-stop" ]
+[ -e "$INSTANCE_ROOT/logs/server.pid" ]
+grep -Fq 'timed out after 200' "$INSTANCE_ROOT/stderr"
+
+if [ ! -r "$FIXTURES/write-only" ]; then
+  run_stop_case stop-write-only 100 0
+  [ ! -s "$INSTANCE_ROOT/stdout" ]
+fi
+
+echo "Unix startup and shutdown scenarios passed with $SHELL_UNDER_TEST"
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index ecaece9..8fbe358 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -70,6 +70,10 @@
       if: runner.os == 'Linux' && matrix.java == '11'
       shell: bash
       run: dash .github/scripts/test-script-util.sh
+    - name: Check Unix startup and shutdown
+      if: runner.os == 'Linux' && matrix.java == '11'
+      shell: bash
+      run: bash .github/scripts/selftest-detached-start.sh /bin/dash
     - name: Java ${{ matrix.Java }} (${{ matrix.os }})
       uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
       with:
diff --git a/opendj-server-legacy/resource/bin/_script-util.sh b/opendj-server-legacy/resource/bin/_script-util.sh
index 09ab895..1a3361d 100644
--- a/opendj-server-legacy/resource/bin/_script-util.sh
+++ b/opendj-server-legacy/resource/bin/_script-util.sh
@@ -177,12 +177,6 @@
   fi
 }
 
-# Give the lifecycle waiter its own heap without changing other Java launches.
-wait_for_file_delete() (
-  unset JAVA_TOOL_OPTIONS JDK_JAVA_OPTIONS _JAVA_OPTIONS
-  exec "${OPENDJ_JAVA_BIN}" -client -Xmx16m org.opends.server.tools.WaitForFileDelete "$@"
-)
-
 print_error_message() {
   if test -z "${OPENDJ_JAVA_BIN}"
   then
@@ -278,6 +272,64 @@
   esac
 }
 
+stop_wait_timer()
+{
+  if [ -n "${WAIT_TIMER_PID}" ]
+  then
+    kill "${WAIT_TIMER_PID}" 2>/dev/null
+    wait "${WAIT_TIMER_PID}" 2>/dev/null
+    WAIT_TIMER_PID=
+  fi
+}
+
+# Wait for a marker to disappear. An optional log is already open on fd 3.
+# When a child PID is supplied, also fail if that child exits during the wait.
+wait_for_marker_removal()
+{
+  WAIT_FILE=$1
+  WAIT_TIMEOUT=$2
+  WAIT_LOG=$3
+  WAIT_CHILD=${4:-}
+  if [ "${WAIT_TIMEOUT}" -gt 0 ]
+  then
+    sleep "${WAIT_TIMEOUT}" > /dev/null &
+    WAIT_TIMER_PID=$!
+  fi
+
+  WAIT_RESULT=0
+  POLL_INTERVAL=0.1
+  while [ -e "${WAIT_FILE}" ] && { [ -z "${WAIT_CHILD}" ] || kill -0 "${WAIT_CHILD}" 2>/dev/null; }
+  do
+    if [ -n "${WAIT_TIMER_PID}" ] && ! kill -0 "${WAIT_TIMER_PID}" 2>/dev/null
+    then
+      wait "${WAIT_TIMER_PID}" 2>/dev/null
+      WAIT_TIMER_PID=
+      if [ -e "${WAIT_FILE}" ]
+      then
+        WAIT_RESULT=2
+      fi
+      break
+    fi
+    if [ -n "${WAIT_LOG}" ]
+    then
+      # Bounded reads advance the same descriptor and allow rechecking the marker.
+      dd bs=8192 count=128 <&3 2>/dev/null
+    fi
+    if ! sleep "${POLL_INTERVAL}" 2>/dev/null
+    then
+      # Some Unix sleep implementations only accept whole seconds.
+      POLL_INTERVAL=1
+      sleep "${POLL_INTERVAL}"
+    fi
+  done
+  if [ -n "${WAIT_CHILD}" ] && ! kill -0 "${WAIT_CHILD}" 2>/dev/null
+  then
+    WAIT_RESULT=1
+  fi
+  stop_wait_timer
+  return "${WAIT_RESULT}"
+}
+
 # Configure the appropriate CLASSPATH for server, using Opend DJ logger.
 set_opendj_logger_classpath() {
   CLASSPATH="${INSTANCE_ROOT}/classes"
diff --git a/opendj-server-legacy/resource/bin/start-ds b/opendj-server-legacy/resource/bin/start-ds
index 49e7817..9f4ab52 100644
--- a/opendj-server-legacy/resource/bin/start-ds
+++ b/opendj-server-legacy/resource/bin/start-ds
@@ -14,7 +14,7 @@
 #
 # Copyright 2006-2009 Sun Microsystems, Inc.
 # Portions Copyright 2011-2014 ForgeRock AS.
-# Portions Copyright 2025-2026 3A Systems LLC.
+# Portions Copyright 2025-2026 3A Systems, LLC.
 
 
 # Capture the current working directory so that we can change to it later.
@@ -73,6 +73,52 @@
 LOG_FILE=${INSTANCE_ROOT}/logs/server.out
 STARTING_FILE=${INSTANCE_ROOT}/logs/server.starting
 
+cleanup_start()
+{
+  if [ -n "${STARTUP_TIMEOUT_FILE}" ]
+  then
+    rm -f "${STARTUP_TIMEOUT_FILE}"
+  fi
+  stop_wait_timer
+}
+
+report_start_failure()
+{
+  CHILD_STATUS=running
+  if ! kill -0 "${SERVER_PID}" 2>/dev/null
+  then
+    wait "${SERVER_PID}"
+    CHILD_STATUS=$?
+  fi
+  START_FAILURE="start-ds: $1; server pid ${SERVER_PID}, status ${CHILD_STATUS}"
+  if [ -n "${2:-}" ]
+  then
+    START_FAILURE="${START_FAILURE}
+$2"
+  fi
+  printf '%s\n' "${START_FAILURE}" >&2
+  {
+    date -u '+%Y-%m-%dT%H:%M:%SZ'
+    printf '%s\n' "${START_FAILURE}"
+  } 2>/dev/null >> "${INSTANCE_ROOT}/logs/start-ds.log" || :
+}
+
+wait_for_startup()
+{
+  wait_for_marker_removal "${STARTING_FILE}" "${START_TIMEOUT}" "$1" "${SERVER_PID}"
+  START_RESULT=$?
+  if [ -n "$1" ] && LOG_SIZE=$(wc -c 2>/dev/null < "$1")
+  then
+    # Drain the startup log without following a server that keeps writing.
+    dd bs=8192 count=$(( (LOG_SIZE + 8191) / 8192 )) <&3 2>/dev/null
+  fi
+  case "${START_RESULT}" in
+    1) report_start_failure "server exited before startup completed (see ${LOG_FILE})" ;;
+    2) report_start_failure "startup timed out after ${START_TIMEOUT} seconds (use --timeout to increase it)" ;;
+  esac
+  return "${START_RESULT}"
+}
+
 # Remove the native libraries the BC FIPS loader extracts into the tmp directory
 # on every start, so that they do not pile up. Nothing else in there is ours to
 # remove: the tmp directory is java.io.tmpdir for every tool, and a tool may
@@ -91,39 +137,67 @@
 # means that the server is already running and we shouldn't try to start it.
 # An exit code of anything else means that we're not trying to start the server
 # and we can just exit with that exit code.
+WAIT_TIMER_PID=
+START_TIMEOUT=
+STARTUP_TIMEOUT_FILE=
+trap cleanup_start 0
+trap 'exit 129' HUP
+trap 'exit 130' INT
+trap 'exit 143' TERM
+STARTUP_TIMEOUT_FILE=$(mktemp "${OPENDJ_TMP_DIR}/opendj-start-ds.XXXXXXXX" 2>/dev/null) ||
+  STARTUP_TIMEOUT_FILE=$(mktemp /tmp/opendj-start-ds.XXXXXXXX 2>/dev/null) ||
+  STARTUP_TIMEOUT_FILE=
+if [ -n "${STARTUP_TIMEOUT_FILE}" ]
+then
+  set -- --startupTimeoutFile "${STARTUP_TIMEOUT_FILE}" "${@}"
+fi
 "${OPENDJ_JAVA_BIN}" -client ${SCRIPT_NAME_ARG} org.opends.server.core.DirectoryServer \
             --configFile "${CONFIG_FILE}" --checkStartability "${@}"
 EC=${?}
+if [ -n "${STARTUP_TIMEOUT_FILE}" ]
+then
+  shift 2
+  IFS= read -r START_TIMEOUT < "${STARTUP_TIMEOUT_FILE}" || START_TIMEOUT=
+  rm -f "${STARTUP_TIMEOUT_FILE}"
+  STARTUP_TIMEOUT_FILE=
+fi
+
 if test ${EC} -eq 99 -o ${EC} -eq 103
 then
-  #
-  # run detach
-  #
-  touch "${STARTING_FILE}"
+  if [ -z "${START_TIMEOUT}" ]
+  then
+    printf '%s\n' 'start-ds: could not read the startup timeout' >&2
+    exit 1
+  fi
+  : > "${LOG_FILE}" || exit 1
+  touch "${STARTING_FILE}" || exit 1
   nohup "${OPENDJ_JAVA_BIN}" ${OPENDJ_JAVA_ARGS} ${SCRIPT_NAME_ARG} \
        org.opends.server.core.DirectoryServer \
-       --configFile "${CONFIG_FILE}" "${@}" > "${LOG_FILE}" 2>&1 &
-  echo $! > "${PID_FILE}"
-  if test ${EC} -eq 99
+       --configFile "${CONFIG_FILE}" "${@}" >> "${LOG_FILE}" 2>&1 &
+  SERVER_PID=$!
+  echo "${SERVER_PID}" > "${PID_FILE}"
+  # Capture the wait status inside the group to distinguish it from a failed log open.
+  if [ "${EC}" -eq 99 ] && {
+    wait_for_startup "${LOG_FILE}"
+    EC=$?
+  } 3< "${LOG_FILE}"
   then
-    wait_for_file_delete \
-         --targetFile "${STARTING_FILE}" --logFile "${LOG_FILE}" "${@}"
+    :
   else
-    wait_for_file_delete \
-         --targetFile "${STARTING_FILE}" "${@}"
+    wait_for_startup ""
+    EC=$?
   fi
-  EC=${?}
   if test ${EC} -eq 0
   then
     # An exit code of 98 means that the server is already running.
-  	"${OPENDJ_JAVA_BIN}" -client ${SCRIPT_NAME_ARG} org.opends.server.core.DirectoryServer \
-            --configFile "${CONFIG_FILE}" --checkStartability > /dev/null 2>&1
+    START_CHECK_OUTPUT=$("${OPENDJ_JAVA_BIN}" -client ${SCRIPT_NAME_ARG} org.opends.server.core.DirectoryServer \
+            --configFile "${CONFIG_FILE}" --checkStartability 2>&1)
     EC=${?}
     if test ${EC} -eq 98
     then
     	exit 0
     else
-      # Could not start the server
+      report_start_failure "checkStartability exited with status ${EC}" "${START_CHECK_OUTPUT}"
       exit 1
     fi
   fi
diff --git a/opendj-server-legacy/resource/bin/stop-ds b/opendj-server-legacy/resource/bin/stop-ds
index 7293b3b..9a3a794 100644
--- a/opendj-server-legacy/resource/bin/stop-ds
+++ b/opendj-server-legacy/resource/bin/stop-ds
@@ -97,6 +97,52 @@
   exit ${RETURN_CODE}
 fi
 
+PID_FILE=${INSTANCE_ROOT}/logs/server.pid
+LOG_FILE=${INSTANCE_ROOT}/logs/errors
+# Match DirectoryServer.DEFAULT_TIMEOUT, the timeout used by WaitForFileDelete.
+STOP_TIMEOUT=200
+
+position_shutdown_log()
+{
+  # Get the size of the open file through procfs on Linux or stdin on BSD.
+  LOG_SIZE=$(stat -Lc '%s' /proc/self/fd/0 2>/dev/null <&3) ||
+    LOG_SIZE=$(stat -f '%z' 2>/dev/null <&3) ||
+    return 1
+  case "${LOG_SIZE}" in
+    ''|*[!0-9]*) return 1 ;;
+  esac
+  # Skip to the last byte and read it on the same descriptor.
+  [ "${LOG_SIZE}" -eq 0 ] ||
+    dd bs=1 skip=$(( LOG_SIZE - 1 )) count=1 2>/dev/null <&3 > /dev/null
+}
+
+wait_for_shutdown()
+{
+  STOP_LOG=$1
+  if [ -n "${STOP_LOG}" ] && ! position_shutdown_log
+  then
+    STOP_LOG=
+  fi
+
+  kill "${PID}" || return $?
+  wait_for_marker_removal "${PID_FILE}" "${STOP_TIMEOUT}" "${STOP_LOG}"
+  STOP_RESULT=$?
+  if [ -n "${STOP_LOG}" ]
+  then
+    if [ "${STOP_RESULT}" -eq 0 ]
+    then
+      # The server closes its log publishers before removing server.pid.
+      cat <&3 2>/dev/null
+    else
+      dd bs=8192 count=128 <&3 2>/dev/null
+    fi
+  fi
+  if [ "${STOP_RESULT}" -eq 2 ]
+  then
+    printf 'stop-ds: shutdown timed out after %s seconds\n' "${STOP_TIMEOUT}" >&2
+  fi
+  return "${STOP_RESULT}"
+}
 
 "${OPENDJ_JAVA_BIN}" ${OPENDJ_JAVA_ARGS} ${SCRIPT_NAME_ARG} \
   org.opends.server.tools.StopDS --checkStoppability "${@}"
@@ -157,28 +203,28 @@
 
 if test ${MUST_STOP_USING_SYSTEM_CALL} -eq 0
 then
-  if test -f "${INSTANCE_ROOT}/logs/server.pid"
+  if test -f "${PID_FILE}"
   then
-    read PID < "${INSTANCE_ROOT}/logs/server.pid"
-    kill ${PID}
-    EXIT_CODE=${?}
+    read PID < "${PID_FILE}"
+    WAIT_TIMER_PID=
+    trap stop_wait_timer 0
+    trap 'exit 129' HUP
+    trap 'exit 130' INT
+    trap 'exit 143' TERM
+    # Capture the status inside the group to distinguish a failed log open.
+    if [ "${QUIET_OPTION}" -eq 0 ] && [ -f "${LOG_FILE}" ] && {
+      wait_for_shutdown "${LOG_FILE}"
+      EXIT_CODE=$?
+    } 3< "${LOG_FILE}"
+    then
+      :
+    else
+      wait_for_shutdown ""
+      EXIT_CODE=${?}
+    fi
     if test ${EXIT_CODE} -eq 0
     then
-      if test ${QUIET_OPTION} -eq 0
-      then
-        wait_for_file_delete \
-            --targetFile "${INSTANCE_ROOT}/logs/server.pid" \
-            --logFile "${INSTANCE_ROOT}/logs/errors"
-      else
-        wait_for_file_delete \
-            --targetFile "${INSTANCE_ROOT}/logs/server.pid" \
-            --logFile "${INSTANCE_ROOT}/logs/errors"  --quiet
-      fi
-      EXIT_CODE=${?}
-      if test ${EXIT_CODE} -eq 0
-      then
-        STOPPED=0
-      fi
+      STOPPED=0
     fi
   else
     echo "ERROR:  Unable to find the server.pid file to determine the process"
@@ -191,9 +237,9 @@
 # has been killed using kill -9).
 if test ${STOPPED} -eq 0
 then
-  if test -f "${INSTANCE_ROOT}/logs/server.pid"
+  if test -f "${PID_FILE}"
   then
-    rm "${INSTANCE_ROOT}/logs/server.pid"
+    rm "${PID_FILE}"
   fi
 fi
 
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java b/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
index 52b15e4..427f4fc 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
@@ -38,6 +38,8 @@
 import java.io.PrintStream;
 import java.lang.management.ManagementFactory;
 import java.net.InetAddress;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.text.DecimalFormat;
 import java.util.Arrays;
 import java.util.Collection;
@@ -4766,6 +4768,7 @@
     // Define the arguments that may be provided to the server.
     final BooleanArgument displayUsage;
     BooleanArgument checkStartability      = null;
+    StringArgument startupTimeoutFile      = null;
     BooleanArgument quietMode              = null;
     IntegerArgument timeout                = null;
     BooleanArgument fullVersion            = null;
@@ -4800,6 +4803,11 @@
                       .description(INFO_DSCORE_DESCRIPTION_CHECK_STARTABILITY.get())
                       .hidden()
                       .buildAndAddToParser(argParser);
+      startupTimeoutFile =
+              StringArgument.builder("startupTimeoutFile")
+                      .hidden()
+                      .valuePlaceholder(INFO_CONFIGFILE_PLACEHOLDER.get())
+                      .buildAndAddToParser(argParser);
       fullVersion =
               BooleanArgument.builder("fullVersion")
                       .shortIdentifier('F')
@@ -4825,7 +4833,7 @@
       quietMode = quietArgument();
       argParser.addArgument(quietMode);
 
-      // Not used in this class, but required by the start-ds script (see issue #3814)
+      // The Unix launcher uses the validated timeout to wait for detached startup.
       timeout =
               IntegerArgument.builder("timeout")
                       .shortIdentifier('t')
@@ -4907,7 +4915,22 @@
       }
       else
       {
-        System.exit(checkStartability(argParser));
+        int startability = checkStartability(argParser);
+        if (startupTimeoutFile.isPresent()
+            && (startability == START_AS_DETACH || startability == START_AS_DETACH_QUIET))
+        {
+          // Keep the launcher metadata separate from the normal command output.
+          try
+          {
+            Files.writeString(Path.of(startupTimeoutFile.getValue()), timeout.getIntValue() + "\n");
+          }
+          catch (IOException | ArgumentException e)
+          {
+            System.err.println("start-ds: could not write the startup timeout: " + e.getMessage());
+            System.exit(CHECK_ERROR);
+          }
+        }
+        System.exit(startability);
       }
     }
     else if (argParser.usageOrVersionDisplayed())

--
Gitblit v1.10.0