diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
new file mode 100644
index 0000000..5de9c14
--- /dev/null
+++ b/.github/workflows/integration.yml
@@ -0,0 +1,135 @@
+name: Integration
+
+# The two start-ups sys-lib is built for, on every environment it is meant
+# for (dev/ROADMAP.md, 0.9): a service's boot phase 0 (examples/boot.rs) and a
+# database start-up (examples/database.rs). Each example exits 1 when a
+# reading breaks its own rules or differs from what the environment is known
+# to give, which each job states with SYS_LIB_EXPECT_* variables.
+on:
+ pull_request:
+ workflow_dispatch:
+
+env:
+ CARGO_TERM_COLOR: always
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
+
+jobs:
+ native:
+ name: ${{ matrix.name }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { name: "Linux server x86-64", os: ubuntu-24.04 }
+ - { name: "Linux server Arm64", os: ubuntu-24.04-arm }
+ - { name: "Windows Server", os: windows-latest }
+ - { name: "macOS Apple silicon", os: macos-latest }
+ - { name: "macOS Intel", os: macos-15-intel }
+ steps:
+ - uses: actions/checkout@v5
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ - name: Build
+ run: cargo build --release --example boot --example database
+ - name: Service boot
+ shell: bash
+ env:
+ SYS_LIB_EXPECT_CONTAINER: none
+ SYS_LIB_EXPECT_KUBERNETES: "false"
+ run: target/release/examples/boot
+ - name: Database start-up
+ shell: bash
+ run: target/release/examples/database "$RUNNER_TEMP/db"
+
+ docker:
+ name: Docker, 1 GiB and 2 CPUs
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v5
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ - name: Build
+ run: cargo build --release --example boot --example database
+ - name: Both start-ups in the container
+ run: |
+ docker run --rm --memory=1g --cpus=2 \
+ -e SYS_LIB_EXPECT_MEMORY=1073741824 -e SYS_LIB_EXPECT_CPUS=2 \
+ -e SYS_LIB_EXPECT_CONTAINER=docker -e SYS_LIB_EXPECT_KUBERNETES=false \
+ -v "$PWD/target/release/examples:/bin/sys-lib:ro" ubuntu:24.04 \
+ sh -c '/bin/sys-lib/boot && /bin/sys-lib/database /var/lib/exampledb'
+
+ kubernetes:
+ name: Kubernetes pod, 512 MiB and 1 CPU
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v5
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ - name: Build
+ run: cargo build --release --example boot --example database
+ - uses: helm/kind-action@v1
+ with:
+ cluster_name: sys-lib
+ - name: Image
+ run: |
+ mkdir -p image
+ cp target/release/examples/boot target/release/examples/database image/
+ printf 'FROM ubuntu:24.04\nCOPY boot database /usr/local/bin/\n' > image/Dockerfile
+ docker build -q -t sys-lib-integration:ci image
+ kind load docker-image sys-lib-integration:ci --name sys-lib
+ - name: Both start-ups in a pod with limits
+ run: |
+ cat > pod.yaml <<'EOF'
+ apiVersion: v1
+ kind: Pod
+ metadata:
+ name: sys-lib
+ spec:
+ restartPolicy: Never
+ containers:
+ - name: start-ups
+ image: sys-lib-integration:ci
+ imagePullPolicy: Never
+ command: ["sh", "-c", "boot && database /var/lib/exampledb"]
+ env:
+ - { name: SYS_LIB_EXPECT_MEMORY, value: "536870912" }
+ - { name: SYS_LIB_EXPECT_CPUS, value: "1" }
+ - { name: SYS_LIB_EXPECT_CONTAINER, value: containerd }
+ - { name: SYS_LIB_EXPECT_KUBERNETES, value: "true" }
+ resources:
+ requests: { memory: 512Mi, cpu: "1" }
+ limits: { memory: 512Mi, cpu: "1" }
+ EOF
+ kubectl apply -f pod.yaml
+ kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/sys-lib --timeout=180s || true
+ kubectl logs pod/sys-lib
+ test "$(kubectl get pod sys-lib -o jsonpath='{.status.phase}')" = Succeeded
+
+ freebsd:
+ name: FreeBSD 14 VM
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v5
+ - name: Both start-ups in FreeBSD
+ uses: vmactions/freebsd-vm@v1.5.9
+ with:
+ release: "14"
+ copyback: false
+ run: |
+ set -eu
+ pw useradd -n ci -m -s /bin/sh
+ chown -R ci .
+ cat > /tmp/ci.sh <<'EOS'
+ set -eu
+ fetch -q -o /tmp/rustup-init https://static.rust-lang.org/rustup/dist/x86_64-unknown-freebsd/rustup-init
+ chmod +x /tmp/rustup-init
+ /tmp/rustup-init -y -q --profile minimal --default-toolchain stable
+ . "$HOME/.cargo/env"
+ cd "$1"
+ cargo build --release --example boot --example database
+ SYS_LIB_EXPECT_CONTAINER=none SYS_LIB_EXPECT_KUBERNETES=false target/release/examples/boot
+ target/release/examples/database "$HOME/db"
+ EOS
+ su -l ci -c "sh /tmp/ci.sh '$PWD'"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d37c44..fe29278 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,45 @@
---
+## [0.9.0] - 2026-12-02
+
+Alpha: sys-lib now runs in the two start-ups it is built for, a service's boot
+phase 0 and a database start-up, on every platform it supports, in a Docker
+container with limits, and in a Kubernetes pod.
+
+### Added
+
+- `GuardBuilder::process_wide(false)`: the guard takes the lock and nothing
+ else. It leaves the umask and the open-file limit alone, for a library or a
+ component inside a larger program that should not change state the whole
+ process shares. Before, this took three calls (`keep_umask()`,
+ `open_files_target(0)`, `open_files_minimum(0)`), and the guard still read
+ the umask, which on Unix means setting it.
+- `examples/database.rs`: a database start-up. The lock beside the data
+ directory, the cache sized from `mem::total()`, workers from
+ `cpu::available()`, the data directory's disk, and the Database readiness
+ report.
+- `examples/boot.rs` is now a service's boot phase 0: the guard, build and
+ instance info, workers, and where it runs. Both examples exit 1 when a
+ reading breaks its own rules or differs from what the environment is known
+ to give.
+- The `Integration` workflow runs both examples on Linux (x86-64 and Arm64),
+ Windows, macOS (Apple silicon and Intel), FreeBSD, in a Docker container
+ limited to 1 GiB and 2 CPUs, and in a Kubernetes pod limited to 512 MiB and
+ 1 CPU, and checks that each one reads the limits it was given.
+
+### Fixed
+
+- `virt::detect()` names containerd in a Kubernetes pod on cgroup v2, where
+ `/proc/1/cgroup` says only `0::/` and no marker file exists: it now reads
+ the pod's mounts (the kubelet's hosts file, the overlay root's layers).
+ Before, such a pod read as `Container::Other`.
+- The access-time check in the readiness report gave the Linux fix
+ (`/etc/fstab`) on Windows and macOS. Each platform now names its own tool:
+ `fsutil` on Windows, `mount -u` on macOS and FreeBSD.
+
+---
+
## [0.8.0] - 2026-12-02
Hardening: every threat in the model has a named attack test, the process
@@ -460,7 +499,8 @@ The scaffold and the plan. No functional code yet.
`dev/ROADMAP.md`.
- `tests/fixtures/` and `fuzz/` skeletons.
-[Unreleased]: https://github.com/jamesgober/sys-lib/compare/v0.8.0...HEAD
+[Unreleased]: https://github.com/jamesgober/sys-lib/compare/v0.9.0...HEAD
+[0.9.0]: https://github.com/jamesgober/sys-lib/compare/v0.8.0...v0.9.0
[0.8.0]: https://github.com/jamesgober/sys-lib/compare/v0.7.0...v0.8.0
[0.7.0]: https://github.com/jamesgober/sys-lib/compare/v0.6.0...v0.7.0
[0.6.0]: https://github.com/jamesgober/sys-lib/compare/v0.5.1...v0.6.0
diff --git a/Cargo.toml b/Cargo.toml
index f3f0ee7..7844511 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@
# =============================================================================
[package]
name = "sys-lib"
-version = "0.8.0"
+version = "0.9.0"
# Minimum Supported Rust Version (MSRV)
# 1.89: `std::fs::File::lock` and `File::try_lock` are stable from 1.89.0, so
@@ -63,6 +63,10 @@ harness = false
name = "boot"
required-features = ["instance", "guard"]
+[[example]]
+name = "database"
+required-features = ["guard"]
+
[[example]]
name = "device_id"
required-features = ["device-id"]
diff --git a/README.md b/README.md
index 0b00e0e..4d98ffe 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@
MSRV is 1.89+ (Rust 2024 edition). unsafe is denied at the crate root and allowed only in one OS module per platform.
- Status: 0.8.0, feature complete, measured, and hardened. The boot kit, the live readings (memory, CPU, disks, network, pressure, this process), detection and identity (virtualization, form factor, topology, power, DNS, the time zone, firmware, launch context, summary(), an application-scoped device id), and now the server readiness, benchmark environment, and security posture reports, temperatures, graphics adapters, and explicit roots for monitoring agents. Linux (64-bit, and 32-bit glibc on x86 and Arm), macOS, Windows, and FreeBSD; Android and iOS best effort. 0.7 measured every reading against the crates people use for it (docs/PERFORMANCE.md); 0.8 hardened it, with every threat and its test in docs/SECURITY.md; the API is in docs/API.md. Design: dev/PLAN.md; schedule: dev/ROADMAP.md.
+ Status: 0.9.0, alpha: feature complete, measured, hardened, and run in real start-ups. The boot kit, the live readings (memory, CPU, disks, network, pressure, this process), detection and identity (virtualization, form factor, topology, power, DNS, the time zone, firmware, launch context, summary(), an application-scoped device id), and now the server readiness, benchmark environment, and security posture reports, temperatures, graphics adapters, and explicit roots for monitoring agents. Linux (64-bit, and 32-bit glibc on x86 and Arm), macOS, Windows, and FreeBSD; Android and iOS best effort. 0.7 measured every reading against the crates people use for it (docs/PERFORMANCE.md); 0.8 hardened it, with every threat and its test in docs/SECURITY.md; 0.9 runs it in a service's boot and a database start-up (examples/boot.rs, examples/database.rs) on Linux, macOS, Windows, FreeBSD, in a Docker container with limits, and in a Kubernetes pod; the API is in docs/API.md. Design: dev/PLAN.md; schedule: dev/ROADMAP.md.
@@ -47,10 +47,10 @@ Cargo's rename makes the crate `sys` in your code:
```toml
[dependencies]
-sys = { package = "sys-lib", version = "0.8" }
+sys = { package = "sys-lib", version = "0.9" }
# The application-scoped device id (brings crypt-io's BLAKE3 stack):
-sys = { package = "sys-lib", version = "0.8", features = ["device-id"] }
+sys = { package = "sys-lib", version = "0.9", features = ["device-id"] }
```
The default features are `instance` (instance info) and `guard` (the process guard). `default-features = false` keeps every reading and report and brings no dependency at all.
diff --git a/dev/PLAN.md b/dev/PLAN.md
index d288aaf..5502660 100644
--- a/dev/PLAN.md
+++ b/dev/PLAN.md
@@ -1285,3 +1285,7 @@ Other ideas:
| D-118 | 2026-11-29 | The owners of CoreFoundation, IOKit, and Mach objects (`Cf::new`, `Cf::lent`, `Io::new`, `Io::matching`, `SendRight::from_raw`, `ProcessorInfo::from_raw`) are `unsafe fn` with a `# Safety` section | they release or read whatever they are given; a Get-rule reference passed to `Cf::new` would compile without `unsafe` and be released twice |
| D-119 | 2026-11-29 | The 24-hour fuzz run is five chained rounds on GitHub's runners (`fuzz.yml`, `long`), eight targets at a time, each round starting from the corpus the last saved | a hosted job stops at 6 hours; eight at a time (about 60 hours for the whole run) leaves runners for every other repository's CI |
| D-120 | 2026-11-29 | macOS keeps the host name port for the life of the process (fetched again in a child after `fork`), and reads the device anchors from the service plane's root by path, matching by class only when that fails | `mach_host_self` and the `mach_port_deallocate` that returns its reference were two traps in every memory and CPU reading; `IOServiceGetMatchingService` searches the registry where a path lookup goes straight to the platform device, which is the gap to machine-uid in `docs/PERFORMANCE.md` |
+| D-121 | 2026-12-02 | `GuardBuilder::process_wide(false)` takes the lock and touches no state the process shares: no umask read or change, no open-file limit change or check, no thread warning | the database example's second guard, the tests, and any library that holds a lock inside a larger program needed three calls to get there, and still had the umask read, which on Unix sets it and races other threads |
+| D-122 | 2026-12-02 | The 0.9 environments run in the `Integration` workflow on every pull request: hosted runners for Linux, Windows, and macOS, a VM for FreeBSD, `docker run --memory --cpus`, and a kind cluster for the Kubernetes pod. Windows 11 and WSL 2 run by hand on the workstation before each release | each environment states what it is known to give (`SYS_LIB_EXPECT_*`), so a wrong limit or a missed container fails the pull request instead of a user's start-up; no hosted runner is Windows 11 or WSL 2 |
+| D-123 | 2026-12-02 | API review against real use, 0.9.0: kept as they are, a default lock directory that another account can change (an old folder with a capability-SID entry inherited from `AppData`) is refused with `RunDirUnavailable`, as on Unix; the readiness report's value names (`noatime`, `relatime`) stay the same words on every platform, with the fix naming each platform's tool | refusing is the guard's purpose and the message says which directory; one set of value names keeps reports comparable across a fleet |
+| D-124 | 2026-12-02 | On Linux, `/proc/self/mountinfo` names the container runtime when nothing stronger does: a `/etc/hosts` or `/etc/hostname` bound from a `kubelet/pods/` directory is containerd (the CRI runtime), and the overlay root's layers under `/var/lib/docker/` are Docker, under a containerd snapshotter are containerd. Strong evidence, after the marker files and `/proc/1/cgroup` | a pod on cgroup v2 with a cgroup namespace shows `0::/` in `/proc/1/cgroup` and containerd writes no marker, so the 0.9 Kubernetes run would have read `Container::Other`; the paths are the runtime's own, set before the process starts |
diff --git a/dev/ROADMAP.md b/dev/ROADMAP.md
index 171ef64..511c078 100644
--- a/dev/ROADMAP.md
+++ b/dev/ROADMAP.md
@@ -95,8 +95,8 @@ Exit: no open finding; every threat has a passing attack test.
## v0.9.0 - Alpha and beta
Exit: both integrations run on every listed environment; two weeks without an API change; every document checked against the build.
-- [ ] 0.9.0 (alpha): integrated in a service's boot phase 0 and in a database start-up (guard beside the data directory, cache sizing from `mem::total()`, the Database readiness report) on Windows 11, WSL 2 Ubuntu, a Linux server, macOS on Apple silicon, FreeBSD, a Docker container with limits, and a Kubernetes pod if available.
-- [ ] API review against real use; changes made in 0.9.0, not later.
+- [x] 0.9.0 (alpha): integrated in a service's boot phase 0 and in a database start-up (guard beside the data directory, cache sizing from `mem::total()`, the Database readiness report) on Windows 11, WSL 2 Ubuntu, a Linux server, macOS on Apple silicon, FreeBSD, a Docker container with limits, and a Kubernetes pod if available. `examples/boot.rs` and `examples/database.rs`, run by the `Integration` workflow on Linux x86-64 and Arm64, Windows Server, macOS Apple silicon and Intel, FreeBSD 14, Docker (1 GiB, 2 CPUs), and a kind pod (512 MiB, 1 CPU); by hand on Windows 11 and WSL 2 Ubuntu (D-122).
+- [x] API review against real use; changes made in 0.9.0, not later. `GuardBuilder::process_wide` (D-121), containerd named in a cgroup v2 pod (D-124), the access-time fix per platform; what was kept and why in D-123.
- [ ] 0.9.x (beta): API frozen; only fixes. Documentation complete; `docs/STABILITY-1.0.md` drafted with the requirement-to-test map.
- [ ] Release candidates `1.0.0-rc.N` as needed.
diff --git a/docs/API.md b/docs/API.md
index 1840d45..504c17c 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -94,11 +94,11 @@ Costs are estimates (marked [est.]) until they are measured in `0.7.0`; measured
```toml
[dependencies]
-sys = { package = "sys-lib", version = "0.8" }
+sys = { package = "sys-lib", version = "0.9" }
# Without instance info and the process guard (no dependencies at all):
-# sys = { package = "sys-lib", version = "0.8", default-features = false }
+# sys = { package = "sys-lib", version = "0.9", default-features = false }
# With device identity (from 0.5):
-# sys = { package = "sys-lib", version = "0.8", features = ["device-id"] }
+# sys = { package = "sys-lib", version = "0.9", features = ["device-id"] }
```
The package is `sys-lib` on crates.io (`sys` and `system` were taken). Cargo's rename makes it `sys` in your code, so every file writes `sys::os::name()` with no import line. Without the rename (`sys-lib = "0.4"`), add `use sys_lib as sys;` at the top of a file and the code is the same.
@@ -866,6 +866,7 @@ impl GuardBuilder {
pub fn keep_umask(self) -> Self; // leave the umask alone
pub fn open_files_target(self, n: u64) -> Self; // default 65_536
pub fn open_files_minimum(self, n: u64) -> Self; // default 1_024
+ pub fn process_wide(self, on: bool) -> Self; // default true; false: the lock only (0.9)
pub fn build(self) -> Result;
}
@@ -924,6 +925,8 @@ What the guard does, in order:
| 5. open-file limit, raised | soft limit raised to the target, capped at the hard limit, on Linux at `/proc/sys/fs/nr_open`, and on macOS at `kern.maxfilesperproc` | not applicable (no per-process descriptor count for sockets); reported as unlimited |
| 6. umask | `umask(0o027)`: owner read and write, group read, others nothing | not applicable; `umask_after` is `None` |
+With `process_wide(false)`, for a library or a component inside a larger program, the guard does steps 2 to 4 only: it neither checks nor raises the open-file limit, and it neither reads nor sets the umask (reading it means setting it, which races the program's other threads). The report shows the umask as `None` and the limit as it was.
+
The lock file is **never deleted**, not even on a clean exit: deleting it would let a waiting process lock the unlinked file while a third creates a new one, and two copies would run. On Unix something else can still delete it while it is held (a temporary-file cleaner, an operator's `rm`, the removal of a directory above it), and a copy started afterwards would lock a new file; a service that runs for long checks `guard.is_held()` periodically and stops when it is false. On Windows the held file cannot be deleted. The name must be 1 to 64 characters of ASCII letters, digits, `-`, `_`, `.`, not starting with `.`. The umask is process-wide, so call the guard before starting threads; on Unix, if other threads already run, the report says so. Privileges are not dropped here: that is shield-sec's job, after the listening sockets are bound.
Errors, each saying what to do:
@@ -2295,7 +2298,7 @@ pub enum Strength { Strong, Weak }
| VRT-03 | `hypervisor()`, `container()` | about 1 ns |
| VRT-04 | `evidence` | 0 |
-Layered checks (CPUID hypervisor leaves, DMI strings, hypervisor files, container marker files and cgroup names, the overlay root, the Kubernetes service account, WSL's kernel release) with every check that fired named in `evidence` (constant strings, never raw values). A Windows **host** with Hyper-V, WSL 2, or virtualization-based security enabled sees "Microsoft Hv" in CPUID too; with the root-partition privilege it is not reported as a VM (checked on such a host). Under Rosetta 2 CPUID is not read: translation is not virtualization. Inside WSL 2 both `is_vm()` and `is_wsl()` are true. A container inside a VM sets both `container` and `hypervisor`. Evidence from environment variables (`KUBERNETES_SERVICE_HOST`) is `Weak`: any process can set it.
+Layered checks (CPUID hypervisor leaves, DMI strings, hypervisor files, container marker files and cgroup names, the kubelet's mounts and the overlay root's layers, the overlay root, the Kubernetes service account, WSL's kernel release) with every check that fired named in `evidence` (constant strings, never raw values). A Windows **host** with Hyper-V, WSL 2, or virtualization-based security enabled sees "Microsoft Hv" in CPUID too; with the root-partition privilege it is not reported as a VM (checked on such a host). Under Rosetta 2 CPUID is not read: translation is not virtualization. Inside WSL 2 both `is_vm()` and `is_wsl()` are true. A container inside a VM sets both `container` and `hypervisor`. Evidence from environment variables (`KUBERNETES_SERVICE_HOST`) is `Weak`: any process can set it.
Detection is advisory. Do not make security decisions on it (threat T14).
diff --git a/docs/SOURCES.md b/docs/SOURCES.md
index 4f6db34..9763194 100644
--- a/docs/SOURCES.md
+++ b/docs/SOURCES.md
@@ -235,7 +235,7 @@ Interface names from the OS are validated before they are used in a `/sys` path:
| DMI strings | Linux (0444 files), Windows (SMBIOS types 0, 1, 2) | `product_name`, `sys_vendor`, `board_vendor`, `bios_vendor`, `product_version` | KVM, OpenStack, KubeVirt, Amazon EC2, QEMU, VMware, innotek GmbH, VirtualBox, Oracle, Xen, Bochs, Parallels, BHYVE, Hyper-V ("Microsoft Corporation" + "Virtual Machine"), Apple Virtualization, Google Compute Engine, Alibaba Cloud ECS |
| hypervisor files | Linux | `/sys/hypervisor/type`; `/proc/xen/capabilities` (`control_d` is Dom0, not a guest); `/proc/device-tree/hypervisor/compatible` | Xen, ARM hypervisors |
| sysctl | macOS | `kern.hv_vmm_present`; `hw.model` `VirtualMac*` | Apple Virtualization, Parallels, VMware Fusion |
-| container files | Linux | `/run/systemd/container`, `/run/.containerenv` (Podman), `/.dockerenv`, `/proc/1/cgroup` v1 names (`docker`, `kubepods`, `lxc`), an overlay root in `/proc/self/mountinfo` | Docker, Podman, LXC, systemd-nspawn, containerd |
+| container files | Linux | `/run/systemd/container`, `/run/.containerenv` (Podman), `/.dockerenv`, `/proc/1/cgroup` v1 names (`docker`, `kubepods`, `lxc`), in `/proc/self/mountinfo` a pod's `/etc/hosts` from the kubelet's directory, the overlay root's layers under Docker's or containerd's state directory, and an overlay root | Docker, Podman, LXC, systemd-nspawn, containerd |
| Kubernetes | Linux | `/var/run/secrets/kubernetes.io/serviceaccount` (strong); `KUBERNETES_SERVICE_HOST` (weak) | Kubernetes |
| not containers | Linux | `/run/systemd/container` saying `wsl`, and an overlay root under WSL or a live image alone (weak evidence, no answer under WSL) | D-061 |
| WSL | Linux | `/proc/sys/kernel/osrelease` containing `Microsoft` (WSL 1) or `microsoft-standard-WSL2` (WSL 2); `/proc/sys/fs/binfmt_misc/WSLInterop`; `WSL_DISTRO_NAME` (weak) | WSL 1 or 2 |
diff --git a/docs/release/v0.9.0.md b/docs/release/v0.9.0.md
new file mode 100644
index 0000000..27b103c
--- /dev/null
+++ b/docs/release/v0.9.0.md
@@ -0,0 +1,27 @@
+# sys-lib v0.9.0 - Alpha
+
+**Run where it will be used.** sys-lib now runs in the two start-ups it was built for: a service's boot phase 0 (`examples/boot.rs`) and a database start-up (`examples/database.rs`). On every pull request both run on Linux (x86-64 and Arm64), Windows, macOS (Apple silicon and Intel), and FreeBSD, in a Docker container limited to 1 GiB and 2 CPUs, and in a Kubernetes pod limited to 512 MiB and 1 CPU. Each one checks what it reads against what the environment is known to give: the container's memory and CPU limits, the container runtime, Kubernetes, WSL 2. They also ran on a Windows 11 workstation and in WSL 2 Ubuntu.
+
+## The database start-up
+
+- The lock goes beside the data directory, before any data file is opened, so two copies on one data directory exclude each other whoever started them.
+- The cache is a quarter of `mem::total()`, which is the container's or job's limit when there is one, and workers come from `cpu::available()`.
+- The data directory's disk and the Database readiness report are printed at start-up.
+
+## New
+
+- `GuardBuilder::process_wide(false)` takes the lock and nothing else. It leaves the umask and the open-file limit alone, for a library or a component inside a larger program. It replaces `keep_umask().open_files_target(0).open_files_minimum(0)`, which still read the umask (on Unix, reading it means setting it).
+
+## Fixed
+
+- `virt::detect()` names containerd in a Kubernetes pod on cgroup v2. Such a pod has no marker file and `/proc/1/cgroup` says only `0::/`, so it read as `Container::Other`; the pod's mounts now name the runtime.
+- The readiness report's access-time fix named `/etc/fstab` on Windows and macOS. Each platform now names its own tool.
+
+## Upgrading
+
+```toml
+[dependencies]
+sys = { package = "sys-lib", version = "0.9" }
+```
+
+Nothing is removed or renamed. The changelog lists everything.
diff --git a/examples/boot.rs b/examples/boot.rs
index 95cd4be..465044a 100644
--- a/examples/boot.rs
+++ b/examples/boot.rs
@@ -1,47 +1,140 @@
-//! The boot kit, as a long-running service uses it in its first milliseconds:
-//! the guard before any file is opened, then build and instance info on the
-//! first log line, then a worker pool sized to what this process may use.
+//! The boot kit, as a long-running service uses it in its first milliseconds
+//! (phase 0): the guard before any file is opened, then build and instance
+//! info on the first log line, then a worker pool sized to what this process
+//! may use, and where it runs.
//!
//! ```text
//! cargo run --example boot
//! ```
//!
-//! A second copy started while the first runs is refused with the first
-//! copy's process id.
+//! It exits 1 when a reading breaks its own rules or differs from what the
+//! environment is known to give, which the integration workflow sets:
+//! `SYS_LIB_EXPECT_CONTAINER` (`docker`, `containerd`, ..., or `none`),
+//! `SYS_LIB_EXPECT_KUBERNETES` (`true` or `false`), `SYS_LIB_EXPECT_WSL`
+//! (`2`), and `SYS_LIB_EXPECT_CPUS`. A second copy started while the first
+//! runs is refused with the first copy's process id.
+
+use std::process::ExitCode;
use sys_lib as sys;
-fn main() -> Result<(), sys::Error> {
- let guard = sys::process::guard("sys-lib-boot-example")?;
+fn expected(name: &str) -> Option {
+ std::env::var(name)
+ .ok()
+ .map(|v| v.trim().to_ascii_lowercase())
+}
+
+fn main() -> ExitCode {
+ let guard = match sys::process::guard("sys-lib-boot-example") {
+ Ok(guard) => guard,
+ Err(e) => {
+ eprintln!("cannot start: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
let build = sys::build_info!();
let instance = sys::Instance::start();
+ let mut problems: Vec = Vec::new();
println!("{build}");
println!("{instance}");
let report = guard.report();
println!(
- "lock {:?} on {:?}",
+ "lock {:?} on {:?}",
report.lock_file, report.lock_filesystem
);
println!(
- "umask {:?} -> {:?}",
+ "umask {:?} -> {:?}",
report.umask_before, report.umask_after
);
println!(
"open files {:?} -> {:?}",
- report.open_files_before, report.open_files_after
+ report.open_files_before.soft, report.open_files_after.soft
);
for warning in &report.warnings {
- println!("warning {warning:?}");
+ println!("warning {warning:?}");
+ }
+ if let (Some(before), Some(after)) =
+ (report.open_files_before.soft, report.open_files_after.soft)
+ && after < before
+ {
+ problems.push(format!("the open-file limit fell from {before} to {after}"));
+ }
+
+ // A second copy is refused, and the refusal names this one.
+ match sys::process::guard("sys-lib-boot-example") {
+ Err(sys::Error::AlreadyRunning { pid, .. }) => {
+ println!("second copy refused, naming pid {pid:?}");
+ if pid != Some(std::process::id()) {
+ problems.push(format!(
+ "the refusal named {pid:?}, not {}",
+ std::process::id()
+ ));
+ }
+ }
+ Ok(_) => problems.push("a second copy took the lock".into()),
+ Err(e) => problems.push(format!("a second copy failed with: {e}")),
}
let workers = sys::cpu::available();
println!(
- "workers {workers} (of {} logical CPUs)",
+ "workers {workers} (of {} logical CPUs)",
sys::cpu::logical()
);
- println!("public {}", build.public());
+ if let Some(want) = expected("SYS_LIB_EXPECT_CPUS")
+ && workers.to_string() != want
+ {
+ problems.push(format!("{workers} CPUs available, not {want}"));
+ }
+ match sys::process::is_elevated() {
+ Ok(e) => println!("elevated {e}"),
+ Err(e) => problems.push(format!("elevation unreadable: {e}")),
+ }
+ match sys::mem::used_percent() {
+ Ok(p) => println!("memory {p} used"),
+ Err(e) => problems.push(format!("memory unreadable: {e}")),
+ }
+
+ // Where it runs: the evidence, and what the environment says it is.
+ let virt = sys::virt::detect();
+ println!(
+ "runs in hypervisor {:?}, container {:?}, kubernetes {}, wsl {:?}",
+ virt.hypervisor, virt.container, virt.kubernetes, virt.wsl
+ );
+ for e in &virt.evidence {
+ println!("evidence {} ({:?})", e.check, e.strength);
+ }
+ if let Some(want) = expected("SYS_LIB_EXPECT_CONTAINER") {
+ let got = virt.container.map_or_else(
+ || "none".to_owned(),
+ |c| format!("{c:?}").to_ascii_lowercase(),
+ );
+ if got != want {
+ problems.push(format!("container {got}, not {want}"));
+ }
+ }
+ if let Some(want) = expected("SYS_LIB_EXPECT_KUBERNETES")
+ && virt.kubernetes.to_string() != want
+ {
+ problems.push(format!("kubernetes {}, not {want}", virt.kubernetes));
+ }
+ if let Some(want) = expected("SYS_LIB_EXPECT_WSL")
+ && virt.wsl.map(|v| v.to_string()) != Some(want.clone())
+ {
+ problems.push(format!("wsl {:?}, not {want}", virt.wsl));
+ }
- std::thread::sleep(std::time::Duration::from_secs(2));
- Ok(())
+ println!("\n{}", sys::summary());
+ println!("public {}", build.public());
+
+ drop(guard);
+ if problems.is_empty() {
+ println!("\nok");
+ ExitCode::SUCCESS
+ } else {
+ for p in &problems {
+ eprintln!("PROBLEM: {p}");
+ }
+ ExitCode::FAILURE
+ }
}
diff --git a/examples/database.rs b/examples/database.rs
new file mode 100644
index 0000000..b291187
--- /dev/null
+++ b/examples/database.rs
@@ -0,0 +1,178 @@
+//! A database start-up on sys-lib: the lock beside the data, the cache sized
+//! from the memory this process may use, workers from the CPUs it may use,
+//! the data directory's disk, and the Database readiness report.
+//!
+//! ```text
+//! cargo run --example database [data-directory]
+//! ```
+//!
+//! It exits 1 when a reading breaks its own rules (a total above the limit, a
+//! second copy that is not refused) or differs from what the environment is
+//! known to give: `SYS_LIB_EXPECT_MEMORY` (bytes) and `SYS_LIB_EXPECT_CPUS`,
+//! which the integration workflow sets for its containers. A failed readiness
+//! check is printed, not fatal: it describes the machine, not the library.
+
+use std::{path::PathBuf, process::ExitCode};
+
+use sys_lib::{
+ self as sys, Bytes, Error,
+ process::Guard,
+ readiness::{self, Profile},
+};
+
+const NAME: &str = "sys-lib-example-db";
+
+/// A quarter of the memory this process may use, at least 64 MiB and never
+/// more than half.
+fn cache_size(total: Bytes) -> Bytes {
+ let total = total.raw();
+ Bytes::new((total / 4).max(64 << 20).min(total / 2))
+}
+
+fn expected(name: &str) -> Option {
+ std::env::var(name).ok().and_then(|v| v.trim().parse().ok())
+}
+
+fn main() -> ExitCode {
+ let data: PathBuf = std::env::args_os()
+ .nth(1)
+ .map_or_else(|| std::env::temp_dir().join(NAME), Into::into);
+ let mut problems: Vec = Vec::new();
+
+ // The lock comes first, before any data file is opened: two copies on one
+ // data directory corrupt it. Beside the data, so copies started by
+ // different users or with different run directories still exclude each
+ // other.
+ let guard = match Guard::builder(NAME)
+ .lock_dir(&data)
+ .open_files_target(1_048_576)
+ .build()
+ {
+ Ok(guard) => guard,
+ Err(e) => {
+ eprintln!("cannot start: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ let report = guard.report();
+ println!("data {}", data.display());
+ if let Some(lock) = guard.lock_file() {
+ println!("lock {}", lock.display());
+ }
+ println!(
+ "open files {:?} -> {:?} (hard {:?})",
+ report.open_files_before.soft, report.open_files_after.soft, report.open_files_after.hard
+ );
+ for warning in &report.warnings {
+ println!("warning {warning:?}");
+ }
+
+ // A second copy is refused, and the refusal names this one.
+ match Guard::builder(NAME)
+ .lock_dir(&data)
+ .process_wide(false)
+ .build()
+ {
+ Err(Error::AlreadyRunning { pid, .. }) => {
+ println!("second copy refused, naming pid {pid:?}");
+ if pid != Some(std::process::id()) {
+ problems.push(format!(
+ "the refusal named {pid:?}, not this process ({})",
+ std::process::id()
+ ));
+ }
+ }
+ Ok(_) => problems.push("a second copy took the lock".into()),
+ Err(e) => problems.push(format!("a second copy failed with: {e}")),
+ }
+
+ // The cache, from the memory this process may use: a container's or a
+ // job's limit when there is one, else the machine's.
+ match (sys::mem::total(), sys::mem::host_total(), sys::mem::limit()) {
+ (Ok(total), Ok(host), Ok(limit)) => {
+ println!("memory {total} of {host} on the host");
+ match &limit {
+ Some(l) => println!("limit {} from {:?}", l.hard, l.source),
+ None => println!("limit none"),
+ }
+ println!("cache {}", cache_size(total));
+ if total > host {
+ problems.push(format!("the total {total} is above the host's {host}"));
+ }
+ if let Some(l) = limit
+ && total > l.hard
+ {
+ problems.push(format!("the total {total} is above the limit {}", l.hard));
+ }
+ if let Some(want) = expected("SYS_LIB_EXPECT_MEMORY")
+ && total.raw() != want
+ {
+ problems.push(format!("the total is {} bytes, not {want}", total.raw()));
+ }
+ }
+ (total, host, limit) => problems.push(format!(
+ "memory unreadable: {:?} {:?} {:?}",
+ total.err(),
+ host.err(),
+ limit.err()
+ )),
+ }
+
+ // Workers, from the CPUs this process may use.
+ let workers = sys::cpu::available();
+ println!(
+ "workers {workers} of {} logical CPUs",
+ sys::cpu::logical()
+ );
+ if workers == 0 || workers > sys::cpu::logical() {
+ problems.push(format!(
+ "{workers} CPUs available of {}",
+ sys::cpu::logical()
+ ));
+ }
+ if let Some(want) = expected("SYS_LIB_EXPECT_CPUS")
+ && workers as u64 != want
+ {
+ problems.push(format!("{workers} CPUs available, not {want}"));
+ }
+
+ // The data directory's disk: room to grow, and what kind of device.
+ match (sys::disk::space(&data), sys::disk::of(&data)) {
+ (Ok(space), Ok(disk)) => {
+ println!(
+ "disk {} free of {} on {} ({}, {:?})",
+ space.available,
+ space.total,
+ disk.mount_point.display(),
+ disk.filesystem,
+ disk.kind
+ );
+ if space.available > space.total || space.free > space.total {
+ problems.push(format!("{space:?} has more free than in total"));
+ }
+ }
+ (space, disk) => problems.push(format!(
+ "the data directory's disk is unreadable: {:?} {:?}",
+ space.err(),
+ disk.err()
+ )),
+ }
+
+ let ready = readiness::report_for(Profile::Database, &data);
+ println!(
+ "\nreadiness ({})",
+ if ready.passed() { "passed" } else { "failed" }
+ );
+ println!("{ready}");
+
+ drop(guard);
+ if problems.is_empty() {
+ println!("\nok");
+ ExitCode::SUCCESS
+ } else {
+ for p in &problems {
+ eprintln!("PROBLEM: {p}");
+ }
+ ExitCode::FAILURE
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index 2775d40..1b1f56b 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -11,7 +11,7 @@
//!
//! ## Tier 1
//!
-//! Add it with Cargo's rename, `sys = { package = "sys-lib", version = "0.8" }`,
+//! Add it with Cargo's rename, `sys = { package = "sys-lib", version = "0.9" }`,
//! and every file writes `sys::`; without the rename, `use sys_lib as sys;`
//! does the same (the examples use that form so they compile either way).
//! One plain call per fact; static facts are read once and cached:
@@ -49,8 +49,11 @@
//!
//! ## Status
//!
-//! `0.8.0`, hardening: every threat in the model has an attack test, with the
-//! defences and their costs in `docs/SECURITY.md`; every reading is measured
+//! `0.9.0`, alpha: a service's boot phase 0 and a database start-up run on it
+//! (`examples/boot.rs` and `examples/database.rs`) on Linux, macOS, Windows,
+//! FreeBSD, in a Docker container with limits, and in a Kubernetes pod. Every
+//! threat in the model has an attack test, with the defences and their costs in
+//! `docs/SECURITY.md`; every reading is measured
//! against the crates people use for it in `docs/PERFORMANCE.md`. Feature complete
//! since `0.6`: the boot kit ([`os`], [`cpu`], [`host`], [`process`],
//! [`build`], and instance info), the live readings ([`mem`], [`disk`],
diff --git a/src/linux/virt.rs b/src/linux/virt.rs
index 38c6222..9127973 100644
--- a/src/linux/virt.rs
+++ b/src/linux/virt.rs
@@ -141,8 +141,24 @@ fn container(root: &Root, v: &mut Virtualization) {
v.fired("/proc/vz", Strong);
v.container.get_or_insert(Container::OpenVz);
}
+ let mounts = root
+ .read(
+ "/proc/self/mountinfo",
+ super::FILE_LIMIT,
+ "mounts",
+ "/proc/self/mountinfo",
+ )
+ .map(|data| mounts_in(&data))
+ .unwrap_or_default();
+ // Where the checks above say nothing, the mount table names the runtime:
+ // a pod on cgroup v2 with a cgroup namespace shows `0::/` in
+ // /proc/1/cgroup, and containerd writes no marker file.
+ if let Some((c, check)) = mounts.runtime {
+ v.fired(check, Strong);
+ v.container.get_or_insert(c);
+ }
// WSL and live images boot from an overlay too.
- if overlay_root(root) {
+ if mounts.overlay_root {
v.fired("overlay root", Weak);
if v.wsl.is_none() {
v.container.get_or_insert(Container::Other);
@@ -150,20 +166,59 @@ fn container(root: &Root, v: &mut Virtualization) {
}
}
-/// An overlay filesystem at `/`: containers, and also some live images.
-fn overlay_root(root: &Root) -> bool {
- root.read(
- "/proc/self/mountinfo",
- super::FILE_LIMIT,
- "mounts",
- "/proc/self/mountinfo",
- )
- .is_ok_and(|data| {
- data.split(|&b| b == b'\n').any(|line| {
- mountinfo::parse_line(line)
- .is_some_and(|m| &*m.mount_point == b"/" && m.fstype == b"overlay")
- })
- })
+/// What `/proc/self/mountinfo` says about a container.
+#[derive(Debug, Default)]
+struct Mounts {
+ /// An overlay filesystem at `/`: containers, and also some live images.
+ overlay_root: bool,
+ /// The runtime the mounts name, and the check that named it.
+ runtime: Option<(Container, &'static str)>,
+}
+
+fn mounts_in(data: &[u8]) -> Mounts {
+ let mut overlay_root = false;
+ let mut layers = None;
+ let mut kubelet = false;
+ for m in mountinfo::mounts(data) {
+ match &*m.mount_point {
+ b"/" if m.fstype == b"overlay" => {
+ overlay_root = true;
+ layers = runtime_in_layers(m.super_options);
+ }
+ // The kubelet writes a pod's hosts file in its own directory and
+ // the runtime binds it in.
+ b"/etc/hosts" | b"/etc/hostname" if has(&m.root, b"/kubelet/pods/") => {
+ kubelet = true;
+ }
+ _ => {}
+ }
+ }
+ let runtime = if kubelet {
+ Some((Container::Containerd, "kubelet pod mounts"))
+ } else {
+ layers.map(|c| (c, "overlay root layers"))
+ };
+ Mounts {
+ overlay_root,
+ runtime,
+ }
+}
+
+/// The runtime whose state directory holds the overlay root's layers.
+fn runtime_in_layers(options: &[u8]) -> Option {
+ // Docker first: with its containerd image store the layers sit under
+ // Docker's directory and still carry containerd's snapshotter name.
+ if has(options, b"/var/lib/docker/") {
+ Some(Container::Docker)
+ } else if has(options, b"io.containerd.snapshotter") {
+ Some(Container::Containerd)
+ } else {
+ None
+ }
+}
+
+fn has(haystack: &[u8], needle: &[u8]) -> bool {
+ haystack.windows(needle.len()).any(|w| w == needle)
}
fn kubernetes(root: &Root, env: Env, v: &mut Virtualization) {
@@ -239,6 +294,46 @@ mod tests {
assert_eq!(e[0].strength, Strength::Weak);
}
+ #[test]
+ fn test_virt_kubernetes_pod_on_cgroup2_names_containerd() {
+ // A kind pod: no marker file and `0::/` in /proc/1/cgroup, so only the
+ // mounts name the runtime.
+ let pod = concat!(
+ "1046 939 0:186 / / rw,relatime master:400 - overlay overlay rw,",
+ "lowerdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/22/fs,",
+ "upperdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/31/fs\n",
+ "1060 1046 254:1 /docker/volumes/4f0e/_data/lib/kubelet/pods/9c1d/etc-hosts ",
+ "/etc/hosts rw,relatime - ext4 /dev/vda1 rw\n",
+ );
+ let m = mounts_in(pod.as_bytes());
+ assert!(m.overlay_root);
+ assert_eq!(
+ m.runtime,
+ Some((Container::Containerd, "kubelet pod mounts"))
+ );
+ // The layers alone say containerd too, and Docker's say Docker, even
+ // with its containerd image store.
+ let layers = "1 0 0:1 / / rw - overlay overlay rw,lowerdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/1/fs\n";
+ assert_eq!(
+ mounts_in(layers.as_bytes()).runtime,
+ Some((Container::Containerd, "overlay root layers"))
+ );
+ let docker = "1 0 0:1 / / rw - overlay overlay rw,lowerdir=/var/lib/docker/containerd/daemon/io.containerd.snapshotter.v1.overlayfs/snapshots/1/fs\n";
+ assert_eq!(
+ mounts_in(docker.as_bytes()).runtime.map(|r| r.0),
+ Some(Container::Docker)
+ );
+ // A live image's overlay names nothing.
+ let live =
+ "1 0 0:1 / / rw - overlay overlay rw,lowerdir=/run/live/rootfs/filesystem.squashfs\n";
+ let m = mounts_in(live.as_bytes());
+ assert!(m.overlay_root);
+ assert_eq!(m.runtime, None);
+ let v = run("docker-cgroup2-limited", None);
+ assert_eq!(v.container, Some(Container::Docker));
+ assert!(v.evidence.iter().any(|e| e.check == "overlay root layers"));
+ }
+
#[test]
fn test_virt_runtime_names() {
assert_eq!(runtime("docker\n"), Container::Docker);
diff --git a/src/process/guard.rs b/src/process/guard.rs
index c6e3988..4f4309c 100644
--- a/src/process/guard.rs
+++ b/src/process/guard.rs
@@ -103,6 +103,7 @@ impl Guard {
umask: Some(DEFAULT_UMASK),
open_files_target: DEFAULT_OPEN_FILES_TARGET,
open_files_minimum: DEFAULT_OPEN_FILES_MINIMUM,
+ process_wide: true,
}
}
@@ -160,6 +161,7 @@ pub struct GuardBuilder {
umask: Option,
open_files_target: u64,
open_files_minimum: u64,
+ process_wide: bool,
}
impl GuardBuilder {
@@ -220,6 +222,19 @@ impl GuardBuilder {
self
}
+ /// Whether the guard may change state the whole process shares: the umask
+ /// and the open-file limit (default true). Pass false from a library or
+ /// a component inside a larger program: the guard then takes the lock
+ /// and nothing else. It neither reads nor sets the umask (reading it
+ /// means setting it, which races other threads), leaves the open-file
+ /// limit alone, and does not check it against the minimum. The report
+ /// shows the umask as `None` and the limit unchanged.
+ #[must_use]
+ pub fn process_wide(mut self, on: bool) -> Self {
+ self.process_wide = on;
+ self
+ }
+
/// Starts the guard. See [`guard`] for the errors.
pub fn build(self) -> Result {
validate_name(&self.name)?;
@@ -227,12 +242,16 @@ impl GuardBuilder {
// Plan the open-file limit first, so a refusal changes nothing (E-67).
let files_before = sys::open_files_limit()?;
- let raise_to = plan_open_files(
- files_before,
- self.open_files_target,
- self.open_files_minimum,
- sys::open_files_ceiling(),
- )?;
+ let raise_to = if self.process_wide {
+ plan_open_files(
+ files_before,
+ self.open_files_target,
+ self.open_files_minimum,
+ sys::open_files_ceiling(),
+ )?
+ } else {
+ None
+ };
let (lock, lock_file, lock_filesystem) = if self.lock {
let dir = match &self.lock_dir {
@@ -287,6 +306,7 @@ impl GuardBuilder {
};
let (umask_before, umask_after) = match self.umask {
+ _ if !self.process_wide => (None, None),
Some(mask) => {
let before = sys::swap_umask(mask);
(before, before.map(|_| mask))
@@ -305,7 +325,7 @@ impl GuardBuilder {
// umask, and every Windows process starts with the loader's worker
// threads, so a count there would warn on every start.
#[cfg(unix)]
- if let Some(threads) = sys::thread_count().filter(|&n| n > 1) {
+ if let Some(threads) = sys::thread_count().filter(|&n| n > 1 && self.process_wide) {
warnings.push(GuardWarning::ThreadsAlreadyRunning { threads });
}
@@ -808,9 +828,7 @@ mod tests {
let dir = temp_dir("second");
let first = Guard::builder("guard-test")
.lock_dir(&dir)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build()
.unwrap();
let lock = first.lock_file().unwrap().to_path_buf();
@@ -821,9 +839,7 @@ mod tests {
);
let second = Guard::builder("guard-test")
.lock_dir(&dir)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build();
match second {
Err(Error::AlreadyRunning { pid, lock_file }) => {
@@ -837,9 +853,7 @@ mod tests {
assert!(lock.exists());
let again = Guard::builder("guard-test")
.lock_dir(&dir)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build();
assert!(again.is_ok());
drop(again);
@@ -853,9 +867,7 @@ mod tests {
let dir = temp_dir("held");
let g = Guard::builder("held")
.lock_dir(&dir)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build()
.unwrap();
assert!(g.is_held());
@@ -878,9 +890,7 @@ mod tests {
fn test_guard_without_lock_is_not_held() {
let g = Guard::builder("unheld")
.lock(false)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build()
.unwrap();
assert!(!g.is_held());
@@ -913,15 +923,50 @@ mod tests {
fn test_guard_lock_false_takes_no_lock() {
let g = Guard::builder("nolock")
.lock(false)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build()
.unwrap();
assert_eq!(g.lock_file(), None);
assert!(g.report().warnings.contains(&GuardWarning::LockDisabled));
}
+ #[test]
+ fn test_guard_process_wide_false_touches_no_process_state() {
+ // A library inside a larger program takes the lock and nothing else.
+ // A minimum no machine meets would refuse the start if it were
+ // checked, and a umask set would change what the test reads back.
+ let dir = temp_dir("embedded");
+ #[cfg(unix)]
+ let before = sys::swap_umask(0o022);
+ let g = Guard::builder("embedded")
+ .lock_dir(&dir)
+ .open_files_minimum(u64::MAX)
+ .umask(0o077)
+ .process_wide(false)
+ .build()
+ .unwrap();
+ #[cfg(unix)]
+ {
+ let after = sys::swap_umask(0o022);
+ assert_eq!(after, Some(0o022));
+ if let Some(b) = before {
+ sys::swap_umask(b);
+ }
+ }
+ let report = g.report();
+ assert!(g.lock_file().is_some());
+ assert_eq!((report.umask_before, report.umask_after), (None, None));
+ assert_eq!(report.open_files_after, report.open_files_before);
+ assert!(
+ !report
+ .warnings
+ .iter()
+ .any(|w| matches!(w, GuardWarning::ThreadsAlreadyRunning { .. }))
+ );
+ drop(g);
+ let _ = fs::remove_dir_all(&dir);
+ }
+
#[test]
fn test_guard_refuses_a_file_as_lock_dir() {
let dir = temp_dir("file");
@@ -996,9 +1041,7 @@ mod tests {
let build = || {
Guard::builder("h")
.lock_dir(&dir)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build()
};
let held = build().unwrap();
@@ -1063,9 +1106,7 @@ mod tests {
fs::write(dir.join("g.pid"), b"999999\n").unwrap();
let g = Guard::builder("g")
.lock_dir(&dir)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build()
.unwrap();
assert_eq!(read_pid(&dir.join("g.pid")), Some(std::process::id()));
diff --git a/src/readiness.rs b/src/readiness.rs
index 0a23fed..4134aa4 100644
--- a/src/readiness.rs
+++ b/src/readiness.rs
@@ -450,6 +450,8 @@ mod fixes {
pub(super) const CLOCK_SOURCE: &str = "";
pub(super) const TURBO: &str = "";
pub(super) const SWAP: &str = "macOS manages swap itself";
+ pub(super) const ATIME: &str =
+ "mount -u -o noatime on the volume, and again at each start from a LaunchDaemon";
}
#[cfg(windows)]
@@ -464,6 +466,7 @@ mod fixes {
pub(super) const CLOCK_SOURCE: &str = "";
pub(super) const TURBO: &str = "powercfg /setacvalueindex SCHEME_CURRENT SUB_PROCESSOR PERFBOOSTMODE 0, then powercfg /setactive SCHEME_CURRENT";
pub(super) const SWAP: &str = "System Properties > Advanced > Performance > Virtual memory";
+ pub(super) const ATIME: &str = "fsutil behavior set disablelastaccess 1, then restart";
}
#[cfg(target_os = "freebsd")]
@@ -481,6 +484,8 @@ mod fixes {
pub(super) const CLOCK_SOURCE: &str = "sysctl kern.timecounter.hardware=TSC-low";
pub(super) const TURBO: &str = "";
pub(super) const SWAP: &str = "add a swap partition or file: swapon(8) and /etc/fstab";
+ pub(super) const ATIME: &str =
+ "add noatime to the options in /etc/fstab, and mount -u -o noatime to apply it now";
}
#[cfg(not(any(target_os = "macos", target_os = "freebsd", windows)))]
@@ -498,6 +503,8 @@ mod fixes {
"echo tsc > /sys/devices/system/clocksource/clocksource0/current_clocksource";
pub(super) const TURBO: &str = "echo 1 > /sys/devices/system/cpu/intel_pstate/no_turbo, or echo 0 > /sys/devices/system/cpu/cpufreq/boost";
pub(super) const SWAP: &str = "add a small swap file or zram: swapon, or zram-generator";
+ pub(super) const ATIME: &str =
+ "mount with noatime: add it to the options in /etc/fstab and remount";
}
fn check(
@@ -962,7 +969,7 @@ fn data_dir_checks(out: &mut Vec, profile: Profile, dir: &DataDir) {
"Data directory access times",
"noatime or relatime",
"Updating the access time on every read turns reads into writes.",
- "mount with noatime: add it to the options in /etc/fstab and remount",
+ fixes::ATIME,
),
|a| (pass_if(a != "strictatime"), a.clone()),
);
@@ -1148,6 +1155,33 @@ mod tests {
r.checks.iter().find(|c| c.id == id).map(|c| c.status)
}
+ #[test]
+ fn test_readiness_fixes_name_this_platforms_tools() {
+ // A fix tells an operator what to run here: on Windows and macOS a
+ // Linux path such as /etc/fstab is no help.
+ let all = [
+ fixes::NOFILE,
+ fixes::MEMLOCK,
+ fixes::BACKLOG,
+ fixes::PORTS,
+ fixes::GOVERNOR,
+ fixes::CLOCK,
+ fixes::CLOCK_SOURCE,
+ fixes::TURBO,
+ fixes::SWAP,
+ fixes::ATIME,
+ ];
+ for fix in all {
+ if cfg!(any(windows, target_os = "macos")) {
+ assert!(!fix.contains("/etc/"), "{fix}");
+ assert!(!fix.contains("/sys/"), "{fix}");
+ }
+ }
+ if cfg!(windows) {
+ assert!(fixes::ATIME.contains("fsutil"));
+ }
+ }
+
#[test]
fn test_readiness_tuned_database_passes_everything() {
let r = evaluate(Profile::Database, &inputs(tuned()));
diff --git a/tests/guard.rs b/tests/guard.rs
index 5e2404c..1dff9e0 100644
--- a/tests/guard.rs
+++ b/tests/guard.rs
@@ -26,9 +26,7 @@ fn lock_dir(tag: &str) -> PathBuf {
fn guard_in(dir: &Path) -> sys_lib::Result {
Guard::builder(NAME)
.lock_dir(dir)
- .keep_umask()
- .open_files_target(0)
- .open_files_minimum(0)
+ .process_wide(false)
.build()
}