Tomcat Standardize

sudo bash ./standardize_tomcat.sh --current /home/prasad/apache-tomcat-9.0.108 --target /middleware/tomcat --user mwadmin --group mwadmin --service-name tomcat9 --create-systemd

Use below scripts to standardise tomcat

#!/usr/bin/env bash
# standardize_tomcat.sh (v2)
# Standardizes an Apache Tomcat install to:
#   - Location: /middleware/tomcat (override with --target)
#   - Owner: mwadmin:mwadmin (override with --user/--group)
#   - Wrapper: $TARGET/bin/tomcatctl
#   - setenv.sh: auto-detect JAVA_HOME from PATH; optional --java-home to pin JDK
#   - systemd: optional, foreground (Type=simple) for stability
#
# Example:
#   sudo bash standardize_tomcat.sh --current /opt/apache-tomcat-10.1.x \
#     --service-name tomcat9 --create-systemd --selinux-fix
set -euo pipefail

# Defaults
TARGET="/middleware/tomcat"
USER_NAME="mwadmin"
GROUP_NAME="mwadmin"
SERVICE_NAME="tomcat"
CREATE_SYSTEMD=0
JAVA_HOME_OPT=""
SELINUX_FIX=0

err(){ echo "ERROR: $*" >&2; exit 1; }
info(){ echo "[*] $*"; }
ok(){ echo "[OK] $*"; }

usage(){
  cat <<'USAGE'
Usage:
  standardize_tomcat.sh --current <path> [options]

Required:
  --current <path>        Existing Tomcat directory (must contain bin/catalina.sh)

Options:
  --target <path>         Target standardized path (default: /middleware/tomcat)
  --user <name>           Service user (default: mwadmin)
  --group <name>          Service group (default: mwadmin)
  --service-name <name>   Systemd service name (default: tomcat)
  --create-systemd        Create and enable a systemd unit (Type=simple foreground)
  --java-home <path>      Pin JAVA_HOME to a specific JDK (otherwise auto-detected)
  --selinux-fix           Apply permissive SELinux labels to $TARGET tree (Fedora/RHEL)
  -h|--help               Show help
USAGE
}

require_root(){ [[ "$(id -u)" -eq 0 ]] || err "Run as root (sudo)."; }

# Parse args
CURRENT=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --current) CURRENT="${2:-}"; shift 2 ;;
    --target) TARGET="${2:-}"; shift 2 ;;
    --user) USER_NAME="${2:-}"; shift 2 ;;
    --group) GROUP_NAME="${2:-}"; shift 2 ;;
    --service-name) SERVICE_NAME="${2:-}"; shift 2 ;;
    --create-systemd) CREATE_SYSTEMD=1; shift ;;
    --java-home) JAVA_HOME_OPT="${2:-}"; shift 2 ;;
    --selinux-fix) SELINUX_FIX=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) err "Unknown option: $1 (use -h)";;
  esac
done

[[ -n "$CURRENT" ]] || err "--current <path> is required"
[[ -d "$CURRENT" ]] || err "Not a directory: $CURRENT"
[[ -f "$CURRENT/bin/catalina.sh" ]] || err "Missing $CURRENT/bin/catalina.sh"

require_root
info "Standardizing Tomcat"
info "Current: $CURRENT"
info "Target : $TARGET"
info "User   : $USER_NAME"
info "Group  : $GROUP_NAME"
info "Svc    : $SERVICE_NAME"
[[ -n "$JAVA_HOME_OPT" ]] && info "JAVA_HOME will be pinned to: $JAVA_HOME_OPT"

# 1) Ensure group/user
getent group "$GROUP_NAME" >/dev/null 2>&1 || { info "Creating group $GROUP_NAME"; groupadd --system "$GROUP_NAME"; }
id "$USER_NAME" >/dev/null 2>&1 || { info "Creating user $USER_NAME"; useradd --system --shell /sbin/nologin --no-create-home -g "$GROUP_NAME" "$USER_NAME"; }

# 2) Create target and sync files
mkdir -p "$TARGET"
if command -v rsync >/dev/null 2>&1; then
  info "Syncing (rsync) -> $TARGET"
  rsync -a --delete --exclude="logs/*" --exclude="temp/*" --exclude="work/*" "$CURRENT"/ "$TARGET"/
else
  info "Syncing (cp -a) -> $TARGET"
  cp -a "$CURRENT"/. "$TARGET"/
fi

# 3) Normalize permissions & strip CRLF
info "Fixing permissions and line endings"
find "$TARGET/bin" -type f -name "*.sh" -exec chmod 0750 {} \;
# CRLF -> LF (use sed if dos2unix not present)
if command -v dos2unix >/dev/null 2>&1; then
  dos2unix "$TARGET"/bin/*.sh >/dev/null 2>&1 || true
else
  for f in "$TARGET"/bin/*.sh; do sed -i 's/\r$//' "$f"; done
fi

# Ensure writable runtime dirs
install -d -o "$USER_NAME" -g "$GROUP_NAME" -m 0770 "$TARGET"/{logs,temp,work}
chmod 0750 "$TARGET"/{bin,conf} || true
find "$TARGET/conf" -type f -exec chmod 0640 {} \; || true

# 4) Ownership
chown -R "$USER_NAME:$GROUP_NAME" "$TARGET"
ok "Ownership set to $USER_NAME:$GROUP_NAME"

# 5) setenv.sh with JAVA_HOME auto-detect (or pinned if provided)
SETENV="$TARGET/bin/setenv.sh"
info "Writing setenv.sh with JAVA_HOME auto-detect"
cat > "$SETENV" <<'EOF'
#!/usr/bin/env bash
# Auto-generated by standardize_tomcat.sh (v2)

# If JAVA_HOME is not set, auto-detect from the java on PATH.
if [[ -z "${JAVA_HOME:-}" ]]; then
  JAVA_BIN="$(readlink -f "$(command -v java 2>/dev/null)" 2>/dev/null || true)"
  if [[ -n "$JAVA_BIN" ]]; then
    export JAVA_HOME="$(dirname "$(dirname "$JAVA_BIN")")"
  fi
fi

export CATALINA_BASE="__CATALINA__BASE__"
export CATALINA_HOME="__CATALINA__BASE__"

# Sensible defaults (tune as needed)
export CATALINA_OPTS="${CATALINA_OPTS:-} -Djava.security.egd=file:/dev/./urandom -Djdk.tls.ephemeralDHKeySize=2048"
EOF
sed -i "s|__CATALINA__BASE__|$TARGET|g" "$SETENV"

# If user pinned JAVA_HOME, append it (overrides auto-detect)
if [[ -n "$JAVA_HOME_OPT" ]]; then
  printf '\nexport JAVA_HOME="%s"\n' "$JAVA_HOME_OPT" >> "$SETENV"
fi

chmod 0750 "$SETENV"
chown "$USER_NAME:$GROUP_NAME" "$SETENV"
ok "setenv.sh created"

# 6) Wrapper: tomcatctl
WRAP="$TARGET/bin/tomcatctl"
info "Creating tomcatctl wrapper"
cat > "$WRAP" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
BASE="__CATALINA__BASE__"
export CATALINA_BASE="$BASE"
export CATALINA_HOME="$BASE"

CMD="${1:-}"
case "$CMD" in
  start)   exec "$BASE/bin/catalina.sh" start ;;
  stop)    exec "$BASE/bin/catalina.sh" stop ;;
  restart) "$BASE/bin/catalina.sh" stop || true; sleep 2; exec "$BASE/bin/catalina.sh" start ;;
  status)
    if pgrep -f "org.apache.catalina.startup.Bootstrap" | xargs -r ps -o pid,cmd -p | grep -q "$BASE"; then
      echo "Tomcat RUNNING ($BASE)"; exit 0
    else
      echo "Tomcat STOPPED ($BASE)"; exit 3
    fi
    ;;
  *)
    echo "Usage: $(basename "$0") {start|stop|restart|status}"; exit 2 ;;
esac
EOF
sed -i "s|__CATALINA__BASE__|$TARGET|g" "$WRAP"
chmod 0750 "$WRAP"
chown "$USER_NAME:$GROUP_NAME" "$WRAP"
ok "Wrapper: $WRAP"

# 7) systemd unit (foreground, Type=simple) - optional
if [[ "$CREATE_SYSTEMD" -eq 1 ]]; then
  UNIT="/etc/systemd/system/${SERVICE_NAME}.service"
  info "Creating systemd unit: $UNIT"
  cat > "$UNIT" <<EOF
[Unit]
Description=Apache Tomcat Service (${SERVICE_NAME})
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${USER_NAME}
Group=${GROUP_NAME}
WorkingDirectory=${TARGET}

# Keep PATH so system java is found
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin

Environment=CATALINA_BASE=${TARGET}
Environment=CATALINA_HOME=${TARGET}

# Run in foreground so systemd tracks the main process reliably
ExecStart=/usr/bin/bash -lc '${TARGET}/bin/catalina.sh run'
ExecStop=/bin/kill -TERM \$MAINPID

StandardOutput=journal
StandardError=journal

Restart=on-failure
RestartSec=5
SuccessExitStatus=143
LimitNOFILE=65535
TimeoutStartSec=60
TimeoutStopSec=60

[Install]
WantedBy=multi-user.target
EOF

  systemctl daemon-reload
  systemctl enable "${SERVICE_NAME}" >/dev/null 2>&1 || true
  ok "Systemd unit created. Start with: systemctl start ${SERVICE_NAME}"
else
  info "Skipping systemd unit creation (use --create-systemd)"
fi

# 8) SELinux labeling (optional, safe no-op on systems without SELinux tools)
if [[ "$SELINUX_FIX" -eq 1 ]]; then
  if command -v semanage >/dev/null 2>&1; then
    info "Applying SELinux context for ${TARGET}"
    semanage fcontext -a -t usr_t "${TARGET}(/.*)?" || true
    restorecon -Rv "${TARGET}" || true
    ok "SELinux context applied"
  else
    info "semanage not found; skipping SELinux adjustments"
  fi
fi

ok "Tomcat standardized at: $TARGET"
echo "[TIP] Run as: sudo -u ${USER_NAME} ${WRAP} start   (or: systemctl start ${SERVICE_NAME})"
bash standardize_tomcat.sh --current /path/to/current/tomcat \
  [--target /middleware/tomcat] [--user mwadmin] [--group mwadmin] \
  [--service-name tomcat9] [--create-systemd] [--java-home /usr/lib/jvm/java-21-openjdk] \
  [--selinux-fix]
Subscribe
Notify of
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments