Compare commits

..
Author SHA1 Message Date
pingqiuandClaude Opus 5.5 489862a4fe seaweed-block: README: the filer wait is bounded; replicated mode wording; best-effort in the figure
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:54:30 -08:00
pingqiuandClaude Opus 5.5 b0053091fd seaweed-block: README: mark v1.1.x as a Beta
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:42:12 -08:00
pingqiuandClaude Opus 5.5 aa12233a31 seaweed-block: README: an overview figure of both modes at the top
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:36:07 -08:00
pingqiuandClaude Opus 5.5 d8b8ddf7db seaweed-block: README: blockmaster is one instance; the filer only in the checkpointed mode
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:18:06 -08:00
pingqiuandClaude Opus 5.5 083458fef7 seaweed-block: README: block storage for SeaweedFS, in two modes
The headline names both modes; a table compares checkpointed local
block (supported) with replicated network block (preview), with one
figure per mode in light and dark. A new Architecture section names
each process, where it runs and what it talks to, and which processes
each mode needs. The Quick Start explains what mini starts and prints
and how it maps to a deployment. Agent workspaces stay the first use
case. The three figures no longer used are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:14:08 -08:00
235 changed files with 1047 additions and 20207 deletions

No files matched your search

+1 -2
View File
@@ -135,9 +135,8 @@ jobs:
docker cp "$container:/usr/local/bin/$binary" "$out/bin/$binary"
done
bash seaweed-block/scripts/refuse-lab-binary.sh "$out/bin/"*
cp seaweed-block/deploy/systemd/sw-block.tmpfiles.conf "$out/bin/sw-block.tmpfiles.conf"
asset="sw-block-${version}-linux-amd64.tar.gz"
tar -C "$out/bin" -czf "$out/$asset" blockmaster blockvolume sw-block sw-block.tmpfiles.conf
tar -C "$out/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$version" == *-* ]]; then prerelease=true; fi
-4
View File
@@ -98,10 +98,6 @@ jobs:
python3 -B ../.github/block/scripts/doc-links-check-test.py
python3 -I ../.github/block/scripts/doc-links-check.py .
- name: Release binary archive contract
if: matrix.suite == 'unit'
run: python3 -I .github/scripts/release-binary-assets-test.py
- name: Runner disk is NVMe
# A self-hosted runner whose work, temp or Go cache directory sits on a
# SATA system disk times the process-level tests out under disk load;
-20
View File
@@ -56,26 +56,6 @@ jobs:
tofu -chdir="$ex" validate
done
provider:
name: provider build, vet and unit tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: terraform/provider/go.mod
cache-dependency-path: terraform/provider/go.sum
- name: vet
working-directory: terraform/provider
run: go vet ./...
- name: unit tests
working-directory: terraform/provider
run: go test -race ./...
smoke:
name: local cluster smoke test (real weed)
runs-on: ubuntu-latest
-8
View File
@@ -97,11 +97,3 @@ TestWeedClustersSideBySideKeepTheirOwnFilerCensus
# Kubernetes state: a holder on a wiped state directory never comes up empty.
TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost
TestRF3WipedPrimaryRefusesAndASurvivorServesItsData
# Non-root mini startup and owned cleanup controls.
TestMiniStartsWithoutRootAndNamesItsBinaries
TestMiniOwnedGroupCleanupStopsDescendants
TestMiniSettledCleanupDoesNotSignal
TestMiniCleanupFailStopAndSettlement
TestMiniContextAllowsChildShutdownGrace
TestMiniLockProofRequiresContention
@@ -7,41 +7,6 @@ REV = "a" * 40
DIGEST = "example.invalid/block@sha256:" + "b" * 64
class ReleaseAssets(unittest.TestCase):
def test_active_root_release_contains_tmpfiles(self):
repo = HERE.parents[2]
workflow = (repo / '.github/workflows/block-release.yml').read_text()
step = workflow.split(' - name: Publish matching binary tarball\n', 1)[1]
script = step.split(' run: |\n', 1)[1].split('\n - name:', 1)[0]
script = '\n'.join(line[10:] for line in script.splitlines())
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
tools = root / 'tools'; tools.mkdir()
image = root / 'image'; image.mkdir()
for name in ('blockmaster', 'blockvolume', 'sw-block'):
(image / name).write_bytes(('#!/bin/sh\necho '+name+' release\n').encode())
(image / name).chmod(0o755)
(tools / 'docker').write_text('''#!/usr/bin/env python3
import os,pathlib,shutil,sys
a=sys.argv[1:]
if a[0]=='create': print('owned-container')
elif a[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/a[1].rsplit('/',1)[1],a[2])
''')
(tools / 'gh').write_text('#!/bin/sh\nexit 0\n')
for tool in tools.iterdir(): tool.chmod(0o755)
env = dict(os.environ, PATH=str(tools)+os.pathsep+os.environ['PATH'],
IMAGE=str(image), RUNNER_TEMP=str(root), BLOCK_IMAGE='example/block',
BLOCK_DIGEST='sha256:'+'b'*64, GITHUB_REF_NAME='seaweed-block/v1.1.2',
GITHUB_REPOSITORY='example/block', NOTES=str(root/'notes'))
result = subprocess.run(['bash', '-c', script], cwd=repo, env=env,
capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stderr)
with tarfile.open(root/'block-release/sw-block-v1.1.2-linux-amd64.tar.gz') as tar:
self.assertEqual(set(tar.getnames()), {'blockmaster', 'blockvolume', 'sw-block', 'sw-block.tmpfiles.conf'})
self.assertEqual(tar.extractfile('sw-block.tmpfiles.conf').read(),
(repo/'seaweed-block/deploy/systemd/sw-block.tmpfiles.conf').read_bytes())
subprocess.run(['sha256sum', '--check', 'SHA256SUMS'], cwd=root/'block-release',
check=True, capture_output=True)
def run_case(self, bad=None, mode="revision", existing=True, tag="v1.1.1",
docker_rm_rc=0, rm_rc=0, publish_rc=0):
with tempfile.TemporaryDirectory() as tmp:
@@ -58,7 +23,6 @@ elif a[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/a[1].rsplit('/',
else: self.fail("invalid fixture mode")
data=(f"#!/bin/sh\necho '{name} revision={revision} modified={modified}{suffix}'\nexit {status}\n").encode()
(image/name).write_bytes(data); (image/name).chmod(0o755); expected[name]=data
expected["sw-block.tmpfiles.conf"]=(HERE.parent.parent/"deploy"/"systemd"/"sw-block.tmpfiles.conf").read_bytes()
log=root/"calls.jsonl"; state=root/"release.json"; state.write_text(json.dumps({"prerelease":"-" not in tag}))
common="""#!/usr/bin/env python3
import json,os,pathlib,shutil,sys
+1 -3
View File
@@ -33,11 +33,9 @@ for binary in blockmaster blockvolume sw-block; do
exit 1
fi
done
# The tmpfiles.d entry that creates the host volume lock directory for the units.
cp -- "$(dirname -- "$0")/../../deploy/systemd/sw-block.tmpfiles.conf" "$work/bin/sw-block.tmpfiles.conf"
mkdir -p "$out"
asset="sw-block-${tag}-linux-amd64.tar.gz"
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block sw-block.tmpfiles.conf
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$tag" == *-* ]]; then prerelease=true; fi
+102 -105
View File
@@ -4,26 +4,56 @@
[![CI](https://github.com/seaweedfs/seaweed-block/actions/workflows/test.yml/badge.svg)](https://github.com/seaweedfs/seaweed-block/actions/workflows/test.yml)
[![Go](https://img.shields.io/github/go-mod/go-version/seaweedfs/seaweed-block)](go.mod)
[![License](https://img.shields.io/github/license/seaweedfs/seaweed-block)](LICENSE)
[![Status: Beta](https://img.shields.io/badge/status-beta-orange)](#project-status)
**Local-first block storage for AI agents.**
**Block storage for [SeaweedFS](https://github.com/seaweedfs/seaweedfs), in two modes.** **Beta:** v1.1.x is a
test release.
*Run locally. Persist incrementally. Resume anywhere.*
Seaweed Block gives a VM, sandbox or container a plain block device over NVMe/TCP or iSCSI. Either the disk lives on
the host and its changed data is checkpointed to your SeaweedFS, or every write is copied to replicas on other hosts.
Its first use case is agent workspaces: disks that must outlive the sandbox that uses them.
Seaweed Block gives each agent sandbox or microVM its own block disk on the host's local storage, and checkpoints the
changed data to your own [SeaweedFS](https://github.com/seaweedfs/seaweedfs). Writes and `fsync` complete locally;
checkpoints, named snapshots and restores carry the workspace's state beyond that host. High density per host is a
design goal; see [Vision](#vision).
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/seaweed-block-mode-overview-dark.svg">
<img src="docs/assets/seaweed-block-mode-overview-light.svg" alt="Seaweed Block in two modes. One blockmaster per cluster issues epochs and leases and decides failover; the sw-block CLI talks to it. Left, checkpointed local block (supported): on a host, the guest writes over NVMe/TCP or iSCSI to blockvolume, which completes write and fsync on its local write-ahead log and extent and checkpoints the changed 4 MiB chunks to SeaweedFS (master, volume servers and filer) in the background; blockmaster reads the HEAD records from the filer. Right, replicated network block (preview): the guest writes to the primary blockvolume, which sends every write to replica blockvolumes on other hosts; SeaweedFS is not used." width="100%">
</picture>
**[Quick start](#quick-start)** · [How it works](#how-it-works) · [Project status](#project-status) ·
[Documentation](#documentation)
**[Quick start](#quick-start-explained)** · [Two modes](#two-modes) · [Architecture](#architecture) ·
[Project status](#project-status) · [Documentation](#documentation)
<p align="center">
<img src="docs/assets/seaweed-block-lifecycle.svg" alt="The Seaweed Block lifecycle. Run locally: agent VMs on host A write to the host's local disk, where writes and fsync complete with no network round trip. Persist incrementally: checkpoints send only the changed 4 MiB chunks to your SeaweedFS in the background, and named snapshots share those chunks. Resume anywhere: host B restores a snapshot into a new volume, or takes a volume over in a planned move; it serves at once and fetches chunks on first read. Normal I/O to locally available data stays on the host." width="100%">
</p>
## Two modes
## Why not just use...
| | Checkpointed local block | Replicated network block |
|---|---|---|
| Status in v1.1.x (Beta) | **Supported** within the Beta | **Preview** inside the Beta, with [known limits](docs/releases/replicated-volumes-preview.md) |
| Where the guest's disk is | A local write-ahead log and extent on the host | A primary on the guest's host, with replicas on other hosts |
| When `fsync` completes | Once the data is on the host's local disk | With `sync-quorum` or `sync-all`, once a quorum or every replica has it (the default `best-effort` waits for none) |
| What leaves the host | The changed 4 MiB chunks, checkpointed to SeaweedFS in the background | Every write, to the replicas |
| Snapshots, restore, planned moves | Yes | Not yet: the two modes cannot be combined in v1.1.x |
| After a host is lost | An operator's forced move continues from the last checkpoint in SeaweedFS | With `--cluster-spec` and the lifecycle loop enabled (`--lifecycle-product-loop-interval`, off by default), blockmaster fails a `sync-quorum` or `sync-all` volume over to a replica when its fencing round decides; the operator then starts the guest on the new primary's host. `best-effort` is not failed over automatically |
| Use it for | Agent workspaces, sandboxes and VMs that need portable state | Workloads that need online copies on other hosts |
| | Local disk | Conventional network block storage | Seaweed Block |
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/seaweed-block-mode-checkpointed-dark.svg">
<img src="docs/assets/seaweed-block-mode-checkpointed-light.svg" alt="Checkpointed local block (supported). The guest writes over NVMe/TCP or iSCSI to blockvolume on the same host, which completes write and fsync on its local write-ahead log and extent. In the background, checkpoints send the changed 4 MiB chunks to SeaweedFS (master, filer and volume servers), which also holds the HEAD records. blockmaster issues epochs and leases to blockvolume. Snapshots, restore and planned moves use the chunks in SeaweedFS." width="100%">
</picture>
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/seaweed-block-mode-replicated-dark.svg">
<img src="docs/assets/seaweed-block-mode-replicated-light.svg" alt="Replicated network block (preview). The guest writes over NVMe/TCP or iSCSI to the primary blockvolume on its host. The primary sends every write to replica blockvolumes on other hosts; with sync-quorum or sync-all, fsync completes once a quorum or every replica has it. Each replica keeps a local store. blockmaster issues epochs, decides failover and names the new primary. No SeaweedFS is involved and there are no snapshots, restore or moves in this mode yet." width="100%">
</picture>
The two biggest limits of the replicated preview: a replica that falls behind the retained log needs a manual re-add,
and a primary cut off from blockmaster is not stopped by a lease, so it may serve stale reads and, under
`best-effort`, accept writes that are later lost. Do not use replicated volumes for data you cannot lose.
## Agent workspaces
The first use case is the checkpointed mode: each agent sandbox or microVM gets its own disk on the host's local
storage. Writes and `fsync` complete locally, and checkpoints, named snapshots and restores carry the workspace's
state beyond that host.
| | Local disk | Conventional network block storage | Checkpointed local block |
|---|---|---|---|
| Where writes and `fsync` complete | On the host | Typically on a remote storage service | On the host |
| Network in the I/O path | No | Typically, for every read and write | No, for data on the host; a restored or moved volume fetches chunks on first read |
@@ -31,12 +61,6 @@ design goal; see [Vision](#vision).
| Resume on another host | Copy the data yourself | Typically, detach the volume and attach it there | Move the volume there, or restore a snapshot into a new volume there (placed by the cluster spec) |
| What persistence sends | Nothing | Typically every write, as it happens | Only the whole 4 MiB chunks that changed, at each checkpoint |
<p align="center">
<img src="docs/assets/seaweed-block-storage-models.svg" alt="Three ways to give an agent VM a disk. Local disk: all I/O stays on the host, fast, but the state is tied to that host. Network block storage: I/O typically crosses the network to a remote volume, so the state outlives the host, but the network is in the I/O path. Seaweed Block: normal I/O to locally available data stays on the host's local disk, and changed chunks go to your SeaweedFS in the background, so it runs at near-local speed and the state outlives the host up to its last checkpoint." width="100%">
</p>
## Run, checkpoint, snapshot, restore
1. **Run.** Start a volume on the host where the agent runs. The guest attaches it over NVMe/TCP or iSCSI, formats it
with its own file system, and works at near-local speed.
2. **Checkpoint.** The changed chunks go to your SeaweedFS: on demand (`sw-block ops chunk cut`), periodically (the
@@ -49,48 +73,32 @@ design goal; see [Vision](#vision).
The commands and what each needs: [snapshots, restore and verification](docs/operations-manual.md#5-snapshots-restore-and-verification).
## Features
Also: AI coding agents whose repositories, dependencies and build caches must outlive the sandbox; long-running
agents that stop, resume and move between hosts; and Kubernetes block volumes through the CSI driver (alpha).
- **Near-local speed for agent workloads.** Writes and `fsync` complete on the host's disk, with no network round
trip, and every guest `fsync` reaches it.
- **Any file system, unchanged tools.** The guest sees a plain block device, so `git`, `npm` and builds run as on a
local disk.
- **Incremental checkpoints.** Only the changed 4 MiB chunks upload: on demand, periodically, or with the daily
snapshot.
- **Snapshots and instant restore.** Named snapshots share chunks, and a restored volume serves before its data
arrives.
- **Safe moves between hosts.** Epochs and leases fence the old host, so a stale host cannot publish over the
workspace's state.
- **Self-hosted and open source.** Your data stays in your SeaweedFS. Apache-2.0, written in Go.
## Architecture
## Use cases
| Process | What it does | Where it runs | Talks to |
|---|---|---|---|
| `blockmaster` | The control plane: epochs, leases, placement and failover. A single instance per cluster in v1.1.x, with no high availability; its authority and lifecycle records are local files. | One host. Put its state directory on its own filesystem. | `blockvolume` (heartbeats, leases, assignments), `sw-block` (control API), and in the checkpointed mode the SeaweedFS filer (HEAD records). There it needs a reachable filer to start. |
| `blockvolume` (the holder) | Serves one volume to its guest over NVMe/TCP or iSCSI, from a write-ahead log and extent. In the checkpointed mode it checkpoints to SeaweedFS; in the replicated mode it sends writes to, or receives them from, the other replicas. | On the host where the guest runs: one process per volume (and per replica). | Its guest, `blockmaster`, SeaweedFS (checkpointed mode), the other replicas (replicated mode) |
| SeaweedFS: `weed master`, `weed volume`, `weed filer` | Holds the checkpointed chunks and the HEAD records. | Your SeaweedFS cluster. | `blockvolume`, `blockmaster` and `sw-block` reach it over the network |
| `sw-block` | The operator CLI: start and stop volumes, checkpoints, snapshots, restore, moves, checks. | Wherever the operator works. | `blockmaster`, each holder's status endpoint, the SeaweedFS filer |
- **AI coding agents** whose repositories, dependencies and build caches must outlive the sandbox.
- **Agent sandboxes and microVM platforms** that give each sandbox its own disk.
- **Long-running agents** that stop, resume and move between hosts.
- **Also:** Kubernetes block volumes through the CSI driver (alpha), and replicated volumes for workloads that need
synchronous copies (`sync-quorum`, `sync-all`; preview).
What each mode needs:
- **Checkpointed:** `blockmaster` (with `--workspace-rpc`), one `blockvolume` per volume, and SeaweedFS.
`blockmaster` contacts the filer only in this mode: at start it waits about 60 s for the filer to answer, then exits
with an error.
- **Replicated:** `blockmaster` and one `blockvolume` per replica, each on its own host. These volumes do not use
SeaweedFS: in a cluster of replicated volumes only, `blockmaster` runs without `--workspace-rpc` and opens no filer
connection.
## One engine, two durability profiles
In a standalone setup the guest runs on the holder's host: remote guests are not supported in v1.1.x. The Kubernetes
CSI driver (alpha) attaches a volume to a pod on another node.
Agent workspaces are the focus. The same block engine (write-ahead log and extent, NVMe/TCP and iSCSI frontends,
blockmaster's epochs) also runs replicated volumes, for workloads that need copies on other hosts before `fsync`
completes (`sync-quorum`, `sync-all`).
| | Checkpointed volume | Replicated volume (preview) |
|---|---|---|
| Built for | Agent workspaces: many independent, portable disks | Workloads that need online copies on other hosts |
| When `fsync` completes | Once the data is on the host's local disk | With `sync-quorum` or `sync-all`, once a quorum or every replica has it (the default `best-effort` waits for none) |
| After a host is lost | An operator's forced move continues from the last checkpoint in SeaweedFS | With `--cluster-spec` and the lifecycle loop enabled (`--lifecycle-product-loop-interval`, off by default), blockmaster fails a `sync-quorum` or `sync-all` volume over to a replica when its fencing round decides; the operator then starts the guest on the new primary's host (no path failover in the guest). `best-effort` is not failed over automatically; the operator's forced failover may lose the last acknowledged writes |
| Snapshots, restore, moves | Yes | Not yet: the two profiles cannot be combined in v1.1.x |
| Status in v1.1.x | Supported | Preview, with [known limits](docs/releases/replicated-volumes-preview.md) |
The two biggest limits of the preview: a replica that falls behind the retained log needs a manual re-add, and a
primary cut off from blockmaster is not stopped by a lease, so it may serve stale reads and, under `best-effort`,
accept writes that are later lost. Do not use replicated volumes for data you cannot lose.
A workload chooses the durability it needs: a checkpointed workspace does not pay for synchronous replicas, and a
replicated volume does not wait for checkpoints.
More: [agent workspace design](docs/design/agent-workspace-design.md), [volume lifecycle](docs/volume-lifecycle.md),
the [core design](docs/design/block-design.md), and the [TLA+ specifications](docs/spec/README.md) of the
protocols where a bug would lose data.
## Performance
@@ -105,70 +113,56 @@ slower); `fsync` latency and `fsync`-bound work are 1.3 to 1.5 times local. Thes
loopback, median of 3: measurements, not SLOs. Every number and how it was measured, with the build where it was
recorded: [workspace measurements](docs/workspace-measurements.md).
## Quick start
## Quick start, explained
A trial on a disposable Linux host, not for data you keep. You need `nvme-cli`, `sudo`, and SeaweedFS's `weed`
binary, tested with SeaweedFS 4.53 (from its [release page](https://github.com/seaweedfs/seaweedfs/releases/tag/4.53),
asset `linux_amd64.tar.gz`, which holds the one `weed` binary).
A trial of the checkpointed mode on a disposable Linux host, not for data you keep. You need `nvme-cli`, `sudo` for
the connect step, and SeaweedFS's `weed` binary, tested with SeaweedFS 4.53 (from its
[release page](https://github.com/seaweedfs/seaweedfs/releases/tag/4.53), asset `linux_amd64.tar.gz`, which holds the
one `weed` binary).
```bash
TAG=v1.1.1
TAG=v1.1.2
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/sw-block-$TAG-linux-amd64.tar.gz
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/SHA256SUMS
sha256sum -c --ignore-missing SHA256SUMS && tar -xzf sw-block-$TAG-linux-amd64.tar.gz
# v1.1.1 prerequisite: its child lookup uses PATH and its lock is host-wide.
export PATH="$PWD:$PATH"
sudo install -d -m 0755 /run/sw-block
sudo install -d -m 0700 -o "$(id -u)" -g "$(id -g)" /run/sw-block/locks
./blockvolume --version # must print the tag's commit
./sw-block mini --dir ./swb-mini --weed /path/to/weed
```
From v1.1.2 `mini` needs no `sudo` to start: it keeps the volume lock under `--dir`, prints every command with the
absolute paths of `sw-block` and `weed`, and on a failed start prints the `--reuse` command that starts again on the
same `--dir`. With v1.1.1, see its [known issue](docs/releases/v1.1.1.md#known-issue-sw-block-mini-as-a-non-root-user-fixed-in-v112).
**What `mini` starts**, as the [standalone deployment](docs/standalone-deployment.md) describes:
- `weed mini`: a one-process SeaweedFS (master, volume server and filer) that holds the checkpointed chunks.
- `blockmaster`: the control plane.
- One `blockvolume`: volume `v1`, 256 MiB, as `walstore-chunk`, on loopback.
**What it shows today:**
- `mini` starts `weed mini`, `blockmaster` and one `blockvolume`: volume `v1`, 256 MiB, on loopback.
- It never runs `sudo` itself. It prints the `nvme connect` command that attaches `v1`, and the status, check and
snapshot commands. After the connect, `sudo nvme list` shows the disk's device (for example `/dev/nvme0n1`).
- Snapshots of `v1` work at once, through the `sw-block ops chunk snapshot` command it prints. From v1.1.2 `mini`
takes no scheduled snapshot (with v1.1.1 a scheduled `sched-<time>` snapshot appears soon after the start). A
restore into a new volume does not run inside `mini` yet; use the standalone setup for it.
- To stop: unmount `v1`, run the `sudo nvme disconnect` that `mini` printed, then press Ctrl-C.
It prints every command before it runs it, and each process logs to `<dir>/<name>.log`. It needs no `sudo` to start,
and it never runs `sudo` itself.
**Next:**
- Other ways to install (the release image, a build from the tag): [operations manual](docs/operations-manual.md#1-install-the-binaries-and-units).
**What it prints for you:** the `nvme connect` command that attaches `v1`, its status URL, and the next commands
(snapshot, checks), each with the absolute paths of `sw-block` and `weed`. After the connect, `sudo nvme list` shows
the disk's device (for example `/dev/nvme0n1`). Snapshots of `v1` work at once, through the `sw-block ops chunk
snapshot` command it prints. A restore into a new volume does not run inside `mini` yet; use the standalone setup for
it. To stop: unmount `v1`, run the `sudo nvme disconnect` that `mini` printed, then press Ctrl-C. After a failed
start, it prints the `--reuse` command that starts again on the same `--dir`.
**From `mini` to a real deployment:**
| In `mini` | In a deployment |
|---|---|
| `weed mini` | Your SeaweedFS cluster: `weed master`, `weed volume` and `weed filer` |
| `blockmaster` | The `sw-blockmaster` systemd unit, its state in `/var/lib/sw-block-master` on its own filesystem ([why](docs/releases/v1.1.2.md#known-issue-blockmaster-restart-can-stall-on-a-busy-filesystem)) |
| `blockvolume` for `v1` | One `sw-blockvolume@<volume>` unit per volume, started with `sudo sw-block volume start` |
| The loopback trial | A cluster spec that names the hosts and the volumes' placements |
Next:
- Install, upgrade and run the services: [operations manual](docs/operations-manual.md#1-install-the-binaries-and-units).
- Services, restore and a second host: [standalone deployment](docs/standalone-deployment.md) and
[two hosts and a planned move](docs/operations-manual.md#appendix-b-two-hosts-and-a-planned-move).
- Kubernetes (alpha): [Kubernetes quick start](docs/quickstart-kubernetes.md), with v1.1.1. v1.1.0's generated pod
cannot start.
## How it works
- **Local execution.** `blockvolume` serves the guest's block device over NVMe/TCP or iSCSI on the same host. A write
lands in a local write-ahead log, and `fsync` completes once the data is on the host's disk. The log then drains
into a local extent.
- **Incremental persistence.** A checkpoint (a *cut* in the CLI and the manuals) uploads the volume's changed 4 MiB
chunks to SeaweedFS. It then advances the volume's HEAD root with a conditional update on its generation and epoch.
A snapshot names a root and shares chunks with the others, with no backing chain.
- **Recovery and mobility.**
- A restore makes a new volume that serves at once and fetches each chunk from the snapshot on first read.
- One `blockmaster` issues epochs and leases, and the holder of a checkpointed (single-replica) volume serves only
under its current lease.
- A planned move first seals the volume with a final checkpoint, then revokes the old holder, waits for its recorded
release, and grants the next epoch on the new host, which loads chunks on first read.
- The store refuses a HEAD update from a stale holder, even before that holder notices it was replaced.
<p align="center">
<img src="docs/assets/seaweed-block-hero.svg" alt="Write path: a microVM writes over NVMe/TCP or iSCSI to blockvolume, which completes write and fsync on its local WAL. Background path: a checkpoint uploads changed 4 MiB chunks to SeaweedFS and updates HEAD on generation and epoch; blockmaster issues epochs and leases; a stale holder's update is refused." width="100%">
</p>
More: [agent workspace design](docs/design/agent-workspace-design.md), [volume lifecycle](docs/volume-lifecycle.md),
and the [TLA+ specifications](docs/spec/README.md) of the protocols where a bug would lose data.
- Kubernetes (alpha): [Kubernetes quick start](docs/quickstart-kubernetes.md).
## Durability model
For the checkpointed mode:
| Level | Reached when | Where the data is | What it protects against |
|---|---|---|---|
| Local synced | the guest's `fsync` returns | the holder host's disk | a crash or restart of the processes on that host |
@@ -185,9 +179,12 @@ and the [TLA+ specifications](docs/spec/README.md) of the protocols where a bug
## Project status
| Capability | v1.1.x |
Seaweed Block v1.1.x is a **Beta**: a test release. "Supported" below means the configuration this Beta is built
and tested for; "Preview" has the stated limits. No production SLO is claimed.
| Capability | v1.1.x (Beta) |
|---|---|
| Local single-replica volumes (`walstore-chunk`) | Supported |
| Checkpointed local volumes (`walstore-chunk`) | Supported |
| NVMe/TCP and iSCSI | Supported; in a standalone setup the guest runs on the holder's host |
| Incremental checkpoints | Supported |
| Named snapshots and lazy restore into a new volume | Supported |
+4 -4
View File
@@ -129,8 +129,8 @@ type flags struct {
durableBlockSize uint
durableWALMultiBlockRecords bool
durableWALRecoveryTestDisableFlusher bool
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden, for
// tests and sw-block mini's one-user trial; refused under systemd).
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden,
// test-only; refused under systemd).
volumeLockDirTestOnly string
// WAL retention window past checkpoint LSN. Zero = strict
@@ -333,7 +333,7 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error))
return flags{}, err
}
if f.volumeLockDirTestOnly != "" && os.Getenv("INVOCATION_ID") != "" {
return flags{}, fmt.Errorf("--%s is for tests and trial runs and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir)
return flags{}, fmt.Errorf("--%s is test-only and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir)
}
if f.recoveryMode != "legacy" && f.recoveryMode != "dual-lane" {
return flags{}, fmt.Errorf("--recovery-mode=%q invalid; want \"legacy\" or \"dual-lane\"", f.recoveryMode)
@@ -757,7 +757,7 @@ func runVolume(f flags, exits *processExit) int {
VolumeLockDirTestOnly: f.volumeLockDirTestOnly,
}
if f.volumeLockDirTestOnly != "" {
fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is an override: one process per volume is enforced only among processes using it\n", f.volumeLockDirTestOnly)
fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is a test override: the one-process-per-host guarantee does not hold\n", f.volumeLockDirTestOnly)
}
var chunkErr error
var chunk chunkWiring
@@ -40,7 +40,7 @@ func TestProcedureMasterKilledAfterMoveBeforeTargetStarts(t *testing.T) {
{"s2", "different-request"}, {"s3", "different-target"},
} {
out, stderr, code := env.h.run(t, env.moveClean(e, conflict.target, conflict.request)...)
if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: rpc error: code = FailedPrecondition desc = workspace move: missing or changed authority/lease; resolve the server's stated precondition before retrying" {
if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: workspace move: missing or changed authority/lease" {
t.Fatalf("competing move to %s: exit=%d stdout=%q stderr=%q; want the definite-refusal exit and changed-authority answer", conflict.target, code, out, stderr)
}
}
@@ -1,220 +0,0 @@
//go:build linux && subprocess && chunkstore_integration
package main_test
import (
"context"
"fmt"
"math/rand"
"net"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
)
// sw-block mini starts as any user on a host without /run/sw-block: the
// holder takes its volume lock under --dir and serves, every sw-block and
// weed command mini prints names the binary by its absolute path, and no
// scheduled snapshot runs. A start that fails after --dir was made stops what
// it started and prints the --reuse command for the same --dir.
func TestMiniStartsWithoutRootAndNamesItsBinaries(t *testing.T) {
assertMiniUnprivileged(t)
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
t.Fatal("CHUNKSTORE_WEED must name the pinned real SeaweedFS binary")
}
var err error
weed, err = filepath.Abs(weed)
if err != nil {
t.Fatal(err)
}
// The real startup/output assertion must exercise the production hint,
// even when CI supplied an ordinary path. Both spaces and apostrophes need
// POSIX quoting; exec still receives the path as one argument.
quotedWeed := filepath.Join(t.TempDir(), "weed's tools")
if err := os.Symlink(weed, quotedWeed); err != nil {
t.Fatal(err)
}
weed = quotedWeed
bins := os.Getenv("SWBLOCK_TEST_BINS")
if bins == "" {
bins = t.TempDir()
for _, b := range []string{"blockmaster", "blockvolume", "sw-block"} {
miniGoBuild(t, filepath.Join(bins, b), "github.com/seaweedfs/seaweed-block/cmd/"+b)
}
}
bins, err = filepath.Abs(bins)
if err != nil {
t.Fatal(err)
}
cli := filepath.Join(bins, "sw-block")
shift := miniPortShift(t)
dir := filepath.Join(t.TempDir(), "mini")
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
p := startOwnedMini(t, ctx, cli, "mini", "--dir", dir, "--bin", bins, "--weed", weed, "--port-shift", fmt.Sprint(shift))
for !strings.Contains(p.output.String(), "sw-block mini: running") {
select {
case <-p.done:
t.Fatalf("mini did not reach running: %v\n%s", p.err, p.output.String())
case <-ctx.Done():
t.Fatalf("mini startup expired: %s", p.output.String())
case <-time.After(20 * time.Millisecond):
}
}
// The running line precedes the hints; await the last hint without reading
// a buffer concurrently with its writer.
for !strings.Contains(p.output.String(), miniHintWord(weed)+" shell -master=") {
select {
case <-p.done:
t.Fatalf("mini exited before its hints: %s", p.output.String())
case <-ctx.Done():
t.Fatalf("mini hints expired: %s", p.output.String())
case <-time.After(20 * time.Millisecond):
}
}
if err := miniLockConflict(filepath.Join(dir, "locks", "v1.lock")); err != nil {
t.Fatalf("serving holder does not own its trial lock: %v", err)
}
if err := p.signalLeader(syscall.SIGINT); err != nil {
t.Fatalf("could not deliver Ctrl-C: %v", err)
}
if err := p.join(t, 40*time.Second); err != nil {
t.Fatalf("mini after Ctrl-C: %v\n%s", err, p.output.String())
}
p.assertStopped(t) // before the safety-net cleanup: product shutdown owns this
t.Logf("sw-block mini output:\n%s", p.output.String())
if !exists(filepath.Join(dir, "locks", "v1.lock")) {
t.Fatalf("the holder's lock is not under --dir")
}
text := p.output.String()
if strings.Contains(text, "+ sw-block ") || strings.Contains(text, " sw-block ") {
t.Errorf("mini prints a sw-block command without its absolute path")
}
for _, want := range []string{" " + miniHintWord(cli) + " ops workspace show", " " + miniHintWord(cli) + " ops chunk snapshot", miniHintWord(weed) + " shell -master=", "mini takes no scheduled snapshot", miniHintWord(cli) + " mini --dir "} {
if !strings.Contains(text, want) {
t.Errorf("mini's output lacks %q", want)
}
}
// A start that fails after --dir exists names the --reuse command.
broken := t.TempDir()
for _, b := range []string{"blockmaster", "sw-block"} {
if err := os.Symlink(filepath.Join(bins, b), filepath.Join(broken, b)); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(broken, "blockvolume"), []byte("#!/bin/sh"+string(rune(10))+"echo refused >&2; exit 1"+string(rune(10))), 0o755); err != nil {
t.Fatal(err)
}
dir2 := filepath.Join(t.TempDir(), "mini")
ctx2, cancel2 := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel2()
p2 := startOwnedMini(t, ctx2, cli, "mini", "--dir", dir2, "--bin", broken, "--weed", weed, "--port-shift", fmt.Sprint(miniPortShift(t)))
err = p2.join(t, 3*time.Minute+miniShutdownGrace+10*time.Second)
p2.assertNaturalExit(t)
b2 := p2.output.String()
t.Logf("failed start:\n%s", b2)
if err == nil || !strings.Contains(b2, "start again on it with") || !strings.Contains(b2, miniHintWord(cli)+" mini --dir "+miniHintWord(dir2)+" --reuse") {
t.Fatalf("a failed start: %v", err)
}
for _, binary := range []string{weed, filepath.Join(broken, "blockmaster"), filepath.Join(broken, "blockvolume")} {
if !strings.Contains(b2, "+ "+miniHintWord(binary)+" ") {
t.Fatalf("failed-start path did not reach %s: %s", binary, b2)
}
}
p2.assertStopped(t) // rejects a failed start which left weed/master running
}
func miniGoBuild(t *testing.T, out, pkg string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
p := startOwnedMini(t, ctx, "go", "build", "-o", out, pkg)
if err := p.join(t, 3*time.Minute+miniShutdownGrace+10*time.Second); err != nil {
t.Fatalf("build %s: %v\n%s", pkg, err, p.output.String())
}
p.assertStopped(t)
}
// miniPortShift picks a --port-shift whose every mini port (defaultMiniPorts
// in cmd/sw-block) is claimed host-wide and free now, as the other harnesses'
// ports are, so a parallel process-level shard never binds one of them.
func miniPortShift(t *testing.T) int {
t.Helper()
defaults := []int{9180, 9201, 9202, 9203, 4420, 9333, 19333, 9340, 19340, 8888, 18888, 12535, 22535}
for i := 0; i < 200; i++ {
shift := 3000 + rand.Intn(6000)
free := true
for _, p := range defaults {
if !claimHostPort(p + shift) {
free = false
break
}
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p+shift))
if err != nil {
free = false
break
}
ln.Close()
}
if free {
return shift
}
}
t.Fatal("no --port-shift with every mini port claimed and free")
return 0
}
func exists(p string) bool {
_, err := os.Stat(p)
return err == nil
}
// Expected command words follow the printed POSIX-shell contract.
func miniHintWord(s string) string {
if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
func miniLockConflict(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if err == syscall.EWOULDBLOCK || err == syscall.EAGAIN {
return nil
}
if err == nil {
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
return fmt.Errorf("lock was available")
}
return err
}
func TestMiniLockProofRequiresContention(t *testing.T) {
path := filepath.Join(t.TempDir(), "v1.lock")
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if err := miniLockConflict(path); err == nil {
t.Fatal("unheld file passed the serving-lock proof")
}
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
t.Fatal(err)
}
if err := miniLockConflict(path); err != nil {
t.Fatalf("held lock failed proof: %v", err)
}
}
@@ -1,615 +0,0 @@
//go:build linux && subprocess && chunkstore_integration
package main_test
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
"golang.org/x/sys/unix"
)
// Preconditions are assertions: a privileged run is not non-root evidence.
func assertMiniUnprivileged(t *testing.T) {
t.Helper()
if os.Getuid() == 0 || os.Geteuid() == 0 {
t.Fatal("non-root qualification must run without uid 0")
}
p := "/run/sw-block/locks"
// A read-only existing file can still be flocked without a directory write.
// Refuse qualification if it can even be opened; never mutate the host path.
lock, err := os.Open(filepath.Join(p, "v1.lock"))
if err == nil {
_ = lock.Close()
t.Fatal("existing host lock is readable; old host-lock path is usable")
}
if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
t.Fatalf("host lock file preflight: %v", err)
}
for {
_, err := os.Stat(p)
if err == nil {
break
}
if errors.Is(err, syscall.EACCES) || errors.Is(err, syscall.EPERM) {
t.Logf("non-root uid=%d euid=%d; host lock path %s is inaccessible: %v", os.Getuid(), os.Geteuid(), p, err)
return
}
if !errors.Is(err, os.ErrNotExist) {
t.Fatalf("host lock preflight: %v", err)
}
p = filepath.Dir(p)
}
if err := syscall.Access(p, 3); err == nil {
t.Fatalf("host lock path/ancestor %s is writable; non-root precondition is unproved", p)
} else if !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
t.Fatalf("host lock access preflight: %v", err)
}
t.Logf("non-root uid=%d euid=%d; host lock ancestor %s is not writable", os.Getuid(), os.Geteuid(), p)
}
type miniOutput struct {
mu sync.Mutex
b bytes.Buffer
}
func (b *miniOutput) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.b.Write(p)
}
func (b *miniOutput) String() string { b.mu.Lock(); defer b.mu.Unlock(); return b.b.String() }
const miniFailStopExit = 86
func miniFailStop(t *testing.T, why string) {
fmt.Fprintf(os.Stderr, "%s: %s; stopping tests before directory cleanup\n", t.Name(), why)
os.Exit(miniFailStopExit)
}
type ownedMini struct {
cmd *exec.Cmd
done chan struct{}
err error
output miniOutput
stopOnce sync.Once
mu sync.Mutex
settled bool
leaderFD int
leaderKey string
dispatches atomic.Int64
watchdog atomic.Bool
// Only the isolated fail-stop controls replace the census or its window.
groupExists func() bool
census func() []int
censusWait time.Duration
captureLeader func(int) (miniProcInfo, error)
}
const miniShutdownGrace = 35 * time.Second // three 10-second child stops plus margin
// Probe before starting any workload. CLONE_PIDFD then obtains the child's
// immutable reference atomically with creation, before a cancellation can run.
func miniPidfdSupport() error {
fd, err := unix.PidfdOpen(os.Getpid(), 0)
if err != nil {
return err
}
defer unix.Close(fd)
return unix.PidfdSendSignal(fd, 0, nil, 0)
}
func startOwnedMini(t *testing.T, ctx context.Context, bin string, args ...string) *ownedMini {
t.Helper()
if err := miniPidfdSupport(); err != nil {
t.Fatalf("pidfd ownership unavailable before start: %v", err)
}
p := &ownedMini{cmd: exec.CommandContext(ctx, bin, args...), done: make(chan struct{}), leaderFD: -1}
p.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, PidFD: &p.leaderFD}
p.cmd.Stdout, p.cmd.Stderr = &p.output, &p.output
// os/exec must not kill only the leader after a short WaitDelay. Our
// watchdog grants the full product shutdown window, then owns group cleanup.
p.cmd.Cancel = func() error { p.watchdog.Store(true); go p.stop(t); return nil }
p.mu.Lock() // a context cancellation cannot observe the unopened pidfd
if err := p.cmd.Start(); err != nil {
p.mu.Unlock()
t.Fatal(err)
}
if p.leaderFD < 0 {
p.mu.Unlock()
p.ownershipFailed(t, "atomic leader pidfd missing")
}
info, err := miniProc(p.cmd.Process.Pid)
if err != nil {
p.mu.Unlock()
p.ownershipFailed(t, fmt.Sprintf("cannot record leader incarnation: %v", err))
}
p.leaderKey = info.key
p.mu.Unlock()
go func() { p.err = p.cmd.Wait(); close(p.done) }()
t.Cleanup(func() { p.stop(t) })
return p
}
// No Wait goroutine exists yet: the unreaped direct child cannot have its
// PID recycled. Stop and reap it before failing closed with directories kept.
func (p *ownedMini) ownershipFailed(t *testing.T, why string) {
_ = p.cmd.Process.Kill()
p.cmd.WaitDelay = time.Second
reaped := make(chan struct{})
go func() { _ = p.cmd.Wait(); close(reaped) }()
select {
case <-reaped:
case <-time.After(5 * time.Second):
}
miniFailStop(t, why)
}
func (p *ownedMini) signalFD(fd int, sig unix.Signal) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.settled {
return os.ErrProcessDone
}
p.dispatches.Add(1)
return unix.PidfdSendSignal(fd, sig, nil, 0)
}
func (p *ownedMini) signalLeader(sig unix.Signal) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.settled {
return os.ErrProcessDone
}
p.dispatches.Add(1)
return unix.PidfdSendSignal(p.leaderFD, sig, nil, 0)
}
func (p *ownedMini) isSettled() bool { p.mu.Lock(); defer p.mu.Unlock(); return p.settled }
func (p *ownedMini) settle() {
p.mu.Lock()
defer p.mu.Unlock()
if !p.settled {
p.settled = true
if p.leaderFD >= 0 {
_ = unix.Close(p.leaderFD)
p.leaderFD = -1
}
}
}
func (p *ownedMini) join(t *testing.T, bound time.Duration) error {
t.Helper()
select {
case <-p.done:
return p.err
case <-time.After(bound):
miniFailStop(t, fmt.Sprintf("owned process did not join in %s", bound))
return nil
}
}
func (p *ownedMini) assertNaturalExit(t *testing.T) {
t.Helper()
if p.watchdog.Load() {
t.Fatal("watchdog intervened; failed-start cleanup was not completed by mini")
}
}
func (p *ownedMini) stop(t *testing.T) {
p.stopOnce.Do(func() {
if p.isSettled() {
return
}
_ = p.signalLeader(unix.SIGTERM)
select {
case <-p.done:
p.assertStopped(t)
return
case <-time.After(miniShutdownGrace):
}
p.stopGroup(t)
})
}
// Never signal a numeric PGID. While the original leader is stopped, its
// group identity cannot disappear; capture and stop each member by pidfd.
// After resuming, TERM/KILL use those immutable references even if a PID is
// recycled. Unknown late members or an exited leader with live residue cause
// fail-stop rather than guessing ownership and signaling an unrelated group.
func (p *ownedMini) stopGroup(t *testing.T) {
t.Helper()
if p.isSettled() {
return
}
select {
case <-p.done:
p.assertStopped(t)
return
default:
}
if err := p.signalLeader(unix.SIGSTOP); err != nil {
select {
case <-p.done:
p.assertStopped(t)
return
default:
miniFailStop(t, fmt.Sprintf("cannot stop owned leader: %v", err))
}
}
pgid := p.cmd.Process.Pid
leaderFD := p.leaderFD
refs := map[string]int{}
defer func() {
for _, fd := range refs {
if fd != leaderFD {
_ = unix.Close(fd)
}
}
}()
deadline := time.Now().Add(time.Second)
for {
select {
case <-p.done:
p.assertStopped(t)
return
default:
}
readLeader := miniProc
if p.captureLeader != nil {
readLeader = p.captureLeader
}
leader, err := readLeader(pgid)
if err != nil || leader.key != p.leaderKey || (leader.state != "T" && leader.state != "t") || unix.PidfdSendSignal(leaderFD, 0, nil, 0) != nil {
if time.Now().After(deadline) {
p.captureExpired(t, "leader incarnation not held during member capture")
return
}
time.Sleep(5 * time.Millisecond)
continue
}
refs[leader.key] = leaderFD
members := miniGroupMembers(t, pgid)
stopped := true
for _, m := range members {
fd, ok := refs[m.key]
if !ok {
fd, err = unix.PidfdOpen(m.pid, 0)
if err != nil {
if errors.Is(err, unix.ESRCH) {
stopped = false
continue
}
miniFailStop(t, fmt.Sprintf("cannot own descendant: %v", err))
}
current, err := miniProc(m.pid)
if err != nil || current.key != m.key || current.group != pgid {
_ = unix.Close(fd)
stopped = false
continue
}
refs[m.key] = fd
}
if m.state != "T" && m.state != "t" {
stopped = false
if err := p.signalFD(fd, unix.SIGSTOP); err != nil && !errors.Is(err, unix.ESRCH) {
miniFailStop(t, fmt.Sprintf("cannot stop descendant: %v", err))
}
}
}
if stopped {
break
}
if time.Now().After(deadline) {
p.captureExpired(t, "descendant capture did not quiesce")
return
}
time.Sleep(5 * time.Millisecond)
}
for _, fd := range refs {
_ = p.signalFD(fd, unix.SIGTERM)
}
for _, fd := range refs {
_ = p.signalFD(fd, unix.SIGCONT)
}
select {
case <-p.done:
case <-time.After(2 * time.Second):
}
for _, fd := range refs {
_ = p.signalFD(fd, unix.SIGKILL)
}
_ = p.join(t, 5*time.Second)
p.assertStopped(t)
}
// A leader that exits as the capture window closes settles through assertStopped.
func (p *ownedMini) captureExpired(t *testing.T, why string) {
t.Helper()
select {
case <-p.done:
p.assertStopped(t)
default:
miniFailStop(t, why)
}
}
func (p *ownedMini) assertStopped(t *testing.T) {
t.Helper()
wait := p.censusWait
if wait == 0 {
wait = 5 * time.Second
}
deadline := time.Now().Add(wait)
census := func() []int {
if p.census != nil {
return p.census()
}
return miniGroupLive(t, p.cmd.Process.Pid)
}
for {
live := census()
// A /proc listing is not atomic: a member can fork then disappear
// between list and stat. Signal 0 is only an existence query (never a
// numeric effect signal); ESRCH proves the entire group is now absent.
absent := false
if p.groupExists != nil {
absent = !p.groupExists()
} else {
err := unix.Kill(-p.cmd.Process.Pid, 0)
absent = errors.Is(err, unix.ESRCH)
}
// A member counted before ESRCH may have exited in between: count
// again, so only a member still listed holds the settlement.
if len(live) != 0 && absent {
live = census()
}
if len(live) == 0 && absent {
select {
case <-p.done:
p.settle()
return
default:
miniFailStop(t, "empty group but leader not joined")
}
}
if time.Now().After(deadline) {
if len(live) == 0 {
miniFailStop(t, "owned group still exists with no live member listed: a member the census missed, or zombies its new parent does not reap")
}
miniFailStop(t, fmt.Sprintf("owned group has live residue %v", live))
}
time.Sleep(5 * time.Millisecond)
}
}
type miniProcInfo struct {
pid, group int
state, key string
}
func miniProc(pid int) (miniProcInfo, error) {
b, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
if err != nil {
return miniProcInfo{}, err
}
end := strings.LastIndexByte(string(b), ')')
if end < 0 {
return miniProcInfo{}, fmt.Errorf("invalid proc stat")
}
fields := strings.Fields(string(b[end+1:]))
if len(fields) < 20 {
return miniProcInfo{}, fmt.Errorf("short proc stat")
}
group, err := strconv.Atoi(fields[2])
if err != nil {
return miniProcInfo{}, err
}
return miniProcInfo{pid: pid, group: group, state: fields[0], key: strconv.Itoa(pid) + ":" + fields[19]}, nil
}
func miniGroupMembers(t *testing.T, pgid int) []miniProcInfo {
entries, err := os.ReadDir("/proc")
if err != nil {
miniFailStop(t, err.Error())
}
var members []miniProcInfo
for _, entry := range entries {
pid, err := strconv.Atoi(entry.Name())
if err != nil {
continue
}
info, err := miniProc(pid)
if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) {
continue
}
if err != nil {
miniFailStop(t, err.Error())
}
if info.group == pgid && info.state != "Z" && info.state != "X" {
members = append(members, info)
}
}
return members
}
func miniGroupLive(t *testing.T, pgid int) []int {
var live []int
for _, m := range miniGroupMembers(t, pgid) {
live = append(live, m.pid)
}
return live
}
// An intentionally TERM-ignoring descendant exercises the safety net itself.
func TestMiniOwnedGroupCleanupStopsDescendants(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap '' TERM; sleep 60 & echo ready; wait")
deadline := time.Now().Add(5 * time.Second)
for !strings.Contains(p.output.String(), "ready") {
if time.Now().After(deadline) {
t.Fatal("fixture did not start")
}
time.Sleep(10 * time.Millisecond)
}
if live := miniGroupLive(t, p.cmd.Process.Pid); len(live) < 2 {
t.Fatalf("descendant fixture not reached: %v", live)
}
p.stop(t)
select {
case <-p.done:
default:
t.Fatal("leader not joined")
}
}
// This real process settles normally before its registered cleanup runs. A
// later cleanup must not dispatch anything to its old group or descriptor.
func TestMiniSettledCleanupDoesNotSignal(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p := startOwnedMini(t, ctx, "/bin/true")
if err := p.join(t, 3*time.Second); err != nil {
t.Fatal(err)
}
p.assertStopped(t)
before := p.dispatches.Load()
p.stop(t)
if got := p.dispatches.Load(); got != before {
t.Fatalf("settled cleanup dispatched %d signals", got-before)
}
}
func TestMiniCleanupFailStopAndSettlement(t *testing.T) {
for _, mode := range []string{"join", "residue", "missed-member", "settled", "late-exit-settled", "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue", "natural", "watchdog"} {
t.Run(mode, func(t *testing.T) {
marker := filepath.Join(t.TempDir(), "cleanup-ran")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
t.Setenv("MINI_CLEANUP_CONTROL", mode)
t.Setenv("MINI_CLEANUP_MARKER", marker)
p := startOwnedMini(t, ctx, self, "-test.run=^TestMiniCleanupFailStopHelper$")
err = p.join(t, 3*time.Second)
p.assertStopped(t)
_, statErr := os.Stat(marker)
if mode == "settled" || mode == "late-exit-settled" || mode == "capture-settled" || mode == "capture-expired-settled" || mode == "natural" {
if err != nil || statErr != nil {
t.Fatalf("positive cleanup twin: err=%v marker=%v", err, statErr)
}
} else if mode == "watchdog" {
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 1 || !strings.Contains(p.output.String(), "watchdog intervened") || statErr != nil {
t.Fatalf("watchdog cannot prove natural cleanup: err=%v marker=%v output=%s", err, statErr, p.output.String())
}
} else {
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != miniFailStopExit || !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("fail-stop %s: err=%v marker=%v output=%s", mode, err, statErr, p.output.String())
}
}
})
}
}
func TestMiniCleanupFailStopHelper(t *testing.T) {
mode := os.Getenv("MINI_CLEANUP_CONTROL")
if mode == "" {
t.Skip("isolated fail-stop helper")
}
t.Cleanup(func() {
if err := os.WriteFile(os.Getenv("MINI_CLEANUP_MARKER"), []byte("cleanup ran"), 0o600); err != nil {
t.Error(err)
}
})
p := &ownedMini{done: make(chan struct{}), leaderFD: -1, censusWait: 10 * time.Millisecond, groupExists: func() bool { return false }}
switch mode {
case "join":
p.join(t, 10*time.Millisecond)
case "residue":
close(p.done)
p.census = func() []int { return []int{1234} }
p.assertStopped(t)
case "missed-member":
close(p.done)
p.census = func() []int { return nil }
p.groupExists = func() bool { return true }
p.assertStopped(t)
case "settled":
close(p.done)
p.census = func() []int { return nil }
p.assertStopped(t)
case "late-exit-settled":
close(p.done)
counted := false
p.census = func() []int {
if counted {
return nil
}
counted = true
time.Sleep(2 * p.censusWait) // the member exits as the window closes
return []int{1234}
}
p.assertStopped(t)
case "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue":
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p := startOwnedMini(t, ctx, "/bin/sleep", "60")
p.censusWait = 10 * time.Millisecond
if strings.HasSuffix(mode, "-residue") {
p.census = func() []int { return []int{1234} }
p.groupExists = func() bool { return true }
}
p.captureLeader = func(int) (miniProcInfo, error) {
if strings.HasPrefix(mode, "capture-expired") {
time.Sleep(1100 * time.Millisecond) // past the one-second capture window
}
_ = p.signalLeader(unix.SIGKILL)
_ = p.join(t, time.Second)
return miniProcInfo{}, os.ErrNotExist
}
p.stopGroup(t)
case "natural", "watchdog":
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
bin, args := "/bin/false", []string{}
if mode == "watchdog" {
bin, args = "/bin/sleep", []string{"60"}
}
p := startOwnedMini(t, ctx, bin, args...)
if mode == "watchdog" {
cancel()
}
_ = p.join(t, time.Second)
p.assertStopped(t)
p.assertNaturalExit(t)
default:
t.Fatal("invalid control")
}
}
// A four-second shutdown exceeds the old WaitDelay. The context watchdog
// must let it finish rather than kill its leader before children are stopped.
func TestMiniContextAllowsChildShutdownGrace(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap 'sleep 4; echo graceful; exit 0' TERM; echo ready; while :; do sleep .05; done")
deadline := time.Now().Add(5 * time.Second)
for !strings.Contains(p.output.String(), "ready") {
if time.Now().After(deadline) {
t.Fatal("shutdown fixture not ready")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
_ = p.join(t, miniShutdownGrace+10*time.Second)
p.assertStopped(t)
if !strings.Contains(p.output.String(), "graceful") {
t.Fatalf("shutdown killed prematurely: %s", p.output.String())
}
}
@@ -6,8 +6,6 @@ import (
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// The test lock directory override is refused under systemd
@@ -52,42 +50,3 @@ func TestVolumeLockDirTestOnlyHiddenFromHelp(t *testing.T) {
t.Fatalf("--help lists the test override:\n%s", out)
}
}
// Without the override the lock directory stays the host one: the provider
// gets no override, so it uses durable.HostVolumeLockDir.
func TestVolumeLockDirDefaultIsTheHostDirectory(t *testing.T) {
t.Setenv("INVOCATION_ID", "")
f, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore"))
if err != nil {
t.Fatal(err)
}
if f.volumeLockDirTestOnly != "" {
t.Fatalf("a default start overrides the lock directory: %q", f.volumeLockDirTestOnly)
}
if durable.HostVolumeLockDir != "/run/sw-block/locks" {
t.Fatalf("the host lock directory moved: %s", durable.HostVolumeLockDir)
}
}
// INV-WS-ONE-PROCESS-PER-HOST-001, the normal start: a start under systemd
// (INVOCATION_ID set, as every shipped unit runs) keeps the host-wide volume
// lock. Without the override it gets no lock directory of its own, so the
// provider uses the host one; with the hidden test-only override it is
// refused, naming the host lock directory it would have bypassed. Only a
// start outside systemd (a test, or mini, which drops INVOCATION_ID from its
// children and keeps data and lock under its --dir) may move the lock.
func TestNormalStartKeepsTheHostVolumeLock(t *testing.T) {
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore")
t.Setenv("INVOCATION_ID", "0123456789abcdef")
f, err := parseFlags(append([]string(nil), base...))
if err != nil || f.volumeLockDirTestOnly != "" {
t.Fatalf("a unit start without the override: lock dir %q, err %v; want the host directory", f.volumeLockDirTestOnly, err)
}
if durable.HostVolumeLockDir != "/run/sw-block/locks" {
t.Fatalf("the host lock directory moved: %s", durable.HostVolumeLockDir)
}
_, err = parseFlags(append(append([]string(nil), base...), "--"+volumeLockDirTestOnlyFlag+"="+t.TempDir()))
if err == nil || !strings.Contains(err.Error(), durable.HostVolumeLockDir) {
t.Fatalf("a unit start with the override: %v; want a refusal naming %s", err, durable.HostVolumeLockDir)
}
}
@@ -1,250 +0,0 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// These are independent wire expectations at command entry boundaries, not
// expected values obtained by calling the policy being tested.
var entryRPCAnswers = []struct {
name string
kind codes.Code
exit int
text string
}{
{"argument", codes.InvalidArgument, 2, "bad_request"},
{"precondition", codes.FailedPrecondition, 1, "not_admitted"},
{"permission", codes.PermissionDenied, 5, "not_authorized"},
{"identity", codes.Unauthenticated, 5, "not_authorized"},
{"data", codes.DataLoss, 4, "readout_unproven"},
{"missing", codes.NotFound, 1, "not_found"},
{"unsupported", codes.Unimplemented, 1, "unsupported"},
{"connection_after_send", codes.Unavailable, 3, "outcome is unknown"},
}
func TestAnswerEntryRestoreFailureTable(t *testing.T) {
for _, row := range entryRPCAnswers {
t.Run(row.name, func(t *testing.T) {
var calls atomic.Int32
var received atomic.Pointer[control.CreateVolumeRequest]
h, env, _, _ := restoreSetup(t, grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) {
if strings.HasSuffix(info.FullMethod, "/CreateVolume") {
calls.Add(1)
q := req.(*control.CreateVolumeRequest)
received.Store(&control.CreateVolumeRequest{VolumeId: q.VolumeId, SourceVolume: q.SourceVolume, SourceSnapshot: q.SourceSnapshot, CreateRequestId: q.CreateRequestId})
return nil, status.Error(row.kind, "entry restore answer")
}
return next(ctx, req)
}))
code, _, diagnostic := runRestore(env, restoreArgs(h)...)
if code != row.exit || !strings.Contains(diagnostic, row.text) || calls.Load() != 1 || h.called("enable") != 0 {
t.Fatalf("exit=%d want=%d calls=%d started=%d: %s", code, row.exit, calls.Load(), h.called("enable"), diagnostic)
}
q := received.Load()
if q == nil || q.VolumeId != "vol-r" || q.SourceVolume != "vol-a" || q.SourceSnapshot != "s1" || q.CreateRequestId != "restore-07b3764162e18f1c4ba7faad0d8c6360" {
t.Fatalf("wire restore tuple/identity changed: %+v", q)
}
if row.exit == 3 && !strings.Contains(diagnostic, "to finish, run the same command:") {
t.Fatalf("restore recovery lost: %s", diagnostic)
}
})
}
}
func TestAnswerEntryPlacementFailureTable(t *testing.T) {
for _, method := range []string{"RegisterWorkspaceBinding", "PlaceWorkspace"} {
for _, row := range entryRPCAnswers {
t.Run(method+"/"+row.name, func(t *testing.T) {
var calls atomic.Int32
h, env, _, _ := restoreSetup(t, grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) {
if strings.HasSuffix(info.FullMethod, "/"+method) {
calls.Add(1)
return nil, status.Error(row.kind, "entry placement answer")
}
return next(ctx, req)
}))
code, _, diagnostic := runRestore(env, restoreArgs(h)...)
if code != row.exit || !strings.Contains(diagnostic, row.text) || calls.Load() != 1 || h.called("enable") != 0 || !strings.Contains(diagnostic, abortCmd) {
t.Fatalf("exit=%d want=%d calls=%d started=%d: %s", code, row.exit, calls.Load(), h.called("enable"), diagnostic)
}
})
}
}
}
func TestAnswerEntryBackupFailureTable(t *testing.T) {
for _, row := range []struct {
name, mode, text string
exit int
}{
{"definite_refusal", "refuse", "not_primary", 2},
{"admitted_lost_answer", "async-gone", "outcome is unknown", 3},
{"wrong_operation", "async-foreign", "outcome is unknown", 3},
{"incomplete_success", "missing-headGen", "outcome is unknown", 3},
} {
t.Run(row.name, func(t *testing.T) {
h := newFakeHost(t)
env := h.env(t)
holder := newSnapHolder(t)
sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(holder.srv.URL, "http://"), true)
holder.setMode(row.mode)
code, _, diagnostic := runBackup(env, "vol-a", "--name", "n1")
if code != row.exit || !strings.Contains(diagnostic, row.text) || holder.postCount() != 1 || !strings.Contains(diagnostic, "volume backup vol-a --name n1") {
t.Fatalf("exit=%d want=%d posts=%d: %s", code, row.exit, holder.postCount(), diagnostic)
}
holder.mu.Lock()
q := holder.lastRequest
holder.mu.Unlock()
if q.VolumeID != "vol-a" || q.Name != "n1" || q.RequestID != "backup-ba5271cb955c6497fcae4d87e745f030" {
t.Fatalf("wire backup tuple/identity changed: %+v", q)
}
})
}
}
type answerEntryCluster struct {
control.UnimplementedClusterEvidenceServiceServer
err error
calls atomic.Int32
}
func (s *answerEntryCluster) GetClusterStatus(context.Context, *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) {
s.calls.Add(1)
return nil, s.err
}
func TestAnswerEntryShellInspectionFailureTable(t *testing.T) {
for _, row := range entryRPCAnswers {
t.Run(row.name, func(t *testing.T) {
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
t.Setenv(key, "")
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
fixture := &answerEntryCluster{err: status.Error(row.kind, "entry shell answer")}
control.RegisterClusterEvidenceServiceServer(server, fixture)
done := make(chan struct{})
go func() { defer close(done); _ = server.Serve(listener) }()
t.Cleanup(func() {
server.Stop()
_ = listener.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Error("inspection server did not join")
}
})
var out, diagnostic bytes.Buffer
code := run([]string{"shell", "-master", listener.Addr().String(), "-c", "cluster.status -o json"}, &out, &diagnostic)
if code != row.exit || !strings.Contains(diagnostic.String(), row.text) || fixture.calls.Load() != 1 || out.Len() != 0 {
t.Fatalf("exit=%d want=%d calls=%d out=%s: %s", code, row.exit, fixture.calls.Load(), &out, &diagnostic)
}
})
}
}
func TestAnswerLegacyStopKeepsAcquiredCutHandle(t *testing.T) {
for _, mode := range []string{"idless-refusal-after-progress", "unversioned-stalled-after-progress"} {
t.Run(mode, func(t *testing.T) {
h, env := startedHost(t, true)
env.Poll = time.Millisecond
h.cutMode.Store(mode)
code, progress, diagnostic := runStop(env, stopOpts{Volume: "vol-a", Timeout: time.Second})
if code != 2 || !strings.Contains(diagnostic, "outcome is unknown") || !strings.Contains(progress+diagnostic, "cut id c1") || h.posts.Load() != 1 || h.called("stop ") != 0 {
t.Fatalf("legacy refusal must retain admitted cut and leave serving unchanged: exit=%d posts=%d output=%s %s", code, h.posts.Load(), progress, diagnostic)
}
})
}
}
func TestAnswerLegacyPublicationUnknownNamesExistingTarget(t *testing.T) {
for _, mode := range []string{"status_saved", "status_failed"} {
t.Run(mode, func(t *testing.T) { testAnswerPublicationUnknownTarget(t, mode == "status_failed") })
}
}
type answerEntryPublicationClient struct {
*lifecycleOwnerTestClient
failStatus bool
statusAttempts int
statusFailures int
attemptedRef ops.OperatorObjectRef
attemptedReason string
}
func (c *answerEntryPublicationClient) WriteFrontendPublicationStatus(ctx context.Context, ref ops.OperatorObjectRef, value ops.SwBlockFrontendPublicationCRDStatus) error {
c.statusAttempts++
c.attemptedRef, c.attemptedReason = ref, value.ReasonCode
if c.failStatus && value.ReasonCode == "frontend_publication_runtime_failed" {
c.statusFailures++
return errors.New("status save failed")
}
return c.lifecycleOwnerTestClient.WriteFrontendPublicationStatus(ctx, ref, value)
}
func testAnswerPublicationUnknownTarget(t *testing.T, failStatus bool) {
t.Helper()
target := cmdFrontendPublicationFailbackExecutableTarget()
client := &answerEntryPublicationClient{lifecycleOwnerTestClient: &lifecycleOwnerTestClient{frontendTargets: []ops.SwBlockFrontendPublicationObject{target}}, failStatus: failStatus}
previous := opsFrontendPublicationExecutorClientFactory
opsFrontendPublicationExecutorClientFactory = func() (ops.FrontendPublicationExecutorClient, error) { return client, nil }
t.Cleanup(func() { opsFrontendPublicationExecutorClientFactory = previous })
var received atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var request ops.FrontendPublicationRuntimeRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.VolumeID != target.Spec.VolumeID {
t.Errorf("request did not reach runtime: %+v %v", request, err)
http.Error(w, "bad request", 400)
return
}
received.Add(1)
connection, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
_ = connection.Close()
}))
t.Cleanup(server.Close)
var out, diagnostic bytes.Buffer
code := run([]string{"ops", "frontend-publication-executor", "--enable-execution", "--execution-policy", "--frontend-publication-runtime-url", server.URL, "--namespace", "kube-system"}, &out, &diagnostic)
if code != 2 || received.Load() != 1 || !strings.Contains(diagnostic.String(), "outcome_unknown") || !strings.Contains(diagnostic.String(), target.Ref.Namespace+"/"+target.Ref.Name) || !strings.Contains(diagnostic.String(), target.Spec.VolumeID) {
t.Fatalf("legacy outer refusal must keep inner unknown and existing target: exit=%d received=%d out=%s diagnostic=%s", code, received.Load(), &out, &diagnostic)
}
wantSaved, wantFailures := 1, 0
if failStatus {
wantSaved, wantFailures = 0, 1
}
if client.statusAttempts != 1 || client.attemptedRef != target.Ref || client.attemptedReason != "frontend_publication_runtime_failed" || client.statusFailures != wantFailures || len(client.frontendPublicationStatusWrites) != wantSaved {
t.Fatalf("status branch not exercised: attempts=%d ref=%+v reason=%s failures=%d saved=%d wantFailures=%d wantSaved=%d", client.statusAttempts, client.attemptedRef, client.attemptedReason, client.statusFailures, len(client.frontendPublicationStatusWrites), wantFailures, wantSaved)
}
if failStatus {
if !strings.Contains(diagnostic.String(), "status save failed") {
t.Fatalf("status-write failure lost: %s", &diagnostic)
}
} else {
saved := client.frontendPublicationStatusWrites[0]
if saved.ref != target.Ref || saved.status.ReasonCode != "frontend_publication_runtime_failed" || strings.Contains(diagnostic.String(), "status save failed") {
t.Fatalf("wrong saved status: %+v diagnostic=%s", saved, &diagnostic)
}
}
}
@@ -1,29 +0,0 @@
package main
import (
"bytes"
"path/filepath"
"testing"
)
func TestCanonicalCredentialExitAtCommandEntries(t *testing.T) {
dir := t.TempDir()
t.Setenv("SW_BLOCK_TLS_CERT", filepath.Join(dir, "missing-cert"))
t.Setenv("SW_BLOCK_TLS_KEY", filepath.Join(dir, "missing-key"))
t.Setenv("SW_BLOCK_TLS_CA", filepath.Join(dir, "missing-ca"))
for _, args := range [][]string{
{"ops", "workspace", "show", "--master", "m:1", "--volume", "v"},
{"ops", "volume", "resolve", "--master", "m:1", "v"},
createAndPlaceArgs("m:1"),
{"cluster", "finalize-format", "--master", "m:1"},
{"cluster", "retire-host", "--master", "m:1", "--server", "h", "--confirm", "h"},
failoverArgs(),
} {
t.Run(args[0]+"/"+args[1]+"/"+args[2], func(t *testing.T) {
var out, diag bytes.Buffer
if exit := run(args, &out, &diag); exit != 78 {
t.Fatalf("args=%v exit=%d out=%s diag=%s", args, exit, &out, &diag)
}
})
}
}
@@ -1,87 +0,0 @@
package main
import (
"bytes"
"context"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type lostRestoreAnswer struct {
control.UnimplementedLifecycleServiceServer
calls atomic.Int64
id atomic.Value
}
func TestChunkHTTPPostLostAnswerIsUnknown(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
_ = conn.Close()
}))
defer server.Close()
var out, diag bytes.Buffer
exit := chunkPost("snapshot", server.URL, "/chunk/snapshot", time.Second, map[string]any{"requestID": "same-snapshot"}, &out, &diag)
got := chunkErrorOut(t, out.String())
if calls.Load() != 1 || exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "replay key") {
t.Fatalf("calls=%d exit=%d answer=%+v", calls.Load(), exit, got)
}
}
func TestChunkHTTPRejectsAnUnlistedServerErrorCode(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`{"code":"unlisted_server_code","message":"retry this new error","retryable":true}`))
}))
defer server.Close()
var out, diag bytes.Buffer
exit := chunkPost("snapshot", server.URL, "/chunk/snapshot", time.Second, map[string]any{"requestID": "same-snapshot"}, &out, &diag)
got := chunkErrorOut(t, out.String())
if calls.Load() != 1 || exit != 3 || got.Code != "unsupported_error_code" || got.Retryable || !strings.Contains(got.Message, "unlisted") {
t.Fatalf("calls=%d exit=%d answer=%+v", calls.Load(), exit, got)
}
}
func (server *lostRestoreAnswer) CreateVolume(_ context.Context, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
server.calls.Add(1)
server.id.Store(req.GetCreateRequestId())
return nil, status.Error(codes.Unavailable, "reply unavailable after request was received")
}
func TestRestoreUnavailableAfterSendIsUnknown(t *testing.T) {
for _, env := range []string{link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA} {
t.Setenv(env, "")
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
service := &lostRestoreAnswer{}
server := link.NewServer(link.ServerConfig{})
control.RegisterLifecycleServiceServer(server, service)
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
var out, diag bytes.Buffer
exit := runOpsChunk([]string{"restore", "--source", "source", "--target", "target", "--snapshot", "daily", "--request-id", "same-restore", "--master", listener.Addr().String(), "--timeout", "5s"}, &out, &diag)
got := chunkErrorOut(t, out.String())
if service.calls.Load() != 1 || service.id.Load() != "same-restore" || exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "replay key") {
t.Fatalf("calls=%d id=%v exit=%d answer=%+v", service.calls.Load(), service.id.Load(), exit, got)
}
}
@@ -11,7 +11,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -19,7 +18,7 @@ import (
type unavailableCatalogRead struct{ *memChunkStore }
func (s unavailableCatalogRead) LookupEntry(context.Context, string, string) (*filerpb.Entry, error) {
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")))
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", status.Error(codes.Unavailable, "connection refused"))
}
func TestOpsChunkCatalogUnavailableIsTyped(t *testing.T) {
@@ -98,14 +97,14 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
code string
retry bool
}{
{"wrapped", fmt.Errorf("lookup: %w", unavailable), "outcome_unknown", true},
{"deadline", errors.Join(context.DeadlineExceeded, unavailable), "outcome_unknown", true},
{"caller cancellation", errors.Join(context.Canceled, unavailable), "outcome_unknown", true},
{"wrapped", fmt.Errorf("lookup: %w", unavailable), "remote_unavailable", true},
{"deadline", errors.Join(context.DeadlineExceeded, unavailable), "deadline_exceeded", true},
{"caller cancellation", errors.Join(context.Canceled, unavailable), "canceled", false},
{"identity", errors.Join(layout.ErrIdentity, unavailable), "identity_mismatch", false},
{"catalog", &chunkstore.CatalogError{Code: "outcome_unknown", Retryable: true, Err: unavailable}, "outcome_unknown", true},
{"permission", status.Error(codes.PermissionDenied, "refused"), "not_authorized", false},
{"permission", status.Error(codes.PermissionDenied, "refused"), "internal", false},
{"unknown", errors.New("unexpected implementation error"), "internal", false},
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "bad_request", false},
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "internal", false},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
@@ -115,15 +114,6 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
if tc.code == codeUnavailableCLI {
wantExit = 75
}
if tc.code == "outcome_unknown" {
wantExit = 3
}
if tc.code == "bad_request" {
wantExit = 78
}
if tc.code == "not_authorized" {
wantExit = 5
}
if exit != wantExit || e.Code != tc.code || e.Retryable != tc.retry {
t.Fatalf("exit=%d answer=%+v", exit, e)
}
@@ -67,7 +67,7 @@ func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCata
if errors.Is(err, layout.ErrHasDependents) {
return nil, &chunkstore.CatalogError{Code: "snapshot_has_dependents", Message: "remove dependent volumes or release their dependency before resuming the same --request-id", Err: err}
}
if knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) {
if chunkTransportFailure(err) || chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if err != nil {
+32 -46
View File
@@ -25,7 +25,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
const (
@@ -68,15 +67,6 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat
func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int {
ctx, cancel := context.WithTimeoutCause(parent, timeout, chunkstore.ErrSingleFilerWindowExpired)
defer cancel()
if cause := context.Cause(ctx); cause != nil {
// No census call was started. Preserve the caller's own completion.
// The pass's silence sentinel and the historical explicit deadline
// signal keep their owned mappings; opaque caller causes need Err too.
if !errors.Is(cause, errVerifyStalled) && !errors.Is(cause, context.DeadlineExceeded) {
cause = answer.RecordContext(ctx, answer.Unsent, errors.Join(ctx.Err(), cause))
}
return chunkResult(name, nil, cause, stdout, stderr)
}
err := checkSingleFiler(ctx, f)
if err != nil && !errors.Is(err, chunkstore.ErrSingleFilerWindowExpired) && parent.Err() != nil {
if c := context.Cause(parent); c != nil && !errors.Is(err, c) {
@@ -86,7 +76,7 @@ func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunks
switch {
case err == nil:
return -1
case knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled):
case chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) || chunkTransportFailure(err):
return chunkResult(name, nil, err, stdout, stderr)
case errors.Is(err, chunkstore.ErrNotSingleFiler):
return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
@@ -187,32 +177,25 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
if len(admission) == 1 && admission[0] != nil {
req.Header.Set("Prefer", "respond-async")
}
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.Unsent)
resp, err := chunkHTTPClient.Do(req)
if err != nil {
return chunkResult(name, nil, err, stdout, stderr)
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
}
defer resp.Body.Close()
responseFailure := func(cause error) int {
if resp.StatusCode >= http.StatusBadRequest {
cause = answer.HTTPStatusFailure(resp.StatusCode, cause)
} else {
cause = answer.Rekind(answer.Record(answer.PossiblyAdmitted, cause), answer.Connection)
}
return chunkResult(name, nil, cause, stdout, stderr)
}
out, err := io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit+1))
if err != nil {
return responseFailure(err)
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "read the response: "+err.Error(), true)
}
if int64(len(out)) > chunkResponseLimit {
// Refuse rather than relay a truncated body; the operation may have
// happened, and its result is what would be lost.
return responseFailure(fmt.Errorf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit))
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI,
fmt.Sprintf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit), false)
}
if resp.StatusCode == http.StatusAccepted && len(admission) == 1 && admission[0] != nil {
a := admission[0]
if err := json.Unmarshal(out, &a.Answer); err != nil || a.Answer.ID != body["requestID"] || resp.Header.Get("Location") == "" {
return responseFailure(fmt.Errorf("snapshot request %v: invalid operation admission; retry with the same --request-id against the original status address", body["requestID"]))
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid snapshot operation admission", false)
}
a.Raw = append([]byte(nil), out...)
a.Location = resp.Header.Get("Location")
@@ -233,20 +216,15 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
}
var e chunkErrBody
if json.Unmarshal(out, &e) != nil || e.Code == "" {
return responseFailure(fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))))
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))), false)
}
// The route's error body is already the CLI's error body: relay it.
policy, check := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Domain(e.Code, e.Retryable, e.Message)))
if check != nil {
policy, _ = answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Guard("unsupported_error_code")))
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, check.Error()+"; "+policy.Cure, false)
}
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, policy.Cure)
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, chunkErrorAdvice(e.Code, e.Retryable, e.Message))
if err := writeAll(stdout, out); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the error: %v\n", name, err)
return chunkExitFailed
}
return policy.Exit
return chunkErrorExit(chunkExitFailed, e.Code, e.Retryable)
}
func chunkCut(args []string, stdout, stderr io.Writer) int {
@@ -389,12 +367,27 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
// chunkResult prints v as JSON, or err as "<code>: <message>".
func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
if err != nil {
contract := answer.Chunk
if name == "verify" {
contract = answer.ChunkVerify
var ce *chunkstore.CatalogError
switch {
case errors.As(err, &ce):
exit := chunkExitFailed
if name == "volume-delete" && ce.Code == "not_admitted" && ce.Retryable {
exit = 75 // temporary admission refusal; retry the same request ID
}
return chunkFail(name, stdout, stderr, exit, ce.Code, ce.Detail(), ce.Retryable)
case chunkCanceled(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeCanceledCLI, "operation interrupted by its caller", false)
case errors.Is(err, context.DeadlineExceeded):
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
case chunkTransportFailure(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
case errors.Is(err, errVerifyStalled):
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
case layoutCode(err) != "":
return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition) || errors.Is(err, layout.ErrBusy))
default:
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
}
policy, detail := chunkAnswerFor(err, contract)
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, detail, policy.Retryable)
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(v); err != nil {
@@ -429,11 +422,6 @@ type chunkErrBody struct {
func chunkFail(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int {
exit = chunkErrorExit(exit, code, retryable)
message = chunkErrorAdvice(code, retryable, message)
return chunkWriteFailure(name, stdout, stderr, exit, code, message, retryable)
}
// chunkWriteFailure only renders an already-decided policy or server answer.
func chunkWriteFailure(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int {
prefix := "sw-block ops chunk"
if name != "" {
prefix += " " + name
@@ -461,15 +449,13 @@ func writeAll(w io.Writer, p []byte) error {
// CLI temporary remote failures use EX_TEMPFAIL consistently across commands.
func chunkErrorExit(exit int, code string, retryable bool) int {
if code == codeUnavailableCLI && retryable {
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, "")))
return policy.Exit
return 75
}
return exit
}
func chunkErrorAdvice(code string, retryable bool, message string) string {
if code == codeUnavailableCLI && retryable {
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, message)))
return policy.Cure
return message + "; retry the same operation when the remote is reachable"
}
return message
}
@@ -1,74 +0,0 @@
package main
import (
"context"
"errors"
"net"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/status"
)
// Translate domain facts and transport evidence; the registry owns the
// output code, retry decision and exit. Partial verify uses the same path.
func chunkAnswer(err error) (answer.Policy, string) {
return chunkAnswerFor(err, answer.Chunk)
}
func chunkAnswerFor(err error, contract answer.Contract) (answer.Policy, string) {
var domain *chunkstore.CatalogError
hasDomain := errors.As(err, &domain)
guard := layoutCode(err)
_, recordedPolicy := answer.PolicyOf(err, contract)
if !hasDomain && guard == "" && recordedPolicy != nil && errors.Is(err, errVerifyStalled) {
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(contract, answer.Guard("deadline_exceeded")))
return policy, err.Error() + "; " + policy.Cure
}
if (!hasDomain || domain.Code == chunkstore.CodeRemoteUnavailable) && (guard == "" || errors.Is(err, layout.ErrHolderActive)) {
observed := err
if kind, listed := answer.ErrorKind(err); listed && kind == answer.Configuration {
observed = answer.EnsureEvidence(answer.Unsent, err)
}
if _, remote := status.FromError(err); remote {
observed = answer.EnsureEvidence(answer.PossiblyAdmitted, err)
}
var network *net.OpError
if errors.As(err, &network) {
observed = answer.EnsureEvidence(answer.PossiblyAdmitted, observed)
}
if policy, check := answer.PolicyOf(observed, contract); check == nil {
if policy.Code == codeCanceledCLI {
return policy, policy.Cure
}
detail := err.Error()
if hasDomain {
detail = domain.Detail()
}
return policy, detail + "; " + policy.Cure
}
}
kind, detail := answer.Guard("internal"), err.Error()
switch {
case hasDomain:
kind = answer.Domain(domain.Code, domain.Retryable, domain.Detail())
case guard != "":
kind = answer.Guard(guard)
case errors.Is(err, context.Canceled):
kind = answer.Canceled
case errors.Is(err, context.DeadlineExceeded):
kind = answer.CallerDeadline
case errors.Is(err, errVerifyStalled):
kind = answer.Guard("deadline_exceeded")
}
policy, check := answer.Lookup(answer.Unsent, answer.ForContract(contract, kind))
if check != nil {
policy, _ = answer.Lookup(answer.Unsent, answer.ForContract(contract, answer.Guard("unsupported_error_code")))
return policy, detail + "; " + check.Error()
}
if hasDomain || policy.Code == codeCanceledCLI {
detail = policy.Cure
}
return policy, detail
}
+16 -6
View File
@@ -17,7 +17,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
@@ -46,7 +45,7 @@ func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdo
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
if chunkCanceled(err) || chunkTransportFailure(err) {
return nil, nil, chunkResult(name, nil, err, stdout, stderr)
}
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
@@ -152,7 +151,7 @@ func (c *bCommand) run(args []string, writes bool, refs func() error, do func(co
return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if err := refs(); err != nil {
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
if chunkCanceled(err) || chunkTransportFailure(err) {
return chunkResult(name, nil, err, c.stdout, c.stderr)
}
if status.Code(err) == codes.NotFound { // the master does not know the volume
@@ -394,10 +393,21 @@ func chunkRestore(args []string, stdout, stderr io.Writer) int {
VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID,
})
if err != nil {
if policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.Restore); check == nil {
return chunkWriteFailure("restore", stdout, stderr, policy.Exit, policy.Code, err.Error()+"; "+policy.Cure, policy.Retryable)
switch status.Code(err) {
case codes.NotFound:
return chunkFail("restore", stdout, stderr, chunkExitFailed, "snapshot_not_found", err.Error(), false)
case codes.AlreadyExists:
return chunkFail("restore", stdout, stderr, chunkExitFailed, "target_exists", err.Error(), false)
case codes.InvalidArgument:
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
case codes.FailedPrecondition:
if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
return chunkFail("restore", stdout, stderr, chunkExitFailed, layoutCode(layout.ErrForeignSource), err.Error(), false)
}
return chunkFail("restore", stdout, stderr, chunkExitFailed, "not_admitted", err.Error(), false)
default:
return chunkResult("restore", nil, err, stdout, stderr)
}
return chunkResult("restore", nil, err, stdout, stderr)
}
if resp.GetVolumeId() != target || !resp.GetStoreReady() {
return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, "master did not confirm the restored target is store-ready", true)
@@ -4,10 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net"
@@ -15,47 +12,13 @@ import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health/grpc_health_v1"
)
func TestChunkCensusPreflightPreservesOpaqueContextCause(t *testing.T) {
previous := checkSingleFiler
t.Cleanup(func() { checkSingleFiler = previous })
calls := 0
checkSingleFiler = func(context.Context, chunkstore.Filer) error { calls++; return nil }
for _, deadline := range []bool{false, true} {
t.Run(fmt.Sprint("deadline=", deadline), func(t *testing.T) {
cause := errors.New("opaque caller reason")
var ctx context.Context
if deadline {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), cause)
defer cancel()
} else {
var cancel context.CancelCauseFunc
ctx, cancel = context.WithCancelCause(context.Background())
cancel(cause)
}
var out, diag bytes.Buffer
exit := refuseUnlessSingleFilerWithin(ctx, "verify", nil, time.Second, &out, &diag)
got := chunkErrorOut(t, out.String())
code := "canceled"
if deadline {
code = "deadline_exceeded"
}
if exit != 1 || got.Code != code || got.Retryable != deadline {
t.Fatalf("exit=%d answer=%+v", exit, got)
}
if calls != 0 {
t.Fatalf("census calls=%d want zero", calls)
}
})
}
}
// A real gRPC call canceled by its caller keeps a cancellation answer.
func TestChunkCallerCancelIsNotTransport(t *testing.T) {
conn, err := link.Dial("127.0.0.1:1")
conn, err := grpc.NewClient("127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
@@ -1,6 +1,7 @@
package main
import (
"context"
"io"
"net"
"net/http"
@@ -12,30 +13,28 @@ import (
"testing/synctest"
)
// Exercise the owned native dial path, not a caller-supplied transport whose
// partial tracing cannot establish whether the request was sent.
func installRefusedHolderDial(t *testing.T) string {
// Keep the refused-dial fixture independent of port reuse and host forwarding:
// net/http still builds and sends the request through its real Transport,
// whose dial boundary supplies the kernel's typed refusal.
func installRefusedHolderDial(t *testing.T) *atomic.Int32 {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
calls := new(atomic.Int32)
transport := &http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
calls.Add(1)
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
}}
old := chunkHTTPClient
chunkHTTPClient = &http.Client{}
t.Cleanup(func() { chunkHTTPClient = old })
return "http://" + addr
chunkHTTPClient = &http.Client{Transport: transport}
t.Cleanup(func() { transport.CloseIdleConnections(); chunkHTTPClient = old })
return calls
}
func TestPlainDetachRefusedDialIsRemoteUnavailable(t *testing.T) {
addr := installRefusedHolderDial(t)
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", addr)
calls := installRefusedHolderDial(t)
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder")
e := chunkErrorOut(t, out)
if code != 75 || e.Code != codeUnavailableCLI || !e.Retryable || strings.Contains(errOut, "outcome_unknown") {
t.Fatalf("refused dial: exit=%d stdout=%s stderr=%s", code, out, errOut)
if code != 75 || e.Code != codeUnavailableCLI || !e.Retryable || strings.Contains(errOut, "outcome_unknown") || calls.Load() != 1 {
t.Fatalf("refused dial: exit=%d dials=%d stdout=%s stderr=%s", code, calls.Load(), out, errOut)
}
}
@@ -15,7 +15,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -33,7 +32,7 @@ func TestChunkErrorFamilyAnswerTable(t *testing.T) {
advice string
only string
}{
{"remote", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
{"remote", status.Error(codes.Unavailable, "connection refused"), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
{"caller timeout", context.DeadlineExceeded, "deadline_exceeded", 1, true, context.DeadlineExceeded.Error(), ""},
{"caller cancel", context.Canceled, "canceled", 1, false, "operation interrupted by its caller", ""},
{"dependents", layout.ErrHasDependents, "snapshot_has_dependents", 1, false, layout.ErrHasDependents.Error(), ""},
@@ -157,7 +156,7 @@ func TestSnapshotDeleteWorkTransportUsesSharedClassifier(t *testing.T) {
return status.Error(codes.Unavailable, "filer stopped after admission")
}, false, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != 3 || answer.Code != "outcome_unknown" || !answer.Retryable {
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
t.Fatalf("exit=%d answer=%+v", exit, answer)
}
retained, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
@@ -177,20 +176,8 @@ func TestVerifyIncompleteTransportPreservesPartialProgress(t *testing.T) {
if err := json.Unmarshal(out.Bytes(), &answer); err != nil {
t.Fatal(err)
}
const message = "rpc error: code = Unavailable desc = filer stopped; verification is read-only; after resolving the failure, run verification again; do not treat the incomplete scan as a clean result"
if exit != 1 || answer.Code != "outcome_unknown" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: outcome_unknown: "+message+" (incomplete)\n" {
const message = "rpc error: code = Unavailable desc = filer stopped; retry the same operation when the remote is reachable"
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: remote_unavailable: "+message+" (incomplete)\n" {
t.Fatalf("exit=%d answer=%+v stderr=%q", exit, answer, diag.String())
}
}
func TestVerifyStartCheckLostAnswerNeverLooksLikeFindings(t *testing.T) {
useMemChunkStore(t, newMemChunkStore())
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
return answer.Record(answer.PossiblyAdmitted, status.Error(codes.Unavailable, "census answer lost"))
}
exit, out, diag := runChunk("verify", "--volume", "verify-00112233", "--chunk-filer", "fake:18888")
body := chunkErrorOut(t, out)
if exit != 1 || body.Code != "outcome_unknown" {
t.Fatalf("exit=%d body=%+v diag=%s", exit, body, diag)
}
}
+1 -2
View File
@@ -13,7 +13,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// chunkTimeoutHelp is the --timeout text of the commands that use chunkPostLoop.
@@ -185,7 +184,7 @@ func chunkStats(statusAddr, volumeID string, deadline time.Time) (chunkStagedSta
if err != nil {
return chunkStagedStats{}, false
}
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
resp, err := chunkHTTPClient.Do(req)
if err != nil {
return chunkStagedStats{}, false
}
+1 -1
View File
@@ -28,7 +28,7 @@ func chunkPlainDetachPost(addr, volume string, timeout time.Duration, deadline t
HeadGen uint64 `json:"headGen"`
}
if err := json.Unmarshal(out.Bytes(), &seal); err != nil || seal.VolumeID != volume || seal.HeadGen == 0 {
return chunkFail("detach", stdout, stderr, chunkExitUnknown, "outcome_unknown", "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation; retry the same plain detach to settle it", true)
return chunkFail("detach", stdout, stderr, chunkExitFailed, codeInternalCLI, "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation", false)
}
if err := writeAll(stdout, out.Bytes()); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err)
@@ -107,7 +107,7 @@ func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) {
return nil, status.Error(codes.Unavailable, "filer unreachable")
}
var out, errs bytes.Buffer
if code := run(args, &out, &errs); code != 3 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), "outcome_unknown") {
if code := run(args, &out, &errs); code != 75 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
t.Fatalf("uncertain restore must be retryable: code=%d out=%q err=%q", code, out.String(), errs.String())
}
}
+2 -2
View File
@@ -135,8 +135,8 @@ func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) {
t.Fatalf("unknown flag: exit %d %q", code, out)
}
t.Run("refused holder dial", func(t *testing.T) {
addr := installRefusedHolderDial(t)
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", addr); code != 75 {
installRefusedHolderDial(t)
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://holder"); code != 75 {
t.Fatalf("unreachable blockvolume: exit %d %q", code, out)
} else if e := chunkErrorOut(t, out); e.Code != codeUnavailableCLI || !e.Retryable {
t.Fatalf("unreachable blockvolume: %+v, want remote_unavailable and retryable", e)
+12 -11
View File
@@ -5,7 +5,7 @@ import (
"errors"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"net"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -29,9 +29,17 @@ func chunkTransportFailure(err error) bool {
if layoutCode(err) != "" && !errors.Is(err, layout.ErrHolderActive) {
return false
}
kind, listed := answer.ErrorKind(err)
return listed && (kind == answer.Connection || kind == answer.PlaintextConnection || kind == answer.DNS || kind == answer.Timeout)
switch status.Code(err) {
case codes.Unavailable, codes.DeadlineExceeded:
return true
}
var address *net.AddrError
var syntax *net.ParseError
if errors.As(err, &address) || errors.As(err, &syntax) {
return false
}
var network net.Error
return errors.As(err, &network)
}
// gRPC cancellation does not wrap context.Canceled. Keep it distinct from an
@@ -46,10 +54,3 @@ func chunkCanceled(err error) bool {
}
return errors.Is(err, context.Canceled) || status.Code(err) == codes.Canceled
}
// Routing only: known error facts go to the shared policy; unknown local
// argument errors remain with the command's validation path.
func knownChunkFailure(err error) bool {
_, listed := answer.ErrorKind(err)
return listed
}
@@ -14,7 +14,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -57,7 +56,6 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
continue
}
t.Run(failure.name+"/"+phase+"/"+command, func(t *testing.T) {
fixtureErr := answer.Record(answer.Unsent, failure.err)
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "transport-source", "daily")
@@ -86,18 +84,18 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
case "resolve":
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) {
calls.Add(1)
return layout.VolumeID{}, fixtureErr
return layout.VolumeID{}, failure.err
}
case "dial":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, fixtureErr }
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, failure.err }
case "census":
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
calls.Add(1)
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, fixtureErr)
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, failure.err)
}
case "read":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
return transportLookupStore{mem, fixtureErr, &calls}, func() error { return nil }, nil
return transportLookupStore{mem, failure.err, &calls}, func() error { return nil }, nil
}
case "restore":
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
@@ -112,11 +110,6 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
if failure.name == "rpc-canceled" {
wantCode, wantRetry, wantExit = "canceled", false, 1
}
if phase == "reserve" || phase == "no-lease" || phase == "restore" {
// These are real server RPCs: the server received the
// request before returning its ambiguous transport status.
wantCode, wantRetry, wantExit = "outcome_unknown", true, 3
}
if calls.Load() == 0 || exit != wantExit || e.Code != wantCode || e.Retryable != wantRetry || (wantCode == codeUnavailableCLI && !strings.Contains(e.Message, "retry")) {
t.Errorf("calls=%d exit=%d answer=%+v", calls.Load(), exit, e)
}
@@ -25,8 +25,8 @@ func jsonCode(t *testing.T, out []byte) string {
// The JSON codes a runner decides by, never the message text: a restore the
// master refused for a foreign source is restore_source_not_own (from its
// typed reason; an untyped FailedPrecondition stays not_admitted), and a
// volume the master does not know is volume_not_found. A resolve failure
// without admission evidence requires recovery of the same operation.
// volume the master does not know is volume_not_found (any other resolve
// transport failure is retryable remote_unavailable).
func TestOpsChunkTypedRefusalCodes(t *testing.T) {
prevRestore, prevResolve := restoreCreateRPC, resolveVolumeID
t.Cleanup(func() { restoreCreateRPC, resolveVolumeID = prevRestore, prevResolve })
@@ -55,7 +55,7 @@ func TestOpsChunkTypedRefusalCodes(t *testing.T) {
code string
}{
{"unknown volume", status.Error(codes.NotFound, "volume not found"), chunkExitFailed, "volume_not_found"},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 3, "outcome_unknown"},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 75, codeUnavailableCLI},
} {
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{}, c.err }
var out, errs bytes.Buffer
+14 -8
View File
@@ -14,7 +14,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// chunkVerify: sw-block ops chunk verify --master master:9180 --volume v --chunk-filer host:port
@@ -22,9 +21,8 @@ import (
// (the current image and every snapshot), their segments and chunks
// (chunkstore.VerifyLayout). --orphans also reports the volume's own names
// that no reachable root names (it never deletes them). Exit 0: clean; 3:
// the pass completed with findings. Incomplete failures retain their typed
// class and partial result: unknown/operational 1, arguments 2, integrity 4,
// auth 5, unsent/retryable remote 75, local configuration 78; never findings 3.
// the pass completed with findings; 1: it could not complete (the partial
// result is printed with the reason); 2: usage.
func chunkVerify(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("verify", stderr)
var (
@@ -116,7 +114,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if knownChunkFailure(err) {
if chunkCanceled(err) || chunkTransportFailure(err) {
return verifyIncomplete(layout.VerifyResult{}, err, stdout, stderr)
}
return usage(err.Error())
@@ -292,9 +290,17 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ
chunkErrBody
Verify layout.VerifyResult `json:"verify"`
}{Verify: res}
policy, detail := chunkAnswerFor(err, answer.ChunkVerify)
body.Code, body.Message, body.Retryable = policy.Code, detail, policy.Retryable
body.Code, body.Message = codeInternalCLI, err.Error()
if chunkCanceled(err) {
body.Code, body.Message = codeCanceledCLI, "operation interrupted by its caller"
} else if chunkTransportFailure(err) {
body.Code, body.Retryable = codeUnavailableCLI, true
}
if errors.Is(err, context.DeadlineExceeded) || (errors.Is(err, errVerifyStalled) && !chunkTransportFailure(err)) {
body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true
}
body.Message = chunkErrorAdvice(body.Code, body.Retryable, body.Message)
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
chunkResult("verify", body, nil, stdout, stderr)
return policy.Exit
return chunkErrorExit(chunkExitFailed, body.Code, body.Retryable)
}
@@ -14,7 +14,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
@@ -96,7 +95,15 @@ func (m *masterAuthority) NoLiveLease(ctx context.Context) error {
// Anything else (unavailable, deadline, a lost response) leaves
// the outcome unknown and a rerun decides.
func authorityErr(err error) error {
return leaseRefusal(err, false)
// A serving holder can renew its horizon indefinitely. A clean stop is
// distinguished by the master's typed detail, never by a dated message.
result := finalLeaseBarrierErr(err)
var refusal *chunkstore.CatalogError
if errors.As(result, &refusal) && refusal.Code == "not_admitted" && refusal.Retryable && !deleteLeaseBarrierDetail(err) {
refusal.Retryable = false
refusal.Message = "stop the volume first"
}
return result
}
func deleteLeaseBarrierDetail(err error) bool {
@@ -111,12 +118,6 @@ func deleteLeaseBarrierDetail(err error) bool {
// finalLeaseBarrierErr projects the dated deletion barrier. Reserve callers
// additionally require the clean-stop detail before allowing timed retry.
func finalLeaseBarrierErr(err error) error {
return leaseRefusal(err, true)
}
// Translate the master's dated refusal and the admission step into facts.
// Retry policy and cure text belong to the shared registry.
func leaseRefusal(err error, committed bool) error {
switch status.Code(err) {
case codes.OK:
return nil
@@ -126,15 +127,7 @@ func leaseRefusal(err error, committed bool) error {
if _, rest, ok := strings.Cut(status.Convert(err).Message(), "workspace delete: live until "); ok {
if stamp, reason, ok := strings.Cut(rest, ": "); ok && reason != "" {
if until, parseErr := time.Parse(time.RFC3339Nano, stamp); parseErr == nil {
kind := answer.LeaseBarrier(until.UTC().Format(time.RFC3339Nano))
if !committed && !deleteLeaseBarrierDetail(err) {
kind = answer.Guard("delete_live_holder")
}
policy, check := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, kind))
if check != nil {
return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, check)
}
return &chunkstore.CatalogError{Code: policy.Code, Message: policy.Cure, Retryable: policy.Retryable, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
return &chunkstore.CatalogError{Code: "not_admitted", Message: "retry the same --request-id after " + until.UTC().Format(time.RFC3339Nano), Retryable: true, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
}
}
}
@@ -234,10 +227,7 @@ func deleteVolumeWithProgress(ctx context.Context, cat *chunkstore.BCatalog, ref
}
return all, nil
}
policy, _ := chunkAnswer(err)
// This is reconciliation of the same full volume ID under the same
// deletion reservation, never admission of a second operation.
transient := policy.Retryable && (chunkTransportFailure(err) || errors.Is(err, context.DeadlineExceeded))
transient := errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Unavailable
if !transient {
return nil, err
}
@@ -10,7 +10,6 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -41,11 +40,7 @@ func (f *transientDeleteFiler) DeleteEntry(ctx context.Context, dir, name string
return err
}
}
phase := answer.Unsent // this fixture refuses before applying any delete
if f.lost {
phase = answer.PossiblyAdmitted
}
return answer.Record(phase, status.Error(f.code, "object deadline"))
return status.Error(f.code, "object deadline")
}
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
}
@@ -124,7 +119,7 @@ func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string,
return err
}
if f.stall {
return answer.Record(answer.Unsent, status.Error(codes.Unavailable, "stalled after first removal"))
return status.Error(codes.Unavailable, "stalled after first removal")
}
if !f.waited {
f.waited = true
@@ -6,7 +6,6 @@ import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
@@ -41,8 +40,7 @@ func TestVolumeDeleteAdmissionRetryAnswer(t *testing.T) {
{"HEAD boundary horizon", fmt.Errorf("%w: %w", layout.ErrHolderActive, lease), 75, "not_admitted", true},
{"invalid admission", authorityErr(status.Error(codes.InvalidArgument, "invalid token")), 1, "not_admitted", false},
{"dependents", layout.ErrHasDependents, 1, "snapshot_has_dependents", false},
{"remote unknown without phase proof", authorityErr(status.Error(codes.Unavailable, "connection refused")), 3, "outcome_unknown", true},
{"remote proven unsent", authorityErr(answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused"))), 75, "remote_unavailable", true},
{"remote unknown", authorityErr(status.Error(codes.Unavailable, "connection refused")), 75, "remote_unavailable", true},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
+15 -34
View File
@@ -11,11 +11,11 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
policy "github.com/seaweedfs/seaweed-block/core/rpc/answer"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -152,8 +152,7 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
@@ -165,15 +164,15 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
if reason == "" {
reason = status.Code(err).String()
}
p, check := policy.PolicyOf(policy.EnsureEvidence(policy.PossiblyAdmitted, err), policy.Cluster)
if check != nil {
return fail("failed", reason, check.Error(), finalizeExitFailed)
}
if p.Code == "not_admitted" {
switch status.Code(err) {
case codes.FailedPrecondition:
answer.Hosts = metadataHosts(md, lifecycleclient.HostMetadataPrefix)
answer.Listed = metadataHosts(md, lifecycleclient.UnconfirmedMetadataPrefix)
return fail("refused", reason, msg, finalizeExitRefused)
case codes.Unavailable, codes.DeadlineExceeded:
return fail("unavailable", reason, msg, finalizeExitTempFail)
}
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
return fail("failed", reason, msg, finalizeExitFailed)
}
answer.FormatLevel = resp.GetFormatLevel()
for _, u := range resp.GetUnconfirmed() {
@@ -290,8 +289,7 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
answer.Server = *server
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
@@ -302,14 +300,14 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
if reason == "" {
reason = status.Code(err).String()
}
p, check := policy.PolicyOf(policy.EnsureEvidence(policy.PossiblyAdmitted, err), policy.Cluster)
if check != nil {
return fail("failed", reason, check.Error(), finalizeExitFailed)
}
if p.Code == "not_admitted" {
switch status.Code(err) {
case codes.FailedPrecondition:
answer.Volumes = retireVolumes(md)
return fail("refused", reason, msg, finalizeExitRefused)
case codes.Unavailable, codes.DeadlineExceeded:
return fail("unavailable", reason, msg, finalizeExitTempFail)
}
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
return fail("failed", reason, msg, finalizeExitFailed)
}
answer.Result, answer.Message = "retired", "host retired from the node inventory"
if !jsonMode {
@@ -318,23 +316,6 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
return finalizeExitOK
}
// Serialize the shared class in the cluster command's existing result field.
func clusterPolicyResult(p policy.Policy) string {
switch p.Code {
case "not_admitted":
return "refused"
case "remote_unavailable":
return "unavailable"
case "outcome_unknown":
if p.Exit == finalizeExitFailed {
return "failed"
}
return "unknown"
default:
return "failed"
}
}
// retireVolumes reads the held volumes from the refusal's typed metadata,
// sorted.
func retireVolumes(md map[string]string) []string {
@@ -4,7 +4,6 @@ import (
"bytes"
"encoding/json"
"errors"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"reflect"
"sort"
"testing"
@@ -51,12 +50,12 @@ func TestClusterFinalizeFormatTypedAnswer(t *testing.T) {
listed: []finalizeHost{{"node-d", "no report"}}},
{name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"},
{name: "dial", dialErr: answer.LocalConfiguration(errors.New("bad address")), exit: 78, result: "failed", reason: "bad_request"},
{name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 3, result: "unknown", reason: "Internal"},
{name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 1, result: "failed", reason: "Internal"},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
return tc.resp, answer.Record(answer.Unsent, tc.err)
return tc.resp, tc.err
}}
withClusterMaster(t, f)
if tc.dialErr != nil {
@@ -180,8 +179,8 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
{name: "not-registered", err: status.Error(codes.FailedPrecondition, "retire refused: host is not registered"), exit: 2, result: "refused", reason: "FailedPrecondition"},
{name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"},
{name: "dial", dialErr: answer.LocalConfiguration(errors.New("bad address")), exit: 78, result: "failed", reason: "bad_request"},
{name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 3, result: "unknown", reason: "Internal"},
{name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 1, result: "failed", reason: "Internal"},
{name: "usage", args: []string{"cluster", "retire-host", "--json", "--bogus", "--master", "m:1"}, exit: 1, result: "failed", reason: "usage"},
} {
t.Run(tc.name, func(t *testing.T) {
@@ -189,7 +188,7 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
calls++
if tc.err != nil {
return nil, answer.Record(answer.Unsent, tc.err)
return nil, tc.err
}
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
}}
@@ -4,15 +4,16 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
const cutObservationSlack = 5 * time.Second
@@ -83,16 +84,15 @@ func chunkObserveHandle(name, route, addr string, window time.Duration, deadline
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
phase := answer.Unsent
if id != "" {
phase = answer.PossiblyAdmitted
}
resp, err := answer.DoHTTP(&client, req, phase)
resp, err := client.Do(req)
var raw []byte
if err != nil && id == "" {
cancel()
if policy, check := answer.PolicyOf(err, answer.Chunk); check == nil {
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, err.Error()+"; "+policy.Cure, policy.Retryable)
// A failed dial sent no admission request. Other transport
// failures may have lost an applied request's answer.
var network *net.OpError
if errors.As(err, &network) && network.Op == "dial" && chunkTransportFailure(err) {
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
}
return unknown(name + " admission answer was not received (" + err.Error() + "); no second one was started")
}
+32 -17
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
@@ -10,8 +11,9 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const opsFailoverName = "sw-block ops failover"
@@ -49,12 +51,10 @@ volumes); a line that moved since is refused.
Needs an admin client certificate: SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and
SW_BLOCK_TLS_CA, all three; without them the command refuses before dialing.
Exit: 0 moved; 1 definite precondition refusal, caller cancellation before
sending, or the line did not move; 2 bad arguments or a server argument
refusal; 3 outcome unknown (or an unsent connection failure or caller
deadline): read the current line with sw-block ops volumes before another
move; 4 unproven integrity readout; 5 authentication rejection; 78 local
credential/configuration error.
Exit: 0 moved; 1 refused by blockmaster, or the line did not move; 2 bad
arguments or identity (no call made); 3 outcome unknown (the connection or the
deadline failed: the line may have moved; read it with sw-block ops volumes
before retrying).
`
func runOpsFailover(args []string, stdout, stderr io.Writer) int {
@@ -93,13 +93,11 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
}
// An admin command never falls back to a plaintext link.
if tls, err := link.MasterTLSFromEnv(); err != nil {
p, detail := operatorAnswer(err, answer.Failover)
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, detail)
return p.Exit
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, err)
return 2
} else if tls == nil {
fmt.Fprintf(stderr, "%s: needs an admin client certificate: set %s, %s and %s\n", opsFailoverName, link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)
p, _ := operatorAnswer(answer.LocalCredential(fmt.Errorf("admin client certificate is required")), answer.Failover)
return p.Exit
return 2
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
@@ -121,15 +119,14 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
EvidenceRefs: []string{"sw-block ops failover", "operator_confirmed_old_node_off=" + volume},
})
if err != nil {
policy, detail := operatorAnswer(err, answer.Failover)
if policy.Retry == answer.Recover {
if failoverOutcomeUnknown(err) {
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=unknown\n", volume, target, curReplica, curEpoch)
fmt.Fprintf(stderr, "%s: outcome unknown (%v): the line may have moved; read it with sw-block ops volumes before retrying\n", opsFailoverName, err)
return policy.Exit
return 3
}
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch)
fmt.Fprintf(stderr, "%s: %v (a refused fencing round may have fenced the survivors)\n", opsFailoverName, detail)
return policy.Exit
fmt.Fprintf(stderr, "%s: refused: %v (no line published; a refused fencing round may have fenced the survivors)\n", opsFailoverName, err)
return 1
}
moved := res.FailbackStarted && res.AuthorityEpochAdvanced && res.SinglePrimaryAfterFailback
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=%s epoch_advanced=%t single_primary=%t publish_target_swapped=%t\n",
@@ -153,3 +150,21 @@ func parseReplicaAtEpoch(s string) (string, uint64, bool) {
}
return s[:i], e, true
}
// failoverOutcomeUnknown: the call did not get blockmaster's decision back
// (connection, deadline, cancellation or an internal failure), so the line
// may or may not have moved. A decided refusal is any other status.
func failoverOutcomeUnknown(err error) bool {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return true
}
s, ok := status.FromError(err)
if !ok {
return true
}
switch s.Code() {
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss, codes.ResourceExhausted:
return true
}
return false
}
+2 -64
View File
@@ -11,7 +11,6 @@ import (
"encoding/pem"
"errors"
"math/big"
"net"
"os"
"os/exec"
"path/filepath"
@@ -20,7 +19,6 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -171,42 +169,6 @@ func TestOpsFailoverReportsAnUnknownOutcome(t *testing.T) {
}
}
// A master that never answers the handshake leaves the call unsent when the
// caller's deadline passes; the operator must still read the line first.
func TestOpsFailoverUnsentCallerDeadlineIsUnknown(t *testing.T) {
cert, key, ca := writeClientIdentity(t, t.TempDir())
t.Setenv(link.EnvTLSCert, cert)
t.Setenv(link.EnvTLSKey, key)
t.Setenv(link.EnvTLSCA, ca)
silent, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
held := make(chan net.Conn, 16)
go func() {
for {
conn, err := silent.Accept()
if err != nil {
close(held)
return
}
held <- conn
}
}()
t.Cleanup(func() {
silent.Close()
for conn := range held {
conn.Close()
}
})
args := failoverArgs("--timeout", "300ms")
args[3] = silent.Addr().String()
var out, errb bytes.Buffer
if rc := run(args, &out, &errb); rc != 3 || !strings.Contains(out.String(), "result=unknown") {
t.Fatalf("rc=%d stdout=%q stderr=%q; want 3 and result=unknown", rc, out.String(), errb.String())
}
}
// The admin command never dials without a complete, valid client identity:
// unset, partial or unreadable TLS settings are refused locally (exit 2, no
// call); a valid identity makes the call.
@@ -240,8 +202,8 @@ func TestOpsFailoverRequiresAClientIdentity(t *testing.T) {
if len(f.calls) != c.calls {
t.Fatalf("calls=%d; want %d (rc=%d stderr %q)", len(f.calls), c.calls, rc, errb.String())
}
if c.calls == 0 && rc != 78 {
t.Fatalf("rc=%d; want 78", rc)
if c.calls == 0 && rc != 2 {
t.Fatalf("rc=%d; want 2", rc)
}
if c.calls == 1 && rc != 0 {
t.Fatalf("rc=%d stderr %q; want 0", rc, errb.String())
@@ -326,27 +288,3 @@ func TestAlphaFailbackExecutorRendersTheSelectedImage(t *testing.T) {
t.Fatalf("rendered executor does not run the selected image: %s", r)
}
}
func TestOpsFailoverUsesSharedDefiniteExitProjection(t *testing.T) {
for _, row := range []struct {
name string
err error
exit int
}{
{"certificate", status.Error(codes.Unauthenticated, "certificate rejected"), 5},
{"role", status.Error(codes.PermissionDenied, "admin required"), 5},
{"integrity", status.Error(codes.DataLoss, "line readout unproven"), 4},
{"arguments", status.Error(codes.InvalidArgument, "invalid target"), 2},
{"precondition", status.Error(codes.FailedPrecondition, "target not ready"), 1},
{"unknown", status.Error(codes.Unavailable, "answer lost"), 3},
{"unsent", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection unavailable")), 3},
} {
t.Run(row.name, func(t *testing.T) {
withFailoverRuntime(t, &fakeFailoverRuntime{err: row.err})
var out, diag bytes.Buffer
if exit := run(failoverArgs(), &out, &diag); exit != row.exit {
t.Fatalf("exit=%d want=%d out=%s diag=%s", exit, row.exit, out.String(), diag.String())
}
})
}
}
+1 -1
View File
@@ -2340,7 +2340,7 @@ func usage(w io.Writer) {
fmt.Fprintln(w, " sw-block ops chunk snapshots|snapshot-delete --volume <id> [--name <name>] --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
fmt.Fprintln(w, " sw-block ops chunk show --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
fmt.Fprintln(w, " sw-block ops chunk verify --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks] [--depth meta|bindings|data] [--orphans] [--timeout <d>]")
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 completed findings; incomplete: 1 operational/unknown, 2 usage/server arguments, 4 unproven readout, 5 auth, 75 unsent/retryable remote, 78 local config; --depth data needs --timeout)")
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)")
fmt.Fprintln(w, " sw-block ops volume resolve --master <addr> [--timeout 10s] <name> (prints the master layout id)")
fmt.Fprintln(w, " sw-block ops volume-unheld --path <volume-file> (exit 0: no process on this host holds it; local filesystems only)")
fmt.Fprintln(w, " sw-block ops failover --master <addr> --volume <id> --target <replica> --target-data <addr> --target-ctrl <addr> --expect-current <replica>@<epoch> --confirm-old-node-off <volume>")
+31 -130
View File
@@ -18,7 +18,6 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// sw-block mini starts the single-host configuration in one command, after
@@ -84,9 +83,6 @@ type miniConfig struct {
// Explicit names the flags given on the command line (fs.Visit); a
// --reuse refuses one that differs from the recorded run.
Explicit map[string]bool
// Self and WeedPath are the absolute paths of this sw-block and of the
// weed it runs, for the commands mini prints; empty in unit tests.
Self, WeedPath string
}
// miniRecord is what a fresh start records in <dir>/mini.json and --reuse
@@ -102,23 +98,6 @@ type miniRecord struct {
const miniRecordFile = "mini.json"
// Make an executable path absolute without collapsing symlink/.. components.
func miniExecutablePath(path string) (string, error) {
if filepath.IsAbs(path) {
return path, nil
}
volume := filepath.VolumeName(path)
base, err := filepath.Abs(volume + ".")
if err != nil {
return "", err
}
relative := strings.TrimPrefix(path, volume)
if len(relative) > 0 && os.IsPathSeparator(relative[0]) {
return filepath.VolumeName(base) + relative, nil
}
return base + string(os.PathSeparator) + relative, nil
}
func writeMiniRecord(dir string, r miniRecord) error {
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
@@ -139,20 +118,6 @@ func reuseMiniRecord(c *miniConfig, weedFound string) (string, error) {
if err := json.Unmarshal(b, &r); err != nil {
return "", fmt.Errorf("--reuse: %s/%s: %w", c.Dir, miniRecordFile, err)
}
if r.Weed != "" {
abs, err := miniExecutablePath(r.Weed)
if err != nil {
return "", fmt.Errorf("--reuse: resolve weed path: %w", err)
}
r.Weed = abs
}
if c.Weed != r.Weed && c.Weed != "" && r.Weed != "" {
now, errNow := os.Stat(c.Weed)
then, errThen := os.Stat(r.Weed)
if errNow == nil && errThen == nil && os.SameFile(now, then) {
c.Weed = r.Weed
}
}
differs := func(flag string, now, then any) error {
if c.Explicit[flag] && fmt.Sprint(now) != fmt.Sprint(then) {
return fmt.Errorf("--reuse: --%s %v differs from this dir's run (%v); drop it to reuse the run as recorded", flag, now, then)
@@ -221,16 +186,9 @@ func miniMasterArgs(c miniConfig, chunk bool) []string {
}
// miniVolumeArgs is blockvolume as swb_start runs it, plus, with a chunk
// store, the walstore-chunk settings and the volume's layout id. Its volume
// lock is under the run's dir, so mini needs no root and no tmpfiles.d entry
// (a trial override, which blockvolume refuses under systemd); with a chunk
// store it takes no scheduled snapshot (mini prints how to take one).
// store, the walstore-chunk settings and the volume's layout id.
func miniVolumeArgs(c miniConfig, chunk bool, layoutID string) []string {
a := append(miniVolumeSpec(c, chunk, layoutID).args(), "--volume-lock-dir-test-only", filepath.Join(c.Dir, "locks"))
if chunk {
a = append(a, "--chunk-snapshot-schedule", "off")
}
return a
return miniVolumeSpec(c, chunk, layoutID).args()
}
// miniVolumeSpec is mini's v1: the same settings volume start writes for a
@@ -310,25 +268,13 @@ type miniRun struct {
// start prints the command, then starts it with its output in <dir>/<name>.log.
func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) {
words := []string{shQuote(bin)}
for _, a := range args {
words = append(words, shQuote(a))
}
fmt.Fprintf(r.out, "+ %s\n", strings.Join(words, " "))
fmt.Fprintf(r.out, "+ %s %s\n", bin, strings.Join(args, " "))
lf, err := os.Create(filepath.Join(r.cfg.Dir, name+".log"))
if err != nil {
return nil, err
}
cmd := exec.Command(bin, args...)
cmd.Stdout, cmd.Stderr, cmd.Stdin = lf, lf, nil
cmd.Env = []string{}
// mini's children are not systemd units even when mini runs under one;
// blockvolume refuses mini's lock directory while INVOCATION_ID is set.
for _, kv := range os.Environ() {
if !strings.HasPrefix(kv, "INVOCATION_ID=") {
cmd.Env = append(cmd.Env, kv)
}
}
if err := cmd.Start(); err != nil {
lf.Close()
return nil, fmt.Errorf("start %s: %w", name, err)
@@ -346,7 +292,6 @@ func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) {
// ready waits until every port listens, while c is alive, bounded.
func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
deadline := time.Now().Add(miniStartWait)
var lastErr error
for {
if d := r.dead(); d != nil {
return fmt.Errorf("%s exited during startup: %v (see %s.log)", d.name, d.err, d.name)
@@ -355,7 +300,6 @@ func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
for _, p := range ports {
conn, err := net.DialTimeout("tcp", loopback(p), 200*time.Millisecond)
if err != nil {
lastErr = answer.Record(answer.Unsent, err) // TCP probe writes no application request
up = false
break
}
@@ -365,40 +309,16 @@ func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log): %w", c.name, miniStartWait, ports, c.name, answer.Present(lastErr, answer.Ops))
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log)", c.name, miniStartWait, ports, c.name)
}
select {
case <-ctx.Done():
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
return ctx.Err()
case <-time.After(250 * time.Millisecond):
}
}
}
// resolveLayoutID looks up volume's layout id through blockmaster,
// retrying while blockmaster registers it, bounded by miniResolveWait.
func (r *miniRun) resolveLayoutID(ctx context.Context, master, volume string) (string, error) {
deadline := time.Now().Add(miniResolveWait)
for {
rctx, rcancel := context.WithTimeout(ctx, 5*time.Second)
id, err := resolveVolumeID(rctx, master, volume)
rcancel()
if err == nil {
return id.String(), nil
}
if d := r.dead(); d != nil {
return "", fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, volume, d.err)
}
if ctx.Err() != nil || time.Now().After(deadline) {
return "", fmt.Errorf("resolve %s's layout id: %v", volume, err)
}
select {
case <-ctx.Done():
case <-time.After(time.Second):
}
}
}
// dead is the first child that has exited, if any.
func (r *miniRun) dead() *miniChild {
for _, c := range r.children {
@@ -491,26 +411,10 @@ func runMini(args []string, stdout, stderr io.Writer) int {
func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, error) {
weed := cfg.Weed
if weed == "" {
var err error
if weed, err = exec.LookPath("weed"); errors.Is(err, exec.ErrDot) {
if !cfg.Reuse {
return ops.VolumeStatusExitInvalid, fmt.Errorf("weed on PATH is in the current directory (%v); pass --weed %s to use it", err, shQuote("./"+weed))
}
weed = ""
}
weed, _ = exec.LookPath("weed")
} else if st, err := os.Stat(weed); err != nil || st.IsDir() {
return ops.VolumeStatusExitInvalid, fmt.Errorf("--weed %s not found", weed)
}
if weed != "" {
abs, err := miniExecutablePath(weed)
if err != nil {
return ops.VolumeStatusExitInvalid, fmt.Errorf("resolve weed path: %w", err)
}
weed = abs
if cfg.Weed != "" {
cfg.Weed = abs
}
}
// A reuse takes the recorded run (its binaries included) before any
// lookup; a fresh start finds the binaries next to sw-block by default.
if cfg.Reuse {
@@ -578,11 +482,7 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
return 1, err
}
}
if exe, err := os.Executable(); err == nil {
cfg.Self = exe
}
cfg.WeedPath = weed
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol"), filepath.Join(cfg.Dir, "locks")} {
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol")} {
if err := os.MkdirAll(d, 0o755); err != nil {
return 1, err
}
@@ -591,8 +491,6 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
defer r.stop()
fail := func(err error) (int, error) {
r.tail(20)
r.stop()
fmt.Fprintf(stderr, "sw-block mini: not started; logs in %s/*.log. After fixing the cause, start again on it with\n %s\nor remove %s and start fresh.\n", shQuote(cfg.Dir), miniResume(cfg), shQuote(cfg.Dir))
return 1, err
}
if chunk {
@@ -621,9 +519,26 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
}
layoutID := ""
if chunk {
fmt.Fprintf(stdout, "+ %s ops volume resolve --master %s %s\n", miniSelf(cfg), loopback(cfg.Ports.Master), miniVolume)
if layoutID, err = r.resolveLayoutID(ctx, loopback(cfg.Ports.Master), miniVolume); err != nil {
return fail(err)
fmt.Fprintf(stdout, "+ sw-block ops volume resolve --master %s %s\n", loopback(cfg.Ports.Master), miniVolume)
deadline := time.Now().Add(miniResolveWait)
for {
rctx, rcancel := context.WithTimeout(ctx, 5*time.Second)
id, err := resolveVolumeID(rctx, loopback(cfg.Ports.Master), miniVolume)
rcancel()
if err == nil {
layoutID = id.String()
break
}
if d := r.dead(); d != nil {
return fail(fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, miniVolume, d.err))
}
if ctx.Err() != nil || time.Now().After(deadline) {
return fail(fmt.Errorf("resolve %s's layout id: %v", miniVolume, err))
}
select {
case <-ctx.Done():
case <-time.After(time.Second):
}
}
}
vc, err := r.start("blockvolume", volume, miniVolumeArgs(cfg, chunk, layoutID))
@@ -683,18 +598,9 @@ func shQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// miniSelf is how a printed command names this sw-block: its absolute path
// when known, so the command runs from any directory.
func miniSelf(c miniConfig) string {
if c.Self == "" {
return "sw-block"
}
return shQuote(c.Self)
}
// miniResume is the command that starts the recorded run in c.Dir again.
func miniResume(c miniConfig) string {
return miniSelf(c) + " mini --dir " + shQuote(c.Dir) + " --reuse"
return "sw-block mini --dir " + shQuote(c.Dir) + " --reuse"
}
// miniNextSteps prints what to run next; mini runs none of it.
@@ -710,14 +616,9 @@ func miniNextSteps(w io.Writer, c miniConfig, chunk bool) {
return
}
cmds := miniCommands(c, chunk)
self := miniSelf(c)
fmt.Fprintf(w, "\nCheck the volume:\n %s %s\n %s %s\n", self, strings.Join(cmds[0], " "), self, strings.Join(cmds[1], " "))
fmt.Fprintf(w, "\nSnapshot (mini takes no scheduled snapshot):\n %s %s\n", self, strings.Join(cmds[2], " "))
weed := "weed"
if c.WeedPath != "" {
weed = shQuote(c.WeedPath)
}
fmt.Fprintf(w, "\nSeaweedFS itself: %s shell -master=%s\n", weed, loopback(c.Ports.WeedMaster))
fmt.Fprintf(w, "\nCheck the volume:\n sw-block %s\n sw-block %s\n", strings.Join(cmds[0], " "), strings.Join(cmds[1], " "))
fmt.Fprintf(w, "\nSnapshot:\n sw-block %s\n", strings.Join(cmds[2], " "))
fmt.Fprintf(w, "\nSeaweedFS itself: weed shell -master=%s\n", loopback(c.Ports.WeedMaster))
}
// miniBeforeStop reminds the user, before the target goes away, to have
+4 -142
View File
@@ -3,7 +3,6 @@ package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
@@ -58,9 +57,6 @@ func fakeMiniChild(mode string) int {
term := make(chan os.Signal, 1)
signal.Notify(term, syscall.SIGTERM)
if mode == "die-"+name {
if marker := os.Getenv("SWB_MINI_FAKE_RAN"); marker != "" {
_ = os.WriteFile(marker, []byte(name), 0o644)
}
time.Sleep(500 * time.Millisecond)
return 9
}
@@ -149,9 +145,7 @@ func TestMiniWalstoreFlagsAreThePage(t *testing.T) {
}
}
for f := range got {
// mini keeps the volume lock under --dir, so it needs no root
// (the page's unit uses the host lock directory).
if _, ok := page[f]; !ok && f != "--volume-lock-dir-test-only" {
if _, ok := page[f]; !ok {
t.Errorf("%s: mini passes %s; the page's swb_start does not", c.binary, f)
}
}
@@ -334,7 +328,7 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
}
})
waitOutput(t, out, "sw-block mini: running")
for _, want := range []string{"+ " + shQuote(filepath.Join(c.Bin, "blockmaster")) + " ", "+ " + shQuote(filepath.Join(c.Bin, "blockvolume")) + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1",
for _, want := range []string{"+ " + filepath.Join(c.Bin, "blockmaster") + " ", "+ " + filepath.Join(c.Bin, "blockvolume") + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1",
"sw-block mini: no chunk store: snapshots unavailable", "trial setup: one host, loopback, no authentication"} {
if !strings.Contains(out.String(), want) {
t.Fatalf("output lacks %q:\n%s", want, out.String())
@@ -350,12 +344,7 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
case <-time.After(30 * time.Second):
t.Fatal("mini did not stop")
}
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
resume := miniResume(miniConfig{Dir: c.Dir, Self: self})
for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + resume + "\n"} {
for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + miniResume(c) + "\n"} {
if !strings.Contains(out.String(), want) {
t.Fatalf("at stop, output lacks %q:\n%s", want, out.String())
}
@@ -453,8 +442,7 @@ func wantChunkCommands(dir, id string) map[string][]string {
"--data-addr", "127.0.0.1:9201", "--ctrl-addr", "127.0.0.1:9202", "--status-addr", "127.0.0.1:9203",
"--durable-root", filepath.Join(dir, "vol"), "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096",
"--chunk-filer", "127.0.0.1:18888", "--chunk-path", "/swblock/chunks", "--chunk-control-endpoint", "--workspace-lease", "--layout-id", id,
"--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1",
"--volume-lock-dir-test-only", filepath.Join(dir, "locks"), "--chunk-snapshot-schedule", "off"},
"--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"},
}
}
@@ -589,52 +577,6 @@ func TestMiniWeedDyingDuringStartupStopsTheRest(t *testing.T) {
}
}
func TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("signals and listening children: Linux")
}
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
ran := filepath.Join(t.TempDir(), "ran")
t.Setenv("SWB_MINI_FAKE_RAN", ran)
bin := fakeBin(t)
abs := filepath.Join(bin, "weed")
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
rel, err := filepath.Rel(cwd, abs)
if err != nil {
t.Fatal(err)
}
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: rel, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
out := &syncBuf{}
code, err := mini(ctx, c, out, io.Discard)
if code == 0 || err == nil {
t.Fatalf("fixture must reach the dying weed: code=%d err=%v", code, err)
}
b, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
if err != nil {
t.Fatal(err)
}
var record miniRecord
if err := json.Unmarshal(b, &record); err != nil {
t.Fatal(err)
}
selected, selectedErr := os.Stat(abs)
recorded, recordedErr := os.Stat(record.Weed)
if selectedErr != nil || recordedErr != nil || !filepath.IsAbs(record.Weed) || !os.SameFile(selected, recorded) {
t.Errorf("record weed=%q changed selected executable %q", record.Weed, abs)
}
if !strings.Contains(out.String(), "+ "+shQuote(record.Weed)+" ") {
t.Errorf("relative weed command: %s", out.String())
}
if _, err := os.Stat(ran); err != nil {
t.Errorf("the selected weed did not run: %v", err)
}
}
// --reuse starts the recorded run again: its size, ports, mode (its weed)
// and NQN, whatever the defaults are; a flag that differs from the record
// is refused, and so are a recorded weed that is gone and a walstore run
@@ -858,83 +800,3 @@ func TestMiniPrintedResumeRunsOnASpacedDir(t *testing.T) {
t.Fatalf("control: the unquoted line reached the dir too (exit %d)", code)
}
}
// mini started from a systemd service's process tree (a CI runner unit, a
// terminal server) inherits INVOCATION_ID; blockvolume refuses the lock-dir
// override under it, so mini's children must start without it.
func TestMiniChildrenStartWithoutInvocationID(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix child environment and signals")
}
t.Setenv("INVOCATION_ID", "0123456789abcdef")
dir := t.TempDir()
r := &miniRun{cfg: miniConfig{Dir: dir}, out: io.Discard, log: io.Discard}
c, err := r.start("env", "/bin/sh", []string{"-c", `echo "id=${INVOCATION_ID-unset}"`})
if err != nil {
t.Fatal(err)
}
joined := false
stop := func() {
if joined {
return
}
_ = c.cmd.Process.Signal(syscall.SIGTERM)
select {
case <-c.done:
joined = true
return
case <-time.After(2 * time.Second):
}
_ = c.cmd.Process.Kill()
select {
case <-c.done:
joined = true
case <-time.After(2 * time.Second):
fmt.Fprintln(os.Stderr, "mini child did not join; stopping tests before directory cleanup")
os.Exit(86)
}
}
t.Cleanup(stop)
select {
case <-c.done:
joined = true
case <-time.After(2 * time.Second):
stop()
t.Fatal("mini environment child did not finish")
}
b, err := os.ReadFile(filepath.Join(dir, "env.log"))
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(string(b)); got != "id=unset" {
t.Fatalf("mini's child saw %q", got)
}
}
// An empty filtered environment must be explicit: nil would inherit again.
func TestMiniOnlyInvocationIDDoesNotLeak(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix environment child")
}
saved := os.Environ()
t.Cleanup(func() {
os.Clearenv()
for _, kv := range saved {
key, value, _ := strings.Cut(kv, "=")
_ = os.Setenv(key, value)
}
})
os.Clearenv()
TestMiniChildrenStartWithoutInvocationID(t)
}
// Assert the actual weed-hint call site, not only the quoting helper. This
// stays sensitive if formatting is correct but the hint stops calling it.
func TestMiniProductionWeedHintQuotesItsExecutable(t *testing.T) {
var out bytes.Buffer
miniNextSteps(&out, miniConfig{WeedPath: "/tmp/weed's tools/weed"}, true)
const want = `SeaweedFS itself: '/tmp/weed'\''s tools/weed' shell -master=`
if !strings.Contains(out.String(), want) {
t.Fatalf("production weed hint lacks %q:\n%s", want, out.String())
}
}
@@ -1,219 +0,0 @@
package main
import (
"context"
"encoding/json"
"io"
"net"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func TestMiniWeedSymlinkParentKeepsSelectedExecutable(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix symlink and child-process fixture")
}
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
bin := fakeBin(t)
root := t.TempDir()
for _, dir := range []string{"tools", "releases/v2"} {
if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil {
t.Fatal(err)
}
}
selected := filepath.Join(root, "releases", "weed")
if err := os.Symlink(filepath.Join(bin, "weed"), selected); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "tools", "weed"), []byte("wrong executable"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "releases", "v2"), filepath.Join(root, "tools", "current")); err != nil {
t.Fatal(err)
}
t.Chdir(root)
rel := "tools/current/../weed"
want, err := os.Stat(selected)
if err != nil {
t.Fatal(err)
}
check := func(t *testing.T, path string) {
t.Helper()
got, err := os.Stat(path)
if err != nil || !filepath.IsAbs(path) || !os.SameFile(want, got) {
t.Fatalf("selected executable changed: path=%q stat=%v", path, err)
}
}
t.Run("fresh", func(t *testing.T) {
ran := filepath.Join(t.TempDir(), "ran")
t.Setenv("SWB_MINI_FAKE_RAN", ran)
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: rel, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
out := &syncBuf{}
_, _ = mini(ctx, c, out, io.Discard)
data, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
if err != nil {
t.Fatalf("did not reach record publication: %v; %s", err, out.String())
}
var record miniRecord
if err := json.Unmarshal(data, &record); err != nil {
t.Fatal(err)
}
check(t, record.Weed)
if !strings.Contains(out.String(), "+ "+shQuote(record.Weed)+" ") {
t.Fatalf("selected executable was not launched: %s", out.String())
}
if _, err := os.Stat(ran); err != nil {
t.Fatalf("the selected weed did not run: %v", err)
}
})
t.Run("legacy", func(t *testing.T) {
dir := t.TempDir()
if err := writeMiniRecord(dir, miniRecord{Weed: rel, Bin: bin, SizeBytes: 1 << 20, NQN: "n"}); err != nil {
t.Fatal(err)
}
c := miniConfig{Dir: dir}
weed, err := reuseMiniRecord(&c, "")
if err != nil {
t.Fatal(err)
}
check(t, weed)
})
}
func TestMiniRefusesWeedFoundThroughDotInPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix PATH lookup")
}
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "weed"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(dir)
t.Setenv("PATH", ".")
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
code, err := mini(context.Background(), c, io.Discard, io.Discard)
if code == 0 || err == nil || !strings.Contains(err.Error(), "current directory") {
t.Fatalf("weed found only through . in PATH: code %d err %v; want a refusal", code, err)
}
if _, err := os.Stat(c.Dir); !os.IsNotExist(err) {
t.Fatalf("refused start created %s: %v", c.Dir, err)
}
}
func TestMiniReuseAcceptsSameWeedFromAnotherDirectory(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix paths")
}
root := t.TempDir()
for _, d := range []string{"a", "b", "bin"} {
if err := os.MkdirAll(filepath.Join(root, d), 0o755); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(root, "bin", "weed"), []byte("x"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "bin", "other"), []byte("x"), 0o755); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
recorded := filepath.Join(root, "a") + "/../bin/weed"
if err := writeMiniRecord(dir, miniRecord{Weed: recorded, Bin: t.TempDir(), SizeBytes: 1 << 20, NQN: "n"}); err != nil {
t.Fatal(err)
}
t.Chdir(filepath.Join(root, "b"))
weedNow := func(t *testing.T, rel string) (string, error) {
t.Helper()
abs, err := miniExecutablePath(rel)
if err != nil {
t.Fatal(err)
}
c := miniConfig{Dir: dir, Weed: abs, Explicit: map[string]bool{"weed": true}}
return reuseMiniRecord(&c, abs)
}
if weed, err := weedNow(t, "../bin/weed"); err != nil || weed != recorded {
t.Fatalf("same weed through another cwd: weed %q err %v; want the recorded %q", weed, err, recorded)
}
if _, err := weedNow(t, "../bin/other"); err == nil || !strings.Contains(err.Error(), "differs") {
t.Fatalf("a different executable: err %v; want a refusal", err)
}
}
func TestMiniStartTraceQuotesPathsWithSpaces(t *testing.T) {
dir := filepath.Join(t.TempDir(), "my tools")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
out := &syncBuf{}
r := &miniRun{cfg: miniConfig{Dir: dir}, out: out}
if _, err := r.start("weed", filepath.Join(dir, "absent"), []string{"mini", "-dir=" + dir}); err == nil {
t.Fatal("an absent executable started")
}
want := "+ " + shQuote(filepath.Join(dir, "absent")) + " mini " + shQuote("-dir="+dir) + "\n"
if got := out.String(); got != want || !strings.Contains(got, "'") {
t.Fatalf("start trace %q; want %q", got, want)
}
}
func TestMiniReuseIgnoresWeedFoundThroughDotInPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix PATH lookup")
}
bin := fakeBin(t)
cwd := t.TempDir()
if err := os.WriteFile(filepath.Join(cwd, "weed"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(cwd)
t.Setenv("PATH", ".")
for name, recorded := range map[string]string{"chunk": filepath.Join(bin, "weed"), "walstore": ""} {
t.Run(name, func(t *testing.T) {
dir := t.TempDir()
if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n", Bin: bin, Weed: recorded}); err != nil {
t.Fatal(err)
}
ports := freePorts(t)
l, err := net.Listen("tcp", loopback(ports.NVMe))
if err != nil {
t.Fatal(err)
}
defer l.Close()
c := miniConfig{Dir: dir, NQN: "n", SizeBytes: 1 << 20, Ports: ports, Reuse: true, Explicit: map[string]bool{}}
code, err := mini(context.Background(), c, io.Discard, io.Discard)
if err == nil || !strings.Contains(err.Error(), "in use") {
t.Fatalf("--reuse with ./weed only through . in PATH: code %d err %v; want the recorded run (then the busy port)", code, err)
}
})
}
}
// The refusal's hint is a pastable shell word: a relative PATH entry with a
// space ("my tools") prints its --weed path quoted, as mini's other printed
// commands are.
func TestMiniDotWeedHintQuotesAPathWithASpace(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix PATH lookup")
}
dir := t.TempDir()
tools := filepath.Join(dir, "my tools")
if err := os.MkdirAll(tools, 0o755); err != nil {
t.Fatal(err)
}
nl := string(rune(10))
if err := os.WriteFile(filepath.Join(tools, "weed"), []byte("#!/bin/sh"+nl+"exit 0"+nl), 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(dir)
t.Setenv("PATH", "my tools")
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
_, err := mini(context.Background(), c, io.Discard, io.Discard)
if err == nil || !strings.Contains(err.Error(), "pass --weed './my tools/weed' to use it") {
t.Fatalf("weed found through a relative PATH entry with a space: %v; want the quoted --weed hint", err)
}
}
@@ -1,75 +0,0 @@
package main
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestReviewInitialPostBodyFailurePreservesStatus(t *testing.T) {
oldBound, oldPause, oldMax := chunkRequestBound, chunkPauseStart, chunkPauseMax
chunkRequestBound, chunkPauseStart, chunkPauseMax = 2*time.Second, 20*time.Millisecond, 20*time.Millisecond
t.Cleanup(func() { chunkRequestBound, chunkPauseStart, chunkPauseMax = oldBound, oldPause, oldMax })
for _, row := range []struct {
status int
code string
exit int
}{
{403, "not_authorized", 5}, {401, "not_authorized", 5}, {400, "bad_request", 2},
{200, "outcome_unknown", 3}, {503, "outcome_unknown", 3},
} {
t.Run(fmt.Sprint(row.status), func(t *testing.T) {
var posts atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
fmt.Fprint(w, `{}`)
return
}
posts.Add(1)
w.Header().Set("Content-Length", "1000")
w.WriteHeader(row.status)
fmt.Fprint(w, `{`)
}))
defer srv.Close()
var out, diag bytes.Buffer
body := map[string]any{"volumeID": "v1", "requestID": "same-operation"}
var exit int
if row.status == 403 {
exit = chunkPostLoop("snapshot", srv.URL, "/chunk/snapshot", 4*time.Second, body, &out, &diag)
} else {
exit = chunkPost("snapshot", srv.URL, "/chunk/snapshot", time.Second, body, &out, &diag)
}
answer := chunkErrorOut(t, out.String())
if exit != row.exit || answer.Code != row.code || posts.Load() != 1 || (row.exit != 3 && answer.Retryable) {
t.Fatalf("HTTP%d: exit=%d answer=%+v posts=%d", row.status, exit, answer, posts.Load())
}
})
}
}
func TestReviewForceMovePreservesServerPolicyExit(t *testing.T) {
for _, row := range []struct {
code codes.Code
exit int
}{{codes.InvalidArgument, 2}, {codes.FailedPrecondition, 1}} {
t.Run(row.code.String(), func(t *testing.T) {
f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) {
return nil, status.Error(row.code, "server refuses this move")
}}
addr, _ := startFakeWorkspace(t, f)
exit, out, diag := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--json"))
if exit != row.exit || !strings.Contains(out, `"admitted":false`) || !strings.Contains(out, `"code":"`+row.code.String()+`"`) || f.n("MoveWorkspace") != 1 || !strings.Contains(diag, "refused by the master") {
t.Fatalf("exit=%d out=%s diag=%s moves=%d", exit, out, diag, f.n("MoveWorkspace"))
}
})
}
}
@@ -1,187 +0,0 @@
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestReviewCompleteBodyKeepsStatusAndAdmission(t *testing.T) {
for _, row := range []struct {
name string
status int
body string
exit int
code string
}{
{"malformed-forbidden", 403, "{", 5, "not_authorized"},
{"malformed-arguments", 400, "{", 2, "bad_request"},
{"malformed-missing", 404, "{", 1, "not_found"},
{"malformed-precondition", 409, "{", 1, "not_admitted"},
{"malformed-rate-limit", 429, "{", 3, "outcome_unknown"},
{"malformed-server", 500, "{", 3, "outcome_unknown"},
{"malformed-gateway", 502, "{", 3, "outcome_unknown"},
{"malformed-unavailable", 503, "{", 3, "outcome_unknown"},
{"malformed-gateway-timeout", 504, "{", 3, "outcome_unknown"},
{"empty-success", 204, "", 3, "outcome_unknown"},
{"malformed-redirect", 302, "{", 3, "outcome_unknown"},
{"oversized-forbidden", 403, "oversized", 5, "not_authorized"},
{"oversized-success", 200, "oversized", 3, "outcome_unknown"},
{"oversized-admission", 202, "oversized", 3, "outcome_unknown"},
} {
t.Run(row.name, func(t *testing.T) {
if row.body == "oversized" && testing.Short() {
t.Skip("64 MiB production body limit: run in native qualification")
}
var posts atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
posts.Add(1)
w.WriteHeader(row.status)
if row.body == "oversized" {
_, _ = io.CopyN(w, repeatResponseByte{}, chunkResponseLimit+1)
} else {
fmt.Fprint(w, row.body)
}
}))
defer srv.Close()
var out, diag bytes.Buffer
var admission snapshotCLIAdmission
exit := chunkPost("snapshot", srv.URL, "/chunk/snapshot", 3*time.Second, map[string]any{"requestID": "original"}, &out, &diag, &admission)
a := chunkErrorOut(t, out.String())
if exit != row.exit || a.Code != row.code || posts.Load() != 1 || (row.exit == 3 && !a.Retryable) {
t.Fatalf("exit=%d answer=%+v posts=%d stderr=%s", exit, a, posts.Load(), &diag)
}
if admission.Accepted {
t.Fatalf("unusable response was accepted: answer=%+v admission=%+v", a, admission)
}
if row.body == "oversized" {
want := fmt.Sprintf("HTTP %d response exceeds %d bytes; not relaying a truncated body", row.status, chunkResponseLimit)
if !strings.Contains(a.Message, want) {
t.Fatalf("oversized response was not observed: want diagnostic %q, answer=%+v stderr=%s", want, a, &diag)
}
}
})
}
}
type repeatResponseByte struct{}
func (repeatResponseByte) Read(p []byte) (int, error) {
for i := range p {
p[i] = 'x'
}
return len(p), nil
}
func TestReviewInvalidAdmissionKeepsOriginalRequest(t *testing.T) {
for _, row := range []struct{ name, body, location string }{
{"malformed", "{", "/operations/original"},
{"wrong-id", `{"operation_id":"other","state":"running"}`, "/operations/other"},
{"missing-location", `{"operation_id":"original","state":"running"}`, ""},
} {
t.Run(row.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", row.location)
w.WriteHeader(202)
fmt.Fprint(w, row.body)
}))
defer srv.Close()
var out, diag bytes.Buffer
var a snapshotCLIAdmission
exit := chunkPost("snapshot", srv.URL, "/chunk/snapshot", 3*time.Second, map[string]any{"requestID": "original"}, &out, &diag, &a)
got := chunkErrorOut(t, out.String())
if exit != 3 || got.Code != "outcome_unknown" || !strings.Contains(got.Message, "original") || a.Accepted {
t.Fatalf("exit=%d answer=%+v accepted=%v", exit, got, a.Accepted)
}
})
}
}
func TestReviewUnsafeSnapshotLocationKeepsOriginalUnknown(t *testing.T) {
var foreignGets atomic.Int32
foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
foreignGets.Add(1)
fmt.Fprint(w, `{"operation_id":"original","state":"succeeded","result":{"ok":true}}`)
}))
defer foreign.Close()
for _, location := range []string{"%zz", foreign.URL + "/operations/original"} {
t.Run(location, func(t *testing.T) {
var posts, gets atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
gets.Add(1)
http.Error(w, "unexpected poll", 500)
return
}
posts.Add(1)
w.Header().Set("Location", location)
w.WriteHeader(202)
fmt.Fprint(w, `{"operation_id":"original","state":"running"}`)
}))
defer srv.Close()
var out, diag bytes.Buffer
exit := chunkObserveSnapshot(srv.URL, 3*time.Second, map[string]any{"requestID": "original"}, false, &out, &diag)
got := chunkErrorOut(t, out.String())
if exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "original") || !strings.Contains(got.Message, "--request-id") || posts.Load() != 1 || gets.Load() != 0 || foreignGets.Load() != 0 {
t.Fatalf("exit=%d answer=%+v posts=%d polls=%d foreign=%d stderr=%s", exit, got, posts.Load(), gets.Load(), foreignGets.Load(), &diag)
}
})
}
}
// An observed success without a usable result does not settle the original operation.
func TestReviewAdmittedMissingResultKeepsUnknown(t *testing.T) {
for _, mode := range []string{"detach", "snapshot-admission", "snapshot-poll"} {
t.Run(mode, func(t *testing.T) {
var posts, gets atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
posts.Add(1)
} else {
gets.Add(1)
}
if mode == "detach" {
fmt.Fprint(w, `{"apiVersion":1,"volumeID":"vol-a","headGen":0}`)
return
}
w.Header().Set("Location", "/operations/original")
if r.Method == http.MethodPost {
w.WriteHeader(202)
if mode == "snapshot-poll" {
fmt.Fprint(w, `{"operation_id":"original","state":"running"}`)
return
}
}
fmt.Fprint(w, `{"operation_id":"original","state":"succeeded"}`)
}))
defer srv.Close()
var out, diag bytes.Buffer
var exit int
if mode == "detach" {
exit = chunkPlainDetachPost(srv.URL, "vol-a", time.Second, time.Time{}, map[string]any{"volumeID": "vol-a"}, &out, &diag)
} else {
exit = chunkObserveSnapshot(srv.URL, time.Second, map[string]any{"requestID": "original"}, false, &out, &diag)
}
got := chunkErrorOut(t, out.String())
if exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || posts.Load() != 1 {
t.Fatalf("exit=%d answer=%+v posts=%d polls=%d stderr=%s", exit, got, posts.Load(), gets.Load(), &diag)
}
if mode != "detach" && (!strings.Contains(got.Message, "original") || !strings.Contains(got.Message, "--request-id")) {
t.Fatalf("original recovery lost: %+v", got)
}
wantGets := int32(0)
if mode == "snapshot-poll" {
wantGets = 1
}
if gets.Load() != wantGets {
t.Fatalf("polls=%d want=%d", gets.Load(), wantGets)
}
})
}
}
+2 -4
View File
@@ -13,7 +13,6 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
type inspectionShell struct {
@@ -208,9 +207,8 @@ func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int {
defer cancel()
cluster, err := readMasterClusterEvidence(ctx, s.master)
if err != nil {
policy, detail := operatorAnswer(err, answer.Shell)
fmt.Fprintf(stderr, "%s: %v\n", name, detail)
return policy.Exit
fmt.Fprintf(stderr, "%s: %v\n", name, err)
return 1
}
var value any = cluster
text := ops.RenderClusterEvidenceText(cluster)
+1 -7
View File
@@ -14,7 +14,6 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
@@ -192,11 +191,6 @@ func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObse
}
o.filerErr = err
}
o.masterErr, o.lifecycleErr, o.filerErr = inspectionError(o.masterErr), inspectionError(o.lifecycleErr), inspectionError(o.filerErr)
for i := range o.volumes {
v := &o.volumes[i]
v.leaseErr, v.holderErr, v.durableErr = inspectionError(v.leaseErr), inspectionError(v.holderErr), inspectionError(v.durableErr)
}
rows := make([]inspectionResult, 0, len(inspectionChecks))
code := 0
for _, c := range inspectionChecks {
@@ -303,7 +297,7 @@ func (s inspectionShell) readHolderAt(ctx context.Context, addr, path, volume st
return err
}
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("status redirects are refused") }}
resp, err := answer.DoHTTP(client, req, answer.Unsent)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"net/url"
@@ -45,16 +44,9 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
}
return 0
}
// Until a handle is validated, retain only the original admission identity.
// An unsafe Location is never a recovery address and must not be followed.
recovery := "retry with --request-id " + a.Answer.ID + " against the original status address"
unobserved := func(err error) int {
err = fmt.Errorf("snapshot operation %s: %s: %w", a.Answer.ID, recovery, err)
return chunkResult("snapshot", nil, answer.Rekind(answer.Record(answer.PossiblyAdmitted, err), answer.Connection), stdout, stderr)
}
if a.Answer.State == "succeeded" {
if len(a.Answer.Result) == 0 || !json.Valid(a.Answer.Result) {
return unobserved(fmt.Errorf("operation has no result"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
}
if err := writeAll(stdout, a.Answer.Result); err != nil {
return chunkExitFailed
@@ -67,19 +59,16 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
}
origin, err := url.Parse(base)
if err != nil {
return unobserved(fmt.Errorf("invalid original operation origin"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeBadRequestCLI, err.Error(), false)
}
loc, err := url.Parse(a.Location)
if err != nil {
return unobserved(fmt.Errorf("invalid operation handle URI"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid operation handle URI", false)
}
handle := origin.ResolveReference(loc)
if handle.Scheme != origin.Scheme || handle.Host != origin.Host || handle.User != nil {
return unobserved(fmt.Errorf("operation handle changed origin"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation handle changed origin", false)
}
recovery = "status at " + handle.String() + "; " + recovery
// A failed handle read says nothing definite about the admitted POST.
// Keep its identity and recovery contract even for a definite GET refusal.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
for {
@@ -87,28 +76,32 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
req, err := http.NewRequestWithContext(callCtx, http.MethodGet, handle.String(), nil)
if err != nil {
cancel()
return unobserved(fmt.Errorf("invalid operation status request"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
}
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
resp, err := chunkHTTPClient.Do(req)
var current snapshotCLIAnswer
if err == nil {
err = json.NewDecoder(io.LimitReader(resp.Body, chunkResponseLimit+1)).Decode(&current)
_ = resp.Body.Close()
if resp.StatusCode != 200 {
err = answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("operation status HTTP %d", resp.StatusCode))
err = fmt.Errorf("operation status HTTP %d", resp.StatusCode)
}
}
cancel()
if ctx.Err() != nil {
fmt.Fprintf(stderr, "snapshot observation interrupted; resume with --request-id %s\n", a.Answer.ID)
return chunkExitFailed
}
if err != nil {
return unobserved(err)
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
}
if current.ID != a.Answer.ID {
return unobserved(fmt.Errorf("operation status changed identity"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation status changed identity", false)
}
switch current.State {
case "succeeded":
if len(current.Result) == 0 || !json.Valid(current.Result) {
return unobserved(fmt.Errorf("operation has no result"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
}
if err := writeAll(stdout, current.Result); err != nil {
return chunkExitFailed
@@ -124,7 +117,7 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, "no_progress", "snapshot stalled; repeat with --request-id "+a.Answer.ID, true)
case "accepted", "running":
default:
return unobserved(fmt.Errorf("unknown operation state"))
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "unknown operation state", false)
}
timer := time.NewTimer(100 * time.Millisecond)
select {
@@ -132,7 +125,7 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
if !timer.Stop() {
<-timer.C
}
return unobserved(ctx.Err())
return chunkExitFailed
case <-timer.C:
}
}
@@ -4,9 +4,7 @@ package main
import (
"context"
"crypto/x509"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
@@ -24,37 +22,11 @@ func TestSnapshotOperationCLIObserverProcess(t *testing.T) {
if os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_CHILD") != "1" {
return
}
if os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_TLS") == "1" {
chunkHTTPClient = &http.Client{Transport: interruptedSnapshotTLS{base: http.DefaultTransport}}
}
args := []string{"ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_URL"), "--name", "s1", "--timeout", "5s"}
os.Exit(run(args, os.Stdout, os.Stderr))
}
func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
testSnapshotOperationCLIInterruptThenResume(t, false)
}
func TestSnapshotOperationCLIInterruptedTLSKeepsUnknownAndHandle(t *testing.T) {
testSnapshotOperationCLIInterruptThenResume(t, true)
}
type interruptedSnapshotTLS struct{ base http.RoundTripper }
func (p interruptedSnapshotTLS) RoundTrip(r *http.Request) (*http.Response, error) {
response, err := p.base.RoundTrip(r)
if r.Method != http.MethodGet {
return response, err
}
if response != nil {
_ = response.Body.Close()
}
// The real GET has entered the server and is held until the parent's
// SIGINT cancels its context. Deliver the certificate failure afterwards.
return nil, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
}
func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool) {
var mu sync.Mutex
var ids []string
var pollIDs []string
@@ -116,9 +88,6 @@ func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotOperationCLIObserverProcess$", "-test.timeout=7s")
cmd.Env = append(os.Environ(), "SW_BLOCK_SNAPSHOT_OBSERVER_CHILD=1", "SW_BLOCK_SNAPSHOT_OBSERVER_URL="+srv.URL)
if tlsFailure {
cmd.Env = append(cmd.Env, "SW_BLOCK_SNAPSHOT_OBSERVER_TLS=1")
}
cmd.Stdout, cmd.Stderr = out, errs
if err := cmd.Start(); err != nil {
t.Fatal(err)
@@ -144,9 +113,8 @@ func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool)
if err := cmd.Process.Signal(os.Interrupt); err != nil {
t.Fatal(err)
}
var observerErr error
select {
case observerErr = <-done:
case <-done:
joined = true
case <-ctx.Done():
t.Fatal("interrupt did not stop the observer")
@@ -160,18 +128,6 @@ func testSnapshotOperationCLIInterruptThenResume(t *testing.T, tlsFailure bool)
t.Fatalf("one resumable printed ID required: %s", b)
}
id := printed[0][1]
var exited *exec.ExitError
if !errors.As(observerErr, &exited) || exited.ExitCode() != 3 {
t.Fatalf("admitted interruption must remain unknown: exit=%v stderr=%s", observerErr, b)
}
result, err := os.ReadFile(out.Name())
if err != nil {
t.Fatal(err)
}
answer := chunkErrorOut(t, string(result))
if answer.Code != "outcome_unknown" || !answer.Retryable || !strings.Contains(answer.Message, id) || !strings.Contains(answer.Message, srv.URL+"/operations/"+id) {
t.Fatalf("admitted identity lost: %+v stderr=%s", answer, b)
}
code, stdout, stderr := runChunkWithin(t, 4*time.Second, "snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", id, "--timeout", "2s")
mu.Lock()
defer mu.Unlock()
@@ -1,197 +0,0 @@
package main
import (
"bytes"
"context"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
type snapshotPollFailure struct {
base http.RoundTripper
mode string
polls *atomic.Int32
invalid *atomic.Bool
}
func snapshotPollRequestError(r *http.Request) error {
if r.Method == http.MethodPost {
if r.URL.Path != "/chunk/snapshot" {
return fmt.Errorf("wrong POST path: %s", r.URL.Path)
}
var body struct {
ID string `json:"requestID"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
return err
}
if body.ID != "original" {
return fmt.Errorf("changed replay ID: %s", body.ID)
}
return nil
}
if r.Method != http.MethodGet || r.URL.RequestURI() != "/operations/original" {
return fmt.Errorf("wrong handle: %s %s", r.Method, r.URL.RequestURI())
}
return nil
}
func (p snapshotPollFailure) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Method != http.MethodGet {
return p.base.RoundTrip(r)
}
p.polls.Add(1)
if snapshotPollRequestError(r) != nil {
p.invalid.Store(true)
}
if p.mode == "tls" {
return nil, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
}
if p.mode == "body-tls" {
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: pollCertificateBody{}, Request: r}, nil
}
return p.base.RoundTrip(r)
}
type pollCertificateBody struct{}
func (pollCertificateBody) Read([]byte) (int, error) {
return 0, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
}
func (pollCertificateBody) Close() error { return nil }
// Each observer runs in an owned child: a polling regression cannot prevent
// the parent from joining it, nor restore a client while it is still in use.
func TestSnapshotAdmittedPollFailureKeepsOriginalOperation(t *testing.T) {
for _, mode := range []string{"401", "403", "404", "409", "412", "428", "503", "tls", "body-tls", "success", "refused", "wrong-id"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotAdmittedPollChild$", "-test.count=1")
cmd.Env = append(os.Environ(), "SWBLOCK_POLL_CONTROL="+mode)
cmd.WaitDelay = time.Second
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bounded observer: %v (context %v): %s", err, ctx.Err(), output)
}
})
}
}
func TestSnapshotAdmittedPollChild(t *testing.T) {
mode := os.Getenv("SWBLOCK_POLL_CONTROL")
if mode == "" {
t.Skip("owned child only")
}
var posts, polls atomic.Int32
var invalid atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := snapshotPollRequestError(r); err != nil {
invalid.Store(true)
http.Error(w, err.Error(), 400)
return
}
if r.Method == http.MethodPost {
posts.Add(1)
w.Header().Set("Location", "/operations/original")
w.WriteHeader(202)
_ = json.NewEncoder(w).Encode(map[string]string{"operation_id": "original", "state": "running"})
return
}
if mode == "success" || mode == "refused" || mode == "wrong-id" || mode == "loop" {
id, state := "original", "succeeded"
if mode == "wrong-id" {
id = "changed"
}
if mode == "loop" {
state = "running"
fmt.Fprintln(os.Stderr, "poll-loop-entered")
}
if mode == "refused" {
state = "refused"
}
_ = json.NewEncoder(w).Encode(map[string]any{"operation_id": id, "state": state, "result": map[string]bool{"ok": true}, "code": "not_admitted", "message": "definite operation refusal"})
return
}
code, err := strconv.Atoi(mode)
if err != nil {
http.Error(w, "unexpected mode", 500)
return
}
http.Error(w, "status read refused", code)
}))
defer server.Close()
previous := chunkHTTPClient
defer func() { chunkHTTPClient = previous }()
chunkHTTPClient = &http.Client{Transport: snapshotPollFailure{base: http.DefaultTransport, mode: mode, polls: &polls, invalid: &invalid}}
var out, diag bytes.Buffer
exit := chunkObserveSnapshot(server.URL, time.Second, map[string]any{"requestID": "original"}, false, &out, &diag)
if posts.Load() != 1 || polls.Load() != 1 || invalid.Load() {
t.Fatalf("wire proof: posts=%d polls=%d invalid=%v", posts.Load(), polls.Load(), invalid.Load())
}
if mode == "success" {
if exit != 0 || !strings.Contains(out.String(), `"ok":true`) {
t.Fatalf("terminal success: exit=%d out=%s", exit, out.String())
}
return
}
body := chunkErrorOut(t, out.String())
if mode == "refused" {
if exit != 1 || body.Code != "not_admitted" || body.Retryable {
t.Fatalf("terminal refusal: exit=%d answer=%+v", exit, body)
}
return
}
if exit != 3 || body.Code != "outcome_unknown" || !body.Retryable || !strings.Contains(body.Message, "replay key") || !strings.Contains(body.Message, "original") || posts.Load() != 1 || polls.Load() != 1 || invalid.Load() {
t.Fatalf("exit=%d answer=%+v posts=%d polls=%d invalid=%v", exit, body, posts.Load(), polls.Load(), invalid.Load())
}
}
func TestSnapshotPollWireControlRejectsChangedIdentityAndRoute(t *testing.T) {
for _, row := range []struct{ method, path, body string }{
{"POST", "/wrong", `{"requestID":"original"}`},
{"POST", "/chunk/snapshot", `{"requestID":"changed"}`},
{"GET", "/operations/changed", ""},
} {
req, _ := http.NewRequest(row.method, "http://example"+row.path, strings.NewReader(row.body))
if err := snapshotPollRequestError(req); err == nil {
t.Fatalf("wire control accepted %+v", row)
}
}
for _, row := range []struct{ method, path, body string }{
{"POST", "/chunk/snapshot", `{"requestID":"original"}`},
{"GET", "/operations/original", ""},
} {
req, _ := http.NewRequest(row.method, "http://example"+row.path, strings.NewReader(row.body))
if err := snapshotPollRequestError(req); err != nil {
t.Fatal(err)
}
}
}
var _ io.ReadCloser = pollCertificateBody{}
// Negative control: an observer that never reaches a terminal state is killed
// and joined before any parent-side fixtures can be reclaimed.
func TestSnapshotPollWatchdogJoinsAnUnfinishedObserver(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotAdmittedPollChild$", "-test.count=1")
cmd.Env = append(os.Environ(), "SWBLOCK_POLL_CONTROL=loop")
cmd.WaitDelay = time.Second
output, err := cmd.CombinedOutput()
if ctx.Err() != context.DeadlineExceeded || err == nil || cmd.ProcessState == nil || !strings.Contains(string(output), "poll-loop-entered") {
t.Fatalf("watchdog did not terminate and join: ctx=%v err=%v state=%v output=%s", ctx.Err(), err, cmd.ProcessState, output)
}
}
@@ -1,52 +0,0 @@
package main
import (
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// A whole-job command has stable derived operation identities. Preserve its
// existing wire exit while obtaining its failure class and cure centrally.
func operatorAnswer(err error, contract answer.Contract) (answer.Policy, error) {
var presented *operatorFailure
if errors.As(err, &presented) && presented.contract == contract {
return presented.policy, err
}
observed := answer.EnsureEvidence(answer.PossiblyAdmitted, err)
if _, listed := answer.ErrorKind(observed); !listed {
// These callers have already checked a reply's identity/completeness
// or lost their workflow's observation; this is not a transport guess.
observed = answer.Rekind(observed, answer.Guard("outcome_unknown"))
}
policy, check := answer.PolicyOf(observed, contract)
if check != nil {
policy, _ = answer.Lookup(answer.Unsent, answer.Guard("internal"))
return policy, fmt.Errorf("%w; %v", err, check)
}
if policy.Code == "outcome_unknown" {
return policy, &operatorFailure{policy, contract, fmt.Errorf("the outcome is unknown (%w); %s", err, policy.Cure)}
}
return policy, &operatorFailure{policy, contract, fmt.Errorf("%s: %w; %s", policy.Code, err, policy.Cure)}
}
type operatorFailure struct {
policy answer.Policy
contract answer.Contract
err error
}
func (e *operatorFailure) Error() string { return e.err.Error() }
func (e *operatorFailure) Unwrap() error { return e.err }
func inspectionError(err error) error {
if err == nil {
return nil
}
if _, listed := answer.ErrorKind(err); !listed {
return err
} // explicit business finding, not a transport failure
_, detail := operatorAnswer(err, answer.Shell)
return detail
}
+38 -27
View File
@@ -19,8 +19,8 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -130,9 +130,8 @@ func volumeBackup(ctx context.Context, env verbEnv, o backupOpts, stdout, stderr
return refuse("snapshot", fmt.Sprintf("%s; a cut that timed out keeps what it uploaded; after correcting the refusal, run the same command (it resumes the same request and reuses completed uploads): %s", text, again))
}
if err != nil {
policy, detail := operatorAnswer(err, answer.VolumeJob)
fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", detail, again)
return policy.Exit
fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", err, again)
return 1
}
fmt.Fprintf(stdout, "sw-block volume backup: snapshot %s of %s: head generation %d, cut LSN %d, at %s\n",
shQuote(a.Name), o.Volume, *a.HeadGen, *a.CutLSN, time.Unix(0, *a.CreatedNs).UTC().Format(time.RFC3339))
@@ -164,13 +163,8 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
client := *env.HTTP
client.Timeout = timeout + 5*time.Second
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
unknown := func(why string, causes ...error) (snapshotAnswer, *snapshotRefusal, error) {
cause := error(errors.New(why))
if len(causes) == 1 {
cause = fmt.Errorf("%s: %w", why, causes[0])
}
_, detail := operatorAnswer(cause, answer.VolumeJob)
return snapshotAnswer{}, nil, detail
unknown := func(why string) (snapshotAnswer, *snapshotRefusal, error) {
return snapshotAnswer{}, nil, fmt.Errorf("the snapshot's outcome is unknown (%s)", why)
}
rctx, cancel := context.WithTimeout(ctx, timeout)
req, err := http.NewRequestWithContext(rctx, http.MethodPost, "http://"+status+"/chunk/snapshot", bytes.NewReader(body))
@@ -180,16 +174,16 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Prefer", "respond-async")
resp, err := answer.DoHTTP(&client, req, answer.Unsent)
resp, err := client.Do(req)
if err != nil {
cancel()
return unknown("snapshot admission answer not received", err)
return unknown(err.Error())
}
b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
resp.Body.Close()
cancel()
if err != nil {
return unknown("snapshot answer unreadable", err)
return unknown("answer unreadable: " + err.Error())
}
if resp.StatusCode == http.StatusAccepted {
var adm snapshotOperationIdentity
@@ -197,7 +191,7 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
return unknown("the admission answer does not identify this backup's operation")
}
if b, err = observeSnapshotOperation(ctx, env, client, status, adm, timeout); err != nil {
return unknown("snapshot observation failed", err)
return unknown(err.Error())
}
var op struct {
State string `json:"state"`
@@ -278,7 +272,7 @@ func observeSnapshotOperation(ctx context.Context, env verbEnv, client http.Clie
cancel()
return nil, err
}
resp, err := answer.DoHTTP(&client, req, answer.PossiblyAdmitted)
resp, err := client.Do(req)
var b []byte
if err == nil {
b, err = io.ReadAll(io.LimitReader(resp.Body, 64<<10))
@@ -408,9 +402,8 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
return ops.VolumeStatusExitInvalid
}
unknown := func(step string, err error) int {
policy, detail := operatorAnswer(err, answer.VolumeJob)
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, detail, ways)
return policy.Exit
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, err, ways)
return 1
}
src, err := readEnvFile(filepath.Join(env.EtcDir, o.Source+".env"))
if err != nil {
@@ -432,11 +425,10 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
resp, err := restoreCreateRPC(rctx, master, &control.CreateVolumeRequest{VolumeId: v.VolumeID, SourceVolume: o.Source, SourceSnapshot: o.Snapshot, CreateRequestId: id})
cancel()
if err != nil {
if policy, detail := operatorAnswer(err, answer.VolumeJob); !policy.Retryable {
fmt.Fprintf(stderr, "sw-block volume restore: restore: %v\n", detail)
return policy.Exit
if code := restoreRefusal(err); code != "" {
return refuse("restore", code+": "+err.Error())
}
return unknown("restore", err)
return unknown("restore", fmt.Errorf("the outcome is unknown (%v)", err))
}
if resp.GetVolumeId() != v.VolumeID || !resp.GetStoreReady() {
return unknown("restore", errors.New("the master did not confirm the new volume store-ready"))
@@ -484,10 +476,10 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
break
}
}
policy, detail := operatorAnswer(err, answer.VolumePlacement)
if policy.Retry == answer.Never && !policy.Retryable {
fmt.Fprintf(stderr, "sw-block volume restore: %s: refused: %v; the new volume exists but is not placed; to undo it: %s\n", step, detail, abort)
return policy.Exit
switch status.Code(err) {
case codes.FailedPrecondition, codes.InvalidArgument, codes.AlreadyExists, codes.PermissionDenied:
fmt.Fprintf(stderr, "sw-block volume restore: %s: refused: %v; the new volume exists but is not placed; to undo it: %s\n", step, err, abort)
return ops.VolumeStatusExitInvalid
}
return unknown(step, err)
}
@@ -639,6 +631,25 @@ var (
runOpsRelease = chunkRelease
)
// restoreRefusal maps a refused restore create to its JSON code (the codes
// ops chunk restore reports); "" for an outcome a re-run may change.
func restoreRefusal(err error) string {
if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
return "restore_source_not_own"
}
switch status.Code(err) {
case codes.NotFound:
return "snapshot_not_found"
case codes.AlreadyExists:
return "target_exists"
case codes.InvalidArgument:
return codeBadRequestCLI
case codes.FailedPrecondition:
return "not_admitted"
}
return ""
}
// restorePlaced reads the volume's published authority line at the master
// (QueryVolumeStatus: the publisher's line itself, which exists before any
// lease is granted on it) and its bindings (QueryWorkspace): placed when
@@ -28,23 +28,17 @@ import (
// --- fakes: the holder's snapshot route and the master's restore ---
type backupWireRequest struct {
VolumeID, Name, RequestID string
Labels map[string]string
}
// snapHolder is the holder's POST /chunk/snapshot: one snapshot per name,
// a replay of the same request id answers the same snapshot.
type snapHolder struct {
lastRequest backupWireRequest
mu sync.Mutex
snaps map[string]string // name -> its backup label ("" for a snapshot without one)
posts int
mode string // "", "lost" (taken, answer lost), "refuse", "unknown", "missing-<field>", "async" (runs two reads), "async-stalled", "async-gone" (handle lost), "async-silent" (reads fail), "async-foreign" (another operation answers), "sync" (no operations)
srv *httptest.Server
op map[string]any // the asynchronous operation's result
opID string // its request id
reads int // operation status reads
mu sync.Mutex
snaps map[string]string // name -> its backup label ("" for a snapshot without one)
posts int
mode string // "", "lost" (taken, answer lost), "refuse", "unknown", "missing-<field>", "async" (runs two reads), "async-stalled", "async-gone" (handle lost), "async-silent" (reads fail), "async-foreign" (another operation answers), "sync" (no operations)
srv *httptest.Server
op map[string]any // the asynchronous operation's result
opID string // its request id
reads int // operation status reads
}
func newSnapHolder(t *testing.T) *snapHolder {
@@ -85,12 +79,14 @@ func newSnapHolder(t *testing.T) *snapHolder {
http.NotFound(w, r)
return
}
var q backupWireRequest
var q struct {
VolumeID, Name, RequestID string
Labels map[string]string
}
_ = json.NewDecoder(r.Body).Decode(&q)
h.mu.Lock()
defer h.mu.Unlock()
h.posts++
h.lastRequest = q
switch h.mode {
case "refuse":
w.WriteHeader(http.StatusServiceUnavailable)
@@ -390,7 +386,7 @@ func (m *restoreMaster) QueryVolumeStatus(_ context.Context, q *control.StatusRe
return out, nil
}
func serveRestoreMaster(t *testing.T, options ...grpc.ServerOption) (*restoreMaster, string) {
func serveRestoreMaster(t *testing.T) (*restoreMaster, string) {
t.Helper()
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
t.Setenv(key, "")
@@ -410,7 +406,7 @@ func serveRestoreMaster(t *testing.T, options ...grpc.ServerOption) (*restoreMas
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer(options...)
server := grpc.NewServer()
control.RegisterLifecycleServiceServer(server, m)
control.RegisterWorkspaceServiceServer(server, m)
control.RegisterEvidenceServiceServer(server, m)
@@ -507,12 +503,12 @@ func restoreArgs(h *fakeHost) []string {
const abortCmd = "sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r --abort"
func restoreSetup(t *testing.T, options ...grpc.ServerOption) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
func restoreSetup(t *testing.T) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
h := newFakeHost(t)
h.name = "vol-r"
env := h.env(t)
base := env.Systemctl
m, master := serveRestoreMaster(t, options...)
m, master := serveRestoreMaster(t)
// Restore owns a separate RPC master; the source lease fixture is r3,
// while the restore target is r9. Start must query the target master.
oldQuery := releaseQuery
@@ -594,9 +590,6 @@ func TestVolumeBackupInterruptedResumesWithTheSameCommand(t *testing.T) {
}
code, _, errs := runBackup(env, "vol-a", "--name", "nightly")
wantCode := 1
if c == "lost" || c == "unknown" {
wantCode = 3
}
if c == "refuse" {
wantCode = 2
}
@@ -624,7 +617,7 @@ func TestVolumeBackupIncompleteAnswerIsUnknown(t *testing.T) {
sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), true)
sh.setMode("missing-" + f)
code, out, errs := runBackup(env, "vol-a", "--name", "n1")
if code != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
t.Fatalf("missing %s: %d %s %s", f, code, out, errs)
}
sh.setMode("")
@@ -727,11 +720,7 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
}
m.failNext = r.fail
code, _, errs := runRestore(env, restoreArgs(h)...)
wantExit := 1
if r.step == "restore" || r.step == "place" || r.fail != "" {
wantExit = 3
}
if code != wantExit || !strings.Contains(errs, "to finish, run the same command: sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r") ||
if code != 1 || !strings.Contains(errs, "to finish, run the same command: sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r") ||
!strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("interrupted restore: %d\n%s", code, errs)
}
@@ -797,7 +786,7 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
// After an abort the name is never created again: the master
// refuses the deleting target, and the catalog's tombstone
// refuses a target that never had HEAD (FailedPrecondition).
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
t.Fatalf("restore after abort: %d %s", code, errs)
}
})
@@ -833,11 +822,7 @@ func TestVolumeRestoreRefusals(t *testing.T) {
{"no snapshot flag", []string{"vol-a", "--as", "vol-r"}, "--snapshot is required"},
{"unknown source", append([]string{"vol-z"}, restoreArgs(h)[1:]...), "was vol-z started"},
} {
wantExit := 2
if c.name == "missing snapshot" {
wantExit = 1
}
if code, _, errs := runRestore(env, c.args...); code != wantExit || !strings.Contains(errs, c.want) {
if code, _, errs := runRestore(env, c.args...); code != 2 || !strings.Contains(errs, c.want) {
t.Errorf("%s: %d %s", c.name, code, errs)
}
}
@@ -846,11 +831,11 @@ func TestVolumeRestoreRefusals(t *testing.T) {
if raw, err := os.ReadFile(filepath.Join(env.EtcDir, "vol-a.env")); err != nil || os.WriteFile(sourceT, raw, 0o640) != nil {
t.Fatal(err)
}
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 1 || !strings.Contains(errs, "restore_source_not_own") {
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 2 || !strings.Contains(errs, "restore_source_not_own") {
t.Errorf("restore target as source: %d %s", code, errs)
}
m.vols["vol-r"] = &restoreRec{source: "vol-a", snap: "s1", req: "another", ready: true}
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "target_exists") {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "target_exists") {
t.Errorf("target of another request: %d %s", code, errs)
}
delete(m.vols, "vol-r")
@@ -868,7 +853,7 @@ func TestVolumeRestoreRefusals(t *testing.T) {
func TestVolumeRestoreRefusedPlacementNamesTheAbort(t *testing.T) {
h, env, m, _ := restoreSetup(t)
m.failNext = "bind-refuse"
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "to undo it: "+abortCmd) {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("refused placement: %d %s", code, errs)
}
if h.called("enable") != 0 {
@@ -1009,7 +994,7 @@ func TestVolumeRestorePublicationDuringThePlacement(t *testing.T) {
h3, env3, m3, _ := restoreSetup(t)
m3.failNext = "publish-race-reread-fails"
code, _, errs = runRestore(env3, restoreArgs(h3)...)
if code != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
t.Fatalf("failed re-read: %d %s", code, errs)
}
if code, _, errs := runRestore(env3, restoreArgs(h3)...); code != 0 {
@@ -1081,7 +1066,7 @@ func TestVolumeRestoreRefusesAMalformedLayoutAnswer(t *testing.T) {
h, env, m, _ := restoreSetup(t)
m.failNext = "create-badlayout"
code, _, errs := runRestore(env, restoreArgs(h)...)
if code != 3 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
if code != 1 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("malformed layout answer: %d %s", code, errs)
}
if m.binds != 0 || h.called("enable") != 0 {
+8 -14
View File
@@ -11,7 +11,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
@@ -54,25 +53,20 @@ func runOpsVolumeCreate(args []string, stdout, stderr io.Writer) int {
}
conn, err := link.DialMasterFromEnv(*master)
if err != nil {
policy, detail := operatorAnswer(err, answer.VolumeCreate)
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", detail)
return policy.Exit
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", err)
return 2
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
fail := func(step string, err error) int {
policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.VolumeCreate)
if check != nil {
fmt.Fprintf(stderr, "sw-block ops volume create: %s: %v\n", step, check)
return 75
code, outcome := 78, "refused"
switch status.Code(err) {
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss:
code, outcome = 75, "unknown"
}
outcome := "refused"
if policy.Retryable {
outcome = "unknown"
}
fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; %s\n", step, outcome, err, policy.Cure)
return policy.Exit
fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; earlier steps may remain recorded; retry the identical name, geometry and placement\n", step, outcome, err)
return code
}
q := &control.CreateVolumeRequest{VolumeId: binding.VolumeId, SizeBytes: *size, ReplicationFactor: 1, Protocol: *protocol, FrontendTransport: *transport, BlockSize: geometry.BlockSize, ChunkBytes: geometry.ChunkBytes}
v, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, q)
+10 -5
View File
@@ -8,7 +8,8 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// runOpsVolume exposes the same master name binding used by ops chunk.
@@ -37,11 +38,15 @@ func runOpsVolume(args []string, stdout, stderr io.Writer) int {
defer cancel()
id, err := resolveVolumeID(ctx, *master, fs.Arg(0))
if err != nil {
if policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.VolumeResolve); check == nil {
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v; %s\n", err, policy.Cure)
return policy.Exit
}
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v\n", err)
// Match blockvolume: an unavailable or unknown master answer is retryable;
// a definite refusal or invalid local configuration needs correction.
if s, ok := status.FromError(err); ok {
switch s.Code() {
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal:
return 75
}
}
return 78
}
fmt.Fprintln(stdout, id.String())
@@ -6,6 +6,7 @@ import (
"io"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
const unknownStartOwnerCost = "The master could not prove the current authority holder. START refuses rather than guessing from issued moves, ACKs or prepared bindings. An operator who independently knows the correct host can use the force-move operation's --target-host option; START cannot choose or print that target."
@@ -72,13 +73,13 @@ func prepareVolumeStart(ctx context.Context, v volumeSpec, stdout, stderr io.Wri
client, err := workspaceDial(v.Master)
if err != nil {
fmt.Fprintf(stderr, "sw-block volume start: volume_start_move_not_sent: %v\n", err)
return workspaceErrorExit(err)
return 1
}
defer client.Close()
grant, err := client.CleanMove(setup, q)
if err != nil {
fmt.Fprintf(stderr, "sw-block volume start: volume_start_move: %v; rerun the same volume start (request %s)\n", err, q.RequestId)
return workspaceErrorExit(err)
return workspaceExit(wsclient.OutcomeOf(err))
}
if grant.GetNewEpoch() != epoch+1 || grant.GetOldHost() != v.ServerID {
fmt.Fprintln(stderr, "sw-block volume start: volume_start_move_outcome_unknown: grant is not epoch+1; the unit was not started")
+8 -25
View File
@@ -21,7 +21,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// The whole-job volume commands: each runs on the volume's host, prints
@@ -387,7 +386,7 @@ func getJSON(ctx context.Context, env verbEnv, url string, into any) error {
if err != nil {
return err
}
resp, err := answer.DoHTTP(env.HTTP, req, answer.Unsent)
resp, err := env.HTTP.Do(req)
if err != nil {
return err
}
@@ -634,32 +633,20 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
payload["deadlineNs"] = deadline.UnixNano()
}
body, _ := json.Marshal(payload)
id := ""
unknown := func(why string, causes ...error) (cutAnswer, error) {
if id != "" {
why = "cut id " + id + ": " + why
}
cause := error(errors.New(why))
if len(causes) == 1 {
cause = fmt.Errorf("%s: %w", why, causes[0])
}
policy, detail := operatorAnswer(cause, answer.VolumeStop)
if policy.Retry == answer.Recover {
detail = fmt.Errorf("%w: it may have published", detail)
}
return cutAnswer{}, detail
unknown := func(why string) (cutAnswer, error) {
return cutAnswer{}, fmt.Errorf("the cut's outcome is unknown (%s): it may have published", why)
}
client := *env.HTTP
client.Timeout = timeout + slack
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
seen, last := uint64(0), time.Now()
id, seen, last := "", uint64(0), time.Now()
for {
until := last.Add(timeout + slack)
if !deadline.IsZero() && deadline.Before(until) {
until = deadline
}
if !time.Now().Before(until) {
return unknown("no progress within the window, or the deadline passed")
return unknown("no progress within the window, or the deadline passed; cut id " + id)
}
method, url := http.MethodPost, "http://"+status+"/chunk/cut"
var reqBody io.Reader = bytes.NewReader(body)
@@ -675,15 +662,11 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
phase := answer.Unsent
if id != "" {
phase = answer.PossiblyAdmitted
}
resp, err := answer.DoHTTP(&client, req, phase)
resp, err := client.Do(req)
if err != nil {
cancel()
if id == "" {
return unknown("cut admission answer not received", err)
return unknown(err.Error())
}
time.Sleep(min(env.Poll, time.Until(until)))
continue
@@ -692,7 +675,7 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
resp.Body.Close()
cancel()
if err != nil {
return unknown("cut answer unreadable", err)
return unknown("answer unreadable: " + err.Error())
}
// Every answer speaks this CLI's integer cut API version (this
// CLI's or the one before). Only the first answer may lack it, as a
+24 -24
View File
@@ -9,7 +9,6 @@ import (
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
@@ -68,12 +67,12 @@ lost-range prints the stored lost ranges of the volume's issued forced moves, in
issue order (all of them, or the one of --request-id). It never prints "no loss"
for a forced move whose record is missing or fails its checks.
exit: 0 done; 1 definite refusal or caller cancellation/deadline before send;
2 local usage/confirmation or server argument refusal; 3 outcome unknown:
rerun with the SAME --request-id; 4 unproven lost-range readout; 5 certificate
or role rejection; 75 proven unsent remote failure; 78 local credential or
configuration error. Set SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and SW_BLOCK_TLS_CA
for a master that requires mutual TLS.
exit: 0 done; 1 refused by the master (nothing moved); 2 refused locally (usage
or confirmation; nothing sent); 3 outcome unknown: rerun with the SAME
--request-id; 4 the move is issued but its lost range is not proven (or a
stored range is unreadable); 5 not authorized by blockmaster (no client
certificate where it requires mutual TLS, or a certificate or role its role
file does not admit; set SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY, SW_BLOCK_TLS_CA).
`
// workspaceDial is swapped by tests.
@@ -106,16 +105,20 @@ func runOpsWorkspace(args []string, stdout, stderr io.Writer) int {
}
}
// Render the shared projection without a second outcome-to-exit table.
func workspaceErrorExit(err error) int {
if err == nil {
func workspaceExit(o wsclient.Outcome) int {
switch o {
case wsclient.OutcomeOK:
return wsExitOK
case wsclient.OutcomeRefusedLocally:
return wsExitRefusedLocally
case wsclient.OutcomeRefused:
return wsExitRefused
case wsclient.OutcomeReadoutUnproven:
return wsExitReadoutUnproven
case wsclient.OutcomeNotAuthorized:
return wsExitNotAuthorized
}
if code, ok := wsclient.ExitOf(err); ok {
return code
}
policy, _ := operatorAnswer(err, answer.Workspace)
return policy.Exit
return wsExitUnknown
}
// workspaceForceMoveAnswer is output only; admission and exit policy stay in
@@ -196,7 +199,7 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "%s: refused locally, nothing sent: master address: %v\n", workspaceForceMoveName, err)
return workspaceErrorExit(err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -236,17 +239,14 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int {
answer.Until = wsclient.FormatTime(at.UnixNano())
fmt.Fprintf(stderr, "%s: admissible at %s, master clock (the lease horizon plus clock skew); wait, there is no bypass\n", workspaceForceMoveName, wsclient.FormatTime(at.UnixNano()))
}
return workspaceErrorExit(err)
case wsclient.OutcomeUnsent:
fmt.Fprintf(stderr, "%s: nothing sent: %v\n", workspaceForceMoveName, err)
return workspaceErrorExit(err)
return wsExitRefused
case wsclient.OutcomeUnknown:
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
fmt.Fprintf(stderr, "%s: outcome unknown: rerun with the SAME --request-id %s\n", workspaceForceMoveName, m.RequestID)
return wsExitUnknown
default:
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
return workspaceErrorExit(err)
return workspaceExit(o)
}
}
@@ -287,7 +287,7 @@ func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.Forced
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintf(stderr, "%s --dry-run: the preview failed; nothing was written\n", workspaceForceMoveName)
}
return workspaceErrorExit(err)
return workspaceExit(wsclient.OutcomeOf(err))
}
if answer != nil {
answer.Admitted, answer.Code = p.GetAdmitted(), p.GetCode()
@@ -350,7 +350,7 @@ func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "%s: master address: %v\n", workspaceLostRangeName, err)
return workspaceErrorExit(err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -361,7 +361,7 @@ func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int {
if wsclient.OutcomeOf(err) == wsclient.OutcomeReadoutUnproven {
fmt.Fprintf(stderr, "%s: a forced move's lost range is missing or unreadable: the readout is NOT proven; do not assume no loss\n", workspaceLostRangeName)
}
return workspaceErrorExit(err)
return workspaceExit(wsclient.OutcomeOf(err))
}
if len(ranges) == 0 {
fmt.Fprintf(stdout, "volume %s has no issued forced move\n", volume)
@@ -54,7 +54,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace move: refused locally, nothing sent: %v\n", err)
return workspaceErrorExit(err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -66,7 +66,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int {
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintf(stderr, "workspace move: outcome unknown; rerun with the SAME --request-id %s\n", q.RequestId)
}
return workspaceErrorExit(err)
return workspaceExit(wsclient.OutcomeOf(err))
}
answer.Issued, answer.MoveID, answer.NewHost, answer.NewReplica = true, g.GetRequestId(), g.GetNewHost(), g.GetNewReplicaId()
epoch := g.GetNewEpoch()
@@ -44,7 +44,7 @@ func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace revoke: refused locally, nothing sent: %v\n", err)
return workspaceErrorExit(err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -55,7 +55,7 @@ func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int {
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintln(stderr, "workspace revoke: outcome unknown; inspect workspace show before proceeding")
}
return workspaceErrorExit(err)
return workspaceExit(wsclient.OutcomeOf(err))
}
fmt.Fprintf(stdout, "revocation requested: volume %s holder %s@%d expiry_ns %d\n", id.VolumeId, id.ReplicaId, id.Epoch, lease.GetExpiresAtNs())
if withoutSeal {
+3 -2
View File
@@ -8,6 +8,7 @@ import (
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
// Read-only M2 Granted -> Revoking -> Acked -> Moved (clean) facts,
@@ -30,7 +31,7 @@ func runWorkspaceShow(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace show: refused locally, nothing sent: %v\n", err)
return workspaceErrorExit(err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -38,7 +39,7 @@ func runWorkspaceShow(args []string, stdout, stderr io.Writer) int {
view, err := c.Show(ctx, volume)
if err != nil {
fmt.Fprintf(stderr, "workspace show: %v\n", err)
return workspaceErrorExit(err)
return workspaceExit(wsclient.OutcomeOf(err))
}
printWorkspaceView(stdout, volume, view)
return wsExitOK
@@ -453,48 +453,3 @@ func TestWorkspaceHelpText(t *testing.T) {
}
}
}
// A master that never answers leaves the call unsent when the caller's
// deadline passes: nothing was refused, and no admission preview is read.
func TestWorkspaceForceMoveUnsentCallerDeadlineIsNotARefusal(t *testing.T) {
silent, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
held := make(chan net.Conn, 16)
go func() {
for {
conn, err := silent.Accept()
if err != nil {
close(held)
return
}
held <- conn
}
}()
t.Cleanup(func() {
silent.Close()
for conn := range held {
conn.Close()
}
})
code, out, errOut := runCLI(forceMoveArgs(silent.Addr().String(), "--confirm-forced", "vol@3", "--timeout", "300ms"))
if code != wsExitRefused || out != "" || strings.Contains(errOut, "refused by the master") || !strings.Contains(errOut, "nothing sent") {
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
}
}
// A master that refuses the connection proves the move unsent: exit 75 and
// "nothing sent", never the unknown outcome's rerun advice.
func TestWorkspaceForceMoveRefusedConnectionIsUnsent(t *testing.T) {
closed, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := closed.Addr().String()
closed.Close()
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--timeout", "2s"))
if code != 75 || out != "" || !strings.Contains(errOut, "nothing sent") || strings.Contains(errOut, "outcome unknown") {
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
}
}
@@ -7,7 +7,6 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net"
"net/http"
@@ -98,7 +97,7 @@ func (r *InClusterPVCMetadataResolver) ResolvePVCUID(ctx context.Context, name,
return "", err
}
req.Header.Set("Authorization", "Bearer "+r.token)
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
resp, err := r.client.Do(req)
if err != nil {
return "", err
}
@@ -151,7 +150,7 @@ func (r *InClusterSwBlockVolumeRegistrar) EnsureVolumeObject(ctx context.Context
return err
}
r.setJSONHeaders(req)
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
resp, err := r.client.Do(req)
if err != nil {
return err
}
@@ -178,7 +177,7 @@ func (r *InClusterSwBlockVolumeRegistrar) patchVolumeSpec(ctx context.Context, n
}
r.setJSONHeaders(req)
req.Header.Set("Content-Type", "application/merge-patch+json")
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
resp, err := r.client.Do(req)
if err != nil {
return err
}
@@ -16,7 +16,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
@@ -294,20 +293,13 @@ func grpcAddress(a string) (string, error) {
// Inspect one owned context's completion before its immutable winning cause.
// Do not mix the parent's pre-expiry cause with the child's later Err.
func singleFilerContextError(ctx context.Context, err error) error {
if answer.DefiniteAnswer(err) {
return err
}
done := ctx.Err()
if done == nil {
return err
}
cause := context.Cause(ctx)
if errors.Is(cause, ErrSingleFilerWindowExpired) {
return answer.Rekind(fmt.Errorf("%w: %w: %w", status.Error(codes.Unavailable, "filer transport unavailable"), cause, err), answer.Connection)
return fmt.Errorf("%w: %w: %v", status.Error(codes.Unavailable, "filer transport unavailable"), cause, err)
}
kind := answer.Canceled
if done == context.DeadlineExceeded {
kind = answer.CallerDeadline
}
return answer.Rekind(fmt.Errorf("%w: %w: %w", done, cause, err), kind)
return fmt.Errorf("%w: %w: %v", done, cause, err)
}
@@ -20,7 +20,6 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
type configFiler struct {
@@ -821,21 +820,3 @@ func TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus(t *testing.T) {
t.Fatalf("invalid configured master must refuse before census: %v", err)
}
}
func TestSingleFilerReviewPreservesDefiniteAndCallerWinner(t *testing.T) {
ctx, cancel := context.WithCancelCause(context.Background())
cancel(ErrSingleFilerWindowExpired)
got := singleFilerContextError(ctx, answer.Record(answer.PossiblyAdmitted, status.Error(codes.Unimplemented, "wrong service")))
p, check := answer.PolicyOf(got)
if check != nil || p.Code != "unsupported" || p.Retryable {
t.Errorf("definite refusal lost: %+v %v", p, check)
}
ctx, cancel = context.WithCancelCause(context.Background())
custom := errors.New("caller canceled census")
cancel(custom)
got = singleFilerContextError(ctx, answer.Record(answer.Unsent, status.Error(codes.Unavailable, "earlier network error")))
p, check = answer.PolicyOf(got)
if check != nil || p.Code != "canceled" || !errors.Is(got, custom) {
t.Errorf("caller winner lost: %+v %v %v", p, check, got)
}
}
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -88,7 +87,9 @@ const blobIdleConnsPerHost = 64
// in flight to one volume server opened a new TCP connection and left a
// TIME_WAIT behind, enough to exhaust ephemeral ports at a high rate.
func newBlobHTTPClient(timeout time.Duration) *http.Client {
tr := answer.NewHTTPTransport(answer.HTTPPool{MaxIdleConnsPerHost: blobIdleConnsPerHost, MaxIdleConns: 4 * blobIdleConnsPerHost})
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.MaxIdleConnsPerHost = blobIdleConnsPerHost
tr.MaxIdleConns = 4 * blobIdleConnsPerHost
return &http.Client{Timeout: timeout, Transport: tr}
}
@@ -369,7 +370,7 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) {
if err != nil {
return nil, err
}
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
@@ -378,7 +379,7 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) {
// Drain before close so the connection is reused: a 404 is an
// ordinary answer while a restore target hydrates.
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
return nil, answer.HTTPStatusFailure(resp.StatusCode, &blobStatusError{code: resp.StatusCode, host: host})
return nil, &blobStatusError{code: resp.StatusCode, host: host}
}
return io.ReadAll(resp.Body)
}
@@ -438,7 +439,7 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error {
if err != nil {
return err
}
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
resp, err := c.http.Do(req)
if err != nil {
return err
}
@@ -446,10 +447,10 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
resp.Body.Close()
if resp.StatusCode == http.StatusBadRequest {
return answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode))
return fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
return answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode))
return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode)
}
}
return nil
@@ -1,48 +0,0 @@
package chunkstore
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestBlobHTTPAnswerSurvivesLayoutFetch(t *testing.T) {
for _, row := range []struct {
status int
code string
exit int
}{
{400, "bad_request", 2}, {401, "not_authorized", 5}, {500, "outcome_unknown", 3}, {503, "outcome_unknown", 3},
} {
t.Run(fmt.Sprint(row.status), func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(row.status) }))
defer server.Close()
host := strings.TrimPrefix(server.URL, "http://")
filer := &fakeFilerGRPC{
lookupResp: &filerpb.LookupDirectoryEntryResponse{Entry: &filerpb.Entry{Name: "root", Chunks: []*filerpb.FileChunk{{FileId: "7,01abcdef", Size: 1}}}},
lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: host}}}}},
}
client := startFakeFiler(t, filer)
catalog, err := NewBCatalog(client, client, "/blocks")
if err != nil {
t.Fatal(err)
}
store, err := catalog.Store(VolumeRef{Name: "v", ID: layout.VolumeID{1}})
if err != nil {
t.Fatal(err)
}
_, found, err := store.Fetch(context.Background(), "/blocks/v-01000000/root")
policy, check := answer.PolicyOf(err, answer.Chunk)
if err == nil || found || check != nil || policy.Code != row.code || policy.Exit != row.exit {
t.Fatalf("found=%t err=%v policy=%+v check=%v", found, err, policy, check)
}
})
}
}
@@ -14,7 +14,6 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"math"
"net"
@@ -208,7 +207,7 @@ func (c *SWFS) probe(ctx context.Context, r blobRange, i int) ([]byte, error) {
if err != nil {
return nil, err
}
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("chunkstore: probe %s: %w", fid, err)
}
@@ -219,7 +218,7 @@ func (c *SWFS) probe(ctx context.Context, r blobRange, i int) ([]byte, error) {
case http.StatusNotFound:
return nil, fmt.Errorf("%w %s", errBlobAbsent, fid)
}
return nil, answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("chunkstore: probe %s: http %d", fid, resp.StatusCode))
return nil, fmt.Errorf("chunkstore: probe %s: http %d", fid, resp.StatusCode)
}
// upload POSTs data raw to fid on the volume server at host.
@@ -236,14 +235,14 @@ func (c *SWFS) upload(ctx context.Context, host, fid, auth string, fsync bool, d
if auth != "" {
req.Header.Set("Authorization", "BEARER "+auth)
}
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("chunkstore: upload %s: %w", fid, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
err := answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body))))
err := fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body)))
switch {
case resp.StatusCode == http.StatusUnauthorized:
return errors.Join(errRangeAuth, err)
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"net/http"
"strings"
)
@@ -56,14 +55,14 @@ func (c *SWFS) headFromAll(ctx context.Context, urls []string, fid string) (uint
if err != nil {
return 0, false, err
}
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
resp, err := c.http.Do(req)
if err == nil {
closeErr := resp.Body.Close()
switch {
case closeErr != nil:
err = closeErr
case resp.StatusCode != http.StatusOK:
err = answer.HTTPStatusFailure(resp.StatusCode, &blobStatusError{code: resp.StatusCode, host: host})
err = &blobStatusError{code: resp.StatusCode, host: host}
case resp.ContentLength < 0:
err = errors.New("chunkstore: needle HEAD has no size")
default:
@@ -197,49 +197,6 @@ func TestRetirementWorkerServingWithOneHundredSlowHeads(t *testing.T) {
}
}
func TestRetirementWorkerJoinsBeforeStoresClose(t *testing.T) {
if !retirementWorkerChild(t) {
return
}
original, _ := retirementScanHost(t, "gone")
cfg := original.cfg
closeTestMaster(t, original)
var h *Host
entered := make(chan struct{})
storeErr := make(chan error, 1)
cfg.LayoutReadHead = func(ctx context.Context, _ lifecycle.VolumeSpec) (layout.Head, error) {
close(entered)
<-ctx.Done()
time.Sleep(200 * time.Millisecond)
_, err := h.boot.Store.Load()
storeErr <- err
return layout.Head{}, ctx.Err()
}
var err error
h, err = New(cfg)
if err != nil {
t.Fatal(err)
}
if err := h.PruneUnusedSpecPlacements(t.Context(), nil); err != nil {
t.Fatal(err)
}
h.Start()
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("retirement worker did not start its read")
}
closeTestMaster(t, h)
select {
case err := <-storeErr:
if err != nil {
t.Fatalf("held read saw a closed store: %v", err)
}
default:
t.Fatal("Close returned before the held read finished")
}
}
func TestRetirementPassReportsOnlyPendingRecords(t *testing.T) {
original, _ := retirementScanHost(t, "kept")
cfg := original.cfg
+1 -2
View File
@@ -7,7 +7,6 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"net/url"
@@ -207,7 +206,7 @@ func (c *KubernetesDeploymentClient) send(req *http.Request) (*http.Response, er
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := answer.DoHTTP(c.httpClient, req, answer.Unsent)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("launcher: Kubernetes %s %s: %w", req.Method, req.URL.Path, err)
}
@@ -1,47 +0,0 @@
package ops
import (
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestKubernetesCredentialsFailTypedBeforeClientConstruction(t *testing.T) {
dir := t.TempDir()
token := filepath.Join(dir, "token")
if err := os.WriteFile(token, []byte("fixture-token"), 0600); err != nil {
t.Fatal(err)
}
ca := authtest.NewCA(t, "client-config")
valid := ca.WriteCA(t, dir)
expired := ca.Issue(t, "expired", time.Now().Add(-time.Minute))
expiredPath := filepath.Join(dir, "expired.pem")
if err := os.WriteFile(expiredPath, expired.CertPEM, 0600); err != nil {
t.Fatal(err)
}
malformed := filepath.Join(dir, "bad.pem")
if err := os.WriteFile(malformed, []byte("not a certificate"), 0600); err != nil {
t.Fatal(err)
}
for _, row := range []struct{ name, token, ca string }{
{"missing-token", filepath.Join(dir, "missing-token"), valid},
{"missing-ca", token, filepath.Join(dir, "missing-ca")},
{"malformed-ca", token, malformed}, {"expired-ca", token, expiredPath},
} {
t.Run(row.name, func(t *testing.T) {
client, err := newKubernetesStatusClient("127.0.0.1", "1", row.token, row.ca)
if client != nil || !errors.Is(err, answer.ErrLocalCredential) {
t.Fatalf("constructed=%t typed=%t error=%v", client != nil, errors.Is(err, answer.ErrLocalCredential), err)
}
p, check := answer.PolicyOf(err, answer.Ops)
if check != nil || p.Code != "bad_request" || p.Retryable || p.Exit != 78 {
t.Fatalf("policy=%+v check=%v", p, check)
}
})
}
}
@@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -45,14 +44,14 @@ func (r *HTTPAuthorityRebuildRuntime) ExecuteRebuild(ctx context.Context, req Au
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
resp, err := answer.DoForContract(client, httpReq, answer.Unsent, answer.Ops)
resp, err := client.Do(httpReq)
if err != nil {
return AuthorityRebuildRuntimeResult{}, fmt.Errorf("post rebuild runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
payload, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return AuthorityRebuildRuntimeResult{}, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("rebuild runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))), answer.Ops)
return AuthorityRebuildRuntimeResult{}, fmt.Errorf("rebuild runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
}
var result AuthorityRebuildRuntimeResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
@@ -33,7 +32,7 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
conn, err = link.DialMasterFromEnv(r.Addr)
}
if err != nil {
return FailbackRuntimeResult{}, answer.Present(err, answer.Ops)
return FailbackRuntimeResult{}, err
}
defer conn.Close()
@@ -51,7 +50,7 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
EvidenceRefs: append([]string(nil), req.EvidenceRefs...),
})
if err != nil {
return FailbackRuntimeResult{}, answer.Present(err, answer.Ops)
return FailbackRuntimeResult{}, err
}
return FailbackRuntimeResult{
FailbackStarted: resp.GetFailbackStarted(),
@@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -45,14 +44,14 @@ func (r *HTTPFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
resp, err := answer.DoForContract(client, httpReq, answer.Unsent, answer.Ops)
resp, err := client.Do(httpReq)
if err != nil {
return FailbackRuntimeResult{}, fmt.Errorf("post failback runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
payload, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return FailbackRuntimeResult{}, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("failback runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))), answer.Ops)
return FailbackRuntimeResult{}, fmt.Errorf("failback runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
}
var result FailbackRuntimeResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -152,7 +152,6 @@ func (r FrontendPublicationExecutorReconciler) executeTarget(ctx context.Context
}
runtimeResult, err := runtime.ExecuteFrontendPublication(ctx, frontendPublicationRuntimeRequest(target))
if err != nil {
err = fmt.Errorf("existing target %s/%s volume %s: %w", target.Ref.Namespace, target.Ref.Name, target.Spec.VolumeID, err)
status.ReasonCode = "frontend_publication_runtime_failed"
if writeErr := r.Client.WriteFrontendPublicationStatus(ctx, target.Ref, status); writeErr != nil {
return fmt.Errorf("write failed frontend publication status after runtime error %v: %w", err, writeErr)
@@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -45,14 +44,14 @@ func (r *HTTPFrontendPublicationRuntime) ExecuteFrontendPublication(ctx context.
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
resp, err := answer.DoForContract(client, httpReq, answer.Unsent, answer.Ops)
resp, err := client.Do(httpReq)
if err != nil {
return FrontendPublicationRuntimeResult{}, fmt.Errorf("post frontend publication runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
payload, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return FrontendPublicationRuntimeResult{}, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("frontend publication runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))), answer.Ops)
return FrontendPublicationRuntimeResult{}, fmt.Errorf("frontend publication runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
}
var result FrontendPublicationRuntimeResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+3 -4
View File
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"net"
"net/url"
"os"
@@ -474,7 +473,7 @@ func waitInventoryTCPReady(ctx context.Context, host string, port int, done <-ch
}
return err
case <-ctx.Done():
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
return ctx.Err()
default:
}
conn, err := net.DialTimeout("tcp", addr, 500*time.Millisecond)
@@ -482,11 +481,11 @@ func waitInventoryTCPReady(ctx context.Context, host string, port int, done <-ch
_ = conn.Close()
return nil
}
lastErr = answer.Record(answer.Unsent, err) // handshake-only probe sends no application bytes
lastErr = err
time.Sleep(250 * time.Millisecond)
}
if lastErr != nil {
return answer.Present(lastErr, answer.Ops)
return lastErr
}
return fmt.Errorf("timed out")
}
@@ -1,75 +0,0 @@
package ops
import (
"context"
"crypto/tls"
"encoding/pem"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
)
// CertificatePool also gates this HTTP writer, not only RPC constructors.
func TestKubernetesStatusCARotationUsesTheVerifiedChain(t *testing.T) {
var goodCalls, badCalls atomic.Int64
good := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PATCH" || r.Header.Get("Authorization") != "Bearer fixture-token" {
t.Errorf("unexpected writer request %s %q", r.Method, r.Header.Get("Authorization"))
}
goodCalls.Add(1)
w.WriteHeader(http.StatusOK)
}))
defer good.Close()
dir := t.TempDir()
ca := authtest.NewCA(t, "unused-rotation")
expired := ca.Issue(t, "expired-alternative", time.Now().Add(-time.Hour))
bundle := append(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: good.Certificate().Raw}), expired.CertPEM...)
caPath, tokenPath := filepath.Join(dir, "ca.pem"), filepath.Join(dir, "token")
if err := os.WriteFile(caPath, bundle, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(tokenPath, []byte("fixture-token"), 0o600); err != nil {
t.Fatal(err)
}
clientFor := func(address string) *KubernetesStatusClient {
host, port, err := net.SplitHostPort(strings.TrimPrefix(address, "https://"))
if err != nil {
t.Fatal(err)
}
client, err := newKubernetesStatusClient(host, port, tokenPath, caPath)
if err != nil {
t.Fatalf("unused expired entry blocks HTTP writer construction: %v", err)
}
t.Cleanup(client.HTTPClient.CloseIdleConnections)
return client
}
write := func(client *KubernetesStatusClient) error {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return client.WriteClusterStatus(ctx, OperatorObjectRef{Namespace: "default", Name: "demo"}, SwBlockClusterCRDStatus{})
}
if err := write(clientFor(good.URL)); err != nil {
t.Fatalf("valid HTTP chain beside unused expired entry: %v", err)
}
if goodCalls.Load() != 1 {
t.Fatalf("status PATCH was not witnessed: calls=%d", goodCalls.Load())
}
bad := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { badCalls.Add(1); w.WriteHeader(http.StatusOK) }))
bad.TLS = &tls.Config{Certificates: []tls.Certificate{expired.TLS}, MinVersion: tls.VersionTLS12}
bad.StartTLS()
defer bad.Close()
if err := write(clientFor(bad.URL)); err == nil {
t.Fatal("selected expired HTTP certificate accepted")
}
if badCalls.Load() != 0 {
t.Fatalf("invalid selected chain reached status writer: calls=%d", badCalls.Load())
}
}
@@ -3,9 +3,7 @@ package ops
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"sort"
@@ -118,7 +116,7 @@ func (c *KubernetesStatusClient) getJSON(ctx context.Context, path string, out a
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -127,7 +125,7 @@ func (c *KubernetesStatusClient) getJSON(ctx context.Context, path string, out a
return json.NewDecoder(resp.Body).Decode(out)
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, kubernetesAPIError{StatusCode: resp.StatusCode, Body: string(raw)}), answer.Ops)
return kubernetesAPIError{StatusCode: resp.StatusCode, Body: string(raw)}
}
func (c *KubernetesStatusClient) apiURL(path string) string {
@@ -231,8 +229,8 @@ func mergeNodeCSIEvidence(conditions []ObservationCondition, namespace, nodeName
}
func isKubernetesNotFound(err error) bool {
var apiErr kubernetesAPIError
return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound
apiErr, ok := err.(kubernetesAPIError)
return ok && apiErr.StatusCode == http.StatusNotFound
}
type kubernetesAPIError struct {
@@ -4,9 +4,9 @@ import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"net/url"
@@ -37,24 +37,20 @@ type KubernetesStatusClient struct {
func NewInClusterKubernetesStatusClient() (*KubernetesStatusClient, error) {
host := os.Getenv("KUBERNETES_SERVICE_HOST")
port := os.Getenv("KUBERNETES_SERVICE_PORT")
return newKubernetesStatusClient(host, port, serviceAccountTokenPath, serviceAccountCAPath)
}
func newKubernetesStatusClient(host, port, tokenPath, caPath string) (*KubernetesStatusClient, error) {
if host == "" || port == "" {
return nil, answer.Present(answer.LocalConfiguration(fmt.Errorf("KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are required for non-dry-run operator status")), answer.Ops)
return nil, fmt.Errorf("KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are required for non-dry-run operator status")
}
token, err := os.ReadFile(tokenPath)
token, err := os.ReadFile(serviceAccountTokenPath)
if err != nil {
return nil, answer.Present(answer.LocalCredential(fmt.Errorf("read service account token: %w", err)), answer.Ops)
return nil, fmt.Errorf("read service account token: %w", err)
}
ca, err := os.ReadFile(caPath)
ca, err := os.ReadFile(serviceAccountCAPath)
if err != nil {
return nil, answer.Present(answer.LocalCredential(fmt.Errorf("read service account CA: %w", err)), answer.Ops)
return nil, fmt.Errorf("read service account CA: %w", err)
}
pool, err := answer.CertificatePool(ca, time.Now())
if err != nil {
return nil, answer.Present(fmt.Errorf("service account CA bundle is empty or invalid: %w", err), answer.Ops)
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(ca) {
return nil, fmt.Errorf("service account CA bundle is empty or invalid")
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{RootCAs: pool}
@@ -109,14 +105,14 @@ func (c *KubernetesStatusClient) ListSwBlockVolumes(ctx context.Context, namespa
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockVolumePlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockVolumePlural, resp.StatusCode, strings.TrimSpace(string(raw)))
}
var list kubernetesSwBlockVolumeList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -160,14 +156,14 @@ func (c *KubernetesStatusClient) ListSwBlockReplicaEligibilities(ctx context.Con
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaEligibilityPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaEligibilityPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
}
var list kubernetesSwBlockReplicaEligibilityList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -209,14 +205,14 @@ func (c *KubernetesStatusClient) ListSwBlockReplicaRebuilds(ctx context.Context,
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaRebuildPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaRebuildPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
}
var list kubernetesSwBlockReplicaRebuildList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -258,14 +254,14 @@ func (c *KubernetesStatusClient) ListSwBlockFrontendPublications(ctx context.Con
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockFrontendPublicationPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockFrontendPublicationPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
}
var list kubernetesSwBlockFrontendPublicationList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -307,14 +303,14 @@ func (c *KubernetesStatusClient) ListSwBlockReplicaFailbacks(ctx context.Context
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaFailbackPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaFailbackPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
}
var list kubernetesSwBlockReplicaFailbackList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -369,7 +365,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaRebuild(ctx context.Context
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -378,7 +374,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaRebuild(ctx context.Context
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaRebuildPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaRebuildPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
func (c *KubernetesStatusClient) CreateSwBlockFrontendPublication(ctx context.Context, namespace string, obj SwBlockFrontendPublicationObject) error {
@@ -410,7 +406,7 @@ func (c *KubernetesStatusClient) CreateSwBlockFrontendPublication(ctx context.Co
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -419,7 +415,7 @@ func (c *KubernetesStatusClient) CreateSwBlockFrontendPublication(ctx context.Co
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create %s/%s failed: http %d %s", SwBlockFrontendPublicationPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return fmt.Errorf("create %s/%s failed: http %d %s", SwBlockFrontendPublicationPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
func (c *KubernetesStatusClient) CreateSwBlockReplicaFailback(ctx context.Context, namespace string, obj SwBlockReplicaFailbackObject) error {
@@ -451,7 +447,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaFailback(ctx context.Contex
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -460,7 +456,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaFailback(ctx context.Contex
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaFailbackPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaFailbackPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Context, ref OperatorObjectRef, finalizers []string) error {
@@ -484,7 +480,7 @@ func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Contex
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -493,7 +489,7 @@ func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Contex
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("patch %s/%s finalizers failed: http %d %s", SwBlockVolumePlural, ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return fmt.Errorf("patch %s/%s finalizers failed: http %d %s", SwBlockVolumePlural, ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, resource, name string, status any) error {
@@ -517,7 +513,7 @@ func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, res
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -526,7 +522,7 @@ func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, res
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("patch %s/%s status failed: http %d %s", resource, name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
return fmt.Errorf("patch %s/%s status failed: http %d %s", resource, name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKubernetesEvent) error {
@@ -568,7 +564,7 @@ func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKu
if client == nil {
client = http.DefaultClient
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -580,7 +576,7 @@ func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKu
return nil
}
rawResp, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create event %s failed: http %d %s", event.Reason, resp.StatusCode, strings.TrimSpace(string(rawResp)))), answer.Ops)
return fmt.Errorf("create event %s failed: http %d %s", event.Reason, resp.StatusCode, strings.TrimSpace(string(rawResp)))
}
func (c *KubernetesStatusClient) statusURL(namespace, resource, name string) string {
+4 -6
View File
@@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"net/http"
"net/url"
"os/exec"
@@ -97,11 +96,10 @@ func NewLiveVolumeStatusReportCollector(cfg LiveVolumeStatusConfig) VolumeStatus
func queryLiveMasterStatus(ctx context.Context, masterAddr, volumeID string) (*control.StatusResponse, error) {
conn, err := link.DialMasterFromEnv(masterAddr)
if err != nil {
return nil, answer.Present(fmt.Errorf("dial master: %w", err), answer.Ops)
return nil, fmt.Errorf("dial master: %w", err)
}
defer conn.Close()
reply, err := control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: volumeID})
return reply, answer.Present(err, answer.Ops)
return control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: volumeID})
}
func getStatusJSON(ctx context.Context, client *http.Client, base, path, volumeID string, out any, allowNotFound bool) error {
@@ -113,7 +111,7 @@ func getStatusJSON(ctx context.Context, client *http.Client, base, path, volumeI
if err != nil {
return err
}
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -122,7 +120,7 @@ func getStatusJSON(ctx context.Context, client *http.Client, base, path, volumeI
return nil
}
if resp.StatusCode != http.StatusOK {
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("GET %s: %s", endpoint, resp.Status)), answer.Ops)
return fmt.Errorf("GET %s: %s", endpoint, resp.Status)
}
return json.NewDecoder(resp.Body).Decode(out)
}
@@ -1,72 +0,0 @@
package answer_test
import (
"net"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// The same produced failures traverse every command-family wire contract.
// Exit compatibility is explicit here, independently of the registry builder.
func TestCommandFamilyTransportGrid(t *testing.T) {
for _, row := range []struct {
name string
produce func(*testing.T) error
}{
{"dial-refused", refusedDial},
{"reset-after-write", resetConnection},
{"dns", failedDNS},
{"read-timeout", readTimeout},
} {
err := row.produce(t)
kind, listed := answer.ErrorKind(err)
if err == nil || !listed {
t.Fatalf("%s did not produce a listed failure: %v", row.name, err)
}
for _, family := range []struct {
contract answer.Contract
unsent, possible int
}{
{answer.Chunk, 75, 3}, {answer.ChunkVerify, 75, 1}, {answer.Workspace, 75, 3},
{answer.VolumeCreate, 75, 75}, {answer.VolumeResolve, 75, 75},
{answer.Cluster, 75, 3}, {answer.Restore, 75, 3}, {answer.Failover, 3, 3},
{answer.VolumeJob, 75, 3}, {answer.VolumeStop, 75, 3}, {answer.VolumePlacement, 75, 3}, {answer.Shell, 75, 3}, {answer.Ops, 75, 3},
} {
t.Run(string(family.contract)+"/"+row.name, func(t *testing.T) {
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
got, check := answer.Lookup(phase, answer.ForContract(family.contract, kind))
code, rule, exit := "remote_unavailable", answer.Resend, family.unsent
if phase == answer.PossiblyAdmitted {
code, rule, exit = "outcome_unknown", answer.Recover, family.possible
if family.contract == answer.ChunkVerify {
rule = answer.Resend
}
}
if check != nil || got.Code != code || !got.Retryable || (got.Retry != rule && family.contract != answer.Failover) || got.Exit != exit || got.Cure == "" {
t.Fatalf("phase=%s policy=%+v check=%v", phase, got, check)
}
}
if _, check := answer.Lookup(answer.Unsent, answer.ForContract(family.contract, answer.Kind{Name: "unlisted"})); check == nil {
t.Fatal("an unlisted family row passed the table check")
}
})
}
}
}
// The platform fixture reserves a destination that cannot gain a listener
// between setup and dialing; assert the native refusal rather than its text.
func refusedDial(t *testing.T) error {
t.Helper()
conn, err := net.DialTimeout("tcp", refusedTCPAddress(t), 5*time.Second)
if conn != nil {
conn.Close()
}
if !isRefusedDial(err) {
t.Fatalf("fixture did not produce a refused TCP dial: %v", err)
}
return err
}
@@ -1,60 +0,0 @@
package answer
import (
"crypto/x509"
"encoding/pem"
"fmt"
"time"
)
// CertificatePool validates locally supplied authentication material before
// any dial. The same provenance is used by RPC and HTTP client constructors.
func CertificatePool(raw []byte, now time.Time) (*x509.CertPool, error) {
count := 0
current := 0
var dateErr error
for rest := raw; len(rest) > 0; {
block, remaining := pem.Decode(rest)
if block == nil {
break
}
rest = remaining
if block.Type != "CERTIFICATE" {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, LocalCredential(err)
}
if err := ValidateCertificate(cert, now); err != nil {
if dateErr == nil {
dateErr = err
}
} else {
current++
}
count++
}
pool := x509.NewCertPool()
if count == 0 || !pool.AppendCertsFromPEM(raw) {
return nil, LocalCredential(fmt.Errorf("CA bundle holds no valid PEM certificate"))
}
// Roots are alternatives during rotation, not one certificate chain.
// An unused stale root does not invalidate a current one. TLS still
// verifies the dates of the chain it actually selects. Preserve the
// local configuration refusal when the bundle has no current entry.
if current == 0 {
return nil, dateErr
}
return pool, nil
}
func ValidateCertificate(cert *x509.Certificate, now time.Time) error {
if now.Before(cert.NotBefore) {
return LocalCredential(fmt.Errorf("certificate is not yet valid (valid from %s)", cert.NotBefore.Format(time.RFC3339)))
}
if now.After(cert.NotAfter) {
return LocalCredential(fmt.Errorf("certificate has expired (valid until %s)", cert.NotAfter.Format(time.RFC3339)))
}
return nil
}
-108
View File
@@ -1,108 +0,0 @@
package answer
import "strings"
// LeaseBarrier is a definite dated admission refusal, not a transport guess.
func LeaseBarrier(stamp string) Kind { return Kind{Name: "delete_lease_barrier", ServerMessage: stamp} }
// Domain preserves an authoritative typed answer, rather than inferring
// admission or retry safety from a transport diagnostic.
func Domain(code string, retryable bool, message string) Kind {
return Kind{Name: "server_domain", ServerCode: code, ServerRetryable: retryable, ServerMessage: message}
}
// Guard names an existing definite local/kernel refusal.
func Guard(code string) Kind { return Kind{Name: "guard/" + code} }
func isDomainKind(kind Kind) bool {
return kind.Name == "server_domain" || strings.HasPrefix(kind.Name, "guard/")
}
func addDomainCells(registry map[key]Policy) {
for _, phase := range []Phase{Unsent, PossiblyAdmitted} {
for _, code := range strings.Fields(`awaiting_assignment bad_request base_installing canceled capture_refused closing
cut_aborted cut_busy cut_stalled deadline_exceeded detach_aborted epoch_stale fenced forbidden
format_level_below_head_version frozen_detach_unsupported frozen_tail_too_large geometry_mismatch
head_conflict host_slot_busy in_progress internal invalid_class invalid_freeze_budget invalid_label
invalid_name invalid_policy layout_busy layout_refused lsn_behind method_not_allowed no_progress
not_chunk_volume not_found not_primary operation_capacity operation_conflict operation_handle_mismatch
operation_incomplete operation_intent_conflict operation_not_found operation_retired outcome_unknown
plain_detach_busy plain_detach_unsupported precopy_not_converged precopy_unknown queue_full reconciling
remote_full remote_unavailable schedule_not_running snapshot_delete_requires_operation snapshot_deleting
snapshot_exists snapshot_generation_mismatch snapshot_generation_unavailable snapshot_has_dependents
snapshot_limit snapshot_name_taken snapshot_not_found snapshot_operations_unsupported target_exists
unknown_cut_id volume_not_served volume_not_found restore_source_not_own not_admitted target_live
identity_mismatch volume_deleting conflict unsupported_api_version unsupported_error_code`) {
registry[key{phase, Kind{Name: "server_domain", ServerCode: code}}] = Policy{Retry: Never}
}
registry[key{phase, LeaseBarrier("")}] = Policy{"not_admitted", true, Recover, "", 0}
}
for _, row := range []struct {
code string
retry bool
cure string
}{
{"bad_request", false, "correct the request before sending it again"},
{"deadline_exceeded", true, "retry the same operation with a sufficient no-progress window"},
{"internal", false, "inspect the reported error before retrying the operation"},
{"readout_unproven", false, "inspect the stored range and its integrity evidence; never infer no loss from an unproven readout"},
{"outcome_unknown", true, "recover the same operation by its replay key or poll its existing handle; do not start another operation"},
{"unsupported_error_code", false, "upgrade the client, then recover the original operation by its replay key or poll; do not start another operation"},
{"queue_full", true, "let pending work drain before retrying the same operation"},
{"layout_busy", true, "retry the same operation after the current layout activity releases"},
{"snapshot_not_found", false, "check the snapshot identity; do not target a replacement as a retry"},
{"snapshot_delete_requires_operation", false, "delete through the snapshot operation interface with a stable request id"},
{"snapshot_has_dependents", false, "remove dependent volumes or release their dependency before resuming the same request id"},
{"restore_source_not_own", false, "use a source that owns its snapshot's chunks"},
{"volume_not_found", false, "check the recorded volume identity"},
{"target_exists", false, "read the existing target and reconcile the original operation"},
{"volume_deleting", false, "resume the existing deletion instead of creating a new operation"},
{"not_admitted", false, "resolve the stated admission refusal before retrying"},
{"delete_live_holder", false, "stop the volume first"},
{"target_live", false, "stop and release the target before retrying"},
{"identity_mismatch", false, "use the recorded full volume identity"},
{"geometry_mismatch", false, "use the recorded geometry"},
{"conflict", true, "read the current state and retry the same operation"},
{"invalid_policy", false, "correct the retention policy before retrying"},
} {
rule := Never
if row.retry {
rule = Resend
}
if row.code == "outcome_unknown" || row.code == "unsupported_error_code" {
rule = Recover
}
for _, phase := range []Phase{Unsent, PossiblyAdmitted} {
code := row.code
if code == "delete_live_holder" {
code = "not_admitted"
}
registry[key{phase, Guard(row.code)}] = Policy{code, row.retry, rule, row.cure, 0}
}
}
}
func projectDomain(policy Policy, kind Kind) Policy {
policy.Code, policy.Retryable, policy.Cure = kind.ServerCode, kind.ServerRetryable, kind.ServerMessage
if kind.ServerRetryable {
policy.Retry = Resend
}
if kind.ServerCode == "outcome_unknown" || kind.ServerCode == "in_progress" || kind.ServerCode == "no_progress" ||
(kind.Contract == Failover && kind.ServerRetryable) ||
(kind.ServerCode == "not_admitted" && kind.ServerRetryable && kind.Contract == Chunk) {
policy.Retry = Recover
}
if kind.ServerCode == "remote_unavailable" && kind.ServerRetryable {
remote := registry[key{Unsent, ForContract(kind.Contract, Connection)}]
if !strings.HasSuffix(policy.Cure, remote.Cure) {
policy.Cure += "; " + remote.Cure
}
}
if kind.Contract == Failover && kind.ServerRetryable {
recovery := registry[key{Unsent, ForContract(Failover, Connection)}].Cure
if !strings.HasSuffix(policy.Cure, recovery) {
policy.Cure += "; " + recovery
}
}
return policy
}
@@ -1,146 +0,0 @@
package answer_test
import (
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// Runtime Lookup rejects dynamic unknown codes. This inventory also catches
// a new locally declared/emitted code before a peer can send it to the CLI.
func TestDeclaredDomainCodesHaveRegistryRows(t *testing.T) {
root := filepath.Join("..", "..", "..")
fset := token.NewFileSet()
var files []*ast.File
constants := map[string]ast.Expr{}
for _, dir := range []string{"core/frontend/chunkstore", "core/host/volume", "cmd/sw-block"} {
paths, err := filepath.Glob(filepath.Join(root, filepath.FromSlash(dir), "*.go"))
if err != nil {
t.Fatal(err)
}
for _, path := range paths {
if strings.HasSuffix(path, "_test.go") {
continue
}
file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
if err != nil {
t.Fatal(err)
}
files = append(files, file)
for _, decl := range file.Decls {
group, ok := decl.(*ast.GenDecl)
if !ok || group.Tok != token.CONST {
continue
}
for _, spec := range group.Specs {
value := spec.(*ast.ValueSpec)
for i, name := range value.Names {
if i < len(value.Values) {
constants[file.Name.Name+"."+name.Name] = value.Values[i]
}
}
}
}
}
}
var literal func(string, ast.Expr, int) (string, bool)
literal = func(pkg string, expr ast.Expr, depth int) (string, bool) {
if depth > 20 {
return "", false
}
switch x := expr.(type) {
case *ast.BasicLit:
if x.Kind == token.STRING {
s, err := strconv.Unquote(x.Value)
return s, err == nil
}
case *ast.Ident:
if next := constants[pkg+"."+x.Name]; next != nil {
return literal(pkg, next, depth+1)
}
case *ast.SelectorExpr:
if owner, ok := x.X.(*ast.Ident); ok {
if next := constants[owner.Name+"."+x.Sel.Name]; next != nil {
return literal(owner.Name, next, depth+1)
}
}
}
return "", false
}
seen := map[string]bool{}
check := func(pkg string, expr ast.Expr) {
code, ok := literal(pkg, expr, 0)
if !ok || code == "" || code[0] < 'a' || code[0] > 'z' {
return
}
seen[code] = true
if _, err := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Domain(code, false, "declared domain answer"))); err != nil {
t.Errorf("%s: domain code %q has no registry row: %v", fset.Position(expr.Pos()), code, err)
}
}
for _, file := range files {
pkg := file.Name.Name
ast.Inspect(file, func(node ast.Node) bool {
switch x := node.(type) {
case *ast.ValueSpec:
for i, name := range x.Names {
if i < len(x.Values) && (strings.HasPrefix(name.Name, "Code") || strings.HasPrefix(name.Name, "code")) {
check(pkg, x.Values[i])
}
}
case *ast.CallExpr:
if name, ok := x.Fun.(*ast.Ident); ok {
index := -1
switch name.Name {
case "catErr":
index = 0
case "writeChunkErr":
index = 2
case "chunkFail":
index = 4
}
if index >= 0 && index < len(x.Args) {
check(pkg, x.Args[index])
}
}
case *ast.CompositeLit:
name := ""
switch typ := x.Type.(type) {
case *ast.Ident:
name = typ.Name
case *ast.SelectorExpr:
name = typ.Sel.Name
}
if name == "CatalogError" || name == "chunkErrorBody" || name == "snapshotRefusal" {
for _, field := range x.Elts {
if item, ok := field.(*ast.KeyValueExpr); ok {
if key, ok := item.Key.(*ast.Ident); ok && key.Name == "Code" {
check(pkg, item.Value)
}
}
}
}
}
return true
})
for _, decl := range file.Decls {
if function, ok := decl.(*ast.FuncDecl); ok && function.Name.Name == "chunkErrorCode" {
ast.Inspect(function.Body, func(node ast.Node) bool {
if ret, ok := node.(*ast.ReturnStmt); ok && len(ret.Results) == 3 {
check(pkg, ret.Results[1])
}
return true
})
}
}
}
if len(seen) < 50 {
t.Fatalf("domain census did not reach the expected emitters: %d codes", len(seen))
}
}
-123
View File
@@ -1,123 +0,0 @@
package answer
import (
"context"
"crypto/x509"
"errors"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"io"
"net"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ErrorKind translates a concrete transport error to a registry key. It
// deliberately has no output code, retry flag, cure or exit decision.
func ErrorKind(err error) (Kind, bool) {
var recorded *failure
if errors.As(err, &recorded) {
return recorded.kind, recorded.kind.Name != ""
}
if errors.Is(err, ErrLocalCredential) {
return Credential, true
}
if errors.Is(err, ErrLocalConfiguration) {
return Configuration, true
}
var httpFailure *httpStatusFailure
if errors.As(err, &httpFailure) {
return httpStatusKind(httpFailure.status), true
}
if remote, ok := status.FromError(err); ok {
if remote.Code() == codes.FailedPrecondition && lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
return Guard("restore_source_not_own"), true
}
switch remote.Code() {
case codes.InvalidArgument, codes.FailedPrecondition, codes.NotFound, codes.AlreadyExists, codes.PermissionDenied, codes.Unauthenticated, codes.Unimplemented, codes.DataLoss:
return rpcKindKey(remote.Code()), true
}
}
var authority x509.UnknownAuthorityError
if errors.As(err, &authority) {
return Trust, true
}
var hostname x509.HostnameError
if errors.As(err, &hostname) {
return Name, true
}
var invalid x509.CertificateInvalidError
if errors.As(err, &invalid) {
return Certificate, true
}
if errors.Is(err, context.Canceled) {
return Canceled, true
}
if errors.Is(err, context.DeadlineExceeded) {
return Timeout, true
}
var address *net.AddrError
var syntax *net.ParseError
if errors.As(err, &address) || errors.As(err, &syntax) {
return Configuration, true
}
var dns *net.DNSError
if errors.As(err, &dns) {
return DNS, true
}
var timed net.Error
if errors.As(err, &timed) && timed.Timeout() {
return Timeout, true
}
var network *net.OpError
if errors.As(err, &network) {
// crypto/tls reports TCP alerts as net.OpError with an unexported
// tls.alert (tls.AlertError is exported for QUIC). Translate only
// this structured remote-alert boundary and its exact finite names,
// never arbitrary gRPC/HTTP diagnostic text. In TLS 1.3 this alert
// may arrive on the first read after the client wrote its request.
if network.Op == "remote error" && network.Err != nil {
switch network.Err.Error() {
case "tls: bad certificate", "tls: unsupported certificate", "tls: revoked certificate",
"tls: expired certificate", "tls: unknown certificate", "tls: unknown certificate authority",
"tls: certificate unobtainable", "tls: bad certificate status response",
"tls: bad certificate hash value", "tls: certificate required":
return Certificate, true
}
}
return Connection, true
}
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return Connection, true
}
if remote, ok := status.FromError(err); ok && remote.Code() > codes.OK && remote.Code() <= codes.Unauthenticated {
return rpcKindKey(remote.Code()), true
}
return Kind{}, false
}
// DefiniteAnswer reports a typed server refusal, never a transport guess.
func DefiniteAnswer(err error) bool {
kind, _ := ErrorKind(err)
if isDomainKind(kind) {
return true
}
switch kind.Name {
case "rpc/InvalidArgument", "rpc/FailedPrecondition", "rpc/NotFound", "rpc/AlreadyExists", "rpc/PermissionDenied", "rpc/Unauthenticated", "rpc/Unimplemented", "rpc/DataLoss",
"http/400", "http/401", "http/403", "http/404", "http/405", "http/406", "http/409", "http/410", "http/412", "http/413", "http/415", "http/422", "http/428", "http/501":
return true
}
return false
}
func rpcKindKey(code codes.Code) Kind {
switch code {
case codes.Unavailable:
return Connection
case codes.DeadlineExceeded:
return Timeout
case codes.Canceled:
return Canceled
}
return Kind{Name: "rpc/" + code.String()}
}
@@ -1,85 +0,0 @@
package answer
import "google.golang.org/grpc/codes"
// One projection owns exits. Classification and recovery are decided before
// this projection; a legacy exit never makes an ambiguous operation safe.
var canonicalExits = map[string]int{
"remote_unavailable": 75, "outcome_unknown": 3, "not_authorized": 5,
"local_configuration": 78, "canceled": 1, "deadline_exceeded": 1,
"readout_unproven": 4, "bad_request": 2, "domain_refusal": 1,
"domain_precondition": 1,
"lease_barrier": 75,
}
// LegacyExit is a documented v1.1.x wire exception, removed in v1.2.
// Command is the registry contract for that command, never an adapter table.
type LegacyExit struct {
Command Contract
Class string
Exit int
Source, Reason, RemovedIn string
}
var legacyExits = []LegacyExit{
{Chunk, "cut_busy", 4, "docs/releases/v1.1.1.md", "A cut refused before admission because its slot is busy documents exit 4; this is distinct from readout_unproven.", "v1.2"},
{Failover, "remote_unavailable", 3, "docs/standalone-deployment.md", "Failover requires reading the current authority line before another move even when its RPC was unsent.", "v1.2"},
{Failover, "deadline_exceeded", 3, "docs/standalone-deployment.md", "A caller deadline before sending also requires reading the current authority line before another move.", "v1.2"},
{ChunkVerify, "outcome_unknown", 1, "docs/standalone-deployment.md", "Incomplete verification must not share exit 3 with a completed scan containing findings; JSON retains the failure class.", "v1.2"},
{VolumeCreate, "bad_request", 78, "docs/standalone-deployment.md", "Create documents server refusal as 78; local argument parsing remains 2.", "v1.2"},
{VolumeResolve, "bad_request", 78, "docs/standalone-deployment.md", "Resolve documents definite server refusal as 78; local argument parsing remains 2.", "v1.2"},
{VolumeCreate, "outcome_unknown", 75, "docs/standalone-deployment.md", "Identical create reuses the recorded layout identity and compatible spec; binding/placement do not overwrite another assignment. Preserve all original settings.", "v1.2"},
{VolumeCreate, "domain_refusal", 78, "docs/standalone-deployment.md", "Documented definite create refusal; no new placement is attempted after refusal.", "v1.2"},
{VolumeCreate, "domain_precondition", 78, "docs/standalone-deployment.md", "Documented definite create refusal, including format admission.", "v1.2"},
{VolumeCreate, "not_authorized", 78, "docs/standalone-deployment.md", "Create documents definite refusal as 78.", "v1.2"},
{VolumeResolve, "outcome_unknown", 75, "docs/standalone-deployment.md", "The documented unknown answer is a read-only query; retry cannot create an operation.", "v1.2"},
{VolumeResolve, "domain_refusal", 78, "docs/standalone-deployment.md", "Resolve documents definite refusal, not-found and invalid identity as 78.", "v1.2"},
{VolumeResolve, "domain_precondition", 78, "docs/standalone-deployment.md", "Resolve documents definite refusal as 78.", "v1.2"},
{VolumeResolve, "not_authorized", 78, "docs/standalone-deployment.md", "Resolve documents definite refusal as 78.", "v1.2"},
{Cluster, "domain_precondition", 2, "docs/operations-manual.md", "Finalize and retire-host document typed precondition refusal as 2.", "v1.2"},
}
// LegacyExits returns the compatibility grid, including its removal boundary.
func LegacyExits() []LegacyExit { return append([]LegacyExit(nil), legacyExits...) }
func exitClass(kind Kind, policy Policy) string {
if kind.Contract == Chunk && kind.Name == "server_domain" && kind.ServerCode == "cut_busy" {
return "cut_busy"
}
if kind.Name == "server_domain" && kind.ServerCode == "forbidden" {
return "not_authorized"
}
if kind.Name == "server_domain" && policy.Code == "remote_unavailable" && !policy.Retryable {
return "domain_refusal"
}
if kind.Name == "delete_lease_barrier" || kind.Name == "server_domain" && kind.ServerCode == "not_admitted" && kind.ServerRetryable && kind.Contract == Chunk {
return "lease_barrier"
}
if kind.Name == Credential.Name || kind.Name == Configuration.Name {
return "local_configuration"
}
if kind.Name == rpcKindKey(codes.FailedPrecondition).Name || kind.Name == "http/409" || kind.Name == "http/412" || kind.Name == "http/428" {
return "domain_precondition"
}
if _, listed := canonicalExits[policy.Code]; listed {
return policy.Code
}
if kind.Name == Guard("unsupported_error_code").Name {
return "outcome_unknown"
}
return "domain_refusal"
}
func projectExit(kind Kind, policy Policy) int {
class := exitClass(kind, policy)
exit := canonicalExits[class]
for _, legacy := range legacyExits {
if legacy.Command == kind.Contract && legacy.Class == class {
if legacy.Exit == 75 && kind.Name == "server_domain" && !policy.Retryable {
continue
}
return legacy.Exit
}
}
return exit
}
@@ -1,167 +0,0 @@
package answer_test
import (
"context"
"crypto/x509"
"errors"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestCanonicalExitProjectionGrid(t *testing.T) {
cert := serverCertificate(t, time.Now().Add(-time.Hour), time.Now().Add(time.Hour))
leaf, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
t.Fatal(err)
}
_, trust := leaf.Verify(x509.VerifyOptions{Roots: x509.NewCertPool()})
_, missing := os.ReadFile(filepath.Join(t.TempDir(), "absent-key"))
_, badAddress := net.DialTimeout("tcp", "127.0.0.1", time.Second)
ctx, cancel := context.WithTimeout(context.Background(), -time.Second)
defer cancel()
for _, row := range []struct {
name string
err error
phase answer.Phase
exit int
}{
{"unsent", refusedDial(t), answer.Unsent, 75},
{"unknown", resetConnection(t), answer.PossiblyAdmitted, 3},
{"trust", trust, answer.Unsent, 5},
{"local-credential", answer.LocalCredential(missing), answer.Unsent, 78},
{"local-configuration", answer.LocalConfiguration(badAddress), answer.Unsent, 78},
{"canceled", canceledCall(t), answer.Unsent, 1},
{"caller-deadline", answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Unsent, 1},
{"readout-unproven", status.Error(codes.DataLoss, "unproven"), answer.PossiblyAdmitted, 4},
} {
for _, contract := range []answer.Contract{"", answer.Chunk, answer.ChunkVerify, answer.Workspace, answer.VolumeCreate, answer.VolumeResolve, answer.Cluster, answer.Restore, answer.Failover, answer.VolumeJob, answer.VolumeStop, answer.VolumePlacement, answer.Shell, answer.Ops} {
t.Run(string(contract)+"/"+row.name, func(t *testing.T) {
got, check := answer.PolicyOf(answer.Record(row.phase, row.err), contract)
want := row.exit
if contract == answer.ChunkVerify && row.name == "unknown" {
want = 1
}
if contract == answer.Failover && (row.name == "unsent" || row.name == "caller-deadline") {
want = 3
}
if (contract == answer.VolumeCreate || contract == answer.VolumeResolve) && row.name == "unknown" {
want = 75
}
if (contract == answer.VolumeCreate || contract == answer.VolumeResolve) && row.name == "trust" {
want = 78
}
if check != nil || got.Exit != want {
t.Fatalf("policy=%+v wantExit=%d check=%v", got, want, check)
}
if row.name == "unknown" && contract != answer.ChunkVerify && got.Retry != answer.Recover {
t.Fatalf("legacy exit weakened recovery: %+v", got)
}
})
}
}
}
func TestEveryLegacyExitHasADocumentedGridRow(t *testing.T) {
expired, cancel := context.WithTimeout(context.Background(), -time.Second)
defer cancel()
expected := []struct {
contract answer.Contract
err error
phase answer.Phase
exit int
}{
{answer.Failover, answer.Record(answer.Unsent, refusedDial(t)), answer.Unsent, 3},
{answer.Failover, answer.RecordContext(expired, answer.Unsent, expired.Err()), answer.Unsent, 3},
{answer.ChunkVerify, resetConnection(t), answer.PossiblyAdmitted, 1},
{answer.VolumeCreate, status.Error(codes.InvalidArgument, "server refused"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, status.Error(codes.InvalidArgument, "server refused"), answer.PossiblyAdmitted, 78},
{answer.VolumeCreate, resetConnection(t), answer.PossiblyAdmitted, 75},
{answer.VolumeCreate, status.Error(codes.AlreadyExists, "same target"), answer.PossiblyAdmitted, 78},
{answer.VolumeCreate, status.Error(codes.FailedPrecondition, "format"), answer.PossiblyAdmitted, 78},
{answer.VolumeCreate, status.Error(codes.PermissionDenied, "role"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, resetConnection(t), answer.PossiblyAdmitted, 75},
{answer.VolumeResolve, status.Error(codes.NotFound, "missing volume"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, status.Error(codes.FailedPrecondition, "identity"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, status.Error(codes.PermissionDenied, "role"), answer.PossiblyAdmitted, 78},
{answer.Cluster, status.Error(codes.FailedPrecondition, "HOST_HOLDS_WORK"), answer.PossiblyAdmitted, 2},
}
legacy := answer.LegacyExits()
if len(legacy) != len(expected)+1 {
t.Fatalf("new legacy row needs an independent control: %d != %d", len(legacy), len(expected)+1)
}
// cut_busy is pinned separately below through its typed domain registry row.
legacy = legacy[1:]
for i, row := range legacy {
want := expected[i]
if row.Command != want.contract || row.Reason == "" || row.RemovedIn != "v1.2" {
t.Fatalf("row%d lacks compatibility contract: %+v", i, row)
}
if _, err := os.Stat(filepath.Join("..", "..", "..", filepath.FromSlash(row.Source))); err != nil {
t.Fatalf("legacy source: %v", err)
}
got, check := answer.PolicyOf(answer.Record(want.phase, want.err), want.contract)
if check != nil || got.Exit != want.exit || got.Exit != row.Exit {
t.Fatalf("row%d %+v check=%v", i, got, check)
}
}
if _, err := answer.PolicyOf(answer.Record(answer.Unsent, errors.New("unlisted")), answer.Ops); err == nil {
t.Fatal("projection invented an unlisted policy")
}
}
func TestTypedRemoteUnavailableRespectsRetryable(t *testing.T) {
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
for _, retryable := range []bool{false, true} {
p, err := answer.Lookup(phase, answer.ForContract(answer.Chunk, answer.Domain("remote_unavailable", retryable, "definite server answer")))
want := 1
if retryable {
want = 75
}
if err != nil || p.Exit != want || p.Retryable != retryable {
t.Fatalf("phase=%s retryable=%t policy=%+v error=%v", phase, retryable, p, err)
}
}
}
}
func TestNonRetryableServerAnswerNeverInvitesTemporaryRetry(t *testing.T) {
for _, contract := range []answer.Contract{answer.Chunk, answer.ChunkVerify, answer.Workspace, answer.VolumeCreate, answer.VolumeResolve, answer.Cluster, answer.Restore, answer.Failover, answer.VolumeJob, answer.VolumeStop, answer.VolumePlacement, answer.Shell, answer.Ops} {
for _, code := range []string{"remote_unavailable", "outcome_unknown", "not_admitted"} {
p, err := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(contract, answer.Domain(code, false, "server refuses retry")))
if err != nil || p.Retryable || p.Exit == 75 {
t.Errorf("contract=%s code=%s policy=%+v error=%v", contract, code, p, err)
}
}
}
}
func TestCutBusyHasItsOwnLegacyExitClass(t *testing.T) {
found := false
for _, row := range answer.LegacyExits() {
if row.Command == answer.Chunk && row.Class == "cut_busy" && row.Exit == 4 {
found = true
if row.Reason == "" || row.RemovedIn != "v1.2" {
t.Fatalf("cut_busy lacks compatibility metadata: %+v", row)
}
if _, err := os.Stat(filepath.Join("..", "..", "..", filepath.FromSlash(row.Source))); err != nil {
t.Fatalf("cut_busy source: %v", err)
}
}
}
if !found {
t.Fatal("documented cut_busy=4 needs a distinct compatibility row")
}
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
p, err := answer.Lookup(phase, answer.ForContract(answer.Chunk, answer.Domain("cut_busy", true, "another cut owns the slot")))
if err != nil || p.Code != "cut_busy" || p.Exit != 4 || !p.Retryable || p.Retry != answer.Resend {
t.Fatalf("phase=%s policy=%+v err=%v", phase, p, err)
}
}
}
-121
View File
@@ -1,121 +0,0 @@
package answer
import (
"context"
"errors"
"fmt"
"google.golang.org/grpc/status"
)
// ErrLocalCredential identifies credential validation before a dial. It is
// independent of diagnostic text, including an underlying file-load error.
var ErrLocalCredential = errors.New("local credentials")
var ErrLocalConfiguration = errors.New("local configuration")
func LocalCredential(err error) error {
if err == nil {
return nil
}
if errors.Is(err, ErrLocalCredential) {
return err
}
return Record(Unsent, fmt.Errorf("%w: %w", ErrLocalCredential, err))
}
func LocalConfiguration(err error) error {
if err == nil {
return nil
}
if errors.Is(err, ErrLocalConfiguration) {
return err
}
return Record(Unsent, fmt.Errorf("%w: %w", ErrLocalConfiguration, err))
}
type failure struct {
phase Phase
kind Kind
cause error
}
func (f *failure) Error() string { return f.cause.Error() }
func (f *failure) Unwrap() error { return f.cause }
func (f *failure) GRPCStatus() *status.Status {
server, ok := status.FromError(f.cause)
if !ok {
return nil
} // transport evidence never manufactures a server answer
return server
}
// Record attaches the evidence of one transport attempt without deciding
// its outcome. An unlisted kind remains unlisted at PolicyOf.
func Record(phase Phase, err error) error {
if err == nil {
return nil
}
kind, _ := ErrorKind(err)
return &failure{phase: phase, kind: kind, cause: err}
}
// EnsureEvidence preserves recorded facts. An opaque RPC error without
// transport evidence can only receive the caller's conservative phase.
func EnsureEvidence(phase Phase, err error) error {
if err == nil {
return nil
}
var existing *failure
if errors.As(err, &existing) {
return err
}
return Record(phase, err)
}
// Rekind translates an owned boundary's error provenance without replacing
// the request's admission evidence. Missing evidence remains conservative.
func Rekind(err error, kind Kind) error {
if err == nil {
return nil
}
phase := PossiblyAdmitted
var recorded *failure
if errors.As(err, &recorded) {
phase = recorded.phase
}
return &failure{phase: phase, kind: kind, cause: err}
}
// PolicyOf reads evidence preserved by a transport adapter. Unannotated
// errors are not evidence that an operation was never admitted.
func PolicyOf(err error, contracts ...Contract) (Policy, error) {
var f *failure
if errors.As(err, &f) {
kind := f.kind
if len(contracts) == 1 {
kind = ForContract(contracts[0], kind)
}
if len(contracts) > 1 {
return Policy{}, fmt.Errorf("answer: multiple wire contracts")
}
return Lookup(f.phase, kind)
}
return Policy{}, fmt.Errorf("answer: failure has no admission evidence: %v", err)
}
// Snapshot one owned context once. A non-nil winning cause is immutable;
// only then read Err to distinguish a custom deadline cause from cancellation.
func RecordContext(ctx context.Context, phase Phase, err error) error {
if err == nil {
return nil
}
kind, _ := ErrorKind(err)
if cause := context.Cause(ctx); cause != nil && (kind == Connection || kind == PlaintextConnection || kind == Timeout || kind == Canceled) {
kind = Canceled
if ctx.Err() == context.DeadlineExceeded {
kind = CallerDeadline
}
return &failure{phase: phase, kind: kind, cause: errors.Join(err, ctx.Err(), cause)}
}
return Record(phase, err)
}
-110
View File
@@ -1,110 +0,0 @@
package answer
import (
"context"
"errors"
"io"
"sync/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/stats"
)
type rpcEvidenceKey struct{}
type rpcEvidence struct {
started uint64
peerGeneration atomic.Uint64
peerPool atomic.Pointer[peerPool]
dial atomic.Pointer[dialObservation]
writeStarted atomic.Bool
tls atomic.Pointer[connectionTLSInfo]
}
// ClientOptions preserve per-call admission facts on every link. OutHeader
// is emitted by gRPC's NewStream before it returns after queuing headers.
// Its absence when Invoke returns proves that no request stream was sent;
// its presence is deliberately conservative across transparent retries.
func ClientOptions() []grpc.DialOption {
return []grpc.DialOption{grpc.WithDefaultServiceConfig(`{"loadBalancingConfig":[{"answer_pick_first":{}}]}`), grpc.WithStatsHandler(rpcStats{}), grpc.WithChainUnaryInterceptor(recordUnary), grpc.WithChainStreamInterceptor(recordStream)}
}
func recordStream(ctx context.Context, desc *grpc.StreamDesc, conn *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
evidence := &rpcEvidence{started: attemptSequence.Load()}
ctx = context.WithValue(ctx, rpcEvidenceKey{}, evidence)
stream, err := streamer(ctx, desc, conn, method, opts...)
if err != nil {
return nil, evidence.record(ctx, err)
}
return &observedStream{ClientStream: stream, record: func(err error) error { return evidence.record(ctx, err) }}, nil
}
func (e *rpcEvidence) record(ctx context.Context, err error) error {
if err == nil {
return nil
}
phase := Unsent
if e.writeStarted.Load() {
phase = PossiblyAdmitted
}
// Picker causes explain fail-fast Unavailable, not a WaitForReady call
// ended by its caller or a definite server answer.
kind, _ := ErrorKind(err)
if phase == Unsent && ctx.Err() == nil && kind == Connection {
if observation := e.dial.Load(); observation != nil {
err = &failure{phase: Unsent, kind: observation.kind, cause: errors.Join(err, observation.cause)}
}
}
return RecordContext(ctx, phase, err)
}
type observedStream struct {
grpc.ClientStream
record func(error) error
}
func (s *observedStream) Header() (metadata.MD, error) {
header, err := s.ClientStream.Header()
return header, s.record(err)
}
func (s *observedStream) SendMsg(msg any) error {
err := s.ClientStream.SendMsg(msg)
if err == io.EOF {
return err
} // callers obtain the final status via RecvMsg
return s.record(err)
}
func (s *observedStream) RecvMsg(msg any) error {
err := s.ClientStream.RecvMsg(msg)
if err == io.EOF {
return err
} // successful stream completion, not a transport EOF
return s.record(err)
}
func (s *observedStream) CloseSend() error { return s.record(s.ClientStream.CloseSend()) }
func recordUnary(ctx context.Context, method string, req, reply any, conn *grpc.ClientConn, invoke grpc.UnaryInvoker, opts ...grpc.CallOption) error {
evidence := &rpcEvidence{started: attemptSequence.Load()}
ctx = context.WithValue(ctx, rpcEvidenceKey{}, evidence)
err := invoke(ctx, method, req, reply, conn, opts...)
return evidence.record(ctx, err)
}
type rpcStats struct{}
func (rpcStats) TagRPC(ctx context.Context, _ *stats.RPCTagInfo) context.Context { return ctx }
func (rpcStats) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context { return ctx }
func (rpcStats) HandleConn(context.Context, stats.ConnStats) {}
func (rpcStats) HandleRPC(ctx context.Context, event stats.RPCStats) {
if _, ok := event.(*stats.OutHeader); ok {
if evidence, ok := ctx.Value(rpcEvidenceKey{}).(*rpcEvidence); ok {
evidence.writeStarted.Store(true)
if p, ok := peer.FromContext(ctx); ok {
if info, ok := p.AuthInfo.(*connectionTLSInfo); ok {
evidence.tls.Store(info)
}
}
}
}
}
-66
View File
@@ -1,66 +0,0 @@
package answer
import (
"context"
"io"
"net/http"
"net/http/httptrace"
"sync/atomic"
)
// DoHTTP records transport evidence for one HTTP call. An already admitted
// operation must pass PossiblyAdmitted even when this call only polls it.
func DoHTTP(client *http.Client, req *http.Request, phase Phase) (*http.Response, error) {
if err := req.Context().Err(); err != nil {
// Do not invoke even a custom transport after a preflight cancellation.
// An earlier admission still belongs to the operation, including polls.
return nil, RecordContext(req.Context(), phase, err)
}
// A concrete http.Transport may delegate through RegisterProtocol. Only
// our privately owned native path can supply positive trace provenance.
if client.Transport == nil {
copy := *client
copy.Transport = defaultHTTPTransport
client = &copy
}
_, trustedTrace := client.Transport.(*nativeHTTPTransport)
// Lack of trace support is not proof of an unsent request. GotConn is
// conservative: from that point a request write may have started, even
// if a WroteHeaders callback never arrives after a partial write.
var traced, connected atomic.Bool
trace := &httptrace.ClientTrace{
GetConn: func(string) { traced.Store(true) },
GotConn: func(httptrace.GotConnInfo) { connected.Store(true) },
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
resp, err := client.Do(req)
observed := PossiblyAdmitted
if phase == Unsent && trustedTrace && traced.Load() && !connected.Load() {
observed = Unsent
}
if err != nil {
recorded := RecordContext(req.Context(), observed, err)
kind, _ := ErrorKind(recorded)
if phase == PossiblyAdmitted && (certificateKind(kind) || kind == Credential || kind == Configuration) {
return resp, Rekind(recorded, Connection)
}
return resp, recorded
}
if resp.Body != nil {
resp.Body = &responseBody{ReadCloser: resp.Body, ctx: req.Context()}
}
return resp, nil
}
type responseBody struct {
io.ReadCloser
ctx context.Context
}
func (body *responseBody) Read(p []byte) (int, error) {
n, err := body.ReadCloser.Read(p)
if err != nil && err != io.EOF {
err = RecordContext(body.ctx, PossiblyAdmitted, err)
}
return n, err
}
@@ -1,61 +0,0 @@
package answer
import (
"fmt"
"google.golang.org/grpc/codes"
"net/http"
"strconv"
)
// HTTPStatusFailure records a response the caller has decided is a failure.
// It does not decide whether a 404/409 is protocol state or an error.
func HTTPStatusFailure(status int, cause error) error {
if cause == nil {
cause = fmt.Errorf("HTTP %d", status)
}
// The response status belongs to this attempt; a nested body-read
// failure cannot replace it. Keep outer operation records authoritative.
return &failure{phase: PossiblyAdmitted, kind: httpStatusKind(status), cause: &httpStatusFailure{status: status, cause: cause}}
}
type httpStatusFailure struct {
status int
cause error
}
func (f *httpStatusFailure) Error() string { return f.cause.Error() }
func (f *httpStatusFailure) Unwrap() error { return f.cause }
func httpStatusKind(status int) Kind { return Kind{Name: "http/" + strconv.Itoa(status)} }
// HTTP adapters supply status facts. These cells derive their policy from
// the same canonical rows as RPC; no adapter owns a parallel decision table.
func addHTTPStatusCells(registry map[key]Policy) {
for status, rpc := range map[int]codes.Code{
http.StatusBadRequest: codes.InvalidArgument, http.StatusUnauthorized: codes.Unauthenticated,
http.StatusForbidden: codes.PermissionDenied, http.StatusNotFound: codes.NotFound,
http.StatusMethodNotAllowed: codes.Unimplemented, http.StatusNotAcceptable: codes.InvalidArgument,
http.StatusConflict: codes.FailedPrecondition, http.StatusGone: codes.NotFound,
http.StatusPreconditionFailed: codes.FailedPrecondition, http.StatusRequestEntityTooLarge: codes.InvalidArgument,
http.StatusUnsupportedMediaType: codes.InvalidArgument, http.StatusUnprocessableEntity: codes.InvalidArgument,
http.StatusPreconditionRequired: codes.FailedPrecondition, http.StatusTooManyRequests: codes.ResourceExhausted,
http.StatusInternalServerError: codes.Internal, http.StatusNotImplemented: codes.Unimplemented,
http.StatusBadGateway: codes.Unavailable, http.StatusServiceUnavailable: codes.Unavailable,
http.StatusGatewayTimeout: codes.DeadlineExceeded, http.StatusInsufficientStorage: codes.ResourceExhausted,
http.StatusLoopDetected: codes.Internal,
} {
canonical := rpcKindKey(rpc)
for cell, policy := range registry {
if cell.kind != ForContract(cell.kind.Contract, canonical) {
continue
}
if status == http.StatusUnauthorized {
policy.Cure = "fix authentication credentials for the HTTP peer before retrying"
}
if status == http.StatusForbidden {
policy.Cure = "fix the HTTP peer's access policy or the caller's credentials before retrying"
}
registry[key{cell.phase, ForContract(cell.kind.Contract, httpStatusKind(status))}] = policy
}
}
}
@@ -1,43 +0,0 @@
package answer_test
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestProducedHTTPStatusPolicyRows(t *testing.T) {
for _, row := range []struct {
status int
code string
retry bool
exit int
}{
{400, "bad_request", false, 2}, {401, "not_authorized", false, 5}, {403, "not_authorized", false, 5},
{404, "not_found", false, 1}, {405, "unsupported", false, 1}, {406, "bad_request", false, 2},
{409, "not_admitted", false, 1}, {410, "not_found", false, 1}, {412, "not_admitted", false, 1},
{413, "bad_request", false, 2}, {415, "bad_request", false, 2}, {422, "bad_request", false, 2},
{428, "not_admitted", false, 1}, {429, "outcome_unknown", true, 3}, {500, "outcome_unknown", true, 3},
{501, "unsupported", false, 1}, {502, "outcome_unknown", true, 3}, {503, "outcome_unknown", true, 3},
{504, "outcome_unknown", true, 3}, {507, "outcome_unknown", true, 3}, {508, "outcome_unknown", true, 3},
} {
t.Run(fmt.Sprint(row.status), func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(row.status) }))
defer server.Close()
req, _ := http.NewRequest(http.MethodPost, server.URL, nil)
resp, err := answer.DoHTTP(server.Client(), req, answer.Unsent)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
err = answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("server answered %s", resp.Status))
got, check := answer.PolicyOf(err)
if check != nil || got.Code != row.code || got.Retryable != row.retry || got.Exit != row.exit || got.Cure == "" {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
}
}
-192
View File
@@ -1,192 +0,0 @@
package answer_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/status"
)
type countedTransport struct{ calls atomic.Int64 }
func (tr *countedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
tr.calls.Add(1)
return nil, req.Context().Err()
}
func TestHTTPCancellationBeforeDispatchKeepsOperationPhase(t *testing.T) {
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
for _, deadline := range []bool{false, true} {
ctx, cancel := context.WithCancel(context.Background())
cause := error(context.Canceled)
if deadline {
cancel()
cause = errors.New("custom caller deadline")
ctx, cancel = context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), cause)
} else {
cancel()
}
tr := &countedTransport{}
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "http://unused.invalid", nil)
_, err := answer.DoHTTP(&http.Client{Transport: tr}, req, phase)
cancel()
got, check := answer.PolicyOf(err, answer.Chunk)
code, exit := "canceled", 1
if deadline {
code = "deadline_exceeded"
}
if phase == answer.PossiblyAdmitted {
code, exit = "outcome_unknown", 3
}
if tr.calls.Load() != 0 || check != nil || got.Code != code || got.Exit != exit || !errors.Is(err, cause) {
t.Fatalf("phase=%s deadline=%t dispatched=%d policy=%+v check=%v error=%v", phase, deadline, tr.calls.Load(), got, check, err)
}
}
}
}
func TestHTTPAdapterKeepsAdmissionEvidence(t *testing.T) {
t.Run("nothing sent", func(t *testing.T) {
req, err := http.NewRequest(http.MethodPost, "http://"+refusedTCPAddress(t), strings.NewReader("request"))
if err != nil {
t.Fatal(err)
}
// A destination port of zero cannot be a listening endpoint. Keeping
// the target unavailable avoids the close/reallocate race of a
// listener's former ephemeral port on a busy test host.
_, err = answer.DoHTTP(&http.Client{Timeout: 5 * time.Second}, req, answer.Unsent)
if !isRefusedDial(err) {
t.Fatalf("fixture did not produce a refused TCP dial: %v", err)
}
if _, ok := status.FromError(err); ok {
t.Fatal("an HTTP dial failure became a typed gRPC server answer", err)
}
got, check := answer.PolicyOf(err)
if check != nil || got.Code != "remote_unavailable" || got.Exit != 75 || got.Retry != answer.Resend {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
t.Run("poll dial cannot erase earlier admission", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://"+refusedTCPAddress(t), nil)
_, err := answer.DoHTTP(&http.Client{Timeout: 5 * time.Second}, req, answer.PossiblyAdmitted)
got, check := answer.PolicyOf(err)
if check != nil || got.Code != "outcome_unknown" || got.Retry != answer.Recover {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
t.Run("request received but answer lost", func(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
io.Copy(io.Discard, r.Body)
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
conn.Close()
}))
defer server.Close()
req, err := http.NewRequest(http.MethodPost, server.URL, strings.NewReader("request"))
if err != nil {
t.Fatal(err)
}
_, err = answer.DoHTTP(&http.Client{Timeout: 5 * time.Second}, req, answer.Unsent)
got, check := answer.PolicyOf(err)
if calls.Load() != 1 || check != nil || got.Code != "outcome_unknown" || got.Exit != 3 || got.Retry != answer.Recover {
t.Fatalf("calls=%d policy=%+v check=%v error=%v", calls.Load(), got, check, err)
}
})
}
type getConnOnlyLostAnswerTransport struct{ inner http.RoundTripper }
func (tr getConnOnlyLostAnswerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// A custom transport supports one trace event but omits GotConn. Its real
// request uses another context so native tracing cannot fill the gap.
if trace := httptrace.ContextClientTrace(req.Context()); trace != nil && trace.GetConn != nil {
trace.GetConn(req.URL.Host)
}
resp, err := tr.inner.RoundTrip(req.WithContext(context.Background()))
if err != nil {
return nil, err
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
return nil, io.EOF // server answered; custom transport lost the answer
}
func TestHTTPPartialCustomTraceCannotProveUnsentAfterReceivedPOST(t *testing.T) {
assertPartialHTTPTraceIsUnknown(t, false)
}
func TestHTTPRegisteredProtocolCannotProveUnsentAfterReceivedPOST(t *testing.T) {
assertPartialHTTPTraceIsUnknown(t, true)
}
func TestHTTPOwnedTransportDoesNotInheritRegisteredDefault(t *testing.T) {
var received atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
received.Add(1)
_, _ = io.Copy(io.Discard, r.Body)
_, _ = io.WriteString(w, "received")
}))
defer server.Close()
native := http.DefaultTransport.(*http.Transport).Clone()
defer native.CloseIdleConnections()
poisoned := &http.Transport{}
poisoned.RegisterProtocol("http", getConnOnlyLostAnswerTransport{inner: native})
previous := http.DefaultTransport
http.DefaultTransport = poisoned
t.Cleanup(func() { http.DefaultTransport = previous; poisoned.CloseIdleConnections() })
client := &http.Client{Transport: answer.NewHTTPTransport(answer.HTTPPool{}), Timeout: 5 * time.Second}
defer client.CloseIdleConnections()
req, _ := http.NewRequest(http.MethodPost, server.URL, strings.NewReader("one operation"))
resp, err := answer.DoHTTP(client, req, answer.Unsent)
if err != nil {
t.Fatal("owned transport inherited the registered protocol:", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil || string(body) != "received" || received.Load() != 1 {
t.Fatalf("body=%q received=%d err=%v", body, received.Load(), err)
}
}
func assertPartialHTTPTraceIsUnknown(t *testing.T, registered bool) {
t.Helper()
var received atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(r.Body)
if err != nil || r.Method != http.MethodPost || string(raw) != "admit-once" {
t.Errorf("receipt: method=%s body=%q error=%v", r.Method, raw, err)
}
received.Add(1)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
native := http.DefaultTransport.(*http.Transport).Clone()
defer native.CloseIdleConnections()
var transport http.RoundTripper = getConnOnlyLostAnswerTransport{inner: native}
if registered {
outer := &http.Transport{}
outer.RegisterProtocol("http", transport)
defer outer.CloseIdleConnections()
transport = outer
}
req, _ := http.NewRequest(http.MethodPost, server.URL, strings.NewReader("admit-once"))
_, err := answer.DoHTTP(&http.Client{Transport: transport, Timeout: 5 * time.Second}, req, answer.Unsent)
policy, check := answer.PolicyOf(err, answer.Chunk)
if received.Load() != 1 || check != nil || policy.Code != "outcome_unknown" || policy.Exit != 3 || policy.Retry != answer.Recover {
t.Fatalf("received=%d policy=%+v check=%v error=%v", received.Load(), policy, check, err)
}
}
@@ -1,42 +0,0 @@
package answer
import (
"net"
"net/http"
"time"
)
// HTTPPool sets idle connection retention, not request concurrency. Zero values
// use the standard transport defaults. No dial or protocol callback is exposed.
type HTTPPool struct {
MaxIdleConns, MaxIdleConnsPerHost int
}
// NewHTTPTransport owns a native transport whose request path cannot be replaced
// with RegisterProtocol. Caller-supplied RoundTrippers have no such provenance.
func NewHTTPTransport(pool HTTPPool) http.RoundTripper {
maxIdle := pool.MaxIdleConns
if maxIdle == 0 {
maxIdle = 100
}
return &nativeHTTPTransport{transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: maxIdle,
MaxIdleConnsPerHost: pool.MaxIdleConnsPerHost,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: time.Second,
}}
}
type nativeHTTPTransport struct{ transport *http.Transport }
func (tr *nativeHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return tr.transport.RoundTrip(req)
}
func (tr *nativeHTTPTransport) CloseIdleConnections() { tr.transport.CloseIdleConnections() }
var defaultHTTPTransport = NewHTTPTransport(HTTPPool{})
-266
View File
@@ -1,266 +0,0 @@
package answer
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"google.golang.org/grpc/balancer"
_ "google.golang.org/grpc/balancer/pickfirst"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/serviceconfig"
)
const observedPickFirst = "answer_pick_first"
const maxPeerDiagnostics = 8
var attemptSequence atomic.Uint64
type peerAttempt struct {
peer string
attempt, completed, nonCertificate uint64
state connectivity.State
kind Kind
cause error
singleAddress bool
}
type peerPool struct {
mu sync.Mutex
generation uint64
ambiguous bool
plaintext bool
peers map[string]*peerAttempt
}
type dialObservation struct {
kind Kind
cause error
}
type evidenceBuilder struct{ inner balancer.Builder }
func init() { balancer.Register(evidenceBuilder{inner: balancer.Get("pick_first")}) }
func (b evidenceBuilder) Name() string { return observedPickFirst }
func (b evidenceBuilder) ParseConfig(raw json.RawMessage) (serviceconfig.LoadBalancingConfig, error) {
if parser, ok := b.inner.(balancer.ConfigParser); ok {
return parser.ParseConfig(raw)
}
return nil, nil
}
func (b evidenceBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer {
creds := opts.DialCreds
if creds == nil && opts.CredsBundle != nil {
creds = opts.CredsBundle.TransportCredentials()
}
pool := &peerPool{peers: map[string]*peerAttempt{}, plaintext: creds != nil && creds.Info().SecurityProtocol == "insecure"}
delegate := b.inner.Build(&evidenceClientConn{ClientConn: cc, pool: pool}, opts)
return &evidenceBalancer{Balancer: delegate, pool: pool}
}
type evidenceBalancer struct {
balancer.Balancer
pool *peerPool
}
func peerKey(addr resolver.Address) string {
if addr.ServerName != "" {
return addr.Addr + " (TLS name " + addr.ServerName + ")"
}
return addr.Addr
}
func (b *evidenceBalancer) UpdateClientConnState(state balancer.ClientConnState) error {
peers := map[string]bool{}
ambiguous := false
add := func(addr resolver.Address) {
key := peerKey(addr)
if peers[key] {
ambiguous = true
}
peers[key] = true
}
if len(state.ResolverState.Endpoints) > 0 {
for _, endpoint := range state.ResolverState.Endpoints {
for _, addr := range endpoint.Addresses {
add(addr)
}
}
} else {
for _, addr := range state.ResolverState.Addresses {
add(addr)
}
}
b.pool.mu.Lock()
b.pool.generation++
b.pool.ambiguous = ambiguous
for peer := range b.pool.peers {
if !peers[peer] {
delete(b.pool.peers, peer)
}
}
for peer := range peers {
if b.pool.peers[peer] == nil {
b.pool.peers[peer] = &peerAttempt{peer: peer}
}
}
b.pool.mu.Unlock()
return b.Balancer.UpdateClientConnState(state)
}
type evidenceClientConn struct {
balancer.ClientConn
pool *peerPool
}
func (cc *evidenceClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
listener := opts.StateListener
peer := ""
if len(addrs) == 1 {
peer = peerKey(addrs[0])
}
cc.pool.mu.Lock()
item := &peerAttempt{peer: peer, singleAddress: len(addrs) == 1}
if previous := cc.pool.peers[peer]; previous != nil {
item.nonCertificate = previous.nonCertificate
cc.pool.peers[peer] = item
}
cc.pool.mu.Unlock()
// A multi-address SubConn hides which address failed. It can never
// support an all-peers certificate proof; preserve the delegate unchanged.
opts.StateListener = func(state balancer.SubConnState) {
cc.pool.mu.Lock()
if cc.pool.peers[peer] == item {
item.singleAddress = len(addrs) == 1
if state.ConnectivityState == connectivity.Connecting {
item.attempt = 0 // notification delivery is not attempt-start evidence
item.completed = 0
item.cause = nil
item.kind = Kind{}
}
if state.ConnectivityState == connectivity.TransientFailure {
item.completed = attemptSequence.Add(1)
item.cause = connectionOrigin(state.ConnectionError)
item.kind, _ = ErrorKind(item.cause)
var actual *attemptFailure
if errors.As(item.cause, &actual) && actual.started > 0 && actual.completed >= actual.started {
item.attempt, item.completed = actual.started, actual.completed
}
if !certificateKind(item.kind) {
item.nonCertificate = item.completed
}
}
if state.ConnectivityState != connectivity.Shutdown {
item.state = state.ConnectivityState
}
}
cc.pool.mu.Unlock()
if listener != nil {
listener(state)
}
}
return cc.ClientConn.NewSubConn(addrs, opts)
}
func (cc *evidenceClientConn) UpdateState(state balancer.State) {
cc.pool.mu.Lock()
generation := cc.pool.generation
cc.pool.mu.Unlock()
state.Picker = &evidencePicker{Picker: state.Picker, pool: cc.pool, generation: generation}
cc.ClientConn.UpdateState(state)
}
type evidencePicker struct {
balancer.Picker
pool *peerPool
generation uint64 // immutable generation that produced this delegate picker
}
func (p *evidencePicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
rpc, _ := info.Ctx.Value(rpcEvidenceKey{}).(*rpcEvidence)
if rpc != nil {
generation := p.generation
if rpc.peerPool.CompareAndSwap(nil, p.pool) {
rpc.peerGeneration.Store(generation)
}
}
result, err := p.Picker.Pick(info)
if rpc != nil && err != nil && !errors.Is(err, balancer.ErrNoSubConnAvailable) {
generation := rpc.peerGeneration.Load()
if rpc.peerPool.Load() != p.pool {
generation = 0
}
rpc.dial.Store(p.pool.observe(rpc.started, generation))
}
return result, err
}
func certificateKind(kind Kind) bool { return kind == Certificate || kind == Trust || kind == Name }
func connectionOrigin(err error) error {
// gRPC's transport ConnectionError exposes its typed Origin publicly
// through this method, although its concrete package is internal.
if source, ok := err.(interface{ Origin() error }); ok {
if cause := source.Origin(); cause != nil {
return cause
}
}
return err
}
func (pool *peerPool) observe(started, generation uint64) *dialObservation {
pool.mu.Lock()
defer pool.mu.Unlock()
all := len(pool.peers) > 0 && pool.generation == generation && !pool.ambiguous
kind := Certificate
hasTrust, hasName := false, false
var localKind Kind
names := make([]string, 0, maxPeerDiagnostics)
for peer, item := range pool.peers {
if len(names) < maxPeerDiagnostics {
names = append(names, peer)
sort.Strings(names)
} else if peer < names[len(names)-1] {
names[len(names)-1] = peer
sort.Strings(names)
}
if !item.singleAddress || item.attempt <= started || item.completed <= started || item.nonCertificate > started || item.state != connectivity.TransientFailure || !certificateKind(item.kind) {
all = false
}
hasTrust = hasTrust || item.kind == Trust
hasName = hasName || item.kind == Name
if pool.generation == generation && item.attempt > started && item.completed > started && (item.kind == Credential || item.kind == Configuration) {
localKind = item.kind
}
}
sort.Strings(names)
descriptions := make([]string, 0, maxPeerDiagnostics)
for _, peer := range names {
if len(descriptions) == maxPeerDiagnostics {
break
}
item := pool.peers[peer]
cause := "attempt not yet proven complete"
if item.cause != nil {
cause = item.cause.Error()
}
descriptions = append(descriptions, fmt.Sprintf("peer %s attempt %d: %s", peer, item.attempt, cause))
}
if len(pool.peers) > len(descriptions) {
descriptions = append(descriptions, fmt.Sprintf("%d more peer causes omitted", len(pool.peers)-len(descriptions)))
}
if hasTrust {
kind = Trust
} else if hasName {
kind = Name
}
if !all {
kind = Connection
}
if localKind.Name != "" {
kind = localKind
}
if kind == Connection && pool.plaintext {
kind = PlaintextConnection
}
return &dialObservation{kind: kind, cause: errors.New(strings.Join(descriptions, "; "))}
}
-108
View File
@@ -1,108 +0,0 @@
package answer
import (
"context"
"crypto/x509"
"errors"
"fmt"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/resolver"
"net"
"strings"
"testing"
"google.golang.org/grpc/connectivity"
)
func TestPeerCertificateProofRequiresEveryFreshCompletedAttempt(t *testing.T) {
for _, row := range []struct {
name string
completed, nonCertificate uint64
state connectivity.State
generation uint64
want Kind
}{
{"fresh-cert", 4, 0, connectivity.TransientFailure, 1, Trust},
{"cached-cert", 2, 0, connectivity.TransientFailure, 1, Connection},
{"network-then-cert-in-same-call", 4, 3, connectivity.TransientFailure, 1, Connection},
{"network-before-call-then-fresh-cert", 4, 1, connectivity.TransientFailure, 1, Trust},
{"attempt-in-flight", 4, 0, connectivity.Connecting, 1, Connection},
{"resolver-changed", 4, 0, connectivity.TransientFailure, 2, Connection},
} {
t.Run(row.name, func(t *testing.T) {
pool := &peerPool{generation: row.generation, peers: map[string]*peerAttempt{"peer-a": {peer: "peer-a", attempt: 3, completed: row.completed, nonCertificate: row.nonCertificate, state: row.state, kind: Trust, cause: errors.New("certificate rejected"), singleAddress: true}}}
got := pool.observe(2, 1)
if got.kind != row.want {
t.Fatalf("proof authorized wrong class: got=%v want=%v cause=%v", got.kind, row.want, got.cause)
}
})
}
}
func TestPeerDiagnosticTruncationNeverAuthorizesTerminalClassification(t *testing.T) {
pool := &peerPool{generation: 1, peers: map[string]*peerAttempt{}}
for i := 0; i < maxPeerDiagnostics; i++ {
name := fmt.Sprintf("a-%02d", i)
pool.peers[name] = &peerAttempt{peer: name, attempt: 3, completed: 4, state: connectivity.TransientFailure, kind: Trust, cause: errors.New("certificate rejected"), singleAddress: true}
}
pool.peers["z-network"] = &peerAttempt{peer: "z-network", attempt: 3, completed: 4, nonCertificate: 4, state: connectivity.TransientFailure, kind: Connection, cause: errors.New("dial refused"), singleAddress: true}
got := pool.observe(2, 1)
if got.kind != Connection || !strings.Contains(got.cause.Error(), "1 more peer causes omitted") {
t.Fatalf("diagnostic cap weakened proof: %v %v", got.kind, got.cause)
}
}
type heldNotificationClientConn struct {
balancer.ClientConn
deliver func(balancer.SubConnState)
}
func (cc *heldNotificationClientConn) NewSubConn(_ []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
cc.deliver = opts.StateListener
return nil, nil
}
type rejectingCredentials struct {
credentials.TransportCredentials
cause error
}
func (c *rejectingCredentials) ClientHandshake(context.Context, string, net.Conn) (net.Conn, credentials.AuthInfo, error) {
return nil, nil, c.cause
}
func TestDelayedPeerNotificationCannotRefreshAnOldTLSFailure(t *testing.T) {
for _, name := range []string{"failure-before-call", "failure-during-call", "unobserved-failure"} {
t.Run(name, func(t *testing.T) {
pool := &peerPool{generation: 1, peers: map[string]*peerAttempt{"peer-a": {peer: "peer-a"}}}
cc := &heldNotificationClientConn{}
observer := &evidenceClientConn{ClientConn: cc, pool: pool}
if _, err := observer.NewSubConn([]resolver.Address{{Addr: "peer-a"}}, balancer.NewSubConnOptions{}); err != nil {
t.Fatal(err)
}
// The TLS boundary fails first; its two balancer notifications remain
// queued until after the next RPC starts, exactly as async delivery may.
cause := error(x509.UnknownAuthorityError{Cert: &x509.Certificate{}})
wrapped, _ := ObserveCredentials(&rejectingCredentials{cause: cause})
started := attemptSequence.Load()
_, _, failure := wrapped.ClientHandshake(context.Background(), "peer-a", nil)
if name == "failure-before-call" {
started = attemptSequence.Load()
}
if name == "unobserved-failure" {
failure = cause
}
cc.deliver(balancer.SubConnState{ConnectivityState: connectivity.Connecting})
cc.deliver(balancer.SubConnState{ConnectivityState: connectivity.TransientFailure, ConnectionError: failure})
got := pool.observe(started, 1)
want := Connection
if name == "failure-during-call" {
want = Trust
}
if got.kind != want {
t.Fatalf("notification relabeled failure: got=%v want=%v cause=%v", got.kind, want, got.cause)
}
})
}
}
-210
View File
@@ -1,210 +0,0 @@
// Package answer owns the operator failure policy shared by CLI and RPC
// adapters. Transport adapters supply facts; they do not decide retry safety.
package answer
import (
"fmt"
"google.golang.org/grpc/codes"
"time"
)
// Phase is admission evidence, not a guess based on an error message.
type Phase string
const (
Unsent Phase = "unsent"
PossiblyAdmitted Phase = "possibly_admitted"
)
// Contract is the existing output protocol, not a retry decision. It is
// part of the error kind so the same pure registry preserves wire exits.
type Contract string
const (
Chunk Contract = "chunk"
ChunkVerify Contract = "chunk_verify"
Workspace Contract = "workspace"
VolumeCreate Contract = "volume_create"
VolumeResolve Contract = "volume_resolve"
Cluster Contract = "cluster"
Restore Contract = "restore"
Failover Contract = "failover"
VolumeJob Contract = "volume_job"
VolumeStop Contract = "volume_stop"
VolumePlacement Contract = "volume_placement"
Shell Contract = "shell"
Ops Contract = "ops"
)
type Kind struct {
Name string
Contract Contract
ServerCode string
ServerRetryable bool
ServerMessage string
}
func (kind Kind) String() string {
name := string(kind.Contract) + "/" + kind.Name
if kind.ServerCode != "" && len(kind.ServerCode) <= 64 {
name += "/" + kind.ServerCode
}
return name
}
func ForContract(contract Contract, kind Kind) Kind { kind.Contract = contract; return kind }
var (
Connection = Kind{Name: "connection"}
PlaintextConnection = Kind{Name: "plaintext_connection"}
Certificate = Kind{Name: "certificate"}
Trust = Kind{Name: "trust"}
Name = Kind{Name: "name"}
DNS = Kind{Name: "dns"}
Timeout = Kind{Name: "timeout"}
Canceled = Kind{Name: "canceled"}
Credential = Kind{Name: "local_credential"}
Configuration = Kind{Name: "local_configuration"}
CallerDeadline = Kind{Name: "caller_deadline"}
)
// RetryRule describes recovery of this operation, never a new operation.
type RetryRule string
const (
Resend RetryRule = "resend_same_operation"
Recover RetryRule = "replay_key_or_poll"
Never RetryRule = "fix_before_retry"
)
type Policy struct {
Code string
Retryable bool
Retry RetryRule
Cure string
Exit int
}
type key struct {
phase Phase
kind Kind
}
// The registry is the sole owner of classification, cure and exit policy.
var registry = buildRegistry()
func buildRegistry() map[key]Policy {
base := map[key]Policy{
{Unsent, Credential}: {"bad_request", false, Never, "fix the local credential files (certificate, key, CA or token) before dialing again", 0},
{Unsent, Configuration}: {"bad_request", false, Never, "correct the local address or transport configuration before dialing again", 0},
{PossiblyAdmitted, Configuration}: {"bad_request", false, Never, "correct the local address or transport configuration, then recover the same operation", 0},
{Unsent, CallerDeadline}: {"deadline_exceeded", true, Resend, "the caller's deadline passed before sending; retry the same operation with a sufficient caller window", 0},
{PossiblyAdmitted, CallerDeadline}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{PossiblyAdmitted, Credential}: {"bad_request", false, Never, "fix the local credential files (certificate, key, CA or token), then recover the same operation", 0},
{Unsent, Connection}: {"remote_unavailable", true, Resend, "retry the same operation when the remote is reachable", 0},
{PossiblyAdmitted, Connection}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{Unsent, DNS}: {"remote_unavailable", true, Resend, "check name resolution, then retry the same operation", 0},
{PossiblyAdmitted, DNS}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{Unsent, Certificate}: {"not_authorized", false, Never, "fix the client certificate, its key and the peer's certificate policy before retrying", 0},
{PossiblyAdmitted, Certificate}: {"not_authorized", false, Never, "fix the client certificate, its key and the peer's certificate policy before retrying", 0},
{Unsent, Trust}: {"not_authorized", false, Never, "fix the trusted CA before retrying", 0},
{PossiblyAdmitted, Trust}: {"not_authorized", false, Never, "fix the trusted CA before retrying", 0},
{Unsent, Name}: {"not_authorized", false, Never, "fix the peer address or its certificate names before retrying", 0},
{PossiblyAdmitted, Name}: {"not_authorized", false, Never, "fix the peer address or its certificate names before retrying", 0},
{Unsent, Timeout}: {"remote_unavailable", true, Resend, "retry the same operation when the remote is reachable", 0},
{PossiblyAdmitted, Timeout}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{Unsent, Canceled}: {"canceled", false, Never, "operation interrupted by its caller", 0},
{PossiblyAdmitted, Canceled}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
}
base[key{Unsent, PlaintextConnection}] = base[key{Unsent, Connection}]
base[key{PossiblyAdmitted, PlaintextConnection}] = base[key{PossiblyAdmitted, Connection}]
for _, row := range []struct {
code codes.Code
policy Policy
}{
{codes.InvalidArgument, Policy{"bad_request", false, Never, "correct the server's stated argument error before retrying", 0}},
{codes.FailedPrecondition, Policy{"not_admitted", false, Never, "resolve the server's stated precondition before retrying", 0}},
{codes.NotFound, Policy{"not_found", false, Never, "check the requested identity; do not create a replacement as a retry", 0}},
{codes.AlreadyExists, Policy{"target_exists", false, Never, "read the existing target and reconcile the original operation", 0}},
{codes.PermissionDenied, Policy{"not_authorized", false, Never, "check the certificate's role in the server's role file before retrying", 0}},
{codes.Unauthenticated, Policy{"not_authorized", false, Never, "check the certificate and the server's trusted CA and role file before retrying", 0}},
{codes.Unimplemented, Policy{"unsupported", false, Never, "use a server that supports this operation", 0}},
{codes.DataLoss, Policy{"readout_unproven", false, Never, "inspect the stored operation and its loss or integrity evidence before proceeding", 0}},
{codes.Internal, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.Unknown, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.Aborted, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.OutOfRange, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.ResourceExhausted, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
} {
for _, phase := range []Phase{Unsent, PossiblyAdmitted} {
base[key{phase, rpcKindKey(row.code)}] = row.policy
}
}
addDomainCells(base)
for _, contract := range []Contract{Chunk, ChunkVerify, Workspace, VolumeCreate, VolumeResolve, Cluster, Restore, Failover, VolumeJob, VolumeStop, VolumePlacement, Shell, Ops} {
for cell, policy := range base {
if cell.kind.Contract != "" {
continue
}
if cell.kind == rpcKindKey(codes.NotFound) && (contract == Restore || contract == VolumeJob) {
policy.Code = "snapshot_not_found"
}
if contract == Failover && policy.Retryable {
policy.Retry = Recover
policy.Cure = "read the current authority line before another move; do not blindly repeat an uncertain move"
}
if contract == VolumeCreate && policy.Retryable {
policy.Cure = "earlier steps may remain recorded; retry identical name, geometry and placement"
}
if contract == Workspace && (cell.kind == rpcKindKey(codes.PermissionDenied) || cell.kind == rpcKindKey(codes.Unauthenticated)) {
policy.Cure = "not authorized by blockmaster: " + policy.Cure
}
base[key{cell.phase, ForContract(contract, cell.kind)}] = policy
}
}
addHTTPStatusCells(base)
return base
}
// Lookup refuses unlisted combinations. Callers must not invent a retry
// policy when an adapter supplies a new error kind or lacks phase evidence.
func Lookup(phase Phase, kind Kind) (Policy, error) {
lookup := kind
if kind.Name == "server_domain" {
if kind.ServerCode == "" || len(kind.ServerCode) > 64 {
return Policy{}, fmt.Errorf("answer: server domain code must have 1..64 bytes")
}
lookup.ServerMessage, lookup.ServerRetryable = "", false
}
if kind.Name == "delete_lease_barrier" {
if len(kind.ServerMessage) > 64 {
return Policy{}, fmt.Errorf("answer: invalid lease barrier stamp")
}
if _, err := time.Parse(time.RFC3339Nano, kind.ServerMessage); err != nil {
return Policy{}, fmt.Errorf("answer: invalid lease barrier stamp: %w", err)
}
lookup.ServerMessage = ""
}
policy, ok := registry[key{phase, lookup}]
if !ok {
return Policy{}, fmt.Errorf("answer: unlisted phase %q, error kind %q", phase, kind)
}
if kind.Name == "server_domain" {
policy = projectDomain(policy, kind)
}
if kind.Name == "delete_lease_barrier" {
policy.Cure = "retry the same --request-id after " + kind.ServerMessage
}
if kind.Contract == Shell && kind.Name != "server_domain" && kind.Name != "delete_lease_barrier" && kind.Name != CallerDeadline.Name && policy.Retryable {
policy.Cure = "recover this read-only inspection by polling the same record; this inspection does not mutate the volume"
}
if kind.Contract == ChunkVerify && policy.Code == "outcome_unknown" && policy.Retryable {
policy.Retry = Resend
policy.Cure = "verification is read-only; after resolving the failure, run verification again; do not treat the incomplete scan as a clean result"
}
if kind.Name == PlaintextConnection.Name && phase == Unsent {
policy.Cure += "; this client is configured for plaintext: check whether the endpoint requires a TLS-capable client (for blockmaster, configure SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and SW_BLOCK_TLS_CA); a closed preface alone does not prove a TLS requirement"
}
policy.Exit = projectExit(kind, policy)
return policy, nil
}
@@ -1,353 +0,0 @@
package answer_test
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"io"
"math/big"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestProducedFailurePolicyTable(t *testing.T) {
for _, row := range []struct {
name string
produce func(*testing.T) error
kind answer.Kind
unsentCode string
unsentRetry bool
unsentExit int
possibleCode string
possibleRetry bool
possibleExit int
}{
{"read-timeout", readTimeout, answer.Timeout, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
{"dns", failedDNS, answer.DNS, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
{"reset-after-request", resetConnection, answer.Connection, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
{"canceled", canceledCall, answer.Canceled, "canceled", false, 1, "outcome_unknown", true, 3},
{"eof", func(*testing.T) error { _, err := io.ReadFull(bytes.NewReader(nil), make([]byte, 1)); return err }, answer.Connection, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
} {
t.Run(row.name, func(t *testing.T) {
err := row.produce(t)
if err == nil {
t.Fatal("fixture did not produce a failure")
}
kind, ok := answer.ErrorKind(err)
if !ok || kind != row.kind {
t.Fatalf("error kind %q, listed=%t: %T: %v", kind, ok, err, err)
}
for _, want := range []struct {
phase answer.Phase
code string
retry bool
exit int
}{
{answer.Unsent, row.unsentCode, row.unsentRetry, row.unsentExit},
{answer.PossiblyAdmitted, row.possibleCode, row.possibleRetry, row.possibleExit},
} {
got, err := answer.Lookup(want.phase, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != want.code || got.Retryable != want.retry || got.Exit != want.exit || got.Cure == "" {
t.Fatalf("%s: %+v", want.phase, got)
}
if want.phase == answer.PossiblyAdmitted && got.Retry != answer.Recover {
t.Fatalf("possibly admitted must recover: %+v", got)
}
}
})
}
}
func failedDNS(t *testing.T) error {
t.Helper()
server, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
defer close(done)
buf := make([]byte, 512)
for {
n, addr, err := server.ReadFrom(buf)
if err != nil {
return
}
if n < 12 {
continue
}
buf[2], buf[3] = 0x81, 0x83 // response, recursion available, NXDOMAIN
for i := 6; i < 12; i++ {
buf[i] = 0
}
_, _ = server.WriteTo(buf[:n], addr)
}
}()
defer func() { server.Close(); <-done }()
resolver := &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "udp", server.LocalAddr().String())
}}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = resolver.LookupHost(ctx, "missing.test.")
return err
}
func resetConnection(t *testing.T) error {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
done := make(chan error, 1)
go func() {
conn, err := listener.Accept()
if err != nil {
done <- err
return
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
_, err = io.ReadFull(conn, make([]byte, 1))
if err == nil {
err = conn.(*net.TCPConn).SetLinger(0)
}
done <- err
}()
conn, err := net.DialTimeout("tcp", listener.Addr().String(), 5*time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
if _, err := conn.Write([]byte{1}); err != nil {
t.Fatal(err)
}
_, err = conn.Read(make([]byte, 1))
if serverErr := <-done; serverErr != nil {
t.Fatal(serverErr)
}
return err
}
func canceledCall(t *testing.T) error {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
cancel()
<-ctx.Done()
return ctx.Err()
}
func readTimeout(t *testing.T) error {
t.Helper()
a, b := net.Pipe()
defer a.Close()
defer b.Close()
a.SetReadDeadline(time.Now().Add(-time.Second))
_, err := a.Read(make([]byte, 1))
return err
}
func TestUnlistedFailureFailsTheTableCheck(t *testing.T) {
if kind, listed := answer.ErrorKind(errors.New("new failure without a policy")); listed {
t.Fatalf("unknown error silently became %q", kind)
}
if _, err := answer.Lookup(answer.Unsent, answer.Kind{Name: "future-kind"}); err == nil {
t.Fatal("unlisted kind accepted")
}
if _, err := answer.Lookup(answer.Phase("unknown-phase"), answer.Connection); err == nil {
t.Fatal("unlisted phase accepted")
}
}
func TestTLS13CertificateRejectionAfterWriteIsTerminal(t *testing.T) {
cert := serverCertificate(t, time.Now().Add(-time.Hour), time.Now().Add(time.Hour))
listener, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{
MinVersion: tls.VersionTLS13, MaxVersion: tls.VersionTLS13,
Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert,
})
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
release := make(chan struct{})
stopped := make(chan struct{})
t.Cleanup(func() { close(release); listener.Close(); <-stopped })
go func() {
defer close(stopped)
conn, err := listener.Accept()
if err != nil {
done <- err
return
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
done <- conn.(*tls.Conn).Handshake()
// Keep TCP open until the client consumes the TLS alert. Closing
// immediately can replace the alert with an unrelated TCP reset.
<-release
}()
pool := x509.NewCertPool()
pool.AddCert(cert.Leaf)
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", listener.Addr().String(), &tls.Config{
MinVersion: tls.VersionTLS13, MaxVersion: tls.VersionTLS13, RootCAs: pool,
})
if err != nil {
t.Fatalf("client handshake must finish before the late alert: %v", err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
if n, err := conn.Write([]byte("request")); err != nil || n != 7 {
t.Fatalf("write: %d %v", n, err)
}
_, err = conn.Read(make([]byte, 1))
if err == nil {
t.Fatal("server accepted missing client certificate")
}
if serverErr := <-done; serverErr == nil {
t.Fatal("server handshake accepted missing client certificate")
}
kind, ok := answer.ErrorKind(err)
if !ok {
t.Fatalf("unlisted post-write certificate alert: %T: %v", err, err)
}
got, err := answer.Lookup(answer.PossiblyAdmitted, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != "not_authorized" || got.Retryable || got.Retry != answer.Never || got.Exit != 5 {
t.Fatalf("certificate rejection after write: %+v", got)
}
}
func serverCertificate(t *testing.T, from, until time.Time) tls.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "local test server"},
NotBefore: from, NotAfter: until, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
leaf, err := x509.ParseCertificate(der)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}
}
func TestProducedTLSValidationPolicies(t *testing.T) {
now := time.Now()
for _, row := range []struct {
name string
from, until time.Time
trust bool
serverName string
kind answer.Kind
cure string
}{
{"unknown-authority", now.Add(-time.Hour), now.Add(time.Hour), false, "", answer.Trust, "fix the trusted CA before retrying"},
{"name-mismatch", now.Add(-time.Hour), now.Add(time.Hour), true, "wrong.invalid", answer.Name, "fix the peer address or its certificate names before retrying"},
{"expired", now.Add(-2 * time.Hour), now.Add(-time.Hour), true, "", answer.Certificate, "fix the client certificate, its key and the peer's certificate policy before retrying"},
{"not-yet-valid", now.Add(time.Hour), now.Add(2 * time.Hour), true, "", answer.Certificate, "fix the client certificate, its key and the peer's certificate policy before retrying"},
} {
t.Run(row.name, func(t *testing.T) {
cert := serverCertificate(t, row.from, row.until)
listener, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12})
if err != nil {
t.Fatal(err)
}
defer listener.Close()
done := make(chan struct{})
go func() {
defer close(done)
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
_ = conn.(*tls.Conn).Handshake()
}()
pool := x509.NewCertPool()
if row.trust {
pool.AddCert(cert.Leaf)
}
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", listener.Addr().String(), &tls.Config{RootCAs: pool, ServerName: row.serverName, MinVersion: tls.VersionTLS12})
if conn != nil {
conn.Close()
}
if err == nil {
t.Fatal("invalid server certificate accepted")
}
<-done
kind, listed := answer.ErrorKind(err)
if !listed || kind != row.kind {
t.Fatalf("kind=%q listed=%t: %T: %v", kind, listed, err, err)
}
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
got, err := answer.Lookup(phase, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != "not_authorized" || got.Retryable || got.Exit != 5 || got.Retry != answer.Never || got.Cure != row.cure {
t.Fatalf("%s: %+v", phase, got)
}
}
})
}
}
func TestRefusedConnectionHasOneUnsentPolicy(t *testing.T) {
err := refusedDial(t)
kind, ok := answer.ErrorKind(err)
if !ok {
t.Fatalf("unlisted dial error: %T: %v", err, err)
}
got, err := answer.Lookup(answer.Unsent, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != "remote_unavailable" || !got.Retryable || got.Exit != 75 || got.Retry != answer.Resend {
t.Fatalf("refused dial: %+v", got)
}
}
func TestMalformedAddressIsConfigurationBeforeDial(t *testing.T) {
conn, err := net.DialTimeout("tcp", "127.0.0.1", 5*time.Second)
if conn != nil {
conn.Close()
}
if err == nil {
t.Fatal("malformed address was accepted")
}
got, check := answer.PolicyOf(answer.Record(answer.Unsent, err), answer.Chunk)
if check != nil || got.Code != "bad_request" || got.Retryable || got.Exit != 78 {
t.Fatalf("policy=%+v check=%v error=%T: %v", got, check, err, err)
}
}
func TestUnlistedServerDomainCodeFailsTheRegistryCheck(t *testing.T) {
_, err := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Domain("unlisted_server_code", true, "retry this new server error")))
if err == nil {
t.Fatal("an unlisted server code acquired a safe-resend policy")
}
}
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more