From 360be28e0376d76a6987241715665455a7fa9ad7 Mon Sep 17 00:00:00 2001 From: klT45 <142670241+klT45@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:25:39 +0800 Subject: [PATCH] [ISSUE #8072] Harden container distributions and document the Kubernetes runtime contract - Modernize the admin/bootstrap image bases: both images now use amazoncorretto:17.0.21-alpine3.24 (linux/amd64, linux/arm64) with an alpine:3.24 prepare stage; the bootstrap image no longer uses the EOL CentOS 7 base. - Pin a fixed numeric non-root UID/GID (USER 10001:10001), declare STOPSIGNAL SIGTERM and a HEALTHCHECK against /actuator/health, and keep the runtime read-only friendly: /tmp is the only writable path by default. wget is installed explicitly in both images (admin also keeps curl). - Rewrite both entrypoint.sh scripts as POSIX sh (the Alpine images do not ship bash), exec the JVM so SIGTERM reaches the Spring Boot shutdown hooks, support a read-only conf directory by falling back to a conf-ext classpath override (and to the classpath when a writable copy only partially succeeds), and keep the BOOT_JVM/ADMIN_JVM overrides intact. - Add docs/container-runtime.md: base-image update policy, runtime contract (user, writable paths, signals/exit codes), JVM and container memory budgets, Kubernetes requests/limits, readiness/liveness probe wiring (including management.endpoint.health.probes.enabled and initial-sync-readiness), Deployment/PDB examples for bootstrap and admin, upgrade/rollback procedure (including the whole-pod-template caveat), measured baseline image size/startup/memory numbers, and SBOM/scanning/signing guidance that stays within the ASF release process. - Add script/docker-image-smoke.sh and .github/workflows/docker-image-smoke.yml: CI smoke test for UID 10001, read-only rootfs, /tmp writability, conf-ext overrides (read-only classpath fallback and legacy copy path), BOOT_JVM/ADMIN_JVM, SIGTERM graceful shutdown (exit code 0/143, not 137), restarts with the same mounted configuration and (real-dist mode) the declared HEALTHCHECK plus /actuator/health = UP. SHENYU_SMOKE_REAL_DIST=1 runs the same checks against real distributions, and SHENYU_SMOKE_PREVIOUS_TAG= verifies a previous published release still starts and stops gracefully with the same mounts. - Add a make smoke-image convenience target, refresh the integrated-test base-image pre-pull list, make the compose healthcheck read-only-rootfs safe, add .gitattributes so the container scripts stay on LF, and fix the pre-existing BOOSTRAP_REPOSITORY typo in the Makefile publish target. --- .gitattributes | 21 + .github/workflows/docker-image-smoke.yml | 62 ++ .github/workflows/integrated-test.yml | 4 +- Makefile | 9 +- docs/container-runtime.md | 621 ++++++++++++++++++ script/docker-image-smoke.sh | 563 ++++++++++++++++ .../shenyu-admin-dist/docker/Dockerfile | 40 +- .../shenyu-admin-dist/docker/entrypoint.sh | 54 +- .../shenyu-bootstrap-dist/docker/Dockerfile | 39 +- .../docker/entrypoint.sh | 55 +- .../src/main/resources/docker-compose.yaml | 2 +- 11 files changed, 1429 insertions(+), 41 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/docker-image-smoke.yml create mode 100644 docs/container-runtime.md create mode 100644 script/docker-image-smoke.sh diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000000..0ecdc2c0e509 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Container runtime files are consumed inside Linux images: a CRLF checkout on +# Windows would break `sh entrypoint.sh` and Dockerfile inputs. +shenyu-dist/**/docker/Dockerfile text eol=lf +shenyu-dist/**/docker/*.sh text eol=lf +script/*.sh text eol=lf diff --git a/.github/workflows/docker-image-smoke.yml b/.github/workflows/docker-image-smoke.yml new file mode 100644 index 000000000000..74683d4bba1e --- /dev/null +++ b/.github/workflows/docker-image-smoke.yml @@ -0,0 +1,62 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: docker-image-smoke + +# Path-filtered on purpose: this is a distribution smoke test, not part of the +# main build. While the `pull_request.paths` filter is present, do not add this +# workflow to the required-status-check list (a docs-only PR would never report a +# result and would stay blocked); remove the filter first if it must be required. +on: + pull_request: + paths: + - 'shenyu-dist/**/docker/**' + - 'shenyu-dist/**/src/main/assembly/**' + - 'Makefile' + - 'script/docker-image-smoke.sh' + - 'docs/container-runtime.md' + - '.github/workflows/docker-image-smoke.yml' + push: + branches: + - master + paths: + - 'shenyu-dist/**/docker/**' + - 'shenyu-dist/**/src/main/assembly/**' + - 'Makefile' + - 'script/docker-image-smoke.sh' + - 'docs/container-runtime.md' + - '.github/workflows/docker-image-smoke.yml' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + smoke: + if: github.repository == 'apache/shenyu' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: ./actions/setup-java-with-retry + with: + java-version: "17" + distribution: "temurin" + - name: Run container runtime smoke checks + run: bash script/docker-image-smoke.sh diff --git a/.github/workflows/integrated-test.yml b/.github/workflows/integrated-test.yml index 3a608d770534..8fc3ded33398 100644 --- a/.github/workflows/integrated-test.yml +++ b/.github/workflows/integrated-test.yml @@ -161,9 +161,9 @@ jobs: docker pull "$image" } - pull_with_retry alpine:latest + pull_with_retry alpine:3.24 + pull_with_retry amazoncorretto:17.0.21-alpine3.24 pull_with_retry amazoncorretto:17.0.11-alpine3.19 - pull_with_retry centos:7 pull_with_retry eclipse-temurin:17-centos7 pull_with_retry elasticsearch:8.2.3 pull_with_retry otel/opentelemetry-collector-contrib:0.111.0 diff --git a/Makefile b/Makefile index 3e8114ac3ca6..eae87e30a98b 100644 --- a/Makefile +++ b/Makefile @@ -51,6 +51,9 @@ build-bootstrap: -Prelease \ clean package +smoke-image: ## smoke test the container runtime contract of the distribution images + @bash script/docker-image-smoke.sh + build-all-image: build-admin-image build-bootstrap-image ## build images on local, does not support multi platforms. @echo "build images" @@ -75,7 +78,7 @@ build-bootstrap-image: build-bootstrap ## build bootstrap image for local publish-all-images: init publish-admin-image publish-bootstrap-image ## build and publish images on buildx, for producing multi platform images @docker buildx rm shenyu -.PHONY: init +.PHONY: init smoke-image init: @docker buildx create --name shenyu @docker buildx use shenyu @@ -95,8 +98,8 @@ publish-bootstrap-image: build-bootstrap @echo "build and push bootstrap image" @docker buildx build --push \ --platform=linux/arm64,linux/amd64 \ - -t ${REGISTRY}/${BOOSTRAP_REPOSITORY}:latest \ - -t ${REGISTRY}/${BOOSTRAP_REPOSITORY}:${VERSION} \ + -t ${REGISTRY}/${BOOTSTRAP_REPOSITORY}:latest \ + -t ${REGISTRY}/${BOOTSTRAP_REPOSITORY}:${VERSION} \ --build-arg APP_NAME=apache-shenyu-${VERSION}-bootstrap-bin \ --label "commit.id=${COMMIT_ID}" \ -f ${SHENYU_HOME}/shenyu-dist/shenyu-bootstrap-dist/docker/Dockerfile \ diff --git a/docs/container-runtime.md b/docs/container-runtime.md new file mode 100644 index 000000000000..805b560c3908 --- /dev/null +++ b/docs/container-runtime.md @@ -0,0 +1,621 @@ +# Container runtime guide + +This document describes the container contract of the `shenyu-admin` and +`shenyu-bootstrap` distribution images built from `shenyu-dist`. It covers the +base-image policy, the runtime filesystem/signal contract, JVM and memory +budgets, the Kubernetes defaults used for production rollouts, and the local and +CI verification steps. + +Related: [#8072](https://github.com/apache/shenyu/issues/8072) (container +distribution hardening), [#5273](https://github.com/apache/shenyu/issues/5273) +(Kubernetes controller follow-up), [#7649](https://github.com/apache/shenyu/issues/7649) +(minimal HTTP distribution). + +## 1. Images + +| Image | Dockerfile | Runtime port | Health endpoint | +|---|---|---|---| +| `apache/shenyu-admin` | `shenyu-dist/shenyu-admin-dist/docker/Dockerfile` | `9095` | `/actuator/health` | +| `apache/shenyu-bootstrap` | `shenyu-dist/shenyu-bootstrap-dist/docker/Dockerfile` | `9195` | `/actuator/health` | + +Both images share the same runtime contract: + +| Property | Value | +|---|---| +| Runtime base | `amazoncorretto:17.0.21-alpine3.24` (JDK 17, Alpine 3.24) | +| Prepare stage | `alpine:3.24` (only unpacks the distribution tarball) | +| Supported platforms | `linux/amd64`, `linux/arm64` (published multi-arch by `Makefile` / `docker-publish*.yml`) | +| User | `10001:10001` (`shenyu:shenyu` in `/etc/passwd`) | +| Signals | `STOPSIGNAL SIGTERM`, JVM is PID 1 | +| Writable paths | `/tmp` only (by default) | +| In-image tooling | `wget` in both images; the admin image also ships `curl` | + +### Base-image update policy + +The JDK patch version and the Alpine generation are pinned on purpose. To keep +the images on maintained bases: + +1. Re-check `amazoncorretto` and `alpine` tags at least once per quarter, and + immediately after a Corretto security release. +2. Bump **both** Dockerfiles and the table above in the same pull request; the + admin and bootstrap images must not drift onto different JDK patches. +3. Run `bash script/docker-image-smoke.sh` before opening the pull request. +4. If a base change is not backward compatible (for example a new Alpine + generation drops a package), record the change in the release notes. + +Do not use floating tags (`17-alpine`, `latest`) in the Dockerfiles. The +`-alpine3.24` and `17.0.21` parts are the compatibility and security pins; the +patch version is what scanners and release notes track. + +### Java runtime + +The images ship a full JDK on purpose: `jcmd`, `jstack`, `jmap` and `jstat` are +available when an operator execs into a running container. The distribution +tarball also contains `bin/start.sh` and `bin/stop.sh`, but those helpers are +bash scripts intended for bare-metal tarball installations and are **not** +runnable inside the images (there is no `bash` interpreter); the container +entrypoint starts the application instead. Switching to a JRE-only or +`-headless` base is a separate decision; native-image compilation is explicitly +**not** part of this contract (see #8072 boundaries). + +## 2. Runtime contract + +### 2.1 Filesystem and read-only root filesystems + +The application writes logs to stdout only (`conf/logback.xml` uses an async +console appender), so the root filesystem can be mounted read-only: + +```bash +docker run --read-only --tmpfs /tmp:rw,size=64m \ + -p 9195:9195 \ + apache/shenyu-bootstrap: +``` + +| Path | Writable? | Purpose | Production guidance | +|---|---|---|---| +| `/tmp` | required | JVM temporary files, HTTP client temp buffers, `java.io.tmpdir` | mount an `emptyDir` or `tmpfs`; size it to at least 64 MiB | +| `/opt/shenyu-{admin,bootstrap}/conf` | no | image configuration | mount ConfigMap files instead of writing into the image | +| `/opt/shenyu-{admin,bootstrap}/conf-ext` | read-only | optional override directory | mount a ConfigMap/Secret directory; see 2.2 | +| `/opt/shenyu-{admin,bootstrap}/logs` | no | unused by default (console logging) | only needed if you replace `logback.xml` with a file appender | + +If you enable file logging or a file-backed database (for example an H2 or +SQLite file instead of the default in-memory/MySQL/PostgreSQL setup), mount a +writable volume for that path; the image will otherwise fail to start with a +read-only root filesystem. + +### 2.2 `conf-ext` overrides + +The entrypoint supports an optional `conf-ext` directory next to `conf`: + +* writable `conf` directory: `conf-ext/*` is copied over `conf` (legacy + behavior); if the copy only partially succeeds, the entrypoint logs a `WARN` + and falls back to the classpath override so no override is silently dropped; +* read-only root filesystem: `conf-ext` is prepended to the classpath instead, + so overrides still win without writing to the image. + +Both paths are logged by the entrypoint at startup. Prefer mounting individual +files (`application.yml`, `application-.yml`) with `subPath`, as the +e2e manifests do, when you only need to replace a few files. + +### 2.3 Signals, shutdown and exit codes + +`entrypoint.sh` ends with `exec java ...`, so the JVM is PID 1 and receives the +container signal directly; the image also declares `STOPSIGNAL SIGTERM`. + +| Event | Behavior | Exit code | +|---|---|---| +| `docker stop` / Kubernetes pod termination (SIGTERM) | Spring Boot shutdown hooks run, Netty event loops and data-sync clients close; the JVM then terminates on the signal | `143` (`128 + SIGTERM`) in the normal case, `0` only if the application exits during shutdown | +| Grace period exceeded, then `SIGKILL` | runtime kills the process | `137` | +| Startup failure (bad config, missing class, port in use) | JVM exits | `1` | + +Both `0` and `143` indicate a graceful stop: the signal reached the JVM and the +hooks ran. `137` means the shutdown took longer than the grace period, which is +the signal to raise `terminationGracePeriodSeconds` or shorten the shutdown +hooks. + +Set `terminationGracePeriodSeconds` to at least `30` for the gateway and `60` +for the admin so that the shutdown hooks can finish before the runtime sends +`SIGKILL`. The default `docker stop` grace period is 10 seconds and is too short +for a busy gateway. + +### 2.4 JVM option overrides + +| Image | Environment variable | Default (unchanged from previous releases) | +|---|---|---| +| bootstrap | `BOOT_JVM` | `-server -Xmx2g -Xms2g -Xmn1g -Xss512k -XX:+DisableExplicitGC -XX:LargePageSizeInBytes=128m` | +| admin | `ADMIN_JVM` | `-server -Xmx2g -Xms2g -Xmn1g -Xss328k -XX:+DisableExplicitGC -XX:LargePageSizeInBytes=128m` | + +`BOOT_JVM` / `ADMIN_JVM` **replace** the default option string; they are not +appended to it. Container-aware sizing is therefore an explicit, reviewable +change per deployment (see section 3). Note that the e2e/compose fixtures pass +`-Xmx768m -Xms768m` through Kubernetes `args:` / Compose `command:`; those are +application arguments passed after the main class, not JVM flags — set JVM +options through `BOOT_JVM`/`ADMIN_JVM` instead. + +## 3. JVM and container memory budgets + +The default `-Xmx2g` is a JVM setting, not a container-aware one: it does not +shrink or grow with the pod limit. Size the container from the JVM budget, not +the other way around. + +| Component | Flag | Default / guidance | +|---|---|---| +| Java heap | `-Xmx`, `-Xms`, `-Xmn` | keep `Xms == Xmx` for gateways; with a container limit use `-XX:MaxRAMPercentage=70..75` | +| Metaspace | `-XX:MaxMetaspaceSize` | 256 MiB is enough for a normal plugin set; a large plugin set can need 384 MiB | +| Code cache | `-XX:ReservedCodeCacheSize` | JVM default is fine (240 MiB reserved, mostly virtual) | +| Direct/native buffers | `-XX:MaxDirectMemorySize` | Netty and HTTP clients allocate outside the heap; budget 10-20% of the limit, at least 256 MiB | +| Thread stacks | `-Xss` | gateway default 512 KiB; every request/selector thread adds a stack | +| GC and JVM overhead | — | reserve ~25-30% headroom above heap + metaspace + direct memory | +| Connection pools | plugin config | `maxConnections` per upstream client, database pool sizes; these consume heap *and* file descriptors | + +Example for a `2Gi` memory limit: + +```yaml +env: + - name: BOOT_JVM + value: >- + -XX:MaxRAMPercentage=70 -XX:InitialRAMPercentage=40 + -XX:MaxMetaspaceSize=256m -XX:MaxDirectMemorySize=256m + -Xss512k -XX:+ExitOnOutOfMemoryError +resources: + requests: + memory: 2Gi + limits: + memory: 2Gi +``` + +Rules of thumb: + +* keep the heap below ~70% of the memory limit so direct buffers, metaspace, + thread stacks and GC structures fit without triggering the OOM killer; +* `-XX:+ExitOnOutOfMemoryError` is recommended for containers: a process that + cannot allocate should restart instead of thrashing; +* for CPU-sized thread pools, remember that `-Xss` multiplies by the number of + threads; raising the thread count without raising the memory limit is a + common OOM source for gateways. + +## 4. Kubernetes production defaults + +The following snippets are starting points, not universal values. They encode +the runtime contract above: non-root, read-only root filesystem, an `emptyDir` +for `/tmp`, probes on the Spring Boot health endpoint, a disruption budget and +topology spread for multi-zone clusters. + +### 4.1 Bootstrap + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: shenyu-bootstrap +spec: + replicas: 2 + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 1 + maxUnavailable: 0 + selector: + matchLabels: + app: shenyu-bootstrap + template: + metadata: + labels: + app: shenyu-bootstrap + spec: + terminationGracePeriodSeconds: 60 + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: + type: RuntimeDefault + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app: shenyu-bootstrap + containers: + - name: shenyu-bootstrap + image: apache/shenyu-bootstrap: + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 9195 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + requests: + cpu: 500m + memory: 2Gi + limits: + cpu: "2" + memory: 2Gi + env: + # Activates the mounted application-bootstrap-sync-websocket.yml; without + # it Spring Boot ignores the file and the gateway keeps the packaged + # ws://localhost:9095 default. + - name: SPRING_PROFILES_ACTIVE + value: bootstrap-sync-websocket + - name: BOOT_JVM + value: >- + -XX:MaxRAMPercentage=70 -XX:InitialRAMPercentage=40 + -XX:MaxMetaspaceSize=256m -XX:MaxDirectMemorySize=256m + -Xss512k -XX:+ExitOnOutOfMemoryError + volumeMounts: + - name: tmp + mountPath: /tmp + - name: shenyu-bootstrap-application + mountPath: /opt/shenyu-bootstrap/conf/application.yml + subPath: shenyu-bootstrap-application.yml + - name: shenyu-bootstrap-sync + mountPath: /opt/shenyu-bootstrap/conf/application-bootstrap-sync-websocket.yml + subPath: application-bootstrap-sync-websocket.yml + startupProbe: + httpGet: + path: /actuator/health/readiness + port: http + periodSeconds: 5 + failureThreshold: 36 + readinessProbe: + httpGet: + path: /actuator/health/readiness + port: http + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 3 + livenessProbe: + httpGet: + path: /actuator/health/liveness + port: http + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 6 + volumes: + - name: tmp + emptyDir: + sizeLimit: 256Mi + - name: shenyu-bootstrap-application + configMap: + name: shenyu-configmap + items: + - key: shenyu-bootstrap-application.yml + path: shenyu-bootstrap-application.yml + - name: shenyu-bootstrap-sync + configMap: + name: shenyu-configmap + items: + - key: application-bootstrap-sync-websocket.yml + path: application-bootstrap-sync-websocket.yml +--- +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: shenyu-bootstrap +spec: + maxUnavailable: 1 + selector: + matchLabels: + app: shenyu-bootstrap +``` + +The readiness group only becomes meaningful with these properties in the mounted +sync profile (`application-bootstrap-sync-websocket.yml`): + +```yaml +management: + endpoint: + health: + probes: + enabled: true + group: + readiness: + include: readinessState,websocketSync + liveness: + include: livenessState +shenyu: + sync: + websocket: + initial-sync-readiness: true + urls: ws://shenyu-admin:9095/websocket +``` + +With `initial-sync-readiness: true`, the `websocketSync` health indicator joins +the readiness group and the pod only reports ready after the first full config +sync; without `probes.enabled: true` the `/actuator/health/readiness` and +`/actuator/health/liveness` endpoints do not exist. `shenyu-cm.yml` in +`shenyu-e2e/shenyu-e2e-case/k8s/sync/` is the working reference. + +### 4.2 Admin + +The admin adds a database dependency and a heavier startup, so it uses a longer +`startupProbe` window. Keep `maxUnavailable: 0` for the admin when the database is +shared with the gateways' configuration, so configuration writes never stop +during a rollout. + +Reuse the bootstrap Deployment scaffolding (pod security context, `emptyDir` +`/tmp`, `readOnlyRootFilesystem`, topology spread, `terminationGracePeriodSeconds`) +and replace everything below `containers:` with this block: + +```yaml + - name: shenyu-admin + image: apache/shenyu-admin: + imagePullPolicy: IfNotPresent + ports: + - name: http + containerPort: 9095 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + requests: + cpu: "1" + memory: 2Gi + limits: + cpu: "2" + memory: 2Gi + env: + # Required by current admin releases: multiple admin instances must + # share the same JWT signing key or tokens fail verification randomly. + - name: SHENYU_JWT_SECRETKEY + valueFrom: + secretKeyRef: + name: shenyu-admin-secrets + key: jwt-secret-key + # Selects the packaged database profile (h2 is the default and is + # in-memory only; use mysql/pg/oracle/ob/og in production). + - name: SPRING_PROFILES_ACTIVE + value: mysql + - name: ADMIN_JVM + value: >- + -XX:MaxRAMPercentage=70 -XX:InitialRAMPercentage=40 + -XX:MaxMetaspaceSize=384m -XX:MaxDirectMemorySize=256m + -Xss328k -XX:+ExitOnOutOfMemoryError + volumeMounts: + - name: tmp + mountPath: /tmp + - name: shenyu-admin-application + mountPath: /opt/shenyu-admin/conf/application.yml + subPath: shenyu-admin-application.yml + startupProbe: + httpGet: + path: /actuator/health + port: http + periodSeconds: 5 + failureThreshold: 60 + readinessProbe: + httpGet: + path: /actuator/health + port: http + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 3 + livenessProbe: + httpGet: + path: /actuator/health + port: http + periodSeconds: 15 + timeoutSeconds: 3 + failureThreshold: 6 +``` + +and the bootstrap `volumes:` block with: + +```yaml + volumes: + - name: tmp + emptyDir: + sizeLimit: 256Mi + - name: shenyu-admin-application + configMap: + name: shenyu-admin-configmap + items: + - key: shenyu-admin-application.yml + path: shenyu-admin-application.yml +``` + +The admin listens on `9095` and must not mount the bootstrap config files. Keep +its probes on the aggregate `/actuator/health`, which includes the database +health indicator: the pod should not be ready while its database is unreachable. + +Without `shenyu.jwt.secret-key` (or `SHENYU_JWT_SECRETKEY`) the admin fails +fast at startup instead of booting with a per-instance random key, which would +cause intermittent `401`s behind a load balancer. + +### 4.3 Probe notes + +* `startupProbe` exists because both applications need to load plugins and + establish the data-sync channel before they are ready; a plain liveness probe + would restart a healthy, still-starting pod. +* Bootstrap probes target `/actuator/health/readiness` and + `/actuator/health/liveness`; those endpoints require the two properties shown + in 4.1. Admin probes use the aggregate `/actuator/health` because it includes + the database health indicator, which is the desired readiness signal for the + control plane; a pod that cannot reach its database should not serve dashboard + traffic. +* Keep probe timeouts at 3 seconds or less; a slow probe itself becomes a + liveness failure during GC pauses. +* The image declares a Docker `HEALTHCHECK` (`/actuator/health`). It is + intentionally not a replacement for Kubernetes probes: `HEALTHCHECK` has no + readiness semantics and Kubernetes ignores it. + +## 5. Upgrade and rollback + +The images are stateless: configuration comes from ConfigMaps/`conf-ext`, +secrets and environment variables; the admin stores state in its database. That +makes rollback a matter of repointing the image tag. + +1. Pin releases by digest (`image: apache/shenyu-bootstrap@sha256:...`) or by an + immutable version tag; never deploy `latest` in production. +2. Roll out with `maxSurge: 1`, `maxUnavailable: 0` and a + `PodDisruptionBudget`. New pods must pass the readiness probe before old pods + are removed. +3. Keep the previous tag available for the rollback window and roll back by + reverting to it. Configuration lives in ConfigMaps, Secrets and `conf-ext`, + not in the image, so the previous image reads the same configuration; the + smoke test restarts the image under a different tag with the same mounted + configuration to verify that invariant, but a cross-version rollback against + a previously published tag remains a manual release step (and a deliberate + follow-up for automated coverage). +4. Database schema changes belong to the admin release process; read the + release notes before rolling the admin back across a schema version. +5. Do not change the base image and the application version in the same + deployment if you can avoid it: it makes bisecting an incident harder. +6. Roll back the whole pod template, not just the image tag. The hardened + manifests assume this contract (`readOnlyRootFilesystem: true`, numeric UID + `10001`, `/actuator/health/readiness` and `/actuator/health/liveness`); + images published before this change run as root, write into `conf`, and do + not expose the readiness groups unless the mounted profile enables + `management.endpoint.health.probes.enabled`. Swapping only the image tag in + the new manifest can therefore CrashLoop or never become ready. + `kubectl rollout undo` reverts the whole ReplicaSet template (image, + security context and probes together) and is the safe path; otherwise keep + the previous Deployment/StatefulSet manifest next to the previous tag. + `script/docker-image-smoke.sh` can verify the image side of this on demand + with `SHENYU_SMOKE_PREVIOUS_TAG=` (see section 8): it pulls + the previous image and starts it with the same `conf-ext` mount under that + release's own (writable, non-read-only) contract. + +## 6. Baseline measurements + +Record these values in the release notes whenever the base image or distribution +changes: + +```bash +# image size (uncompressed bytes) and digest (falls back to the local image ID +# for a tag that was never pushed) +docker image inspect --format '{{.Size}} {{if .RepoDigests}}{{index .RepoDigests 0}}{{else}}{{.Id}}{{end}}' apache/shenyu-bootstrap: + +# time to healthy +start=$(date +%s) +docker run --rm -d --read-only --tmpfs /tmp:rw,size=64m -p 9195:9195 \ + apache/shenyu-bootstrap: +until wget -q -O /dev/null http://127.0.0.1:9195/actuator/health; do sleep 1; done +echo "healthy after $(( $(date +%s) - start ))s" + +# steady-state memory after the gateway has served traffic +docker stats --no-stream +``` + +Reference numbers for `2.7.2-SNAPSHOT` on `linux/amd64` (Docker 29, 4 vCPU, +default H2 admin profile, no `conf-ext` overrides). Image sizes are the +`docker image inspect --format '{{.Size}}'` values (the same number `docker image +ls` shows; it sums the uncompressed base layers plus the distribution payload, +so registry-compressed sizes are smaller). The time-to-healthy values come from +`SHENYU_SMOKE_REAL_DIST=1 script/docker-image-smoke.sh`; the startup and RSS +values come from a separate run that uses the default `BOOT_JVM`/`ADMIN_JVM` +option strings from the image and leaves the container idle after startup: + +| Metric | bootstrap | admin | +|---|---|---| +| image size on disk (uncompressed `docker image inspect .Size`) | 745 MB (~711 MiB) | 751 MB (~716 MiB) | +| time to "Started Shenyu*" | ~7 s | ~15 s | +| time to `/actuator/health` = `UP` | ~11 s | ~20 s | +| idle RSS with the default JVM options | ~436 MiB | ~1002 MiB | +| idle RSS with the container-aware options in section 3, 2 GiB limit | ~340 MiB | ~404 MiB | + +The idle RSS figures are measured before the gateway serves any traffic (no +plugins with routes registered). Gateway memory grows with the number of +selectors/rules, plugin caches, upstream connections and in-flight requests, so +use them as a starting point for the `limits` value, not as a target. + +The images include a full JDK, so most of that size is the base image; the +compressed registry size is smaller. Startup time grows with the number of +gateway plugins and with a remote database, so treat these values as a floor for +regression tracking rather than as deployment expectations. + +The `script/docker-image-smoke.sh` script prints image sizes and verifies the +non-root/read-only/shutdown contract; use it together with the numbers above as +the change record. + +## 7. SBOMs, scanning and signing + +The image contract supports standard supply-chain tooling: + +```bash +# SBOM (SPDX or CycloneDX) +syft packages docker:apache/shenyu-bootstrap: -o spdx-json > bootstrap.spdx.json +syft packages docker:apache/shenyu-admin: -o cyclonedx-json > admin.cdx.json + +# vulnerability scan +trivy image --severity HIGH,CRITICAL --ignore-unfixed apache/shenyu-bootstrap: +``` + +Integrating scanning into CI and attaching SBOMs to releases is a follow-up on +top of #8072: image signing and provenance must go through the existing ASF +release process (the artifact must not acquire a second, parallel release +authority). Until that is agreed, generate SBOMs/scans locally or in an external +pipeline rather than publishing them as release artifacts. + +## 8. Local verification + +```bash +# 1. Runtime contract only: builds stub distributions, no Maven build needed +bash script/docker-image-smoke.sh +# same thing through the convenience target +make smoke-image + +# 2. Full images from the real distributions +./mvnw -Prelease package -DskipTests -Drat.skip=true -Djacoco.skip=true \ + -pl shenyu-dist/shenyu-bootstrap-dist,shenyu-dist/shenyu-admin-dist -am +SHENYU_SMOKE_REAL_DIST=1 bash script/docker-image-smoke.sh + +# 2b. Cross-version rollback check: starts the previous published release with +# the same mounted configuration (pulls apache/shenyu-{bootstrap,admin}:) +SHENYU_SMOKE_PREVIOUS_TAG=2.7.1 bash script/docker-image-smoke.sh + +# 3. Manual image build (also used by the Makefile) +docker build -t apache/shenyu-bootstrap:local \ + -f shenyu-dist/shenyu-bootstrap-dist/docker/Dockerfile \ + --build-arg APP_NAME=apache-shenyu--bootstrap-bin \ + shenyu-dist/shenyu-bootstrap-dist +``` + +On Windows, run the script from Git Bash (`C:\Program Files\Git\bin\bash.exe`) or +from WSL with Docker Desktop integration; a plain `bash` in `cmd`/PowerShell can +resolve to the WSL launcher, which cannot talk to the Windows Docker daemon. The +repository's `.gitattributes` keeps the entrypoints and scripts on LF so a +Windows checkout does not break `sh entrypoint.sh` inside the image. + +The smoke test checks the following: + +* both images: UID `10001`, a read-only root filesystem while `/tmp` stays + writable, and `BOOT_JVM`/`ADMIN_JVM` applied (the stub app writes to `/tmp` + explicitly; the real-dist run exercises the real entrypoint and JVM); +* `SIGTERM` reaches the JVM, the shutdown hook completes, and the process exits + with `0`/`143` instead of being killed with `137`; +* real-dist mode additionally waits for `/actuator/health` = `UP` and for Docker + to report the image `HEALTHCHECK` as `healthy`, so a broken healthcheck cannot + ship silently; +* stub mode additionally checks the `conf-ext` paths (read-only classpath + fallback and the legacy writable copy) and that restarting the image under a + different tag reads the same mounted configuration; +* `SHENYU_SMOKE_PREVIOUS_TAG=` additionally pulls that published + release and verifies it starts and stops gracefully with the same mounted + configuration (the previous image is run with its own contract: writable root + filesystem, no fixed UID, old entrypoint). + +CI runs the stub variant (`.github/workflows/docker-image-smoke.yml`) for pull +requests that touch the distribution Dockerfiles, entrypoints, assembly +descriptors, `Makefile`, this guide or the smoke script itself. + +## 9. Behavior changes relative to the previous images + +| Change | Impact | +|---|---| +| Runtime base moved from `eclipse-temurin:17-centos7` (CentOS 7, EOL) to `amazoncorretto:17.0.21-alpine3.24`; the admin image moved from `17.0.11-alpine3.19` to the same tag | maintained base with security patches for `linux/amd64` and `linux/arm64` | +| Bootstrap switched from glibc (CentOS 7) to musl (Alpine) | pure-Java plugins are unaffected; JNI libraries built only against glibc cannot be loaded (check the native dependencies of custom plugins before upgrading) | +| `bash` is no longer present (the bootstrap image used to ship it; the admin image was already Alpine-based) | `docker exec ... bash` and the tarball's `bin/*.sh` helpers do not work inside the container; use `sh` and the POSIX entrypoint, or `jcmd`/`jstack` for diagnostics | +| Bootstrap loses `curl` (the old CentOS 7 base shipped `curl` and GNU `wget`); both images now ship BusyBox-traditional `wget` only, the admin image also keeps `curl` | in-container scripts/healthchecks that call `curl` must switch to `wget -q -O /dev/null` (or install `curl` in a derived image); the image `HEALTHCHECK` and the compose example already use `wget` | +| Entrypoint rewritten as POSIX `sh` and always `exec`s the JVM | no bash dependency; SIGTERM is delivered to the JVM directly | +| Fixed numeric UID/GID `10001` (`USER 10001:10001`) | `runAsUser` is stable, and `runAsNonRoot: true` can be verified by the kubelet; explicitly set `runAsUser`/`runAsGroup` in manifests that previously relied on an image-local user | +| `readOnlyRootFilesystem` fully supported | mount `emptyDir`/`tmpfs` on `/tmp`; `conf-ext` falls back to a classpath override | +| `HEALTHCHECK` and `STOPSIGNAL SIGTERM` declared | Docker/Compose users get a health signal and a correct stop signal by default; `HEALTHCHECK` uses `wget`, so the admin image keeps `curl` only as an operator convenience | diff --git a/script/docker-image-smoke.sh b/script/docker-image-smoke.sh new file mode 100644 index 000000000000..46c8745def9d --- /dev/null +++ b/script/docker-image-smoke.sh @@ -0,0 +1,563 @@ +#!/usr/bin/env bash + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Container runtime smoke test for the shenyu-dist images. +# +# It validates the parts of the image contract that are easy to regress: +# * a fixed non-root UID, +# * startup on a read-only root filesystem with only /tmp writable, +# * conf-ext overrides working without writing to the image, +# * SIGTERM forwarding to the JVM and graceful shutdown, +# * the JVM option environment override (BOOT_JVM / ADMIN_JVM), +# * restarting the image with the same mounted configuration (rollback mounts). +# +# By default the script builds throw-away stub distributions, so it does not need +# a Maven build. Set SHENYU_SMOKE_REAL_DIST=1 to smoke the tarballs produced by: +# ./mvnw -Prelease package -pl shenyu-dist/shenyu-bootstrap-dist,shenyu-dist/shenyu-admin-dist -am +# +# Requirements: bash, docker, javac/jar (17+), tar. +# +# Optional environment variables: +# SHENYU_SMOKE_REAL_DIST=1 smoke the real tarballs instead of stubs +# SHENYU_SMOKE_BASE_IMAGE expected runtime base (default: the pinned tag) +# SHENYU_SMOKE_PREPARE_IMAGE expected prepare-stage base +# SHENYU_SMOKE_UID expected container UID (default 10001) +# SHENYU_SMOKE_JVM_ARGS JVM options used inside the smoke containers +# SHENYU_SMOKE_IMAGE_PREFIX image name prefix (default shenyu-smoke) +# SHENYU_SMOKE_PREVIOUS_TAG opt-in: also verify a previous published release +# (e.g. 2.7.1) still starts with the same mounted +# configuration (pulls the image from the registry) +# SHENYU_SMOKE_PREVIOUS_IMAGE_PREFIX +# registry prefix for previous images +# (default apache/shenyu) + +set -euo pipefail + +# Git Bash/MSYS would rewrite the container-side paths passed to docker. +export MSYS_NO_PATHCONV=1 + +REPO_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +readonly REPO_ROOT + +BASE_IMAGE=${SHENYU_SMOKE_BASE_IMAGE:-amazoncorretto:17.0.21-alpine3.24} +readonly BASE_IMAGE +PREPARE_IMAGE=${SHENYU_SMOKE_PREPARE_IMAGE:-alpine:3.24} +readonly PREPARE_IMAGE +USE_REAL_DIST=${SHENYU_SMOKE_REAL_DIST:-0} +readonly USE_REAL_DIST +EXPECTED_UID=${SHENYU_SMOKE_UID:-10001} +readonly EXPECTED_UID +JVM_ARGS_OVERRIDE=${SHENYU_SMOKE_JVM_ARGS:-} +readonly JVM_ARGS_OVERRIDE +PREVIOUS_TAG=${SHENYU_SMOKE_PREVIOUS_TAG:-} +readonly PREVIOUS_TAG +PREVIOUS_IMAGE_PREFIX=${SHENYU_SMOKE_PREVIOUS_IMAGE_PREFIX:-apache/shenyu} +readonly PREVIOUS_IMAGE_PREFIX + +WORK_DIR=$(mktemp -d) +readonly WORK_DIR +CONTAINERS=() + +log() { + # Progress goes to stderr so that command substitutions can only capture + # values (image tags, context paths). + printf '[docker-image-smoke] %s\n' "$*" >&2 +} + +fail() { + printf '[docker-image-smoke] ERROR: %s\n' "$*" >&2 + exit 1 +} + +cleanup() { + local name + for name in "${CONTAINERS[@]:-}"; do + docker rm -f "${name}" >/dev/null 2>&1 || true + done + rm -rf "${WORK_DIR}" +} +trap cleanup EXIT + +# Git Bash/MSYS rewrites arguments that look like Linux paths. Hand docker and +# the host JDK the native representation of host paths; container paths stay as +# they are because MSYS_NO_PATHCONV is exported above. +to_native_path() { + if command -v cygpath >/dev/null 2>&1; then + cygpath -m "$1" + else + printf '%s\n' "$1" + fi +} + +# GNU tar treats "C:/..." as a remote host spec; on Git Bash the archive paths +# must be passed in the MSYS form instead. +to_tar_path() { + if command -v cygpath >/dev/null 2>&1; then + cygpath -u "$1" + else + printf '%s\n' "$1" + fi +} + +require_tools() { + local tool tools="docker tar" + # javac/jar are only needed to synthesize the stub distributions. + if [ "${USE_REAL_DIST}" = "0" ]; then + tools="${tools} javac jar" + fi + for tool in ${tools}; do + command -v "${tool}" >/dev/null 2>&1 || fail "required tool not found: ${tool}" + done + docker info >/dev/null 2>&1 || fail "docker daemon is not available" +} + +repo_dist_dir() { + printf '%s/shenyu-dist/shenyu-%s-dist' "${REPO_ROOT}" "$1" +} + +dist_mount_path() { + case "$1" in + bootstrap) printf '/opt/shenyu-bootstrap' ;; + admin) printf '/opt/shenyu-admin' ;; + *) fail "unknown distribution kind: $1" ;; + esac +} + +write_stub_source() { + local package="$1" class="$2" out_dir="$3" src_dir + src_dir="${out_dir}/${package//.//}" + mkdir -p "${src_dir}" + cat >"${src_dir}/${class}.java" < System.out.println("SHUTDOWN_HOOK_OK"))); + Path temp = Files.createTempFile("shenyu-smoke", ".tmp"); + Files.writeString(temp, "ok", StandardCharsets.UTF_8); + Files.deleteIfExists(temp); + System.out.println("TMP_OK"); + try (InputStream marker = ${class}.class.getClassLoader().getResourceAsStream("stub.marker")) { + if (marker != null) { + System.out.println("CONF_OVERRIDE_OK:" + new String(marker.readAllBytes(), StandardCharsets.UTF_8).trim()); + } + } + System.out.println("READY"); + System.out.flush(); + new CountDownLatch(1).await(); + } +} +EOF +} + +copy_docker_context_files() { + local kind="$1" context_dir="$2" + mkdir -p "${context_dir}/docker" "${context_dir}/target" + cp "$(repo_dist_dir "${kind}")/docker/Dockerfile" "${context_dir}/docker/Dockerfile" + cp "$(repo_dist_dir "${kind}")/docker/entrypoint.sh" "${context_dir}/docker/entrypoint.sh" + cp "$(repo_dist_dir "${kind}")/docker/logback.xml" "${context_dir}/docker/logback.xml" +} + +build_stub_context() { + local kind="$1" package="$2" class="$3" + local context_dir app_name class_dir + context_dir="${WORK_DIR}/context-${kind}" + app_name="apache-shenyu-smoke-${kind}-bin" + class_dir="${WORK_DIR}/classes-${kind}" + + copy_docker_context_files "${kind}" "${context_dir}" + rm -rf "${WORK_DIR}/src-${kind}" "${class_dir}" + write_stub_source "${package}" "${class}" "${WORK_DIR}/src-${kind}" + mkdir -p "${class_dir}" + # The stub runs inside the image JVM, so target its bytecode level explicitly. + javac --release 17 -d "$(to_native_path "${class_dir}")" \ + "$(to_native_path "${WORK_DIR}/src-${kind}/${package//.//}/${class}.java")" + mkdir -p "${WORK_DIR}/unpack-${kind}/${app_name}/lib" "${WORK_DIR}/unpack-${kind}/${app_name}/conf" + (cd "$(to_native_path "${class_dir}")" && jar --create --file "$(to_native_path "${WORK_DIR}/unpack-${kind}/${app_name}/lib/shenyu-smoke.jar")" .) + cp "$(repo_dist_dir "${kind}")/docker/logback.xml" "${WORK_DIR}/unpack-${kind}/${app_name}/conf/logback.xml" + tar -czf "$(to_tar_path "${context_dir}/target/${app_name}.tar.gz")" -C "$(to_tar_path "${WORK_DIR}/unpack-${kind}")" "${app_name}" + [ -s "${context_dir}/target/${app_name}.tar.gz" ] || fail "failed to create the stub distribution tarball for ${kind}" + printf '%s\n' "${context_dir}" +} + +build_real_context() { + local kind="$1" context_dir tarball="" candidate + context_dir="${WORK_DIR}/context-${kind}" + for candidate in "$(repo_dist_dir "${kind}")/target"/*-"${kind}"-bin.tar.gz; do + if [ -f "${candidate}" ]; then + tarball="${candidate}" + break + fi + done + [ -n "${tarball}" ] || fail "SHENYU_SMOKE_REAL_DIST=1 but no shenyu-${kind} distribution tarball exists; run the Maven build first" + copy_docker_context_files "${kind}" "${context_dir}" + cp "${tarball}" "${context_dir}/target/" + printf '%s\n' "${context_dir}" +} + +build_image() { + local kind="$1" context_dir app_name image candidate tarball_file="" + context_dir=$(if [ "${USE_REAL_DIST}" = "1" ]; then build_real_context "${kind}"; else + case "${kind}" in + bootstrap) build_stub_context "bootstrap" "org.apache.shenyu.bootstrap" "ShenyuBootstrapApplication" ;; + admin) build_stub_context "admin" "org.apache.shenyu.admin" "ShenyuAdminBootstrap" ;; + *) fail "unknown distribution kind: ${kind}" ;; + esac + fi) + [ -n "${context_dir}" ] && [ -d "${context_dir}" ] || fail "failed to prepare the ${kind} docker build context" + for candidate in "${context_dir}/target/"*.tar.gz; do + if [ -f "${candidate}" ]; then + tarball_file="${candidate}" + break + fi + done + [ -n "${tarball_file}" ] || fail "no distribution tarball found in ${context_dir}/target" + app_name=$(basename "${tarball_file}" .tar.gz) + image="${SHENYU_SMOKE_IMAGE_PREFIX:-shenyu-smoke}-${kind}:test" + log "building ${image} from ${app_name}" + if ! docker build --quiet \ + --build-arg "APP_NAME=${app_name}" \ + --file "$(to_native_path "${context_dir}/docker/Dockerfile")" \ + --tag "${image}" \ + "$(to_native_path "${context_dir}")" >/dev/null; then + fail "docker build failed for ${image}" + fi + printf '%s\n' "${image}" +} + +image_size() { + docker image inspect --format '{{.Size}}' "$1" +} + +# Match against captured logs instead of piping them into grep: with +# `set -o pipefail`, `docker logs | grep -q` can fail with 141 (SIGPIPE) when the +# logs are larger than the pipe buffer and grep exits after the first match. +logs_contain() { + local logs="$1" marker="$2" + case "${logs}" in + *"${marker}"*) return 0 ;; + *) return 1 ;; + esac +} + +container_logs() { + docker logs "$1" 2>&1 || true +} + +assert_non_root() { + local image="$1" uid + uid=$(docker run --rm --entrypoint id "${image}" -u) + [ "${uid}" = "${EXPECTED_UID}" ] || fail "${image} runs as uid ${uid}, expected ${EXPECTED_UID}" + log "OK ${image} runs as uid ${uid}" +} + +assert_read_only_rootfs() { + local image="$1" result + # Probe as root so the check depends on the read-only mount, not on the + # non-root user being unable to write /opt in the writable case. The result + # is read back explicitly, so a broken image (no shell, wrong arch) fails + # here instead of being mistaken for a read-only filesystem. + result=$(docker run --rm --read-only --user root --entrypoint sh "${image}" \ + -c 'if touch /read-only-probe 2>/dev/null; then echo writable; else echo readonly; fi' 2>/dev/null || true) + [ "${result}" = "readonly" ] || fail "${image} root filesystem probe returned '${result}', expected 'readonly'" + log "OK ${image} root filesystem is read-only" +} + +assert_healthcheck_configured() { + local image="$1" config + config=$(docker image inspect --format '{{json .Config.Healthcheck}}' "${image}") + logs_contain "${config}" "actuator/health" || fail "${image} does not declare a HEALTHCHECK on /actuator/health" + logs_contain "${config}" "wget" || fail "${image} HEALTHCHECK does not use wget, which the image must ship" + log "OK ${image} declares a HEALTHCHECK on /actuator/health" +} + +wait_for_docker_healthy() { + local container="$1" attempt status + for attempt in $(seq 1 60); do + status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "${container}" 2>/dev/null || echo unknown) + case "${status}" in + healthy) return 0 ;; + unhealthy) fail "container ${container} reported unhealthy" ;; + esac + sleep 5 + done + fail "container ${container} never became healthy (last status: ${status})" +} + +wait_for_log() { + local container="$1" marker="$2" attempt + for attempt in $(seq 1 90); do + if logs_contain "$(container_logs "${container}")" "${marker}"; then + return 0 + fi + if [ "$(docker inspect -f '{{.State.Running}}' "${container}" 2>/dev/null || echo false)" != "true" ]; then + docker logs "${container}" >&2 || true + fail "container ${container} stopped before logging ${marker}" + fi + sleep 1 + done + docker logs "${container}" >&2 || true + fail "timed out waiting for ${marker} in container ${container}" +} + +jvm_args() { + local kind="$1" + if [ -n "${JVM_ARGS_OVERRIDE}" ]; then + printf '%s' "${JVM_ARGS_OVERRIDE}" + elif [ "${USE_REAL_DIST}" = "1" ] && [ "${kind}" = "admin" ]; then + printf '%s' '-Xmx1g -Xms512m' + else + printf '%s' '-Xmx256m -Xms128m' + fi +} + +dist_port() { + case "$1" in + bootstrap) printf '9195' ;; + admin) printf '9095' ;; + *) fail "unknown distribution kind: $1" ;; + esac +} + +start_container() { + local kind="$1" image="$2" conf_dir="$3" jvm_env="$4" extra_env="${5:-}" read_only="${6:-1}" name + local env_args=(--env "${jvm_env}=$(jvm_args "${kind}")") + if [ -n "${extra_env}" ]; then + env_args+=(--env "${extra_env}") + fi + local tmp_args=() + if [ "${read_only}" = "1" ]; then + tmp_args=(--read-only --tmpfs /tmp:rw,size=64m) + fi + name="shenyu-smoke-$$-${RANDOM}" + CONTAINERS+=("${name}") + docker run --detach \ + --name "${name}" \ + "${tmp_args[@]}" \ + "${env_args[@]}" \ + --volume "$(to_native_path "${conf_dir}"):$(dist_mount_path "${kind}")/conf-ext:ro" \ + "${image}" >/dev/null + printf '%s\n' "${name}" +} + +stop_container_gracefully() { + local name="$1" marker="$2" code waited=0 + docker kill --signal=SIGTERM "${name}" >/dev/null + # Never block forever on a container that ignores SIGTERM. + while [ "$(docker inspect -f '{{.State.Running}}' "${name}" 2>/dev/null || echo false)" = "true" ]; do + waited=$((waited + 1)) + if [ "${waited}" -ge 60 ]; then + docker kill --signal=SIGKILL "${name}" >/dev/null 2>&1 || true + fail "container ${name} did not exit within 60s after SIGTERM" + fi + sleep 1 + done + code=$(docker inspect -f '{{.State.ExitCode}}' "${name}") + logs_contain "$(container_logs "${name}")" "${marker}" || fail "shutdown marker ${marker} was not logged by ${name}" + # A JVM that handles SIGTERM runs its shutdown hooks and exits with 143 + # (128 + SIGTERM); 137 would mean it had to be SIGKILLed after the grace period. + case "${code}" in + 0|143) ;; + *) fail "container ${name} exited with ${code} after SIGTERM" ;; + esac + log "OK ${name} stopped gracefully with ${marker} (exit code ${code})" + docker rm -f "${name}" >/dev/null 2>&1 || true +} + +smoke_image() { + local kind="$1" jvm_env="$2" image="$3" conf_dir name + conf_dir="${WORK_DIR}/conf-ext-${kind}" + mkdir -p "${conf_dir}" + + assert_non_root "${image}" + assert_read_only_rootfs "${image}" + assert_healthcheck_configured "${image}" + log "${image} image size: $(image_size "${image}") bytes" + + if [ "${USE_REAL_DIST}" = "1" ]; then + local extra_env="" started=${SECONDS} + if [ "${kind}" = "admin" ]; then + # Current admin releases require an explicit JWT signing key. + extra_env="SHENYU_JWT_SECRETKEY=shenyu-smoke-jwt-secret-key" + fi + name=$(start_container "${kind}" "${image}" "${conf_dir}" "${jvm_env}" "${extra_env}") + wait_for_log "${name}" "Started Shenyu" + logs_contain "$(container_logs "${name}")" "environment variable ${jvm_env} set" \ + || fail "the ${jvm_env} override was not applied" + # Validate the endpoint used by the image HEALTHCHECK and the Kubernetes probes. + local health + health=$(docker exec "${name}" wget -q -O - "http://127.0.0.1:$(dist_port "${kind}")/actuator/health") + logs_contain "${health}" '"status":"UP"' \ + || fail "the actuator health endpoint of ${image} did not report UP: ${health}" + log "OK ${image} reports status UP on /actuator/health after $((SECONDS - started))s" + wait_for_docker_healthy "${name}" + log "OK ${image} Docker HEALTHCHECK reports healthy after $((SECONDS - started))s" + # Logback registers a JVM shutdown hook, so this line proves the SIGTERM + # was delivered to the JVM and its shutdown hooks ran. + stop_container_gracefully "${name}" "Logback context being closed via shutdown hook" + return 0 + fi + + printf 'shenyu-smoke\n' >"${conf_dir}/stub.marker" + name=$(start_container "${kind}" "${image}" "${conf_dir}" "${jvm_env}") + wait_for_log "${name}" "READY" + local logs + logs=$(container_logs "${name}") + logs_contain "${logs}" "TMP_OK" || fail "the JVM could not use a writable temp directory" + logs_contain "${logs}" "CONF_OVERRIDE_OK:shenyu-smoke" \ + || fail "conf-ext overrides were not visible on a read-only root filesystem" + logs_contain "${logs}" "environment variable ${jvm_env} set" \ + || fail "the ${jvm_env} override was not applied" + log "OK ${image} started read-only with conf-ext overrides and ${jvm_env}" + stop_container_gracefully "${name}" "SHUTDOWN_HOOK_OK" +} + +smoke_writable_conf_ext() { + local kind="$1" image="$2" jvm_env="$3" conf_dir name logs + conf_dir="${WORK_DIR}/conf-ext-${kind}" + # Without --read-only the entrypoint must keep the legacy behavior of copying + # conf-ext over conf. + name=$(start_container "${kind}" "${image}" "${conf_dir}" "${jvm_env}" "" "0") + wait_for_log "${name}" "READY" + logs=$(container_logs "${name}") + logs_contain "${logs}" "Applied conf-ext overrides" \ + || fail "the writable conf-ext copy path was not used by ${image}" + logs_contain "${logs}" "CONF_OVERRIDE_OK:shenyu-smoke" \ + || fail "conf-ext overrides were not copied into conf for ${image}" + stop_container_gracefully "${name}" "SHUTDOWN_HOOK_OK" + log "OK writable conf-ext copy path still applies overrides" +} + +smoke_restart_same_config() { + local kind="$1" image="$2" jvm_env="$3" conf_dir name + conf_dir="${WORK_DIR}/conf-ext-${kind}" + # Restarting the image with a different tag and the same mounted config shows + # that overrides are not tied to the image content (a version rollback reuses + # the same ConfigMap/Secret mounts). + docker tag "${image}" "${image}-previous" + name=$(start_container "${kind}" "${image}-previous" "${conf_dir}" "${jvm_env}") + wait_for_log "${name}" "READY" + logs_contain "$(container_logs "${name}")" "CONF_OVERRIDE_OK:shenyu-smoke" \ + || fail "the restarted image did not see the mounted conf-ext configuration" + stop_container_gracefully "${name}" "SHUTDOWN_HOOK_OK" + docker rmi -f "${image}-previous" >/dev/null 2>&1 || true + log "OK restarting the image with the same mounted configuration keeps the overrides" +} + +previous_jvm_env() { + case "$1" in + bootstrap) printf 'BOOT_JVM=-Xmx512m -Xms256m' ;; + admin) printf 'ADMIN_JVM=-Xmx1g -Xms512m' ;; + *) fail "unknown distribution kind: $1" ;; + esac +} + +start_previous_container() { + local kind="$1" image="$2" conf_dir="$3" name extra_env=() + name="shenyu-smoke-previous-$$-${RANDOM}" + CONTAINERS+=("${name}") + if [ "${kind}" = "admin" ]; then + # Current admin releases fail fast without an explicit JWT signing key; + # pass one so a previous release can start too (it is ignored if unused). + extra_env=(--env "SHENYU_JWT_SECRETKEY=shenyu-smoke-jwt-secret-key") + fi + # Previous releases run as root/shenyu with a writable root filesystem and + # copy conf-ext over conf, so they are started with their own contract. The + # point of the check is that the same ConfigMap/conf-ext mounts and the same + # environment still let the previous image start. + docker run --detach \ + --name "${name}" \ + "${extra_env[@]}" \ + --env "$(previous_jvm_env "${kind}")" \ + --volume "$(to_native_path "${conf_dir}"):$(dist_mount_path "${kind}")/conf-ext:ro" \ + "${image}" >/dev/null + printf '%s\n' "${name}" +} + +stop_previous_container() { + local name="$1" code + docker stop --time 60 "${name}" >/dev/null + code=$(docker inspect -f '{{.State.ExitCode}}' "${name}") + case "${code}" in + 0|143) ;; + *) fail "previous-release container ${name} exited with ${code} after SIGTERM" ;; + esac + docker rm -f "${name}" >/dev/null 2>&1 || true +} + +smoke_previous_tag() { + local kind="$1" image conf_dir name + image="${PREVIOUS_IMAGE_PREFIX}-${kind}:${PREVIOUS_TAG}" + conf_dir="${WORK_DIR}/conf-ext-${kind}" + mkdir -p "${conf_dir}" + log "pulling ${image} for the cross-version rollback check" + docker pull "${image}" >/dev/null || fail "could not pull the previous release image ${image}" + name=$(start_previous_container "${kind}" "${image}" "${conf_dir}") + wait_for_log "${name}" "Started Shenyu" + stop_previous_container "${name}" + log "OK previous release ${image} starts and stops with the same mounted configuration" +} + +assert_dockerfile_base() { + local kind + for kind in bootstrap admin; do + grep -q "^FROM ${BASE_IMAGE}" "$(repo_dist_dir "${kind}")/docker/Dockerfile" \ + || fail "the ${kind} Dockerfile must use FROM ${BASE_IMAGE}; bump the Dockerfiles, this script and docs/container-runtime.md together" + grep -q "^FROM ${PREPARE_IMAGE} AS prepare" "$(repo_dist_dir "${kind}")/docker/Dockerfile" \ + || fail "the ${kind} Dockerfile must unpack the distribution on FROM ${PREPARE_IMAGE} AS prepare" + done + log "OK both Dockerfiles pin the expected base image ${BASE_IMAGE} (prepare: ${PREPARE_IMAGE})" +} + +main() { + require_tools + [ "${EXPECTED_UID}" != "0" ] || fail "the expected UID must not be 0: the image contract requires a non-root user" + log "base image: ${BASE_IMAGE}" + assert_dockerfile_base + local bootstrap_image admin_image + bootstrap_image=$(build_image bootstrap) + admin_image=$(build_image admin) + + smoke_image "bootstrap" "BOOT_JVM" "${bootstrap_image}" + smoke_image "admin" "ADMIN_JVM" "${admin_image}" + + if [ "${USE_REAL_DIST}" = "0" ]; then + smoke_writable_conf_ext "bootstrap" "${bootstrap_image}" "BOOT_JVM" + smoke_restart_same_config "bootstrap" "${bootstrap_image}" "BOOT_JVM" + fi + + if [ -n "${PREVIOUS_TAG}" ]; then + log "cross-version rollback check against ${PREVIOUS_IMAGE_PREFIX}-*:${PREVIOUS_TAG}" + smoke_previous_tag bootstrap + smoke_previous_tag admin + fi + + log "all container runtime smoke checks passed" +} + +main "$@" diff --git a/shenyu-dist/shenyu-admin-dist/docker/Dockerfile b/shenyu-dist/shenyu-admin-dist/docker/Dockerfile index 44d28b76ba85..97992ef1fec3 100644 --- a/shenyu-dist/shenyu-admin-dist/docker/Dockerfile +++ b/shenyu-dist/shenyu-admin-dist/docker/Dockerfile @@ -14,7 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -FROM alpine AS prepare +# The prepare stage only unpacks the distribution tarball. Keep it on the same +# maintained Alpine generation as the runtime image so no EOL base is pulled. +FROM alpine:3.24 AS prepare ARG APP_NAME @@ -23,26 +25,44 @@ ENV LOCAL_PATH /opt/shenyu-admin ADD target/${APP_NAME}.tar.gz /opt RUN mv /opt/${APP_NAME} ${LOCAL_PATH} -FROM amazoncorretto:17.0.11-alpine3.19 +# Runtime: a maintained Corretto 17 JDK on Alpine (linux/amd64 and linux/arm64). +# Keep the exact patch tag in sync with shenyu-bootstrap-dist; bump both together +# and record the change in docs/container-runtime.md. +FROM amazoncorretto:17.0.21-alpine3.24 -RUN apk --no-cache add wget curl && \ - addgroup -S shenyu && \ - adduser -S shenyu -G shenyu && \ - mkdir -p /home/shenyu && \ - chown -R shenyu:shenyu /home/shenyu +# Stable non-root UID/GID: Kubernetes securityContext.runAsUser can rely on it and +# file ownership survives image rebuilds. wget is used by HEALTHCHECK; curl is kept +# for operators that already use it from inside the container. +RUN apk --no-cache add wget curl \ + && addgroup -S -g 10001 shenyu \ + && adduser -S -u 10001 -G shenyu -h /home/shenyu shenyu \ + && mkdir -p /home/shenyu \ + && chown -R shenyu:shenyu /home/shenyu ENV LOCAL_PATH /opt/shenyu-admin ENV ADMIN_JVM "" +# The JVM only needs a writable temp directory at runtime. Mount an emptyDir or +# tmpfs on /tmp when the root filesystem is read-only (see docs/container-runtime.md). +ENV TMPDIR /tmp COPY --chown=shenyu:shenyu --from=prepare ${LOCAL_PATH} ${LOCAL_PATH} COPY --chown=shenyu:shenyu docker/logback.xml ${LOCAL_PATH}/conf/logback.xml COPY --chown=shenyu:shenyu docker/entrypoint.sh ${LOCAL_PATH}/entrypoint.sh -RUN chmod +x ${LOCAL_PATH}/entrypoint.sh +RUN chmod 0755 ${LOCAL_PATH}/entrypoint.sh -WORKDIR /opt/shenyu-admin +WORKDIR ${LOCAL_PATH} -USER shenyu +# Numeric user on purpose: a named user prevents kubelet from verifying a pod +# that only sets securityContext.runAsNonRoot: true (restricted PodSecurity). +USER 10001:10001 EXPOSE 9095 +# The entrypoint execs the JVM, so the JVM stays PID 1 and receives SIGTERM +# directly. Spring Boot then runs its shutdown hooks before the process exits. +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=30s --timeout=5s --start-period=90s --retries=3 \ + CMD wget -q -O /dev/null http://127.0.0.1:9095/actuator/health || exit 1 + ENTRYPOINT ["/bin/sh", "entrypoint.sh"] diff --git a/shenyu-dist/shenyu-admin-dist/docker/entrypoint.sh b/shenyu-dist/shenyu-admin-dist/docker/entrypoint.sh index fcc0e0dd48e9..98c1d204aec7 100644 --- a/shenyu-dist/shenyu-admin-dist/docker/entrypoint.sh +++ b/shenyu-dist/shenyu-admin-dist/docker/entrypoint.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/bin/sh # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file @@ -16,19 +16,59 @@ # See the License for the specific language governing permissions and # limitations under the License. -[[ -d ./conf-ext ]] && cp -f ./conf-ext/* ./conf +# POSIX sh on purpose: both distribution images are Alpine based and do not ship +# bash. Keep this script free of bash-only syntax ([[ ]], arrays, source, ...). + +set -eu + +umask 027 DEPLOY_DIR=$(pwd) EXT_LIB=${DEPLOY_DIR}/ext-lib +EXT_CONF="" + +# Optional configuration overrides. The legacy behavior copies ./conf-ext into +# ./conf; when the image filesystem is read-only, prepend ./conf-ext to the +# classpath instead so the overrides still win without writing to the image. +if [ -d ./conf-ext ]; then + if ( : > ./conf/.shenyu-conf-probe ) 2>/dev/null; then + rm -f ./conf/.shenyu-conf-probe + if cp -f ./conf-ext/* ./conf 2>/dev/null; then + echo "Applied conf-ext overrides into ${DEPLOY_DIR}/conf" + elif [ -n "$(ls -A ./conf-ext 2>/dev/null)" ]; then + # Partial copy: fall back to the classpath so every override still wins. + EXT_CONF=./conf-ext + echo "WARN: conf-ext entries could not be fully copied into ${DEPLOY_DIR}/conf; loading ./conf-ext from the classpath" >&2 + fi + else + EXT_CONF=./conf-ext + echo "Read-only conf directory detected; loading ./conf-ext from the classpath" + fi +fi + +CLASS_PATH=. +if [ -n "${EXT_CONF}" ]; then + CLASS_PATH="${CLASS_PATH}:${EXT_CONF}" +fi +CLASS_PATH="${CLASS_PATH}:${DEPLOY_DIR}/conf:${DEPLOY_DIR}/lib/*:${EXT_LIB}/*" -CLASS_PATH=.:${DEPLOY_DIR}/conf:${DEPLOY_DIR}/lib/*:${EXT_LIB}/* -if [ -z "${ADMIN_JVM}" ]; then +if [ -z "${ADMIN_JVM:-}" ]; then JAVA_OPTS=" -server -Xmx2g -Xms2g -Xmn1g -Xss328k -XX:+DisableExplicitGC -XX:LargePageSizeInBytes=128m" - echo "Use default jvm options: $JAVA_OPTS" + echo "Use default jvm options: ${JAVA_OPTS}" else JAVA_OPTS=${ADMIN_JVM} - echo "Start with the environment variable JAVA_OPTS set: $JAVA_OPTS" + echo "Start with the environment variable ADMIN_JVM set: ${JAVA_OPTS}" +fi + +if [ -n "${JAVA_HOME:-}" ]; then + JAVA_BIN=${JAVA_HOME}/bin/java +else + JAVA_BIN=java fi echo "Starting the Apache ShenYu Admin ..." -exec ${JAVA_HOME}/bin/java ${JAVA_OPTS} -classpath ${CLASS_PATH} org.apache.shenyu.admin.ShenyuAdminBootstrap "$@" + +# exec keeps the JVM as PID 1 so SIGTERM from the container runtime reaches the +# Spring Boot shutdown hooks directly and the JVM exit code is propagated. +# shellcheck disable=SC2086 # JAVA_OPTS is an option string and must word-split. +exec "${JAVA_BIN}" -Djava.io.tmpdir="${TMPDIR:-/tmp}" ${JAVA_OPTS} -classpath "${CLASS_PATH}" org.apache.shenyu.admin.ShenyuAdminBootstrap "$@" diff --git a/shenyu-dist/shenyu-bootstrap-dist/docker/Dockerfile b/shenyu-dist/shenyu-bootstrap-dist/docker/Dockerfile index 06772955f4aa..d7ecdeb3b6dc 100644 --- a/shenyu-dist/shenyu-bootstrap-dist/docker/Dockerfile +++ b/shenyu-dist/shenyu-bootstrap-dist/docker/Dockerfile @@ -14,7 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -FROM centos:7 AS prepare +# The prepare stage only unpacks the distribution tarball. Keep it on the same +# maintained Alpine generation as the runtime image so no EOL base is pulled. +FROM alpine:3.24 AS prepare ARG APP_NAME @@ -23,27 +25,44 @@ ENV LOCAL_PATH /opt/shenyu-bootstrap ADD target/${APP_NAME}.tar.gz /opt RUN mv /opt/${APP_NAME} ${LOCAL_PATH} -# FROM amazoncorretto:17.0.11-alpine3.19 -FROM eclipse-temurin:17-centos7 +# Runtime: a maintained Corretto 17 JDK on Alpine (linux/amd64 and linux/arm64). +# Keep the exact patch tag in sync with shenyu-admin-dist; bump both together and +# record the change in docs/container-runtime.md. +FROM amazoncorretto:17.0.21-alpine3.24 -RUN groupadd -r shenyu && \ - useradd -r -g shenyu -m -d /home/shenyu shenyu && \ - chown -R shenyu:shenyu /home/shenyu - -# RUN apk --no-cache add wget curl +# Stable non-root UID/GID: Kubernetes securityContext.runAsUser can rely on it and +# file ownership survives image rebuilds. wget is installed explicitly because +# HEALTHCHECK depends on it (do not rely on a BusyBox applet staying available). +RUN apk --no-cache add wget \ + && addgroup -S -g 10001 shenyu \ + && adduser -S -u 10001 -G shenyu -h /home/shenyu shenyu \ + && mkdir -p /home/shenyu \ + && chown -R shenyu:shenyu /home/shenyu ENV LOCAL_PATH /opt/shenyu-bootstrap ENV BOOT_JVM "" +# The JVM only needs a writable temp directory at runtime. Mount an emptyDir or +# tmpfs on /tmp when the root filesystem is read-only (see docs/container-runtime.md). +ENV TMPDIR /tmp COPY --chown=shenyu:shenyu --from=prepare ${LOCAL_PATH} ${LOCAL_PATH} COPY --chown=shenyu:shenyu docker/logback.xml ${LOCAL_PATH}/conf/logback.xml COPY --chown=shenyu:shenyu docker/entrypoint.sh ${LOCAL_PATH}/entrypoint.sh -RUN chmod +x ${LOCAL_PATH}/entrypoint.sh +RUN chmod 0755 ${LOCAL_PATH}/entrypoint.sh WORKDIR ${LOCAL_PATH} -USER shenyu +# Numeric user on purpose: a named user prevents kubelet from verifying a pod +# that only sets securityContext.runAsNonRoot: true (restricted PodSecurity). +USER 10001:10001 EXPOSE 9195 +# The entrypoint execs the JVM, so the JVM stays PID 1 and receives SIGTERM +# directly. Spring Boot then runs its shutdown hooks before the process exits. +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ + CMD wget -q -O /dev/null http://127.0.0.1:9195/actuator/health || exit 1 + ENTRYPOINT ["/bin/sh", "entrypoint.sh"] diff --git a/shenyu-dist/shenyu-bootstrap-dist/docker/entrypoint.sh b/shenyu-dist/shenyu-bootstrap-dist/docker/entrypoint.sh index ea5a638a5304..fa027b095bc5 100644 --- a/shenyu-dist/shenyu-bootstrap-dist/docker/entrypoint.sh +++ b/shenyu-dist/shenyu-bootstrap-dist/docker/entrypoint.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/bin/sh # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file @@ -16,20 +16,59 @@ # See the License for the specific language governing permissions and # limitations under the License. -[[ -d ./conf-ext ]] && cp -f ./conf-ext/* ./conf +# POSIX sh on purpose: both distribution images are Alpine based and do not ship +# bash. Keep this script free of bash-only syntax ([[ ]], arrays, source, ...). + +set -eu + +umask 027 DEPLOY_DIR=$(pwd) EXT_LIB=${DEPLOY_DIR}/ext-lib +EXT_CONF="" + +# Optional configuration overrides. The legacy behavior copies ./conf-ext into +# ./conf; when the image filesystem is read-only, prepend ./conf-ext to the +# classpath instead so the overrides still win without writing to the image. +if [ -d ./conf-ext ]; then + if ( : > ./conf/.shenyu-conf-probe ) 2>/dev/null; then + rm -f ./conf/.shenyu-conf-probe + if cp -f ./conf-ext/* ./conf 2>/dev/null; then + echo "Applied conf-ext overrides into ${DEPLOY_DIR}/conf" + elif [ -n "$(ls -A ./conf-ext 2>/dev/null)" ]; then + # Partial copy: fall back to the classpath so every override still wins. + EXT_CONF=./conf-ext + echo "WARN: conf-ext entries could not be fully copied into ${DEPLOY_DIR}/conf; loading ./conf-ext from the classpath" >&2 + fi + else + EXT_CONF=./conf-ext + echo "Read-only conf directory detected; loading ./conf-ext from the classpath" + fi +fi + +CLASS_PATH=. +if [ -n "${EXT_CONF}" ]; then + CLASS_PATH="${CLASS_PATH}:${EXT_CONF}" +fi +CLASS_PATH="${CLASS_PATH}:${DEPLOY_DIR}/conf:${DEPLOY_DIR}/lib/*:${EXT_LIB}/*" -CLASS_PATH=.:${DEPLOY_DIR}/conf:${DEPLOY_DIR}/lib/*:${EXT_LIB}/* -if [ -z "${BOOT_JVM}" ]; then +if [ -z "${BOOT_JVM:-}" ]; then JAVA_OPTS=" -server -Xmx2g -Xms2g -Xmn1g -Xss512k -XX:+DisableExplicitGC -XX:LargePageSizeInBytes=128m" -# JAVA_OPTS="${JAVA_OPTS} -XX:+UseFastAccessorMethods -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70" - echo "Use default jvm options: $JAVA_OPTS" + echo "Use default jvm options: ${JAVA_OPTS}" else JAVA_OPTS=${BOOT_JVM} - echo "Start with the environment variable JAVA_OPTS set: $JAVA_OPTS" + echo "Start with the environment variable BOOT_JVM set: ${JAVA_OPTS}" +fi + +if [ -n "${JAVA_HOME:-}" ]; then + JAVA_BIN=${JAVA_HOME}/bin/java +else + JAVA_BIN=java fi echo "Starting the Apache ShenYu Bootstrap ..." -exec ${JAVA_HOME}/bin/java ${JAVA_OPTS} -classpath ${CLASS_PATH} org.apache.shenyu.bootstrap.ShenyuBootstrapApplication "$@" + +# exec keeps the JVM as PID 1 so SIGTERM from the container runtime reaches the +# Spring Boot shutdown hooks directly and the JVM exit code is propagated. +# shellcheck disable=SC2086 # JAVA_OPTS is an option string and must word-split. +exec "${JAVA_BIN}" -Djava.io.tmpdir="${TMPDIR:-/tmp}" ${JAVA_OPTS} -classpath "${CLASS_PATH}" org.apache.shenyu.bootstrap.ShenyuBootstrapApplication "$@" diff --git a/shenyu-dist/shenyu-docker-compose-dist/src/main/resources/docker-compose.yaml b/shenyu-dist/shenyu-docker-compose-dist/src/main/resources/docker-compose.yaml index ec0778f1118f..99864b2f7db6 100644 --- a/shenyu-dist/shenyu-docker-compose-dist/src/main/resources/docker-compose.yaml +++ b/shenyu-dist/shenyu-docker-compose-dist/src/main/resources/docker-compose.yaml @@ -31,7 +31,7 @@ services: environment: - shenyu.sync.websocket.urls=ws://shenyu-admin:9095/websocket healthcheck: - test: [ "CMD", "wget", "http://shenyu-bootstrap:9195/actuator/health" ] + test: [ "CMD", "wget", "-q", "-O", "/dev/null", "http://shenyu-bootstrap:9195/actuator/health" ] timeout: 2s retries: 30 shenyu-admin: