Add crac module: Spring Boot 4.2 started by CRaC checkpoint/restore vs JDK AOT cache vs native image

One service, seven start-up configurations measured over ten interleaved rounds on Temurin 25, Zulu 25 CRaC and Oracle GraalVM 25;
the open-file checkpoint failure and its fix, stale environment values, secrets in the checkpoint, warp and CRIU engines, cold page cache.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i
This commit is contained in:
asmhatre
2026-11-29 13:51:08 +05:30
co-authored by Claude Sonnet 5.5
parent de2660e998
commit c0062ea398
33 changed files with 882 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
target/
+63
View File
@@ -0,0 +1,63 @@
# crac: one Spring Boot service started four ways
Companion module for the ankurm.com post **Spring Boot with CRaC: Checkpoint/Restore Startup Compared with the JDK AOT Cache and a Native Image**.
No `docs/` folder: this README, the sources and the raw files in [`output/`](output) are the documentation; the explanations live in the post.
## What was tested against
| Thing | Version |
|---|---|
| Spring Boot | 4.2.0 (Spring Framework 7.1.0, Tomcat 11.0.27), `webmvc` + `validation` + `actuator`, no database |
| `org.crac:crac` | 1.5.0 (managed by the Boot 4.2.0 BOM) |
| Plain JVM and AOT cache | Temurin 25.0.5.1+2 (LTS) |
| CRaC JVM | Azul Zulu 25.38.203 with CRaC, `25.0.5.1.1` (LTS) |
| Native image | Oracle GraalVM 25.0.4+7.1, `native-image` 25.0.4, Spring Boot's `native` profile |
| Machine | 2 vCPU, 8 GB, Linux 6.18 (Firecracker VM), running as root. The host was shared with other jobs, so treat milliseconds as indicative and ratios as the result |
## The service
`OrderController` (`/ping`, `POST /orders`, `GET /orders/{id}`), `InfoController` (`/info`: pid, restore count, an environment variable read at start-up and read now),
`RestoreTracker` (a plain `org.crac.Resource`), and three profiles of the audit-log resource:
| Profile | Class | Behaviour |
|---|---|---|
| (none) | - | no file is held open |
| `leaky` | [`LeakyAuditLog`](src/main/java/com/ankurm/crac/LeakyAuditLog.java) | opens a file in the constructor and keeps it: a checkpoint is refused |
| `managed` | [`ManagedAuditLog`](src/main/java/com/ankurm/crac/ManagedAuditLog.java) | opens in `start()`, closes in `stop()`: Spring closes it before the checkpoint and reopens it after the restore |
## Run it
```bash
export JDK_PLAIN=/path/to/temurin-25 JDK_CRAC=/path/to/zulu-25-crac JDK_GRAAL=/path/to/graalvm-25 # defaults are in scripts/env.sh
./scripts/build.sh # jar + extracted layout
./scripts/native.sh # native image (5 to 14 minutes, 5 GB peak)
./scripts/versions.sh # output/01
./scripts/checkpoints.sh # CRaC checkpoints (start-up and warmed-up) and AOT caches; output/02
./scripts/resources.sh # open file, managed file, environment variables, secrets in the image; output/03-05
./scripts/engines.sh # warp and CRIU engines; output/06
./scripts/bench.sh 10 # interleaved rounds of seven start-up configurations; output/08
./scripts/cold.sh 5 # the same with the page cache emptied (root); output/09
./scripts/run-all.sh # everything above, about 25 minutes
```
The scripts use a private port (18771) and a work directory (`/tmp/crac-work`) so they do not collide with other services. Checkpoints, caches and logs live there and are not committed.
## Captured output
| File | Produced by | What it shows |
|---|---|---|
| `01-versions.txt` | `versions.sh` | the exact JDKs, Spring jars and machine |
| `02-create.txt` | `checkpoints.sh` | creating the two checkpoints and two AOT caches: time, size, log lines |
| `03-leaky.txt` | `resources.sh` | `CheckpointOpenFileException`: start-up checkpoint kills the app (exit 1), `jcmd` checkpoint is refused and the app keeps running |
| `04-managed.txt` | `resources.sh` | the fixed file: close/open hooks, Spring's lifecycle restart, the audit file continuing across a restore |
| `05-environment.txt` | `resources.sh` | `System.getenv()` after restore vs a value cached in a field, a new pid, a secret found in `core.img` |
| `06-engines.txt` | `engines.sh` | `warp` and `criuengine` both checkpoint and restore here; what CRIU needs from the process |
| `07-native-build.txt` | `native.sh` (summary of the real build log) | native build time, memory, image size |
| `08-bench.txt` | `bench.sh` | median and range of ten rounds: ready time, first POST, steady state, RSS |
| `09-cold-cache.txt` | `cold.sh` | ready time with an empty page cache |
Timings and RSS differ from run to run; everything else (exceptions, log lines, counts) is stable.
## Things that are not covered
No Docker image was built or run for CRaC; no Kubernetes, no Liberica CRaC JDK, no database or connection pool, and no restore on a different machine or CPU.
+43
View File
@@ -0,0 +1,43 @@
== machine
Linux 6.18.44-fc-v880
cpus: 2
memory MB: 8023
== plain JVM and AOT cache
openjdk version "25.0.5.1" 2026-11-17 LTS
OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS)
OpenJDK 64-Bit Server VM Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS, mixed mode, sharing)
== CRaC JVM
openjdk version "25.0.5.1.1" 2026-11-17 LTS
OpenJDK Runtime Environment Zulu25.38+203-CRaC-CA (build 25.0.5.1.1+1-LTS)
OpenJDK 64-Bit Server VM Zulu25.38+203-CRaC-CA (build 25.0.5.1.1+1-LTS, mixed mode, sharing)
engines shipped: criu criuhelper libcriuengine.so libwarp.so
== native-image
native-image 25.0.4 2026-07-21
GraalVM Runtime Environment Oracle GraalVM 25.0.4+7.1 (build 25.0.4+7-LTS-jvmci-b01)
Substrate VM Oracle GraalVM 25.0.4+7.1 (build 25.0.4+7-LTS, serial gc, compressed references)
== Spring
Implementation-Version: 4.2.0
crac-1.5.0.jar
spring-boot-4.2.0.jar
spring-boot-actuator-4.2.0.jar
spring-boot-actuator-autoconfigure-4.2.0.jar
spring-boot-autoconfigure-4.2.0.jar
spring-boot-health-4.2.0.jar
spring-boot-http-converter-4.2.0.jar
spring-boot-jackson-4.2.0.jar
spring-boot-jarmode-tools-4.2.0.jar
spring-boot-micrometer-metrics-4.2.0.jar
spring-boot-micrometer-observation-4.2.0.jar
spring-boot-servlet-4.2.0.jar
spring-boot-tomcat-4.2.0.jar
spring-boot-validation-4.2.0.jar
spring-boot-web-server-4.2.0.jar
spring-boot-webmvc-4.2.0.jar
spring-context-7.1.0.jar
spring-core-7.1.0.jar
spring-webmvc-7.1.0.jar
tomcat-embed-core-11.0.27.jar
+21
View File
@@ -0,0 +1,21 @@
== CRaC checkpoint at start-up (-Dspring.context.checkpoint=onRefresh)
process exited after 6989 ms; checkpoint dir: core.img engine size: 110 MB
INFO 9383 --- [crac-demo] [ main] com.ankurm.crac.CracDemoApplication : Starting CracDemoApplication v1.0.0 using Java 25.0.5.1.1 with PID 9383 (<work>/app/crac-demo-1.0.0.jar started by root in <work>)
RestoreTracker: beforeCheckpoint
[6.927s][info][crac] Checkpoint ...
3230.887277: warp: Checkpoint 9383 to <work>/cp-refresh
3230.929900: warp: Checkpoint successful!
== CRaC checkpoint after warm-up (300 POST + 300 GET, then jcmd JDK.checkpoint)
jcmd JDK.checkpoint returned after 506 ms; process gone after 616 ms; checkpoint size: 136 MB
INFO 9520 --- [crac-demo] [Attach Listener] jdk.crac : Starting checkpoint
RestoreTracker: beforeCheckpoint
[7.441s][info][crac] Checkpoint ...
3238.421212: warp: Checkpoint 9520 to <work>/cp-warm
3238.499849: warp: Checkpoint successful!
== JDK AOT cache (JEP 514), context-only training
training took 11045 ms; 60 MB
== JDK AOT cache, training with the same 300-request warm-up
training took 15222 ms; 68 MB
+19
View File
@@ -0,0 +1,19 @@
== 1. A file opened in a constructor and never closed (profile 'leaky'), checkpoint at start-up
java exit code: 1
WARN 11231 --- [crac-demo] [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to take CRaC checkpoint on refresh
ERROR 11231 --- [crac-demo] [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Failed to take CRaC checkpoint on refresh
Caused by: org.crac.CheckpointException
Suppressed: jdk.internal.crac.mirror.impl.CheckpointOpenFileException: <work>/audit.log
checkpoint directory exists: no
== 2. The same mistake, checkpoint requested later with jcmd JDK.checkpoint
11275:
An exception during a checkpoint operation:
jdk.internal.crac.mirror.CheckpointException
Suppressed: jdk.internal.crac.mirror.impl.CheckpointOpenFileException: <work>/audit.log
at java.base/jdk.internal.crac.JDKFileResource.lambda$beforeCheckpoint$0(JDKFileResource.java:134)
at java.base/jdk.internal.crac.mirror.Core.checkpointRestore1(Core.java:195)
at java.base/jdk.internal.crac.mirror.Core.checkpointRestore(Core.java:291)
at java.base/jdk.internal.crac.mirror.Core.checkpointRestoreInternal(Core.java:327)
application still running and answering: pong
+23
View File
@@ -0,0 +1,23 @@
== 3. The fix: open in start(), close in stop() (profile 'managed'), checkpoint with jcmd, restore
orders before checkpoint; audit file has 3 lines
--- log of the checkpointed process (hooks only)
INFO 11435 --- [crac-demo] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 18771 (http)
INFO 11435 --- [crac-demo] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
INFO 11435 --- [crac-demo] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/11.0.27]
INFO 11435 --- [crac-demo] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 18771 (http) with context path '/'
ManagedAuditLog: opened <work>/audit.log
INFO 11435 --- [crac-demo] [io-18771-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
ManagedAuditLog: closed <work>/audit.log
RestoreTracker: beforeCheckpoint
--- log of the restored process (hooks only)
RestoreTracker: afterRestore (restore #1)
INFO 11435 --- [crac-demo] [Attach Listener] o.s.c.support.DefaultLifecycleProcessor : Restarting Spring-managed lifecycle beans after JVM restore
INFO 11435 --- [crac-demo] [Attach Listener] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 18771 (http) with context path '/'
ManagedAuditLog: opened <work>/audit.log
INFO 11435 --- [crac-demo] [Attach Listener] o.s.c.support.DefaultLifecycleProcessor : Spring-managed lifecycle restart completed (restored JVM running for 93 ms)
--- after restore: new order (id continues from the checkpointed counter), audit file now has 4 lines:
{"id":4,"customer":"ada","sku":"X","quantity":1}
created order 1
created order 2
created order 3
created order 4
+6
View File
@@ -0,0 +1,6 @@
== 4. Environment variables and secrets
before checkpoint: {"pid":11657,"restores":0,"greetingAtStartup":"value-at-checkpoint-S3CRET-7f3a91","greetingNow":"value-at-checkpoint-S3CRET-7f3a91","jvmUptimeMs":3954}
restored with DEMO_GREETING=value-at-restore:
after restore: {"pid":11791,"restores":1,"greetingAtStartup":"value-at-checkpoint-S3CRET-7f3a91","greetingNow":"value-at-restore","jvmUptimeMs":123}
occurrences of the checkpoint-time value in core.img: 4
checkpoint file mode: 600 root
+30
View File
@@ -0,0 +1,30 @@
files in the JDK's lib directory that belong to CRaC:
criu
criuhelper
libcriuengine.so
libsimengine.so
libwarp.so
== the same flag on the stock Temurin 25 JDK
Unrecognized VM option 'CRaCCheckpointTo=<work>/cp-temurin'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
engine recorded in the default checkpoint (cp-refresh/engine): warp
process capabilities (CapEff): 000001fffeffffff, uid 0
== -XX:CRaCEngine=warp, checkpoint at start-up then restore
checkpoint directory: core.img engine (2 files); size: 129 MB
RestoreTracker: beforeCheckpoint
[4.243s][info][crac] Checkpoint ...
4184.436746: warp: Checkpoint 24528 to <work>/cp-eng-warp
4184.499576: warp: error: Cannot reset arguments to (-->)00007ffcab2bd075-00007ffcab2bd166: Operation not permitted
4184.499614: warp: error: Cannot reset arguments to 00007ffcab2bd075-00007ffcab2bd166(<--): Operation not permitted
4184.500952: warp: Checkpoint successful!
restored; GET /ping -> pong; Restored CracDemoApplication in 0.251 seconds (process running for 0.256)
== -XX:CRaCEngine=criuengine, checkpoint at start-up then restore
checkpoint directory: core-24639.img core-24641.img core-24642.img (39 files); size: 112 MB
RestoreTracker: beforeCheckpoint
[3.535s][info][crac] Checkpoint ...
restored; GET /ping -> pong; Restored CracDemoApplication in 0.183 seconds (process running for 0.184)
+18
View File
@@ -0,0 +1,18 @@
build wall time: 834 s (mvn -Pnative -DskipTests native:compile, measured around the whole Maven run, 2 vCPU shared with other jobs)
[1/8] Initializing... (16.0s @ 0.17GB)
Java version: 25.0.4+7-LTS, vendor version: Oracle GraalVM 25.0.4+7.1
Graal compiler: optimization level: 2, target machine: x86-64-v3, PGO: ML-inferred
Garbage collector: Serial GC (max heap size: 80% of RAM)
[2/8] Performing analysis... [*****] (173.6s @ 2.02GB)
22,195 types, 31,358 fields, and 109,350 methods found reachable
8,538 types, 5,070 fields, and 22,270 methods registered for reflection
68 types, 71 fields, and 58 methods registered for JNI access
[3/8] Building universe... (19.2s @ 2.34GB)
[4/8] Parsing methods... [********] (72.7s @ 2.58GB)
[5/8] Inlining methods... [***] (9.1s @ 2.76GB)
[6/8] Compiling methods... [*********************] (461.3s @ 3.28GB)
[7/8] Laying out methods... [*****] (26.6s @ 3.10GB)
[8/8] Creating image... [***] (11.6s @ 3.43GB)
94.7s (11.8% of total time) in 3046 GCs | Peak RSS: 4.99GB | CPU load: 1.31
Finished generating 'crac-demo' in 13m 17s.
binary size: 99 MB (target/crac-demo, plus 6 small .so shims)
+18
View File
@@ -0,0 +1,18 @@
rounds: 10 load average before: 0.80 0.94 2.53 cpus: 2
configuration ready ms (median [min..max]) 1st POST ms next 50 ms RSS MB
plain-temurin 3973 [3517..4290] 138.7 2.28 184
plain-zulu-crac 3847 [3378..4270] 129.7 2.57 186
aot-ctx-only 2186 [1890..2457] 121.6 2.43 193
aot-traffic 2077 [1944..2323] 65.0 3.59 192
crac-on-refresh 430 [395..540] 211.3 3.21 170
crac-warm 108 [93..153] 12.1 1.95 152
native 86 [83..118] 3.3 0.40 98
raw ready ms per round:
plain-temurin: 3517 4156 3996 4093 3993 3890 3953 4290 3723 3807
plain-zulu-crac: 3984 3802 3951 3869 4089 4270 3749 3805 3378 3824
aot-ctx-only: 1890 2240 2214 2158 2030 1979 2457 2268 2039 2307
aot-traffic: 2081 2053 1944 2012 2090 2072 2125 1973 2110 2323
crac-on-refresh: 407 428 399 540 448 395 452 437 432 421
crac-warm: 107 109 104 153 93 98 117 104 109 122
native: 90 94 86 87 117 83 118 86 83 85
load average after: 2.22 1.62 2.54
+5
View File
@@ -0,0 +1,5 @@
ready (ms) after dropping the page cache, 5 rounds, interleaved:
plain-temurin: 4462 4196 4304 4342 4091
aot-traffic: 2217 2110 2052 2319 2149
crac-warm: 257 255 207 221 247
native: 216 251 193 249 204
+46
View File
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>crac-demo</artifactId>
<version>1.0.0</version>
<name>crac-demo</name>
<description>One small Spring Boot service started five ways: plain JVM, JDK AOT cache, CRaC checkpoint/restore, native image</description>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Spring's CRaC support is switched on by this jar being on the class path (version managed by Boot 4.2: 1.5.0). -->
<dependency>
<groupId>org.crac</groupId>
<artifactId>crac</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Interleaved rounds of every start-up configuration; "ready" = spawn -> first HTTP 200 from GET /ping.
# Needs: build.sh, native.sh, checkpoints.sh already run. Usage: ./scripts/bench.sh [rounds]
source "$(dirname "$0")/lib.sh"
R="${1:-10}"
{ echo "rounds: $R load average before: $(cut -d' ' -f1-3 /proc/loadavg) cpus: $(nproc)"; $TOOL bench "$R" 2>/dev/null; echo "load average after: $(cut -d' ' -f1-3 /proc/loadavg)"; } | tee "$OUT/08-bench.txt"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Build the jar once and extract it to the layout every start-up variant uses.
set -euo pipefail
source "$(dirname "$0")/env.sh"
cd "$ROOT"
JAVA_HOME="$JDK_PLAIN" PATH="$JDK_PLAIN/bin:$PATH" mvn -B -q -DskipTests clean package
rm -rf "$WORK/app"
run_env "$JDK_PLAIN/bin/java" -Djarmode=tools -jar target/crac-demo-1.0.0.jar extract --destination "$WORK/app"
ls -la "$WORK/app"
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Creates the checkpoints and AOT caches the benchmark restores/uses, and records what it cost.
source "$(dirname "$0")/lib.sh"
cd "$WORK"; : > "$OUT/02-create.txt"
say() { echo "$@" | tee -a "$OUT/02-create.txt"; }
say "== CRaC checkpoint at start-up (-Dspring.context.checkpoint=onRefresh)"
rm -rf cp-refresh; t0=$(now_ms)
run_env "$JDK_CRAC/bin/java" -XX:CRaCCheckpointTo="$WORK/cp-refresh" -Dspring.context.checkpoint=onRefresh -jar "$APPJAR" --server.port=$PORT > refresh.log 2>&1 || true
t1=$(now_ms)
say "process exited after $((t1-t0)) ms; checkpoint dir: $(ls cp-refresh | tr '\n' ' ') size: $(du_mb cp-refresh) MB"
grep -E 'Starting CracDemo|Checkpoint|warp: Checkpoint' refresh.log | grep -v 'always available' | scrub | tee -a "$OUT/02-create.txt"
say; say "== CRaC checkpoint after warm-up (300 POST + 300 GET, then jcmd JDK.checkpoint)"
rm -rf cp-warm
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$JDK_CRAC/bin/java" -XX:CRaCCheckpointTo="$WORK/cp-warm" -jar "$APPJAR" --server.port=$PORT > warm.log 2>&1 < /dev/null &
wait_ready || { say "app did not start"; exit 1; }
PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-warm" | head -1)
$TOOL traffic "$PORT" 300
t0=$(now_ms); run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint > jcmd.log 2>&1 || true; t1=$(now_ms)
wait_exit "$PID"; t2=$(now_ms)
say "jcmd JDK.checkpoint returned after $((t1-t0)) ms; process gone after $((t2-t0)) ms; checkpoint size: $(du_mb cp-warm) MB"
grep -E 'Spring-managed|Checkpoint|checkpoint|warp: Checkpoint' warm.log | scrub | tee -a "$OUT/02-create.txt"
say; say "== JDK AOT cache (JEP 514), context-only training"
rm -f ctx.aot; t0=$(now_ms)
run_env "$JDK_PLAIN/bin/java" -XX:AOTCacheOutput="$WORK/ctx.aot" -Dspring.context.exit=onRefresh -jar "$APPJAR" --server.port=$PORT > aot-ctx.log 2>&1
say "training took $(( $(now_ms)-t0 )) ms; $(ls -l ctx.aot | awk '{printf "%.0f MB", $5/1048576}')"
say; say "== JDK AOT cache, training with the same 300-request warm-up"
rm -f traffic.aot
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$JDK_PLAIN/bin/java" -XX:AOTCacheOutput="$WORK/traffic.aot" -jar "$APPJAR" --server.port=$PORT > aot-traffic.log 2>&1 < /dev/null &
t0=$(now_ms); wait_ready; PID=$(pgrep -f "AOTCacheOutput=$WORK/traffic.aot" | head -1)
$TOOL traffic "$PORT" 300; kill -TERM "$PID"; wait_exit "$PID"
say "training took $(( $(now_ms)-t0 )) ms; $(ls -l traffic.aot | awk '{printf "%.0f MB", $5/1048576}')"
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# One start per configuration with the Linux page cache emptied first (a freshly pulled container image or a freshly scheduled pod).
# 5 repetitions each, interleaved. Needs root (writes /proc/sys/vm/drop_caches).
source "$(dirname "$0")/lib.sh"
R="${1:-5}"
declare -A res
for r in $(seq 1 "$R"); do
for c in plain-temurin aot-traffic crac-warm native; do
sync; echo 3 > /proc/sys/vm/drop_caches
v=$($TOOL once "$c" | python3 -c 'import json,sys; print(round(json.load(sys.stdin)["ready"]))')
res[$c]="${res[$c]} $v"
done
done
{ echo "ready (ms) after dropping the page cache, $R rounds, interleaved:"; for c in plain-temurin aot-traffic crac-warm native; do echo " $c:${res[$c]}"; done; } | tee "$OUT/09-cold-cache.txt"
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Measurement helper for the CRaC post. Standard library only.
crac_tool.py bench ROUNDS interleaved rounds of every configuration, prints a table
crac_tool.py once LABEL start one configuration, print time to first 200 and first POST
crac_tool.py traffic PORT N send N valid POST /orders and GET /orders/{id} requests (warm-up)
"Ready" = milliseconds from the moment the process is spawned until the first HTTP 200 from GET /ping
(polled every 2 ms from a raw socket, so the poll itself costs almost nothing).
"""
import json, os, signal, socket, statistics, subprocess, sys, time
ENV = {k: v for k, v in os.environ.items() if k not in ("JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS")}
W = os.environ.get("WORK", "/tmp/crac-work")
PORT = int(os.environ.get("PORT", "18771"))
JDK_PLAIN, JDK_CRAC = os.environ["JDK_PLAIN"], os.environ["JDK_CRAC"]
APP = f"{W}/app/crac-demo-1.0.0.jar"
CONFIGS = {
"plain-temurin": [f"{JDK_PLAIN}/bin/java", "-jar", APP, f"--server.port={PORT}"],
"plain-zulu-crac": [f"{JDK_CRAC}/bin/java", "-jar", APP, f"--server.port={PORT}"],
"aot-ctx-only": [f"{JDK_PLAIN}/bin/java", f"-XX:AOTCache={W}/ctx.aot", "-jar", APP, f"--server.port={PORT}"],
"aot-traffic": [f"{JDK_PLAIN}/bin/java", f"-XX:AOTCache={W}/traffic.aot", "-jar", APP, f"--server.port={PORT}"],
"crac-on-refresh": [f"{JDK_CRAC}/bin/java", f"-XX:CRaCRestoreFrom={W}/cp-refresh"],
"crac-warm": [f"{JDK_CRAC}/bin/java", f"-XX:CRaCRestoreFrom={W}/cp-warm"],
"native": [f"{W}/native/crac-demo", f"--server.port={PORT}"],
}
def http(method, path, body=None, timeout=5.0):
s = socket.create_connection(("127.0.0.1", PORT), timeout=timeout)
try:
data = json.dumps(body).encode() if body is not None else b""
hdr = f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"
if body is not None:
hdr += f"Content-Type: application/json\r\nContent-Length: {len(data)}\r\n"
s.sendall(hdr.encode() + b"\r\n" + data)
buf = b""
while True:
c = s.recv(65536)
if not c: break
buf += c
return int(buf.split(b" ", 2)[1]), buf.split(b"\r\n\r\n", 1)[1].decode()
finally:
s.close()
def port_free():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # TIME_WAIT sockets from the last run must not count as busy
try:
s.bind(("127.0.0.1", PORT)); return True
except OSError:
return False
finally:
s.close()
def session_rss_mb(sid):
best = 0
for pid in os.listdir("/proc"):
if not pid.isdigit(): continue
try:
if os.getsid(int(pid)) != sid: continue
for line in open(f"/proc/{pid}/status"):
if line.startswith("VmRSS:"):
best = max(best, int(line.split()[1]) // 1024)
except (OSError, ProcessLookupError):
pass
return best
def run(label, log=None):
assert port_free(), "port busy"
t0 = time.perf_counter()
p = subprocess.Popen(CONFIGS[label], env=ENV, cwd=W, start_new_session=True,
stdout=open(log or os.devnull, "w"), stderr=subprocess.STDOUT)
ready = None
while time.perf_counter() - t0 < 60:
try:
st, _ = http("GET", "/ping", timeout=1)
if st == 200:
ready = (time.perf_counter() - t0) * 1000; break
except OSError:
time.sleep(0.002)
if ready is None:
kill(p); raise RuntimeError(label + ": not ready")
t1 = time.perf_counter()
st, _ = http("POST", "/orders", {"customer": "ada", "sku": "X-1", "quantity": 2})
first_post = (time.perf_counter() - t1) * 1000
assert st == 201, st
times = []
for i in range(50):
t = time.perf_counter(); http("GET", "/orders/1"); times.append((time.perf_counter() - t) * 1000)
rss = session_rss_mb(p.pid)
kill(p)
return dict(ready=ready, first_post=first_post, next50=statistics.median(times), rss=rss)
def kill(p):
try: os.killpg(p.pid, signal.SIGKILL)
except ProcessLookupError: pass
try: p.wait(5)
except Exception: pass
for _ in range(500):
if port_free(): return
time.sleep(0.01)
def bench(rounds):
res = {k: [] for k in CONFIGS}
for r in range(rounds):
for k in CONFIGS:
res[k].append(run(k)); time.sleep(0.3)
print(f"round {r+1}/{rounds} done", file=sys.stderr)
print(f"{'configuration':<18}{'ready ms (median [min..max])':<34}{'1st POST ms':>12}{'next 50 ms':>12}{'RSS MB':>8}")
for k, rs in res.items():
rd = [x["ready"] for x in rs]
print(f"{k:<18}{statistics.median(rd):>8.0f} [{min(rd):.0f}..{max(rd):.0f}]".ljust(52)
+ f"{statistics.median(x['first_post'] for x in rs):>12.1f}"
+ f"{statistics.median(x['next50'] for x in rs):>12.2f}"
+ f"{statistics.median(x['rss'] for x in rs):>8.0f}")
print("raw ready ms per round:")
for k, rs in res.items():
print(f" {k}: " + " ".join(f"{x['ready']:.0f}" for x in rs))
def traffic(n):
for i in range(n):
st, body = http("POST", "/orders", {"customer": f"c{i%7}", "sku": f"S-{i%13}", "quantity": 1 + i % 5})
assert st == 201, (st, body)
http("GET", f"/orders/{i+1}")
http("POST", "/orders", {"customer": "", "sku": "X", "quantity": 0}) # a 400, so the validation error path is warm
http("GET", "/orders/999999") # a 404
http("GET", "/actuator/health")
if __name__ == "__main__":
cmd = sys.argv[1]
if cmd == "bench": bench(int(sys.argv[2]))
elif cmd == "once": print(json.dumps(run(sys.argv[2], f"{W}/once-{sys.argv[2]}.log")))
elif cmd == "traffic":
PORT = int(sys.argv[2]); traffic(int(sys.argv[3]))
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# The Zulu 25 CRaC JVM ships more than one engine. Which one ran above, and does the CRIU one work in this sandbox?
source "$(dirname "$0")/lib.sh"
cd "$WORK"; J="$JDK_CRAC/bin/java"; : > "$OUT/06-engines.txt"
say() { echo "$@" | tee -a "$OUT/06-engines.txt"; }
say "files in the JDK's lib directory that belong to CRaC:"; ls "$JDK_CRAC/lib" | grep -i -E 'criu|crac|warp|engine' | sed 's/^/ /' | tee -a "$OUT/06-engines.txt"
say; say "== the same flag on the stock Temurin 25 JDK"
run_env "$JDK_PLAIN/bin/java" -XX:CRaCCheckpointTo="$WORK/cp-temurin" -version 2>&1 | head -3 | scrub | tee -a "$OUT/06-engines.txt"
say; say "engine recorded in the default checkpoint (cp-refresh/engine): $(cat cp-refresh/engine 2>/dev/null)"
say "process capabilities (CapEff): $(grep CapEff /proc/self/status | awk '{print $2}'), uid $(id -u)"
for ENG in warp criuengine; do
say; say "== -XX:CRaCEngine=$ENG, checkpoint at start-up then restore"
rm -rf "cp-eng-$ENG"
# CRIU is picky about the process it dumps: a regular file open as stdout must not change size before the restore ("has bad size"),
# a stdin that is a socket fails the dump ("External socket is used"), and a JVM that is not its own session leader cannot be restored
# ("Current gid ... intersects with pid ... in images"). So: new session (setsid), stdin /dev/null, stdout through a pipe (cat).
setsid --wait bash -c "env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS '$J' -XX:CRaCEngine=$ENG -XX:CRaCCheckpointTo='$WORK/cp-eng-$ENG' -Dspring.context.checkpoint=onRefresh -jar '$APPJAR' --server.port=$PORT 2>&1 | cat > 'eng-$ENG-1.log'" < /dev/null
say "checkpoint directory: $(ls cp-eng-$ENG 2>/dev/null | head -3 | tr "\n" " ")($(ls cp-eng-$ENG | wc -l) files); size: $(du -sm cp-eng-$ENG 2>/dev/null | cut -f1) MB"
grep -E 'warp:|criu|CRIU|Error|error:|Checkpoint' "eng-$ENG-1.log" | grep -v 'always available' | scrub | head -8 | tee -a "$OUT/06-engines.txt"
if [ -d "cp-eng-$ENG" ]; then
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCEngine=$ENG -XX:CRaCRestoreFrom="$WORK/cp-eng-$ENG" > "eng-$ENG-2.log" 2>&1 < /dev/null &
if wait_ready; then say "restored; GET /ping -> $(curl -s localhost:$PORT/ping); $(grep -E 'Restored CracDemo' eng-$ENG-2.log | scrub | sed -E 's/.*: //')"; else say "restore did not become ready"; grep -v '^$' "eng-$ENG-2.log" | scrub | head -6 | tee -a "$OUT/06-engines.txt"; fi
stop_port
fi
done
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Where the JDKs live. Override on the command line, e.g. JDK_CRAC=/opt/zulu-crac ./scripts/run-all.sh
export JDK_PLAIN="${JDK_PLAIN:-/tmp/tools/tem/jdk-25.0.5.1+2}" # Temurin 25.0.5.1 (plain JVM, AOT cache)
export JDK_CRAC="${JDK_CRAC:-/tmp/tools/zulu/zulu25.38.203-ca-crac-jdk25.0.5.1.1-linux_x64}" # Azul Zulu 25 with CRaC
export JDK_GRAAL="${JDK_GRAAL:-/tmp/tools/graal/graalvm-jdk-25.0.4+7.1}" # Oracle GraalVM 25.0.4 (native-image)
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"; export ROOT
export OUT="$ROOT/output"; mkdir -p "$OUT"
export WORK="${WORK:-/tmp/crac-work}"; mkdir -p "$WORK" # checkpoints, caches, logs: not committed
export PORT="${PORT:-18771}"
# The JVM prints "Picked up JAVA_TOOL_OPTIONS" on every launch in some sandboxes; it is noise in a transcript.
# (Maven itself needs the variable in such a sandbox, so only the run scripts clear it, never build.sh.)
run_env() { env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$@"; }
export TOOL="python3 $ROOT/scripts/crac_tool.py"; export JDK_PLAIN JDK_CRAC WORK PORT
+10
View File
@@ -0,0 +1,10 @@
# shared helpers (sourced)
source "$(dirname "${BASH_SOURCE[0]}")/env.sh"
APPJAR="$WORK/app/crac-demo-1.0.0.jar"
wait_ready() { for i in $(seq 1 600); do curl -s -o /dev/null "localhost:$PORT/ping" && return 0; sleep 0.1; done; return 1; }
wait_exit() { for i in $(seq 1 600); do kill -0 "$1" 2>/dev/null || return 0; sleep 0.1; done; return 1; }
now_ms() { echo $(( $(date +%s%N) / 1000000 )); }
du_mb() { du -sm "$1" | cut -f1; }
# keep transcripts free of machine paths and wall-clock dates
scrub() { sed -E "s#$WORK#<work>#g; s#$ROOT#<repo>#g; s#/tmp/tools/[^ /]*/[^ /]*#<jdk>#g; s#^[0-9T:.+-]{29} ##"; }
stop_port() { fuser -k -9 "$PORT/tcp" >/dev/null 2>&1; sleep 0.5; } # kills whatever listens on our (private) port
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Builds the native image with Oracle GraalVM 25 (about 5 to 14 minutes on 2 vCPU; 5 GB peak) and records the build summary.
source "$(dirname "$0")/env.sh"
cd "$ROOT"
S=$(date +%s)
JAVA_HOME="$JDK_GRAAL" PATH="$JDK_GRAAL/bin:$PATH" mvn -B -Pnative -DskipTests native:compile > "$WORK/native-build.log" 2>&1
E=$(( $(date +%s) - S ))
mkdir -p "$WORK/native"; cp target/crac-demo "$WORK/native/"
{ echo "build wall time: ${E} s "; grep -E '^\[[0-9]/8\]|Finished generating|Peak RSS|in .* GCs|types, |Garbage collector|target machine' "$WORK/native-build.log" | sed -E 's/ {3,}/ /g';
echo "binary size: $(du -m "$WORK/native/crac-demo" | cut -f1) MB"; } | tee "$OUT/07-native-build.txt"
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# What happens to open files, environment variables and secrets across a checkpoint.
source "$(dirname "$0")/lib.sh"
cd "$WORK"; stop_port
AUDIT="$WORK/audit.log"
J="$JDK_CRAC/bin/java"
echo "== 1. A file opened in a constructor and never closed (profile 'leaky'), checkpoint at start-up" | tee "$OUT/03-leaky.txt"
rm -rf cp-leaky "$AUDIT"
run_env "$J" -XX:CRaCCheckpointTo="$WORK/cp-leaky" -Dspring.context.checkpoint=onRefresh -jar "$APPJAR" --server.port=$PORT --spring.profiles.active=leaky --demo.audit-file="$AUDIT" > leaky.log 2>&1
echo "java exit code: $?" | tee -a "$OUT/03-leaky.txt"
grep -E 'ERROR|ApplicationContextException|Caused by|CheckpointOpenFileException|Suppressed' leaky.log | scrub | tee -a "$OUT/03-leaky.txt"
echo "checkpoint directory exists: $([ -d cp-leaky ] && echo yes || echo no)" | tee -a "$OUT/03-leaky.txt"
echo | tee -a "$OUT/03-leaky.txt"; echo "== 2. The same mistake, checkpoint requested later with jcmd JDK.checkpoint" | tee -a "$OUT/03-leaky.txt"
rm -rf cp-leaky2 "$AUDIT"
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCCheckpointTo="$WORK/cp-leaky2" -jar "$APPJAR" --server.port=$PORT --spring.profiles.active=leaky --demo.audit-file="$AUDIT" > leaky2.log 2>&1 < /dev/null &
wait_ready; PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-leaky2" | head -1)
run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint 2>&1 | grep -v '^$' | scrub | head -8 | tee -a "$OUT/03-leaky.txt"
sleep 1
echo "application still running and answering: $(curl -s localhost:$PORT/ping)" | tee -a "$OUT/03-leaky.txt"
kill -9 "$PID"; wait_exit "$PID"
echo "== 3. The fix: open in start(), close in stop() (profile 'managed'), checkpoint with jcmd, restore" | tee "$OUT/04-managed.txt"
rm -rf cp-managed "$AUDIT"
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCCheckpointTo="$WORK/cp-managed" -jar "$APPJAR" --server.port=$PORT --spring.profiles.active=managed --demo.audit-file="$AUDIT" > managed1.log 2>&1 < /dev/null &
wait_ready; PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-managed" | head -1)
for i in 1 2 3; do curl -s -o /dev/null -X POST -H 'Content-Type: application/json' -d '{"customer":"ada","sku":"X","quantity":1}' localhost:$PORT/orders; done
echo "orders before checkpoint; audit file has $(wc -l < "$AUDIT") lines" | tee -a "$OUT/04-managed.txt"
run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint > /dev/null 2>&1; wait_exit "$PID"
echo "--- log of the checkpointed process (hooks only)" | tee -a "$OUT/04-managed.txt"
grep -E 'ManagedAuditLog|RestoreTracker|Spring-managed|Stopping|Tomcat' managed1.log | scrub | tee -a "$OUT/04-managed.txt"
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS "$J" -XX:CRaCRestoreFrom="$WORK/cp-managed" > managed2.log 2>&1 < /dev/null &
wait_ready; sleep 0.3
echo "--- log of the restored process (hooks only)" | tee -a "$OUT/04-managed.txt"
grep -E 'ManagedAuditLog|RestoreTracker|Spring-managed|Tomcat|Restored' managed2.log | scrub | tee -a "$OUT/04-managed.txt"
curl -s -o /dev/null -X POST -H 'Content-Type: application/json' -d '{"customer":"ada","sku":"X","quantity":1}' localhost:$PORT/orders
echo "--- after restore: new order (id continues from the checkpointed counter), audit file now has $(wc -l < "$AUDIT") lines:" | tee -a "$OUT/04-managed.txt"
curl -s localhost:$PORT/orders/4 | tee -a "$OUT/04-managed.txt"; echo | tee -a "$OUT/04-managed.txt"
cat "$AUDIT" | tee -a "$OUT/04-managed.txt"
stop_port
echo "== 4. Environment variables and secrets" | tee "$OUT/05-environment.txt"
rm -rf cp-env
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS DEMO_GREETING=value-at-checkpoint-S3CRET-7f3a91 "$J" -XX:CRaCCheckpointTo="$WORK/cp-env" -jar "$APPJAR" --server.port=$PORT > env1.log 2>&1 < /dev/null &
wait_ready; PID=$(pgrep -f "CRaCCheckpointTo=$WORK/cp-env" | head -1)
echo "before checkpoint: $(curl -s localhost:$PORT/info)" | tee -a "$OUT/05-environment.txt"
run_env "$JDK_CRAC/bin/jcmd" "$PID" JDK.checkpoint > /dev/null 2>&1; wait_exit "$PID"
setsid env -u JAVA_TOOL_OPTIONS -u _JAVA_OPTIONS DEMO_GREETING=value-at-restore "$J" -XX:CRaCRestoreFrom="$WORK/cp-env" > env2.log 2>&1 < /dev/null &
wait_ready
echo "restored with DEMO_GREETING=value-at-restore:" | tee -a "$OUT/05-environment.txt"
echo "after restore: $(curl -s localhost:$PORT/info)" | tee -a "$OUT/05-environment.txt"
echo "occurrences of the checkpoint-time value in core.img: $(grep -a -c 'value-at-checkpoint-S3CRET-7f3a91' cp-env/core.img)" | tee -a "$OUT/05-environment.txt"
echo "checkpoint file mode: $(stat -c '%a %U' cp-env/core.img)" | tee -a "$OUT/05-environment.txt"
stop_port
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Regenerates every file in output/. About 25 minutes on 2 vCPU (the native build alone is 5 to 14 minutes).
# Needs JDK_PLAIN, JDK_CRAC, JDK_GRAAL (see env.sh), Maven, Python 3, curl, and root for cold.sh.
set -euo pipefail
cd "$(dirname "$0")"
./build.sh
./native.sh
./versions.sh
./checkpoints.sh
./resources.sh
./engines.sh
./bench.sh 10
./cold.sh 5
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# What every number in the post was measured on.
source "$(dirname "$0")/lib.sh"
{
echo "== machine"; uname -sr; echo "cpus: $(nproc)"; free -m | awk 'NR==2{print "memory MB: "$2}'
echo; echo "== plain JVM and AOT cache"; run_env "$JDK_PLAIN/bin/java" -version 2>&1 | scrub
echo; echo "== CRaC JVM"; run_env "$JDK_CRAC/bin/java" -version 2>&1 | scrub
echo "engines shipped: $(ls "$JDK_CRAC/lib" | grep -E 'criu|libcriuengine|warp' | tr '\n' ' ')"
echo; echo "== native-image"; run_env "$JDK_GRAAL/bin/native-image" --version 2>&1 | scrub
echo; echo "== Spring"; unzip -p "$WORK/app/lib/spring-boot-4.2.0.jar" META-INF/MANIFEST.MF | grep -E 'Implementation-Version'
ls "$WORK/app/lib" | grep -E '^(spring-(core|context|webmvc|boot)-|crac-|tomcat-embed-core)'
} 2>&1 | tee "$OUT/01-versions.txt"
@@ -0,0 +1,6 @@
package com.ankurm.crac;
/** Something that holds an operating-system resource (here: an open file). */
public interface AuditSink {
void write(String line);
}
@@ -0,0 +1,12 @@
package com.ankurm.crac;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** One small service used for every start-up measurement in the "CRaC vs AOT cache vs native image" post. */
@SpringBootApplication
public class CracDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CracDemoApplication.class, args);
}
}
@@ -0,0 +1,33 @@
package com.ankurm.crac;
import java.lang.management.ManagementFactory;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Shows what a restored process remembers. {@code greetingAtStartup} is read once in the constructor, {@code greetingNow} on every call:
* after a restore into a different environment the two differ, which is the "stale configuration" trap.
*/
@RestController
public class InfoController {
private final String greetingAtStartup = System.getenv().getOrDefault("DEMO_GREETING", "(unset)");
private final RestoreTracker tracker;
public InfoController(RestoreTracker tracker) {
this.tracker = tracker;
}
@GetMapping("/info")
public Map<String, Object> info() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("pid", ProcessHandle.current().pid());
m.put("restores", tracker.restores());
m.put("greetingAtStartup", greetingAtStartup);
m.put("greetingNow", System.getenv().getOrDefault("DEMO_GREETING", "(unset)"));
m.put("jvmUptimeMs", ManagementFactory.getRuntimeMXBean().getUptime());
return m;
}
}
@@ -0,0 +1,37 @@
package com.ankurm.crac;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* The mistake: a file is opened once and held for the life of the process.
* Active with {@code --spring.profiles.active=leaky}. A checkpoint taken while this file is open is the failure the post shows.
*/
@Component
@Profile("leaky")
public class LeakyAuditLog implements AuditSink {
private final BufferedWriter out;
public LeakyAuditLog(@Value("${demo.audit-file:/tmp/crac-demo-audit.log}") Path file) throws IOException {
this.out = Files.newBufferedWriter(file, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
@Override
public synchronized void write(String line) {
try {
out.write(line);
out.newLine();
out.flush();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,68 @@
package com.ankurm.crac;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* The fix: the same file, opened in {@code start()} and closed in {@code stop()}. Spring calls {@code stop()} on every running
* lifecycle bean before a checkpoint and {@code start()} again after a restore, so no file is open while the process image is written.
* Active with {@code --spring.profiles.active=managed}.
*/
@Component
@Profile("managed")
public class ManagedAuditLog implements AuditSink, SmartLifecycle {
private final Path file;
private BufferedWriter out;
public ManagedAuditLog(@Value("${demo.audit-file:/tmp/crac-demo-audit.log}") Path file) {
this.file = file;
}
@Override
public synchronized void start() {
try {
out = Files.newBufferedWriter(file, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println("ManagedAuditLog: opened " + file);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public synchronized void stop() {
try {
if (out != null) {
out.close();
out = null;
System.out.println("ManagedAuditLog: closed " + file);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public synchronized boolean isRunning() {
return out != null;
}
@Override
public synchronized void write(String line) {
try {
out.write(line);
out.newLine();
out.flush();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,56 @@
package com.ankurm.crac;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/** Spring MVC + Jackson + Bean Validation, no database: enough classes to make start-up interesting. */
@RestController
public class OrderController {
public record OrderRequest(@NotBlank String customer, @NotBlank String sku, @Min(1) int quantity) {}
public record Order(long id, String customer, String sku, int quantity) {}
private final Map<Long, Order> store = new ConcurrentHashMap<>();
private final AtomicLong ids = new AtomicLong();
private final ObjectProvider<AuditSink> audit;
public OrderController(ObjectProvider<AuditSink> audit) {
this.audit = audit;
}
@GetMapping("/ping")
public String ping() {
return "pong";
}
@PostMapping("/orders")
@ResponseStatus(HttpStatus.CREATED)
public Order create(@Valid @RequestBody OrderRequest request) {
Order order = new Order(ids.incrementAndGet(), request.customer(), request.sku(), request.quantity());
store.put(order.id(), order);
audit.ifAvailable(a -> a.write("created order " + order.id()));
return order;
}
@GetMapping("/orders/{id}")
public Order get(@PathVariable long id) {
Order order = store.get(id);
if (order == null) {
throw new org.springframework.web.server.ResponseStatusException(HttpStatus.NOT_FOUND);
}
return order;
}
}
@@ -0,0 +1,36 @@
package com.ankurm.crac;
import java.util.concurrent.atomic.AtomicInteger;
import org.crac.Context;
import org.crac.Core;
import org.crac.Resource;
import org.springframework.stereotype.Component;
/**
* The plain org.crac API, for code that does not depend on Spring: a {@link Resource} registered with the global context is told
* before a checkpoint and after a restore. Here it only counts and logs, which is enough to prove the hooks run.
*/
@Component
public class RestoreTracker implements Resource {
private final AtomicInteger restores = new AtomicInteger();
public RestoreTracker() {
// The global context keeps only a weak reference, so this bean (a singleton) must stay strongly referenced elsewhere. Spring does that.
Core.getGlobalContext().register(this);
}
@Override
public void beforeCheckpoint(Context<? extends Resource> context) {
System.out.println("RestoreTracker: beforeCheckpoint");
}
@Override
public void afterRestore(Context<? extends Resource> context) {
System.out.println("RestoreTracker: afterRestore (restore #" + restores.incrementAndGet() + ")");
}
public int restores() {
return restores.get();
}
}
@@ -0,0 +1,3 @@
spring.application.name=crac-demo
management.endpoints.web.exposure.include=health,info
spring.main.banner-mode=off