Compare commits

...
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 fc1db38fab erasure_coding: describe the orphan cleanup's needle check as a record match
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 00:53:40 -08:00
Chris LuandClaude Opus 5.5 52f6347766 erasure_coding: age an orphan source sighting against the shard count that made it complete
The prune compared every sighting with the default 14 shards, so a volume
whose collection uses another EC ratio lost its sighting at the start of
every detection pass and its orphan source was never cleaned. Record the
expected shard count with the sighting and prune against that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 00:53:04 -08:00
Chris Lu 68b595d7ca erasure_coding: bound the orphan cleanup's index reads
Detection runs with a background context, so a server that stalled while
streaming an .idx or .ecx held up the whole scan. Give each read a
deadline; a timed-out .ecx read moves on to the next shard holder, and the
replica is kept when none answers.
2026-12-06 00:48:11 -08:00
Chris Lu 3b07ea7145 erasure_coding: keep a source replica whose needle record differs from the EC volume's
A replica that was writable again after the encode can rewrite a needle
under a key the .ecx already lists. Checking only the key let cleanup
delete that newer copy.

Account for a live replica needle only when the .ecx holds it at the same
size, or holds it deleted at the same offset, which is the encoded record
deleted on the EC volume since. A needle resized, or deleted in the .ecx
while the replica holds another record of it, keeps the replica.
2026-12-06 00:46:12 -08:00
Chris Lu 13199aaf5f erasure_coding: prune orphan source sightings in one topology walk
Pruning counted the EC shards of each remembered sighting with its own
walk of the topology, under the sightings lock. Count the shards of all
sighted volumes in a single walk, outside the lock.
2026-12-06 00:41:55 -08:00
Chris Lu 29ca7f3fe3 ec: return EC shard holders by their advertised address
LargestEcGenerationHolders returned the data node id, which drops a
holder's Address and custom gRPC port, so reading its .ecx dialed the
wrong endpoint. Build each holder address from the data node instead.
2026-12-06 00:40:39 -08:00
Chris Lu f81b0e3a49 erasure_coding: treat a source replica as orphaned only after it has sat beside the shards for a while
A volume being decoded holds a freshly built regular copy beside its
complete shard set until the shards are removed, and that copy is
read-only with every needle in the .ecx, so the orphan cleanup could
delete it before the shards go.

Detection now records when it first sees each regular replica beside a
complete shard set and forgets the sighting once that stops being true.
Cleanup deletes a replica only after minOrphanSourceCoexistence (30m) of
coexistence. The record is in memory; a restart only delays cleanup.
2026-12-06 00:05:01 -08:00
Chris Lu 2984d0622e erasure_coding: keep a source replica that holds needles the EC volume lacks
A regular replica that coexists with a complete EC shard set was deleted
whenever it was read-only. Read-only does not show the replica took no
writes after the encode, so deleting it can drop needles the EC volume
never had.

Before deleting, read the replica's .idx and the .ecx of a holder of the
counted EC generation over CopyFile, and delete only when every live needle
key in the replica is a key of the .ecx, in any state. A replica holding
other live needles is kept with a warning; a replica or holder that cannot
be read refuses the delete.
2026-12-05 23:44:55 -08:00
Chris Lu 9d069cfd08 ec: name the holders of the largest EC shard generation
CountExistingEcShardsForVolume picks the largest encode generation by shard
count; LargestEcGenerationHolders returns the nodes holding that generation,
so a caller can read files of the EC volume that was counted rather than of
a stale run. A tie names no holder.
2026-12-05 23:41:15 -08:00
d4893ebffb seaweed-block: sw-block mini starts as any user with no sudo (#13421)
* seaweed-block: sw-block mini starts as any user with no sudo

blockvolume gets --volume-lock-dir, a trial-run override of the host
volume lock directory (refused under systemd and together with the test
override). sw-block mini passes <dir>/locks to its holder, so it starts
as any user on a host without /run/sw-block. mini also runs v1 with no
scheduled snapshot (it prints the command that takes one), names
sw-block and weed by their absolute paths in every command it prints,
and after a failed start stops what it started and prints the --reuse
command for the same --dir. The release archive carries
sw-block.tmpfiles.conf for the units' lock directory. The README Quick
Start drops its sudo lines, and the v1.1.1 known issue reads fixed in
v1.1.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: mini under a systemd process tree, and no new lock-dir flag (on #13421) (#13425)

* seaweed-block: mini starts its children without INVOCATION_ID

Run from a systemd service's process tree (a CI runner unit, a terminal
server), mini passed INVOCATION_ID to blockvolume, which then refused
mini's lock directory and the run stopped at startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: mini's interrupt test expects the resume command with mini's own path

mini prints the resume command with os.Executable(), so the in-process
test saw the test binary's path, not a bare sw-block, and failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: mini uses the existing hidden lock-dir override, no new flag

--volume-lock-dir set the same field as the hidden --volume-lock-dir-test-only
with the same systemd refusal, and mini was its only caller. Keep one hidden
override so operators are not offered a documented knob that drops the
one-holder-per-volume guarantee outside systemd (containers, hand-run hosts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* docs: track mini resolve helper time bounds

* Test active release assets and relative mini paths

* Complete mini release assets and bounded process checks

* Terminate owned mini groups before checking for residue

* Accept inaccessible host locks as a non-root precondition

* Harden mini test ownership and fail-stop cleanup

* test: reproduce empty filtered mini child environment

* fix(block): complete mini startup and cleanup proof

* test(block): claim the mini test's ports host-wide

The pid-derived --port-shift put mini's 13 ports inside the handoff and
weed pair ranges the other process-level harnesses claim, unclaimed, so a
parallel CI shard could bind one of them. Pick a shift whose every port is
claimed and free, as handoffAddress does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): claim the failed-start mini launch's ports too

The second launch ran at shift+1, whose ports were neither claimed nor
checked, so a parallel shard could take one and fail the launch before
it reached the deliberate blockvolume refusal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): exercise production mini hint with quoted paths

* docs(block): explain mini local data lock scope

* fix(block): preserve mini executable and cleanup proof

* test(block): settle a leader that exits as member capture expires

stopGroup checked done only at the top of each capture iteration. A
leader that exited after that check, once the one-second window had
passed, made the next failed read fail-stop even though the group had
settled. Both capture deadlines now defer to assertStopped when done has
closed, so live residue still fail-stops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block): refuse a PATH weed found through the current directory

exec.LookPath reports exec.ErrDot for a weed found only through . in PATH.
Making that name absolute let exec.Command start it, where it refused
before; mini now refuses it and names --weed ./weed as the explicit choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block): accept a reused --weed that names the recorded executable

A relative --weed made absolute from another working directory names the
same file through a different path; mini compared the strings and refused
the retry. Compare file identity when the paths differ, so a different
executable is still refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): prove the selected weed ran in the mini startup tests

A start failure and the fixture weed's exit both return 1, and the printed
command and the record exist either way. The dying fixture weed now writes
a marker file, and both startup tests require it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): name the mini trial lock in the M4 start arrows

The table already says a mini trial's blockvolume locks the run's
--dir/locks; the diagram's start arrows still named only the host lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block): shell-quote mini's startup trace

Making --weed absolute can put a space from the working directory into the
printed command. Quote the executable and each argument with shQuote, as
mini's other printed commands already are, so the trace runs as printed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): count the mini group again when it is gone after a census

A member listed by the census can exit before the signal-0 query reports
ESRCH. On the iteration that crosses the deadline that stale count
fail-stopped a settled group. Count again when the group is absent, so only
a member still listed holds the settlement; the residue control still
fail-stops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): name the empty-census case in the mini group fail-stop

A group that still exists while the census lists no live member failed
with "live residue []". Say what it can be: a member the census missed,
or zombies their new parent does not reap. Both stay fail-stops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): match the quoted failed-start trace in the non-root mini test

The startup trace is shell-quoted now, and this test's weed path has a
quote in it, so match each binary through miniHintWord.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block): let --reuse take its recorded run past a weed found through .

The exec.ErrDot refusal ran before the record was read, so a reuse of a
recorded run failed whenever . in PATH found a ./weed, although the reuse
would use the recorded weed (or none for a walstore run). A reuse now
ignores that weed; a fresh start still refuses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): match the shell-quoted start trace in the mini unit tests

mini shell-quotes each word of its "+" trace, so a TMPDIR holding a
space prints the blockmaster, blockvolume and weed paths quoted, and
three unit tests looked for them bare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(block): pin that a normal start keeps the host volume lock

A start under systemd (INVOCATION_ID set, as every shipped unit runs)
gets no lock directory of its own, so the provider uses the host one,
and the hidden test-only override is refused, naming the host lock
directory. The test is listed under INV-WS-ONE-PROCESS-PER-HOST-001.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block): mini quotes the --weed path in its dot-in-PATH hint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 23:30:27 -08:00
99d2116564 mount: a delayed own rename moves the source only while it holds the renamed file (#13495)
* mount: a delayed own rename moves the source only while it holds the renamed file

MovePath refused an own rename event only while the table still knew the
inode the event names. A writer that renames tmp files into place displaces
each file from the target name with the next rename, and the kernel then
forgets it, so the table soon no longer knows its number. A rename event
that arrives that late, as the ones a mount replays after a takeover do,
moved the next tmp file at the old name to the target name whenever no
handle held it, between its close and its own rename. Both names then
resolved to that file, and GNU mv refused the writer's own rename ("are the
same file").

MovePath now refuses whenever the source holds another inode than the one
an own event names. An event about a hard link names none and moves as
before, and so does a peer's rename.

A file the table knows by another number, at a name it kept, is moved by
the local rename when the response arrives (handleRenameResponse passes
0), so its own event finds nothing left to move. That local apply can be
lost if the rename stream breaks after the filer committed. The source then
keeps such a file until the kernel forgets it or looks the name up again.

Tests: a delayed own rename of an earlier file the kernel has forgotten
leaves the next file at its name; it fails before this change. A peer's
rename of a file the table knows by another number still moves it; this
replaces the own-event case, which no longer holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: a delayed own rename leaves a later forgotten file at the source

With -nfsExport the table retains the path of a file the kernel forgot.
A delayed own rename of an earlier file could find the next tmp file
retained at the name, forgotten between its close and its own rename,
and move it: its retained path went to the target and the live file
there lost the name. moveForgotten now refuses the same way MovePath
does when the source maps to another inode than the event names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 23:14:13 -08:00
eb19e93f7b seaweed-block: activate the spec deletion retry invariant (#13493)
* docs(block): activate the specification retirement retry invariant

* docs(block): cite retirement retry and pacing coverage

* test(block): assert the retirement worker joins before stores close

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): cite the close-order test for INV-SPEC-DELETE-RETRY-001

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 23:02:38 -08:00
Chris LuandClaude Opus 5.5 02f4c8dfe0 mq broker test: wait for the follower's ack before retiring the leader (#13490)
TestRetiredLeaderClosesItsFollowerOnlyWhenAllIsStored retired the partition
right after an unacked publish. When the abandon closed the client
connection before gRPC's writer goroutine had sent the follow stream's
headers, the transport refused to start the stream, so the follower never
saw it and could not report it broken. A publisher only gets its ack once
the follower holds the entry, so wait for that ack as well.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:11:55 -08:00
Chris LuandClaude Opus 5.5 6820fdafea filer: clear the tombstone rebuild gate before closing it (#13488)
A lazy read woken by the closed channel could still load the old gate
pointer, which made TestRebuildRemoteDeletionTombstones_EmptyLogReleasesGate
fail on Test 32-bit.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:11:30 -08:00
687c2844c3 seaweed-block: classify operator failures by admission evidence (#13477)
* seaweed-block: unify operator answer policy with admission evidence

* seaweed-block: failover keeps exit 3 for a caller deadline before send

A failover whose caller deadline passed before the request was sent
(e.g. a master that never completes the handshake) is Recover under the
failover contract, so the command prints result=unknown and asks the
operator to read the current line. The canonical projection gave it
exit 1, which the help text reserves for a definite answer, while
v1.1.x returned 3. Add the failover legacy row next to the unsent
remote-failure one so the exit matches the printed outcome.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: document the failover caller-deadline exit

The failover help, the v1.1.x legacy table and the classification design
note name the caller deadline before send next to the unsent remote
failure as the two failover cases that keep exit 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test CA rotation with unused expired and future roots

* Allow unused CA alternatives during certificate rotation

* seaweed-block: workspace caller deadline before send is not a master refusal

A workspace RPC whose caller deadline passed (or was canceled) before it
was sent projects to exit 1, and the exit-1 branch turned it into
OutcomeRefused. force-move then printed "refused by the master (nothing
moved)" and read an admission preview, though the master never answered.
Report these as unsent; the policy exit stays 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: master-crash test expects the shared refusal presentation

Competing clean moves after the master restart are still definite
refusals (exit 1). The workspace client now keeps the gRPC status in the
error chain and appends the registry cure, so the stderr line carries the
status prefix and "resolve the server's stated precondition before
retrying".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Cover CA rotation in the Kubernetes status writer

* test: pin answer precedence and certificate-chain boundaries

* fix: preserve answer provenance through observation and recovery

* fix(block): preserve admitted outcomes and caller completion

* fix(block): preserve response precedence and refusal origin

* Preserve definite refusals and admitted operation recovery

* docs(block): forced-move unknown row covers possibly admitted failures

A proven-unsent transport failure of a forced move reports nothing sent
and exits 75, not an unknown outcome. Narrow the row and cover the unsent
path at the command (holder read refused) and in the client (move RPC).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Consolidate domain recovery selection

* Retain response and admission evidence for unusable answers

* Pin command answer entries and preserve recovery identities

* Document uncertain HTTP status outcomes completely

* Keep publication identity when status persistence also fails

* Require size-limit evidence in oversized response controls

* Preserve unresolved results and verify received operation identities

* Focus failure release notes on operator recovery

* Qualify unsent and certificate failure exit guidance

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:10:18 -08:00
Chris LuandClaude Opus 5.5 79e99e7865 terraform: add a SeaweedFS Terraform provider for S3, IAM and S3 Tables (#13478)
* terraform/provider: import the SeaweedFS Terraform provider

Import terraform-provider-seaweedfs by Luís Costa (MIT) as a nested Go
module. It manages S3 buckets and their configuration (tags, CORS,
lifecycle, versioning, policy, encryption, public access block,
ownership controls, request payment, quota), IAM users, access keys,
groups, roles, policies, attachments, OIDC providers and service
accounts, and S3 Tables buckets, namespaces, tables, policies and
maintenance configuration.

The module path and the provider source address move to seaweedfs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: build and test in-tree

Drop the standalone repo's release and git-hook instructions, credit the
original author, and list the provider in the terraform layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform: vet and unit-test the provider in CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: keep configured JSON in state after apply

Bucket, group, managed and S3 Tables policies stored the compacted JSON
sent to the server, so a policy written as a heredoc or with file()
failed apply with an inconsistent result. Keep the planned string, and
keep configured table metadata while the server's copy is semantically
equal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: read IAM policy documents without query unescaping

SeaweedFS returns user, group and managed policy documents as raw JSON
and role trust policies path-escaped. Query unescaping turned a "+" in a
resource into a space and failed on a literal "%". Return valid JSON as
is and path-unescape anything else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: keep service account settings left out of the config

description, expiration and status are optional and computed, so a
change to another attribute planned them as unknown and Update sent
empty values. SeaweedFS reads an empty Expiration as "never expires".
Carry the prior state forward for unknown values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: use the root IAM path in the full example

The user resource accepts only "/", so the example failed at user
creation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: make the smoke test and local build portable

Use the in-repo chart by default and check it before touching the
cluster, bind the port-forward to 127.0.0.1 and fail when it does not
start, build from the module directory, and point dev_overrides at the
directory holding the binary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: keep large JSON numbers exact when normalizing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: compare single statements, empty Sid and scalar conditions canonically

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: reject unknown provider settings instead of using the environment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: do not adopt a bucket owned by another identity

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: clear tags of an adopted bucket when the config sets none

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: report bucket configuration settings SeaweedFS did not store

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: treat empty and absent lists alike when comparing bucket configuration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: refuse to adopt an existing IAM user unless a retried create made it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: keep omitted role settings so a trust policy change updates in place

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: resend a service account expiration only when it changes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: keep a configured expiration that names the same instant

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: stop retrying CreateAccessKey when a failed attempt left a key

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: add new group members before removing old ones

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: reject empty or padded OIDC client IDs, thumbprints and URL

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: keep an empty OIDC list as a known empty set

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: reject an empty namespace or name for a table policy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: compare table metadata with the server's omitted required=false

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: do not replace a table when only metadata formatting differs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: keep a created S3 Tables object in state when its cleanup fails

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: reject an explicitly empty compaction strategy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: document import IDs and the object lock versioning destroy case

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: stop on any uncertain CreateAccessKey failure and name the keys it left

Only NoSuchEntity (user not visible yet) is retried. Any other failure,
including cancellation and a failure on the last attempt, lists the
user's keys once more and reports the new ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: do not adopt an IAM user found after a failed CreateUser attempt

A retry that hits EntityAlreadyExists cannot tell whether the failed
attempt or another client created the user, so ask for an import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: point BucketAlreadyExists on bucket create to terraform import

SeaweedFS answers BucketAlreadyExists both for another identity's bucket
and for the caller's own bucket that has an ACL, so the create cannot
adopt it safely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: treat omitted public access block flags as false when comparing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: restore the BucketOwner-only note on the request payment resource

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: say the smoke test runs the version the chart deploys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* terraform/provider: make the unknown endpoint test check the unknown-setting error

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:08:19 -08:00
ee547ef399 seaweed-block: stop lifecycle ancestor sync at the state filesystem boundary (#13475)
* Stop lifecycle ancestor sync at the state filesystem boundary

* docs(block): preserve existing master state when changing filesystems

* docs(block): sync the migrated master state before remounting

* docs(block): require the migrated state mount before master startup

* docs(block): keep blockmaster from starting during the state migration

A stopped but enabled blockmaster starts at the next boot, and a v1.1.0
volume unit's restart pulls it in through Wants=. Either can start it
against the source being copied or the empty state path. Disable it for
the migration, stop v1.1.0 volume units first, and enable it with the
final start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): keep an old state filesystem as the migration backup

When the old state directory is itself a mount point, moving it aside
moves only the empty mount-point directory; the stores stay on the old
filesystem. Unmount it, keep it intact as the backup, and drop its
persistent mount so it does not come back over the new one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): unmount a dedicated master state filesystem before removal

rm -rf on the mounted state path deletes its contents, then fails on the
mount root, and the && chain never removes the units, binaries or user.
Empty and unmount it first, drop its persistent mount, and remove the
blockmaster drop-in with the other unit overrides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): disable stopped v1.1.0 volume units during the state migration

A v1.1.0 volume stop only stops the unit, and the v1.1.0 unit Wants=
blockmaster, so a reboot mid-migration started the volume and with it
the disabled blockmaster before the mount guard was installed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): move aside the directory an old state mount uncovers

Unmounting an old state filesystem can expose older files that the
mount hid, so that directory is not empty; leaving it at the state path
would put stale stores beneath the new mount.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): install the units before a new install's state mount drop-in

The new-install sentence sent the operator to the mount drop-in before the
units were installed, and `systemctl edit` refuses a unit that does not
exist yet. Install the units first, then mount the state filesystem and
configure its persistent mount and drop-in, before the first start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): verify the lifecycle store only when one is configured

The shipped blockmaster.env leaves --lifecycle-store unset, so an
installation on it has only the authority store; the migration's
verification step required a lifecycle store it could not find. Check
the authority store, and the lifecycle store when --lifecycle-store is
set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): keep the sw-block removal off filesystems mounted below it

find and rm -rf both descend into a filesystem mounted below the state
or volume directories and delete its contents before failing on the
mount point. Unmount such filesystems first, and run the removal with
-xdev and --one-file-system so a missed one stops it with its data kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): refuse the sw-block removal while a bind mount sits below it

-xdev and --one-file-system compare device numbers, so a bind mount from the
same filesystem looks like a plain directory to them and the removal deletes
its source's contents. Both removal commands now list mounts below the
sw-block directories and remove nothing while one remains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): require removal of same-device nested mounts

* docs(block): scope state isolation to measured directory syncs

* docs(block): refuse mounts at removal operand roots

* docs(block): name the state filesystem where 'it' lost its antecedent

911890f385 moved the measurements in front of "Run sync after creating and
mounting it", so in the release note "it" followed "a start-time promise",
and in the manual it followed "the shared filesystem". Both now say the state
filesystem, as does the release note's "keep holders' data off" sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): match removal mount guards against resolved paths

findmnt reports a mount made through a symlinked ancestor under the
resolved path, so the literal patterns let a bind mount through the alias
pass both guards. Build the patterns from realpath -m of each directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): guard every directory the final removal deletes

The final removal also deletes the systemd drop-in directories and
/run/sw-block, but its mount check covered only the three data roots.
Include them in the same resolved-path check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): keep grants the copied stores took during a failed migration check

Step 7 starts blockmaster before the reload is verified, so reconnecting
holders can already have grants in the copied stores. The failure path now
says to keep them and correct the copy in place rather than recopy from the
retained original.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): compare removal mount guards literally

Resolved paths went into grep -E as a pattern: a path with a regex
metacharacter such as an unmatched [ made grep fail, and the leading !
turned that failure into a pass. Compare each mount against the resolved
directories with awk index(), so an awk error stops the command too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): decode escaped mount targets before removal

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:53:21 -08:00
2a7cee5dda seaweed-block: a fenced replace always reaches a publication (#13435)
* fix(master): a promotion gate's replace decision logs what the controller did with it

A replace decided by the promotion gate went to the topology controller,
which can drop it on six paths without a word. These are: a stale basis,
superseded slot facts, a boot-grace hold, no evidence on the target, an
ask that is already desired, and an unsupported topology. When a volume
then did not fail over, nothing on the master's log said why.

The controller now records, per volume, what its last intake did: the ask
it enqueued, or why it enqueued none (LastOutcome). After each tick's
submit, the master logs every replace decision with that outcome, or with
why the decisions were not submitted. Every publication is logged too.

The creation-gap process test derives its failover bound from its own
flags: one loop to the tick that ends creation, plus the freshness window
to the loss, plus one loop to the tick that reads it. It waits twice that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a replace decision is reported with its own submission's outcome, and on a binding-read failure

Review round 1:
- The tick reads the controller's outcome for each volume inside the
  intake that carried it (SubmitObservedStateOutcomes, under the
  controller's lock): the background observation host shares the
  controller and may submit before a later read.
- A workspace binding read that fails after the probe reports the tick's
  replace decisions as not submitted, with the error, before returning.
- The production-tick test waits for the publication line (bounded): the
  publisher logs it from its observer after the line is visible.
- A replace decision is identified by a flag set where it is decided, not
  by its display text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: red: a gate replace the controller keeps, and a lost Reassign held for ever

Two reds for the master's fenced replace that never publishes.

A primary only the gate rejects (its node reads an older format level,
its own flags still read reachable and ready, no loss recorded) is
replaced by a fencing round on every tick, and the controller answers
"no ask: the current primary is acceptable" on every tick.

A Reassign the publisher took and ended without publishing is lost, and
the same-ask dedupe answers "already desired" on every later intake, so
nothing enqueues it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a fenced replace always reaches the controller as a failover, and a lost Reassign is enqueued again

The gate marks the replaced primary's slot unacceptable in what it submits
on every fenced replace, not only when a loss is recorded. A primary only
the gate rejects (a node below the cluster's format level) was kept by the
controller's own acceptability predicate on every tick.

The same-ask dedupe holds a desired ask only while it is pending: queued,
or taken by the publisher and still being applied (the queue records the
ask the publisher holds until it asks for the next one). An identical ask
that is neither ended without a publication and is enqueued again, keeping
its DesiredAt so a repeatedly lost ask still reports Stuck.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ledger row for the replace-decision report

Review round 2: Part C rule 4. INV-PROMOTE-DECISION-REPORTED-001 names the
regression tests this change adds (an intake after the submission, the
binding-read failure after the probe) and their enforcing functions.
Diagnostics only: no state machine or model change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the desired-ask retry keeps its DesiredAt to Stuck; contract rows

Review round 2 (both P2s):
- TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck runs four
  take -> ended-without-publication -> re-enqueue cycles across the retry
  window: DesiredAt stays the first desire and the Stuck evidence names it.
  A retry that re-anchors DesiredAt fails it.
- docs/design/invariants.md: M2 gains the controller-ask machine between
  the promotion gate and the publisher (queued, held, lost, re-enqueued,
  Stuck; the fenced-replace handoff), with its diagram, and the rows
  INV-AUTH-DESIRED-RETRY-001 and INV-PROMOTE-REPLACE-HANDOFF-001 naming the
  regression tests. No published specification models this handoff; the
  rows say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: red: an ask published during the intake is enqueued again

The publisher can publish the desired ask and come back for its next one
between the line read an intake decides against and that intake's same-ask
dedupe. The queue then holds nothing for the volume, so the dedupe reads
the ask as lost and enqueues it again; a planned move carries no fence, so
the publisher would mint it a second time at a new epoch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: split the replace-decision ledger row under the statement limit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a desired ask published during the intake is not enqueued again

The lost-ask retry read "not pending" as "ended without a publication",
but the publisher also stops holding an ask once it has published it and
asked for the next one. When that happens between the line read the intake
decided against and the dedupe, re-read the line: the ask is lost only
while the line is still the one it was decided against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: gateNoteMu also guards gateReplaces

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: split the controller-ask contract rows to one property each

INV-AUTH-DESIRED-RETRY-001 (346 characters) and
INV-PROMOTE-REPLACE-HANDOFF-001 (459) were over the 300-character
statement limit TestInvariantStatementsAreShort enforces. Each becomes two
rows; the lost-ask row also names the published-during-intake regression
and its line re-read guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the controller-ask rows cite the promotion liveness model r6

The model now splits the intake as the code does (read the line and decide;
enqueue only if the ask is not pending and the line is unchanged). It
holds RoundProgress and QueuedMatchesLine and catches the mutants
dedupe_keeps_lost, predicate_split and nonatomic_submit. The four rows and
the M2 controller-ask section name them; the retry window and Stuck are not
modelled, and the rows say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: mark the PromoLive r6 citations as checked outside the repository (on #13435) (#13442)

seaweed-block: mark the PromoLive r6 citations as checked outside the repository

The convention says a TLA+ entry names a specification in docs/spec/,
and PromoLive r6 is not there.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: red: a queued Reassign overwrites a later publication

A controller Reassign waits in the queue until the publisher takes it. A
failback published outside the queue in that window is overwritten by
the ask decided against the older line, both for a first ask and for a
lost one enqueued again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a controller Reassign names the line it was decided against

The rebalance and failover asks carry ExpectCurrent, as the controller's
endpoint refresh already does, so the publisher refuses one whose line
moved while it waited in the queue. A refused ask ends without a
publication and the next intake decides again against the new line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: a Reassign is refused when its expected line moved

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the Reassigned row states what the expected-line check compares

Review: expectedLineMoved compares replica, epoch and addresses, so a
same-address endpoint reissue (new endpoint version or incarnation)
still matches and a queued move decided before it publishes; the
move's epoch bump fences the reissued line. The row now says so instead
of claiming every later publication.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the queued-rebalance known issue is fixed in v1.1.2

blockmaster's rebalance and failover now name the line they were decided
against and are refused when it moved: the v1.1.1 known issue and the
replicated preview's item 6 say it is fixed in v1.1.2, and the v1.1.2
notes list the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the expected-line check compares addresses only when the ask names them

Review: expectedLineMoved treats an empty expected address as a wildcard,
and an operator's failback names replica and epoch only, so an endpoint
move to other addresses does not refuse a failback. The Reassigned row
now says the address comparison applies only to asks that name them (the
controller's moves).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the v1.1.2 fix covers moves decided before the failover

Review: a rebalance decided after an operator's failover names the new
line and can still move the primary; the fixed-in note now covers only
a move decided before the failover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 19:25:12 -08:00
6ecc5c0ed0 Blockmaster: retire deleted metadata outside the serving path (#13430)
* perf(blockmaster): retire deleted metadata outside the serving path

* docs(block): cite the post-start retirement progress model

* test(block): drop the retirement layout identity probe site

The retirement pass no longer reads the record's LayoutID (the deferred
HEAD read log now goes through the pass skip summary), so the guard's
allowlist entry is stale and TestLayoutIdentityWriterAndReaders fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): keep INV-SPEC-DELETE-RETRY-001 under the statement limit

The rewritten statement was 586 characters, over the 300 that
TestInvariantStatementsAreShort allows. Keep the property in the
statement and move the visit bound to the DeleteReserved transition row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(blockmaster): keep idle retirement passes silent

The worker runs a pass every freshness window (10 s by default), and each
pass logged a start and an end line even with nothing to retire: two
lines every 10 s on every idle master. Report a pass only when it has
pending eligible records.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): align retirement traces with the current model

* test(block): pin retirement recovery and complete slow-pass evidence

* test(block): resume restore setup after filer reconnects

* fix(block): isolate retirement catalog connection

* test(block): remove unused restore retry import

* docs(block): describe retirement guards per attempt

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 18:35:25 -08:00
b807d48e2f seaweed-block: use exit 74 for lifecycle persistence faults (#13474)
* Use durability-unknown exit for lifecycle persistence faults

* Document the lifecycle durability-unknown exit in release notes

* Align lifecycle transition labels with exit 74

* seaweed-block: INV-LIFECYCLE-FAILSTOP-001 states exit 74

The lifecycle fail-stop tests now require authority.ExitDurabilityUnknown, so the
contract row names that status instead of any nonzero one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ExitDurabilityUnknown names the lifecycle fail-stop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(block): distinguish durability exit from lifecycle log reason

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 16:53:03 -08:00
github-actions[bot] 49d8243eba docs: regenerate star history chart 2026-12-06 00:33:30 +00:00
10b949183c seaweed-block: a promotion gate's replace decision logs what the controller did with it (#13428)
* fix(master): a promotion gate's replace decision logs what the controller did with it

A replace decided by the promotion gate went to the topology controller,
which can drop it on six paths without a word. These are: a stale basis,
superseded slot facts, a boot-grace hold, no evidence on the target, an
ask that is already desired, and an unsupported topology. When a volume
then did not fail over, nothing on the master's log said why.

The controller now records, per volume, what its last intake did: the ask
it enqueued, or why it enqueued none (LastOutcome). After each tick's
submit, the master logs every replace decision with that outcome, or with
why the decisions were not submitted. Every publication is logged too.

The creation-gap process test derives its failover bound from its own
flags: one loop to the tick that ends creation, plus the freshness window
to the loss, plus one loop to the tick that reads it. It waits twice that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a replace decision is reported with its own submission's outcome, and on a binding-read failure

Review round 1:
- The tick reads the controller's outcome for each volume inside the
  intake that carried it (SubmitObservedStateOutcomes, under the
  controller's lock): the background observation host shares the
  controller and may submit before a later read.
- A workspace binding read that fails after the probe reports the tick's
  replace decisions as not submitted, with the error, before returning.
- The production-tick test waits for the publication line (bounded): the
  publisher logs it from its observer after the line is visible.
- A replace decision is identified by a flag set where it is decided, not
  by its display text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ledger row for the replace-decision report

Review round 2: Part C rule 4. INV-PROMOTE-DECISION-REPORTED-001 names the
regression tests this change adds (an intake after the submission, the
binding-read failure after the probe) and their enforcing functions.
Diagnostics only: no state machine or model change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: split the replace-decision ledger row under the statement limit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: gateNoteMu also guards gateReplaces

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 14:37:46 -08:00
08aeac6b53 seaweed-block: sw-block metadata writers send the chunk condition; ChunkGuard reports it truthfully (#13471)
* seaweed-block: red: a snapshot delete is published over a page whose data was freed

Two overlapping runs of one snapshot delete write their intent pages under
the same tag. If the first run's stalled page update lands between the
second run's read of a page and its adoption (after a cleaning pass
deleted and the second run re-staged the page), the second run adopts and
publishes an intent whose page data was freed: later snapshot deletes on
the volume are refused and its cleaning stops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a snapshot delete re-reads each intent page after adopting it

Publication reads every intent page, adopts it under this run's tag, then
publishes. A stalled update from another run of the same delete can land
between that read and the adoption and put a deleted page's data reference
on the entry. Reading the page again after the adoption, before the
transition publishes, refuses that case: once this run's tag is on the
entry, no such update passes. No persisted change; a run that hits it
stays refused, and a new request id writes new pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ledger row for the intent page re-read

INV-SNAPSHOT-DELETE-ADOPT-002 names the re-read after adoption, its test
and the model row it projects (PublishedReadable; the refused run is the
residue a new request id clears).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the intent page re-read: typed refusal, twins and a store witness

Review: the re-read test now separates the guard from weaker ones. A page
that reads but holds other bytes, and a change to only the later of two
pages, are refused as well as a freed page; the refusal is a precondition
that writes nothing to HEAD, keeps the snapshot, and comes after the
adoption; the same schedule with intact bytes publishes. The test is a
consequence-level projection; a store-level witness shows the tag-only
metadata update writing a deleted object's chunk over a re-created one,
which the re-read does not depend on refusing. The ledger row names the
witness and marks the model as checked outside the repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the intent page re-read keeps its error's cause

The refusal wrapped the re-read's error with %v, so a caller deadline
that ended the re-read reached the CLI as a precondition ("page changed
during adoption", no_progress) instead of deadline_exceeded, unlike the
same deadline on the chain's first read. Wrap both errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the intent page re-read sees only data the filer already freed

The filer frees a deleted entry's chunks, and the chunks an update drops,
from its deletion queue: polled every 1.123 s, and retried after 5 min
when a volume server does not answer. A stale update that puts such a
reference on an adopted page therefore reads back intact while the
deletion is still queued, and the intent publishes over data that is
freed moments later. The intact-bytes twin publishes for that reason.
State that bound in INV-SNAPSHOT-DELETE-ADOPT-002 and at the guard
instead of "changed or vanished ... refuses the publication".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the delete intent publication row and diagram carry the re-read

Part C rule 2 moves a changed guard's Part A row and diagram with it.
The publication row now names the re-read after adoption and
INV-SNAPSHOT-DELETE-ADOPT-002, and the M9 diagram gains the transition's
idle and snap self-loops, which it lacked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: red: a stale adoption or mark lands on a re-created object

A metadata change writes the looked-up entry back, chunks included,
conditional only on its tags: paused between its lookup and its update, it
lands on an object deleted and created again with the same tags in between,
puts the deleted object's chunk on it, and a cleaner's stale mark then
deletes it. The filer's IF_CHUNKS_EQUAL condition refuses such a write.

This commit adds the plumbing and the tests, not the guard itself:
- the filer protocol subset gains WriteCondition (IF_CHUNKS_EQUAL) on
  UpdateEntryRequest; SWFS sends it through UpdateEntryIfChunks, and the
  fakes evaluate it (or drop it, as an older filer does);
- a startup probe sends a mismatched conditional update to the disposable
  probe HEAD; only a definite refusal turns the guard on for the stores the
  catalog opens. The startup log and /status/chunk (metadata_guard) name it.
The two guard tests fail here: changeMeta does not send the condition yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: metadata changes send the filer's chunk condition

With the guard on (the startup probe saw the filer enforce it), an
adoption or mark sends IF_CHUNKS_EQUAL with the looked-up entry's chunk
fids. A re-created object always has a new chunk, so a stale whole-entry
write is refused instead of putting a deleted object's chunk on it; a
cleaner's delete expects its own mark and so follows. Without the guard
the write is unchanged and the intent page re-read stays the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ledger rows for the chunk condition and its probe

INV-LAYOUT-META-CHUNKS-001 (adoption and mark under IF_CHUNKS_EQUAL) and
INV-WS-CHUNK-CONDITION-PROBE-001 (the startup probe decides it, the log
and /status/chunk name it); ADOPT-002 names the renamed store test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the chunk probe without a definite refusal leaves the guard off; fallback wording

Review: the existing failure cases stop at the HEAD gate. New cases pass
the gate and then fail only the chunk condition probe (unavailable, lost,
deadline, filer error, vanished entry, failed HEAD read): the catalog, its
stores, the startup log and the usage all stay on page_reread_only.
page_reread_only now reads as enforcement not established, not as a filer
without the condition; INV-SNAPSHOT-DELETE-ADOPT-002 cites MetaABA r2's
delayed-free counterexample, r1 kept as historical scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: sw-block metadata writers run the chunk condition probe

sw-block opens its catalog with NewBCatalog, and only DialBCatalog ran
the probe, so a snapshot-delete, retain, release or volume-delete from
the CLI sent its adoptions and marks without the chunk condition even
on a filer that enforces it. bCatalog now runs the same probe
(checkConditionalHead, via ProbeChunkGuard) for a writing command; a
failed probe only leaves the guard off. Read-only commands write
nothing. The volume-delete fakes that stall object deletes let the
probe's own cleanup through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ChunkGuard reports only a chunk condition the filer can carry

SetChunkGuard(true) on a store whose filer does not implement
ChunkConditionFiler made ChunkGuard report true while changeMeta sent a
plain UpdateEntry. Both now ask chunkCondition: the guard is on and the
filer can carry the condition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: Part A rows for the chunk condition probe and guard

Part C rule 2: the M4 table gains the startup probe's guard selection
(INV-WS-CHUNK-CONDITION-PROBE-001), and the M9 publication, clean
removal and list page retirement rows and diagram carry the chunk
condition on adoptions and marks (INV-LAYOUT-META-CHUNKS-001), whose
Part B row now names the clean removal as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: sw-block usage leaves out a metadata guard it never probed

The usage command opens a read-only catalog, which runs no chunk
condition probe, so its answer always said page_reread_only even over a
filer every writer sends the condition to. The field is now omitted
there; blockvolume's /status/chunk still reports its probed guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the sw-block chunk condition probe runs within --timeout

A writing command ran the probe on context.Background(), so after a
passing census a stalled disposable HEAD create held it for the probe's
own 10 s whatever --timeout said. The probe now runs within the command's
filer timeout; its cleanup keeps its own 5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a stale sw-block adoption is refused through the CLI catalog

The probe test proved only guard selection. This one composes it: through
the store of the catalog bCatalog opens, an adoption paused between its
lookup and its update while the object is deleted and created again is
refused with the re-created chunk intact. An unchanged object is still
adopted, and a catalog that ran no probe lets the stale write through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the M9 diagram qualifies the chunk condition by the guard

The adoption and mark labels read as always chunk-conditioned, while the
tables beside them say so only with the guard on; guard off, the page
re-read is the only check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a failed chunk guard probe turns the guard off

ProbeChunkGuard set the guard only when checkConditionalHead got as far
as the chunk probe, so a second call that failed earlier kept the first
call's guard on. It now starts from off. Its comment also says a store
takes the guard when it is opened, so the probe goes before the stores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: pingqiu <pingqiu@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 12:26:46 -08:00
Ping Qiu 7d960d01a3 seaweed-block: docs: warn about restart delays on busy state filesystems (#13472)
* docs: document blockmaster restart delays on busy filesystems

* docs: correct measured startup range and lease safety explanation

* docs: explain filesystem-wide import sync wait

* docs: clarify import sync applies per changed store

* docs: qualify restart continuity and ancestor sync exposure
2026-12-05 12:26:15 -08:00
759b7f3a36 seaweed-block: test the import syncfs selector and report each store's import mode (on #13458) (#13469)
* seaweed-block: preserve unchanged imports and batch durable publication

* seaweed-block: name the rejected entry in a startup import error

The batch import returned the bare validation error, so a bad cluster-spec
node or placement seed stopped startup without saying which entry. The
per-entry RegisterNode/ApplyPlan loop named it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: name the import path in the freshness row and registry guard

Startup now replays nodes through ImportNodes, not RegisterNode; list it
where the freshness invariant and the registry-writer guard name the
writers. Drop a doubled blank line in the operations manual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: poison a lifecycle store only on a persistence error

A node registration whose SeenAt cannot be encoded failed before any file
I/O, but RegisterNode latched the marshal error and every later mutation
returned ErrLifecycleRecoveryRequired until reopen. Latch only a
RecordPersistenceError, as the volume store already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: keep a node's SeenAt when its declaration changes

registrationLocked kept SeenAt only for an unchanged declaration. A
restart that changed a node's declared pools or address stamped the
current time, so a silent node passed the stale-observation check. A
declaration without an observation time now keeps the stored one; a new
node still gets the current time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: use the import syncfs only on filesystems that report its errors

The batch path was chosen from the kernel release alone. On overlayfs,
syncfs checks the overlay superblock's writeback errors, not the upper
file's, and on FUSE it does not send FSYNC to the daemon, so an import
could publish records whose data never became durable. Select syncfs
only when the records directory is on ext4, xfs, btrfs or tmpfs, and keep
per-file fsync elsewhere. The startup line now reports the path for the
lifecycle store, after it exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: assert the imported values before the reopen check

The import step control compared the store's snapshot with a reopen, so
an import that synced and renamed but committed the old values passed.
Check the changed and unchanged values before and after reopen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: check both views after a removal retry

present() returned record && snapshot, so a removal that cleared only one
view passed the final check. Report both and require both absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: assert the one-second fail-stop bound

The blocked-logger control checked only exit status 1 inside a four-second
child timeout, so a longer exit timer still passed. The child now reports
when it triggers the failure, and the parent requires exit within the
one-second deadline plus one second of scheduler tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: add the lifecycle machine's transition table

Every other Part A machine lists its transitions with guard, enforcing
code and Part B rows; the lifecycle record I/O machine had only its
diagram. Also name DeletePlacement and DeleteVolume beside RemoveNode in
the open gap: none of them syncs the directory after removing a record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: scope the manual's lifecycle exit policy to the stores it covers

Only the node, placement and volume stores have the fail-stop handler.
State that deletion-reservation and workspace-binding write failures
return the error without exiting, and that an uncertain binding store
needs a restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: test the import's syncfs selection through the production selector

TestSyncfsFilesystemGate checked the filesystem predicate directly and
the selector only with an unreadable directory, so a selector that took
syncfs after any successful Statfs passed. A test hook now rewrites the
filesystem type a successful Statfs reports; an import into a readable
directory reported as overlay must sync each file, and its ext4 twin
must issue one syncfs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: report import durability for the node and placement store directories

Startup probed the lifecycle root, but the node and placement imports
select syncfs from their own nodes/ and placements/ directories, so a
subdirectory on a separate mount could report one path and use the
other. Each store now reports the mode its import selects, startup
prints both, and nothing is printed without a lifecycle store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: list the syncfs selector and per-store mode tests in the ledger

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 12:25:46 -08:00
Chris LuandClaude Opus 5.5 b30537483f filer: stamp rename stream responses with the move's commit stamp (#13473)
* filer: stamp rename stream responses with the move's commit stamp

The responses carried time.Now(), but the client applies them against the
versions its earlier writes left at their log stamps. Stamps are drawn as
max(now, last+1), so on a coarse clock (Windows) they run ahead of the
wall clock, and a rename right after a flush of its source was stamped
below that flush. The mount's version fence then kept the source in its
cache: a renamed-away file still stat'ed and listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test rename responses stamp above earlier events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the Windows mount on changes to the filer's rename handler

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 12:25:02 -08:00
Chris LuandClaude Opus 5.5 d4e1ca4bed release: cut the COSI driver too, and keep the chart on its newest image (#13407)
* release: cut the COSI driver too, and keep the chart on its newest image

The release job points the chart's cosi.image at the newest COSI driver
release whose image is pullable (never backwards), so a driver release no
longer needs its own chart PR. The downstream job also dispatches the COSI
driver's prepare_release.yaml (on its main branch); that image reaches the
chart at the next release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* release: bound the COSI release and image lookups

A stalled GitHub or GHCR response now fails the lookup and keeps the
current cosi.image, instead of holding the release until the job timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* release: the COSI driver pins seaweedfs without -u

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 12:21:46 -08:00
94e6fcf61c ci: integrate the imported block module workflows (#13360)
* ci: port block workflows to the shared repository

* ci: preserve policy self-exclusion at the root path

* ci: check block documentation relative links

* ci: keep the block post-merge-review check on hosted runners

The job's own comment records that it ended in 'Set up job' with no log on
every self-hosted runner, and the source repository ran it on ubuntu-latest.
The port made it follow BLOCK_RUNNER_LABEL, so setting the variable would
bring that failure back for every labelled same-repository PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: publish block releases from hosted runners

The release job holds contents: write and packages: write and logs in to
GHCR, and builds its images with the runner's Docker. Following
BLOCK_RUNNER_LABEL put it on the persistent pool that same-repository PR
test jobs also use, whose Docker and build cache those jobs can leave
state in, and whose Docker setup is still listed as unvalidated. The
source repository published from ubuntu-latest; keep that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: refuse a block release without notes before pushing images

The notes file was first checked in the last step, after both images
(and, for the highest stable tag, :alpha) were already pushed to GHCR, so
a tag without docs/releases/vX.Y.Z.md left the images published and no
GitHub release. Check it with the tag format, before anything is pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the block documentation link check from root scripts

The Relative documentation links step called .github/scripts/doc-links-check.py
and its test inside seaweed-block/, but neither the imported module nor
upstream seaweed-block has them, so the unit suite would fail once the step
runs. Add the checker and its test under .github/block/scripts/ with the
other port scripts and point the step and its contract test there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: use the integrated root documentation link checker

* ci(block): bound runner disk use and clean job workspaces

* ci(block): pin merge evidence and refuse control changes

* ci(block): refuse workspace aliases before cleanup

* fix(block-ci): refresh test evidence before reporting readiness

* block-ci: judge known bugs with the module helper; list only live reproductions

The inline loop called an empty -run match or a skip a fix, and the list
still named #188 (closed, test passes) and #189 (test absent), so every
nightly run failed. Use known-bugs.sh and its controls, as the module
workflow does, and keep only #186: #187's reproduction passes at this
revision because values.yaml sets blockmaster.stateHostPath.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: let a release rerun replace the assets of a published tag

gh release create fails once the tag's release exists, after both image
pushes have already run again. Keep the imported helper's existing-release
path: edit the prerelease flag and upload with --clobber.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: list both sides of a move when planning unit packages

Without --no-renames a file moved out of core/storage/ shows only its new
path, so the planner skipped the package it left. The sibling scope scripts
already pass the flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: give each master push its own Block Test concurrency group

A group admits one running and one pending run; a newer push cancels the
pending one even with cancel-in-progress off, so a burst of merges left
some without a post-merge result. Key pushes on the commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: refuse only control changes the PR itself makes

The two-dot diff against current master listed every block workflow master
changed after the PR branched, so an older docs-only PR hit
workflow_review_required for good. Diff from the merge base; the gate
already requires the tested base to be current master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: check host paths in a labelled post-merge-review PR

The changed-path list holds module paths and block controls only, so a
labelled PR that also changed host files passed on its module part. Add
every other changed path with its root name; the allow list refuses it.
The spec-trace scope stays module-only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: keep the public-text adapter in step with the module checker

The root adapter carried the v1.1.0 signatures: it passed /home/<user>/
paths and run metadata, and an empty docs/spec/**/recorded-* artifact,
which the module checker refuses. Take the module's pattern and artifact
path check, keep module-relative paths, skip the root adapter's own
pattern when run from the root, and run the module self-test against the
adapter so the two cannot drift.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: match doc links per paragraph, with nested parentheses and long fences

A link whose label wraps onto the next line was never checked, a target
such as guide(v2).md was cut at its first ')', and a three-backtick line
inside a four-backtick fence closed it. Close a fence only with the same
character at least as long, keep one level of balanced parentheses in a
destination, and match links over each paragraph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: test the root wiring the active workflows use

The nested self-tests read the module's inactive test.yml, deploy/
Dockerfiles and chunkstore-scope.sh. Assert the docs-only gates in
block-test.yml, that each root image refuses every binary it builds, and
that the root classifier selects run for chunkstore, storage and durable
edits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: refuse host files in a labelled PR outside the allow list

Host paths went through the module allow list, where "*_test.go", "*.md"
and "docs/*" also match root files, so a labelled PR changing
weed/example_test.go or README.md passed. List host changes separately
and fail on any of them; the module list still runs. The port test now
runs the step in a scratch repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* block-ci: keep root block CI files clean under the public-text scan

The port test fixture spelled out a recorded-artifact path, and the unit
group test a pid literal, so the checker flagged both as added lines of
any PR that touches them. Build the fixture path from parts, name the
pid through a variable, and scan the root block CI files with the
checker's own pattern.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block-ci): normalize artifact paths from both checker entry points

* fix(block-ci): refuse ambiguous merge bases in readiness checks

* fix(block-ci): mask code spans that wrap lines before matching links

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block-ci): publish the draft a rerun of block-release finds

An interrupted first run can leave the tag with an unpublished draft.
The rerun took the existing-release branch, replaced the assets and
exited 0 with the release still a draft. Publish after the uploads,
keeping it off the repository's Latest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(block-ci): require complete matching code-span delimiters

* fix(block-ci): preserve escapes and context when masking code

* fix(block-ci): preserve original link destination bytes

* fix(block-ci): validate original destination syntax

* test(block-ci): cover masked whitespace in reference destinations

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:30:00 -08:00
cccad8d5ce seaweed-block: a stale metadata change cannot land on a re-created intent page (filer chunk condition, page re-read as fallback) (#13457)
* seaweed-block: red: a snapshot delete is published over a page whose data was freed

Two overlapping runs of one snapshot delete write their intent pages under
the same tag. If the first run's stalled page update lands between the
second run's read of a page and its adoption (after a cleaning pass
deleted and the second run re-staged the page), the second run adopts and
publishes an intent whose page data was freed: later snapshot deletes on
the volume are refused and its cleaning stops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: a snapshot delete re-reads each intent page after adopting it

Publication reads every intent page, adopts it under this run's tag, then
publishes. A stalled update from another run of the same delete can land
between that read and the adoption and put a deleted page's data reference
on the entry. Reading the page again after the adoption, before the
transition publishes, refuses that case: once this run's tag is on the
entry, no such update passes. No persisted change; a run that hits it
stays refused, and a new request id writes new pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ledger row for the intent page re-read

INV-SNAPSHOT-DELETE-ADOPT-002 names the re-read after adoption, its test
and the model row it projects (PublishedReadable; the refused run is the
residue a new request id clears).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the intent page re-read: typed refusal, twins and a store witness

Review: the re-read test now separates the guard from weaker ones. A page
that reads but holds other bytes, and a change to only the later of two
pages, are refused as well as a freed page; the refusal is a precondition
that writes nothing to HEAD, keeps the snapshot, and comes after the
adoption; the same schedule with intact bytes publishes. The test is a
consequence-level projection; a store-level witness shows the tag-only
metadata update writing a deleted object's chunk over a re-created one,
which the re-read does not depend on refusing. The ledger row names the
witness and marks the model as checked outside the repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the intent page re-read keeps its error's cause

The refusal wrapped the re-read's error with %v, so a caller deadline
that ended the re-read reached the CLI as a precondition ("page changed
during adoption", no_progress) instead of deadline_exceeded, unlike the
same deadline on the chain's first read. Wrap both errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the intent page re-read sees only data the filer already freed

The filer frees a deleted entry's chunks, and the chunks an update drops,
from its deletion queue: polled every 1.123 s, and retried after 5 min
when a volume server does not answer. A stale update that puts such a
reference on an adopted page therefore reads back intact while the
deletion is still queued, and the intent publishes over data that is
freed moments later. The intact-bytes twin publishes for that reason.
State that bound in INV-SNAPSHOT-DELETE-ADOPT-002 and at the guard
instead of "changed or vanished ... refuses the publication".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the delete intent publication row and diagram carry the re-read

Part C rule 2 moves a changed guard's Part A row and diagram with it.
The publication row now names the re-read after adoption and
INV-SNAPSHOT-DELETE-ADOPT-002, and the M9 diagram gains the transition's
idle and snap self-loops, which it lacked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: red: a stale adoption or mark lands on a re-created object

A metadata change writes the looked-up entry back, chunks included,
conditional only on its tags: paused between its lookup and its update, it
lands on an object deleted and created again with the same tags in between,
puts the deleted object's chunk on it, and a cleaner's stale mark then
deletes it. The filer's IF_CHUNKS_EQUAL condition refuses such a write.

This commit adds the plumbing and the tests, not the guard itself:
- the filer protocol subset gains WriteCondition (IF_CHUNKS_EQUAL) on
  UpdateEntryRequest; SWFS sends it through UpdateEntryIfChunks, and the
  fakes evaluate it (or drop it, as an older filer does);
- a startup probe sends a mismatched conditional update to the disposable
  probe HEAD; only a definite refusal turns the guard on for the stores the
  catalog opens. The startup log and /status/chunk (metadata_guard) name it.
The two guard tests fail here: changeMeta does not send the condition yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: metadata changes send the filer's chunk condition

With the guard on (the startup probe saw the filer enforce it), an
adoption or mark sends IF_CHUNKS_EQUAL with the looked-up entry's chunk
fids. A re-created object always has a new chunk, so a stale whole-entry
write is refused instead of putting a deleted object's chunk on it; a
cleaner's delete expects its own mark and so follows. Without the guard
the write is unchanged and the intent page re-read stays the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: ledger rows for the chunk condition and its probe

INV-LAYOUT-META-CHUNKS-001 (adoption and mark under IF_CHUNKS_EQUAL) and
INV-WS-CHUNK-CONDITION-PROBE-001 (the startup probe decides it, the log
and /status/chunk name it); ADOPT-002 names the renamed store test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: the chunk probe without a definite refusal leaves the guard off; fallback wording

Review: the existing failure cases stop at the HEAD gate. New cases pass
the gate and then fail only the chunk condition probe (unavailable, lost,
deadline, filer error, vanished entry, failed HEAD read): the catalog, its
stores, the startup log and the usage all stay on page_reread_only.
page_reread_only now reads as enforcement not established, not as a filer
without the condition; INV-SNAPSHOT-DELETE-ADOPT-002 cites MetaABA r2's
delayed-free counterexample, r1 kept as historical scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 11:29:24 -08:00
de239e7404 seaweed-block: preserve unchanged master imports and batch durability (#13458)
* seaweed-block: preserve unchanged imports and batch durable publication

* seaweed-block: name the rejected entry in a startup import error

The batch import returned the bare validation error, so a bad cluster-spec
node or placement seed stopped startup without saying which entry. The
per-entry RegisterNode/ApplyPlan loop named it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: name the import path in the freshness row and registry guard

Startup now replays nodes through ImportNodes, not RegisterNode; list it
where the freshness invariant and the registry-writer guard name the
writers. Drop a doubled blank line in the operations manual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: poison a lifecycle store only on a persistence error

A node registration whose SeenAt cannot be encoded failed before any file
I/O, but RegisterNode latched the marshal error and every later mutation
returned ErrLifecycleRecoveryRequired until reopen. Latch only a
RecordPersistenceError, as the volume store already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: keep a node's SeenAt when its declaration changes

registrationLocked kept SeenAt only for an unchanged declaration. A
restart that changed a node's declared pools or address stamped the
current time, so a silent node passed the stale-observation check. A
declaration without an observation time now keeps the stored one; a new
node still gets the current time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: use the import syncfs only on filesystems that report its errors

The batch path was chosen from the kernel release alone. On overlayfs,
syncfs checks the overlay superblock's writeback errors, not the upper
file's, and on FUSE it does not send FSYNC to the daemon, so an import
could publish records whose data never became durable. Select syncfs
only when the records directory is on ext4, xfs, btrfs or tmpfs, and keep
per-file fsync elsewhere. The startup line now reports the path for the
lifecycle store, after it exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: assert the imported values before the reopen check

The import step control compared the store's snapshot with a reopen, so
an import that synced and renamed but committed the old values passed.
Check the changed and unchanged values before and after reopen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: check both views after a removal retry

present() returned record && snapshot, so a removal that cleared only one
view passed the final check. Report both and require both absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: assert the one-second fail-stop bound

The blocked-logger control checked only exit status 1 inside a four-second
child timeout, so a longer exit timer still passed. The child now reports
when it triggers the failure, and the parent requires exit within the
one-second deadline plus one second of scheduler tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: add the lifecycle machine's transition table

Every other Part A machine lists its transitions with guard, enforcing
code and Part B rows; the lifecycle record I/O machine had only its
diagram. Also name DeletePlacement and DeleteVolume beside RemoveNode in
the open gap: none of them syncs the directory after removing a record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: scope the manual's lifecycle exit policy to the stores it covers

Only the node, placement and volume stores have the fail-stop handler.
State that deletion-reservation and workspace-binding write failures
return the error without exiting, and that an uncertain binding store
needs a restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:28:54 -08:00
1fe0429d05 docs: add non-root PVC deployment example (#13463)
* docs: add non-root PVC deployment example

Signed-off-by: NginxL <8777777+NginxL@users.noreply.github.com>

* helm: move the non-root example's data and logs off hostPath

kubelet does not apply fsGroup to hostPath, and master, volume and filer
data and logs default to hostPath, so the example alone left root-owned
mounts the uid 1000 process cannot write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: NginxL <8777777+NginxL@users.noreply.github.com>
Co-authored-by: NginxL <8777777+NginxL@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:28:12 -08:00
0a30cfada1 seaweed-block: docs: point the snapshot delete known issue's heading and the manual at the interrupted delete (#13462)
* seaweed-block: docs: exiting or a no_progress answer does not stop a snapshot delete run

Review: a write the earlier run already sent to the filer can still land
after a no_progress answer, a timeout or the command's exit, so the note
asks for the earlier run's final answer before a resume, says waiting for
the filer only lowers the risk, and says resumes the volume host starts on
its own are outside the operator's control in v1.1.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: v1.1.1 has no reliable workaround for an overlapping snapshot delete

Review: waiting for a final answer or for the filer is not a workaround an
operator can rely on. The note now says there is none in v1.1.1, that not
re-running or resuming an interrupted snapshot delete by hand reduces
exposure, and that the fix is planned for v1.1.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the volume host retries only its own delete, for up to 30 seconds

Review: the host never picks up a delete the command started; a delete
sent to the host is retried by the host itself for up to 30 seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the outstanding filer write, not a live run, is what makes a resume unsafe

Review: the trigger described an earlier run that is still alive, so an
operator could read a terminated process as ruling it out. The trigger
and the advice now name the filer write the earlier run already sent,
which can land after a no_progress answer, a timeout or the command's
exit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: a paused run has not sent its page update yet

Review: the trigger now names both cases of an update that has not landed:
the earlier run's process paused before sending it, or the update sent
and not yet applied by the filer. Only in the second case need the
earlier run not still be running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: name the failures the volume host retries

Review: the host retries its own delete for up to 30 seconds only while an
attempt answers layout_busy or head_conflict; any other failure, including
no_progress, is returned at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: title the snapshot delete known issue by the interrupted delete

The Trigger now says the earlier run need not still be running, so a
heading about a delete that is still running suggests an exited command
is safe to resume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: point the manual's snapshot-delete retry advice at the v1.1.1 known issue

The typed-error table told operators to keep retrying a snapshot delete
with the same request id after no_progress or layout_busy. The v1.1.1
notes now say resuming an interrupted delete is not safe, and a volume
that hit the issue answers layout_busy for good.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: give snapshot and snapshot-delete separate no_progress actions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: do not repeat an interrupted snapshot-delete after an unknown outcome

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the host's last snapshot delete retry can start after 30 seconds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: pingqiu <pingqiu@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:23:05 -08:00
Chris LuandClaude Opus 5.5 e4321a3e89 master: write a recovered TopologyId into the hashicorp raft log on leadership (#13467)
* master: write a recovered TopologyId into the hashicorp raft log on leadership

A hashicorp raft leader whose TopologyId came from the max_volume_id mirror
never wrote it to the raft log, so followers kept an empty id. The next leader
then minted a new one, and the first master crashed with split-brain on its
next restart when it read the old id back from its mirror. Sync the id after
the barrier, as the goraft path already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: test that followers learn a leader's mirrored TopologyId

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: call the TopologyId sync directly in its test

The leader loop never returns, so running it leaked a goroutine per test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: retry the barrier before syncing the TopologyId

A failed barrier skipped the sync for the whole leader term, leaving
followers without the id the next leader needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: test that the next leader keeps a mirrored TopologyId

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:22:02 -08:00
Chris LuandClaude Opus 5.5 4a4651007a seaweed-block: the observation host reads the store clock under its lock (#13455)
* seaweed-block: the observation host reads the store clock under its lock

The rebuild loop read the store's clock source without the store lock
while SetNowForTest swaps it under that lock, so a test that swaps the
clock on a running host raced the loop arming its deadline timer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: test swapping the clock on a running observation host

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:19:58 -08:00
Chris LuandClaude Opus 5.5 ff9c9ca007 filer: keep the metadata log a shutdown could not flush and restore it on start (#13470)
* filer: keep the metadata log a shutdown could not flush and restore it on start

When the shutdown flush budget runs out, the events still in the log
buffer were dropped, so a peer or subscriber that had not read them yet
never got them. Keep the unflushed records in the filer store instead,
in parts small enough for stores that cap value size, and put them back
into the log buffer with their original timestamps when the store is
set, before the filer serves. The buffer then flushes them as usual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep the unflushed metadata log per address on a shared store

Filers sharing one store would overwrite and replay each other's kept
log under one key. Once a peer has been seen on this filer's store, key
the kept log by the filer's address; a store of its own keeps the
address-free key, so a filer restarting under a new address (a new pod
IP) still finds what it left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: drop the restored metadata log copy only once a flush covers it

The kept copy was deleted as soon as its records were back in the log
buffer, so a crash before the next flush lost them again. Keep it until
a flush covers the last restored entry, and let the next shutdown's
kept log replace it, since that shutdown's flushes and kept tail then
hold every restored record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: do not count the subscription to itself as a peer on the store

Every filer follows its own log, and that subscription always reports
the filer's own store, so every store looked shared and the kept log
was keyed by address even on an embedded store, where a new pod IP
then missed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:19:09 -08:00
6e91dc97b8 worker: reject a task at capacity without blocking the manager loop (#13453)
* worker: reject a task at capacity without blocking the manager loop

* worker: gofmt the capacity test and trim its comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: report a task rejected at capacity back to the admin

The admin marks a task assigned before sending it, has no assignment
timeout, and only reclaims tasks from workers whose heartbeats stop.
A worker that rejects a task at capacity keeps heartbeating, so the
task stayed assigned to it and blocked further work on its volume.
Report the rejection as a failure so the admin reschedules it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:15:01 -08:00
Yip LeoandClaude Opus 5.5 2637ff09c5 mount: answer ESTALE for an inode whose name the filer no longer has (#13447)
* mount: answer ESTALE for an inode whose name the filer no longer has

A job that writes a status file through a tmp name retried a failed
round by opening the tmp name again. The kernel still resolved the name
to the failed round's inode, and the mount still mapped it, but the filer
had no such file: the open failed with ENOENT although it asked for
O_CREAT, and the job exited.

lookupEntry already logged such a tracked name ("filer ErrNotFound for
tracked path"). It now drops the name from the inode table when no open
handle and no pending flush owns the inode, and requests for the inode by
node id answer ESTALE (maybeReadEntry, AcquireHandle), as
pathlessInodeStatus already does for an inode without a name. The kernel
looks the name up again and, for an open with O_CREAT, creates the file,
which gets an inode of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drop a vanished name only while it maps to the inode looked up

lookupEntry read the name's inode after the filer answered. A rename
that gave the name to another inode while the request was in flight, a
directory say, had that inode's name dropped on the strength of an answer
about the name as it was. The inode is now taken before the request, and
the name is dropped only while it still maps to that one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep the vanished name mapped; ESTALE alone has the kernel look again

Dropping the name raced with an open of the same inode: a handle
published between the check for one and the removal, or just after it,
had no name left, so a peer's rename of that name no longer reached it
and its flush went to the old name. pathlessInodeStatus answers ESTALE
for any inode the kernel still holds, so maybeReadEntry and AcquireHandle
get the kernel to look the name up again without the table losing it.
A file created at the name meanwhile reuses the inode number, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:13:51 -08:00
Chris LuandClaude Opus 5.5 68f99dc114 seaweed-block: docs: no read of the line confirms a failover stays (#13449)
* seaweed-block: docs: read the line again before relying on a failover

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: a read of the line is a snapshot, not a confirmation

The queued rebalance applies when blockmaster's assignment queue reaches
it, so a second read can come before it as well. Say that no read
confirms the primary stays, and that the guest is started again on the
new primary if it moves later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:13:09 -08:00
16a6a70a08 mount: keep delayed events about an earlier file off the next file at its name (#13445)
* mount: keep delayed events about an earlier file off the next file at its name

A writer that publishes a status file by writing NNNN.json.tmp-PID,
fsyncing it and renaming it over NNNN.json recreates the tmp name every
few seconds. Without -writebackCache a mount applies its own events from
the metadata subscription after the local apply (the events of a rename
stream carry the response time, not the log position, so the dedup ring
does not match them), and their invalidations reach whatever file sits at
the path by then. With about 200 such writers in one directory, two of
these events failed a round of the next file:

- the rename of round k moved round k+1's tmp file to NNNN.json. Its
  handle published under that name and was refused (EIO); the retry wrote
  into NNNN.json, and the rename of the tmp name failed with ENOENT.
- the create of round k became the entry and base of round k+1's file,
  and every flush of the round was refused (EIO).

Both hit the new file in the window in which Create had put its handle in
the map but not yet marked it an unpublished create: it did that
afterwards, holding no lock, so the event found a clean handle with a base
and took it for a published file. On master the second event, which
carries the inode number the creating mount stored, makes the handle give
the name up instead (replacedByAnotherFile) and marks it deleted: its
writes are never published, and close returns success.

- AcquireCreatedFileHandle puts a new handle in the state the create
  leaves it in before the handle is in the map. An existing handle, whose
  inode number outlived an earlier file, is installed under its lock.
- An invalidation carries which file its event is about: the inode number
  the file's creator stored and its creation time (hard links excluded).
  An open handle ignores a rename of another file, and any other event
  about an earlier one (another number, created before the file held). A
  later file at the name still reaches the handle.
- MovePath takes the inode number a rename event reports. A source that
  maps to another inode, while the table knows the renamed file by that
  number, holds another file and stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: judge another file by its creation time only for this mount's own events

A peer's file can take the name with an older creation time: renamed in
from another name, or created on a host whose clock runs behind. Dropping
its event left the name on the replaced file's inode. A peer's rename can
also name a file by a stored inode number another file here holds, when two
mounts made the same path within one second, and was refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: a delete of another file at the name leaves the open handle alone

Like a rename, a delete names the file it removed. A peer's delayed delete
of an earlier file at the name, logged by a filer other than the one behind
the handle's version, marked the held file deleted and dropped its writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 11:12:29 -08:00
120d786818 mount: update a directory's times once, without retries (#13443)
* mount: update a directory's times once, without retries

touchDirMtimeCtime sent its UpdateEntry through saveEntry's retries, 1, 2
and 4 s apart. Every create, link, rename and removal in the directory
waits for that update and ignores how it went. In a directory many
writers share, the update of its entry conflicts in the filer store with
theirs (TiKV reports "write conflict"), and the call waited out the
backoffs: in one directory about 200 jobs shared, three mounts logged 3646
such retries in two hours, each holding a create or a rename for up to
about 7 s.

saveEntry takes a bestEffort flag: such an update is tried once and its
failure logged at V(1). touchDirMtimeCtime sets it; setattr and the xattr
calls keep their retries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: shorten the directory times comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 11:11:43 -08:00
Chris LuandClaude Opus 5.5 373eb29e59 s3tables: table policy, maintenance and tag operations refuse a view (#13439)
* s3tables: table policy and maintenance reads refuse views and unfinished records

readTableMetadataAttr only checked that the table-metadata attribute was
present, so the table policy and maintenance operations accepted a view or
a record a create or rename had not finished writing. Route it through
tableMetadata, the check GetTable and the other table operations use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: tagging a table ARN refuses a view or unfinished record

TagResource, ListTagsForResource and UntagResource read the
table-metadata attribute directly for a table ARN, so a view or a record
still being created or renamed under that name took and answered tags as
a table. Read a table target through readTableMetadataAttr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: table record writes refuse a view

requireTableCreatedAt compared only the creation time, so a view holding
the name at write time was not rejected on its own. Refuse it, so table
policy, tag and maintenance writes never land on a view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: test table operations against a view and an unfinished record

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:10:42 -08:00
ca5c659d9b s3api: answer a malformed SSE-KMS key ID with KMS.NotFoundException (#13433)
* s3api: answer a malformed SSE-KMS key ID with KMS.NotFoundException

PutObject and UploadPart with an SSE-KMS key ID that has spaces or control
characters returned 500 InternalError, which clients retry. CopyObject
already answers the same ID with KMS.NotFoundException, the error a KMS
gives for a key ID it can't parse. PUT and UploadPart now do too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: refuse a malformed SSE-KMS key ID at CreateMultipartUpload

AWS answers a key ID it can't use at CreateMultipartUpload. A malformed
one was accepted there, so every UploadPart of the upload failed instead.
ValidateRequestEncryption now answers it with KMS.NotFoundException,
which also covers PutObject before a bucket auto-create.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 11:09:21 -08:00
Tiago PosseandClaude Opus 5.5 90aae21e6b kms/local: read key_material from ${ENV} references (#13434)
A local KMS key's key_material can now be written as ${NAME}, so the key
can come from a Kubernetes Secret, or any secret store that hands it to the
process as an environment variable, instead of sitting in the config file.
This works in the S3 JSON config and in filer.toml.

A reference to a variable that is unset or empty, or one that isn't written
as ${NAME}, fails the load with an error that leaves the reference and the
material out. The expansion is the one static S3 credentials already use,
moved to weed/util so both share it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:08:32 -08:00
adb07ee3ce s3api: answer GET with the KMS error when the KMS won't decrypt (#13432)
* s3api: answer GET with the KMS error when the KMS won't decrypt

A GET of an SSE-KMS object whose key the KMS no longer holds, or refuses
to use, returned 500 InternalError, which clients retry. PUT and
CopyObject already answer the same KMS errors with their S3 codes, like
KMS.NotFoundException. GET now does too, on the full, per-chunk key,
range and directory content paths. The per-chunk key path wrapped the
decrypt error with %v, which dropped the KMS error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kms: report a provider outage as an internal failure

GET now answers a KMS error with its S3 code, so a provider outage that
the converters tagged as a key error turned a retryable read into a 400
that blames the key. OpenBao and Azure 5xx answers and GCP Unavailable
or DeadlineExceeded matched the "not found" or "unavailable" substrings,
and AWS KeyUnavailableException is retryable per the KMS API. All of
these now map to KMSInternalException, which S3 answers as 500.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 11:08:03 -08:00
04a93bd7dd s3api: support UploadPartCopy from SSE-KMS sources (#13431)
* s3api: support UploadPartCopy from SSE-KMS sources

UploadPartCopy from an SSE-KMS source returned 501, so `aws s3 cp`, `mv`
and `sync` failed for SSE-KMS objects over the multipart threshold. The
re-encrypting copy path now decrypts the source the way GET does: chunks
with their own SSE-KMS metadata decrypt with it, and a source without any
uses the entry-level key. A ranged copy starts at the chunk holding the
range, so copying the tail of a large object doesn't fetch and decrypt
everything before it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: start an SSE-S3 part copy at the chunk holding the range

A ranged UploadPartCopy from a per-chunk SSE-S3 source fetched and
decrypted every chunk before the range and discarded it, so copying a
large SSE-S3 object part by part read the source quadratically. Start at
the chunk holding the range start, as the SSE-KMS path does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: answer UploadPartCopy with the KMS error when the source won't decrypt

A part copy from an SSE-KMS source whose key the KMS no longer holds,
has disabled or refuses answered 500 InternalError, whether the refusal
came while opening the source or mid-stream. Answer it with the KMS
error, as PUT and CopyObject do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: refuse an SSE-KMS part copy over chunks of another SSE type

A source mixing SSE-KMS chunks with SSE-S3 or SSE-C ones would stream
the foreign chunks through as plaintext, copying their ciphertext into
the destination part. Refuse the copy before fetching anything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-05 11:07:31 -08:00
Chris LuandClaude Opus 5.5 6c0859349b s3api, iam: match policy variable values literally (#13413)
* wildcard: match expanded variable text literally

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: match policy variable values literally in resource, action and principal patterns

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: match policy variable values literally in Like conditions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iam: match policy variable values literally in role policies

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:02:14 -08:00
Chris LuandClaude Opus 5.5 ba4370183a s3api: keep the derived aws:s3:arn in a CopyObject SSE-KMS context (#13451)
* s3api: keep the derived aws:s3:arn in a CopyObject SSE-KMS context

ParseSSEKMSCopyHeaders took the destination context header verbatim, so
a copy could carry no aws:s3:arn or name another bucket's ARN, and a KMS
key policy conditioned on aws:s3:arn could be met that way. Without the
header, the default context was built from the filer path, which made
the ARN arn:aws:s3:::b//buckets/b/key.

Build the destination context the way PutObject does: the derived ARN
of the destination object plus the client's extra keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: reject a CopyObject SSE-KMS context the KMS would refuse

The copy validation only checked that the context header was non-empty,
so a malformed context failed later, after the copy had started, with
InternalError. Apply the same checks PutObject applies and answer
InvalidRequest up front.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: answer InvalidRequest when the destination KMS context is refused

The derived aws:s3:arn of a destination key with a control character
fails the KMS context checks, and the copy answered InternalError.
Return it as a CopyValidationError and let the copy error mapping honor
that type, so the client gets InvalidRequest as PutObject does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 11:01:40 -08:00
Ping QiuandClaude Opus 5.5 20854b3a66 seaweed-block: docs: a no_progress answer or exiting does not stop a snapshot delete run (#13459)
* seaweed-block: docs: exiting or a no_progress answer does not stop a snapshot delete run

Review: a write the earlier run already sent to the filer can still land
after a no_progress answer, a timeout or the command's exit, so the note
asks for the earlier run's final answer before a resume, says waiting for
the filer only lowers the risk, and says resumes the volume host starts on
its own are outside the operator's control in v1.1.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: v1.1.1 has no reliable workaround for an overlapping snapshot delete

Review: waiting for a final answer or for the filer is not a workaround an
operator can rely on. The note now says there is none in v1.1.1, that not
re-running or resuming an interrupted snapshot delete by hand reduces
exposure, and that the fix is planned for v1.1.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the volume host retries only its own delete, for up to 30 seconds

Review: the host never picks up a delete the command started; a delete
sent to the host is retried by the host itself for up to 30 seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the outstanding filer write, not a live run, is what makes a resume unsafe

Review: the trigger described an earlier run that is still alive, so an
operator could read a terminated process as ruling it out. The trigger
and the advice now name the filer write the earlier run already sent,
which can land after a no_progress answer, a timeout or the command's
exit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: a paused run has not sent its page update yet

Review: the trigger now names both cases of an update that has not landed:
the earlier run's process paused before sending it, or the update sent
and not yet applied by the filer. Only in the second case need the
earlier run not still be running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: name the failures the volume host retries

Review: the host retries its own delete for up to 30 seconds only while an
attempt answers layout_busy or head_conflict; any other failure, including
no_progress, is returned at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the host retry applies only on a version-1 HEAD

Review: a version-0 HEAD takes v1.0's name-only delete, which the host
does not retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the issue needs a version-1 HEAD

Review: a version-0 or absent HEAD takes v1.0's name-only delete, which
stages no intent pages, so it is not affected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: 30 seconds is the host's retry threshold, not a bound

Review: the host checks its deadline before each wait, so its last attempt
can start and run past 30 seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: the host retries for about 30 seconds

Review ruling: the plainer, strictly weaker wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:01:26 -08:00
Ping QiuandClaude Opus 5.5 ab25506331 seaweed-block: docs: known issue: resuming a snapshot delete that is still running (#13454)
* seaweed-block: docs: known issue: resuming a snapshot delete that is still running

Two overlapping runs of one snapshot delete, with a cleaning pass between,
can record the delete with an intent page whose data was freed; every
later snapshot delete on the volume is then refused (queue_full) and the
volume's cleaning stops. The v1.1.1 notes give the trigger, the effect,
what to do, and that v1.1.1 has no recovery for an affected volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: docs: a stuck snapshot delete answers layout_busy, not queue_full

Review: with the intent stuck, a later snapshot delete stops at the
catalog's pre-check and answers layout_busy, a retryable answer that does
not clear on retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 07:08:10 -08:00
Ping QiuandClaude Opus 5.5 acc22a4270 seaweed-block: docs: known issue: a queued rebalance can undo an operator failover (replicated preview) (#13444)
Docs only. Includes the maintainer's #13446 (the commands to check and redo the primary after a failover).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:56:07 -08:00
Ping QiuandClaude Opus 5.5 e17e30b4aa seaweed-block: keep only the runner scenarios this tree uses (#13418)
Removes lab-only runner scenarios and suites from seaweed-block/, keeps the scenarios this tree's CI uses with environment placeholders, and guards every artifact-root use before any cleanup. Includes the maintainer's follow-ups from #13419 and #13423.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:20:55 -08:00
Ping QiuandClaude Opus 5.5 f92efd4437 seaweed-block: docs: re-point stale model action citations (#13437)
Docs only: model action citations in the trace table, invariants and time bounds point at the current DeleteRetire actions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 02:39:57 -08:00
Ping QiuandClaude Opus 5.5 fe2d016c41 seaweed-block: docs: cite PlainSealReplay for the seal-replay invariant; drop removed scoped-GC prose (#13429)
Docs only (seaweed-block design invariants and trace).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 00:01:19 -08:00
Nguyễn Lộc PhúcandClaude Opus 5.5 cf3eda7e57 perf(s3vectors): read the bucket once per authorization (#13427)
s3vectors: read the bucket once per authorization

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:54:04 -08:00
Chris LuandClaude Opus 5.5 68d56d8ff8 mini: admit volume servers started against the embedded master (#13416)
* mini: admit volume servers started against the embedded master

A single-master weed mini pinned its embedded volume server as the only
admitted reporter, so the master refused every extra weed volume pointed
at it. Use the expected-reporter release a single-master weed server
already uses: the embedded server's first clean inventory still collapses
the post-mint allocation hold, and other volume servers are admitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mini: test that a single-master mini does not pin its volume server

Move the reporter choice into setMiniExpectedReporter so a command-level
test can check it: the embedded volume server is the expected reporter
in single-master mode, never the only admitted one, and a multi-master
rerun clears it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:52:25 -08:00
Chris LuandClaude Opus 5.5 39f568f614 wdclient: use a master only after it answers as the leader (#13415)
* wdclient: use a master only after it answers as the leader

Since the announce gate was added, every client marked a master as
current as soon as its KeepConnected stream opened, before the master
answered. When that master is a follower, its answer only names the
leader, but calls made in the meantime go to the follower, and
leader-only ones (lock, volume.list, collection.*, ...) fail with
"raft.Server: Not current leader". A weed shell fed a script runs its
first command right in that window.

Keep the early hand-out for clients behind an announce gate (a starting
filer), and let other clients wait for the first answer as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: start the follower check only after it got the registration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: hand out a master early only while the announce gate is closed

A filer that already announced and reconnects after a failover kept the
early hand-out, so calls waiting in GetMaster went to a follower that
had not answered yet and failed with "Not current leader".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: stop handing out a master once it redirects to the leader

A filer that reached a follower behind its announce gate kept that
follower as the current master after the redirect, until the leader
answered, so leader-only calls in that window failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: keep the redirecting master when canceled before the leader answers

Clearing the current master on a redirect left it empty if the client
was canceled before the hinted leader answered, so a later GetMaster
without a deadline blocked forever.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:50:46 -08:00
Chris LuandClaude Opus 5.5 4a58968439 Cut per-request CPU on filer gRPC tokens and S3 header scrubbing (#13414)
* security: reuse the filer admin token signed in the same second

An admin token's only claim is its expiry, which jwt truncates to the
second, so every token signed with one key in one second is the same.
Each filer gRPC call from a client with a filer signing key signed a new
one: about 4us and 40 allocations per call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: add a filer token without copying the outgoing metadata

WithFilerToken copied the outgoing metadata twice on every filer gRPC
call to check for an authorization the caller set and to add its own.
Look the key up in place and append the token instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: canonicalize the scrubbed internal header names once

scrubInternalHeaders runs on every request, and Header.Del
canonicalized each of its nine names again; five are not in canonical
form, so each request allocated their canonical forms anew. Delete the
precomputed canonical keys instead: 775ns and 5 allocations down to
120ns and none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: benchmark the token path with a fixed key, test the reuse itself

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: keep GenJwtForFilerAdmin's doc comment on the function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:50:18 -08:00
f9febc7ee5 filer: a store's listing expires an entry as the filer does (#13399)
* filer: a store's listing expires an entry as the filer does

The tikv and redis stores remove the entries a listing finds expired,
and judged that by Crtime + TtlSec. For an S3 object the filer counts
from mtime instead, and an overwrite keeps Crtime while it moves mtime.
So a listing deleted an S3 object that was overwritten within its TTL:
a GET still returned it, and after one ListObjects it was gone. The same
check dropped a directory carrying a TTL from an older build, stranding
what it holds, which the filer's lookups refuse to do.

These stores, and the rocksdb compaction filter, now use Entry.ExpiresAt.

* filer: trim the store expiry comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:49:33 -08:00
Chris LuandClaude Opus 5.5 0ce344d559 redis3: remove names left by expired entries, fix skip-list split and listing (#13408)
* redis3: a listing removes the names of expired entries from the directory

A listing skipped the name of an entry whose value redis expired and left
it in the directory's list for good, so the list key also outlived the
directory's last entry. For an entry past its TTL it ran ZREM on the list,
which in this store is a string key, so that name stayed as well.

Both now leave the directory's list once the walk ends, under the list's
lock and only when the master holds no value for the name, so an insert
that wrote its value first keeps its name. An entry past its TTL is
deleted only if it still holds the bytes the listing judged expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: a lookup removes what a redis-expired entry left behind

The filer asks a store that implements ExpiredLeftoverStore to clean up
after a lookup that missed under a TTL rule, as the redis and redis2
stores do. redis3 now removes the name from the directory's list too,
checking the list first so a miss on a name never written costs only
the reads of the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: key the upper half of a split node by its smallest name

When a full node splits and the new name goes to the lower half, the
upper half was keyed by that new name, which it does not hold. Deleting
the name then matched the upper node by key and removed nothing, so the
name stayed listed, and listings from a start name could come back out
of order. Only a directory list of more than one node splits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: list from a start name inside an earlier node

A listing from a start name that falls inside a node, rather than on a
node's key, began at the next node and skipped the rest of the node that
holds the start name. A paged directory listing resumes from the last
name it returned, so every page after the first lost names once the
directory's list had more than one node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: check a lookup's name against the one node that would hold it

The check that a missed name is still listed walked the list from that
name, which fetched the rest of its node, up to a million names, to look
at the first. It now asks that node for the one name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: stop a list change on a failed read of a node's smallest name

NodeMin returned "" for a failed read as for an empty node. Deleting a
node's key name then dropped the whole node with the names it still
held, and a split keyed a node by the empty name. It now returns the
error, and both stop on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: an update that finds its value expired lists the name again

UpdateEntry only wrote the value. When redis expired the value between
the caller's read and the update, a lookup or listing could take the
name out of the directory in between, and the update left a live entry
that no listing shows. The value is now written by a script that also
reports whether one was stored, and an update that found none adds the
name back, under the list's lock as an insert does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: read a split node's new smallest name before changing the list

A split that failed this read had already unlinked the node and saved
the new lower node, and returned before the list header was saved, so
the names of the node were no longer reachable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: return a failed read of a node's membership

A failed read passed for a missing name: a lookup's leftover check
reported no leftover, and a delete returned success with the name still
listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: take back an update's value when listing its name fails

An update that found its value expired wrote it again and then listed
the name. If listing the name failed, the value stayed, so a retry found
it stored and returned without listing the name. The value is now
deleted again if it is still the one written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: stop a list change on a failed count of a node's names

NodeSize and NodeInnerPosition read 0 from a failed ZLEXCOUNT. A delete
then took the node for emptied and dropped it with the names it still
held, and a split added the name in a node of its own ahead of the names
before it, so listings came back out of order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: read the directory list from the masters when changing it

With useReadOnly or routeByLatency, redis_cluster3 sent the reads of a
list change to replicas. A lagging replica could miss a node's other
names, and the delete that read it dropped the node with them; a listing
or a lookup that removes an expired name now runs that delete too.

List changes and the EXISTS checks before them go through a second
cluster client that reads from the masters, created only when the store
reads from replicas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: list an expired update's name before writing its value back

An update that wrote back an expired value and then failed to list the
name deleted the value again when it still held the update's bytes. A
concurrent write of the same bytes was deleted with it, and a failed
delete or a concurrent update of other bytes left the value without its
name for a retry that no longer looked.

The update now writes with SET XX. When the value is missing, it lists
the name and then writes the value under the list's lock, which the
removal of an expired name also takes. A failure leaves the value
missing, so the retry lists the name again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: list an updated name again when the list lock's lease ran out

An update that finds its value missing lists the name and writes the value
under the list lock. If the write outlasts the lock's lease, another filer's
cleanup can take the lock, see no value and remove the name before the value
lands, leaving a value no listing shows. Unlock now reports a lost lease, and
the name is then listed again under a new lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: list a cleaned-up name again when the list lock's lease ran out

A listing or lookup removes a name after finding its value missing under the
list lock. If the removal outlasts the lock's lease, an update can list the
name and write its value in between, and the removal then takes out the name
of a live value. Unlock now reports a lost lease, and the name is then listed
again; if its value is still missing, the next listing removes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: list the name again when a change fails after the lease ran out

A cleanup that lost its lease could remove the name from its node and then
fail on the next read. The failed change skipped the lease check, so the
name of a value written in between stayed removed. The lease is now checked
whenever a write or check ran under the lock, and the change's own error is
kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: retry listing a name again after the lease ran out

Listing the name again after a lost lease is the only thing that lists a
value another filer wrote in between. A transient failure of that one
attempt left the value unlisted, so it is now retried.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis3: list an inserted name again when the list lock's lease ran out

An insert's list change made after the lease ran out could be overwritten by
another filer's change based on an earlier read of the list, dropping the
name while its value stays stored. Every insertChild now ends with the lease
check, so the name is listed again, as an update's already was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:47:15 -08:00
Ping QiuandClaude Opus 5.5 63c50b8cfe seaweed-block: v1.1.1 notes list five more known issues (#13420)
Matches the published v1.1.1 release page. Docs only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 21:29:56 -08:00
Ping QiuandClaude Opus 5.5 ad5d7338bc seaweed-block: neutral names and no lab notes in the public tree (#13417)
Replaces internal identifiers in seaweed-block/ docs, specs and comments with neutral wording. Wording only: no code behaviour, test assertion or spec meaning changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 20:14:44 -08:00
720 changed files with 35784 additions and 37274 deletions

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
# Block CI in the shared repository
The block module stays in `seaweed-block/` with its own `go.mod` and unchanged module path. Root `block-*.yml` workflows run shell commands there; action inputs name the subdirectory explicitly. The imported subtree is unchanged: every port file lives under root `.github/`. Existing module scripts and data remain base-owned inputs; only the Git adapters, unit-group coordinator and relative documentation link check live in root `.github/block/scripts/`. The existing nested workflows are inert because GitHub only discovers root workflows.
PR and master-push workflows select `seaweed-block/**` and their root block workflow files. All jobs default to `ubuntu-latest`. Set the repository variable `BLOCK_RUNNER_LABEL` only after the corresponding dedicated runner label is registered and available; same-repository/trusted events of the test, spec-trace and known-bugs jobs then use that label. The post-merge-review paths check and the release always run hosted. Fork PRs always use GitHub-hosted runners. GitHub Actions cannot fall back after requesting an unavailable label, so an unset variable is the explicit safe default. Unset it again if the registered pool is withdrawn. Runner discovery would require runner-management API access that the read-only workflow token does not have; no new credential is requested.
The unit check keeps `go test (linux)` and `process-level tests (real binaries)` under workflow `Block Test`. Module-relative diff/blob adapters preserve the block model map and allow list. Root block workflow/Docker recipe changes still pass the block trace/public-text checks; unrelated host code is excluded. No imported module paths or product formats change.
## Read-only merge checks
From a trusted current master checkout, run inside the module:
```sh
python3 ../.github/block/scripts/safe-merge-check.py 123
```
It requires an open, ready, mergeable PR, the latest successful `Block Test` run at its exact head against current master, both successful named jobs, and the base-owned spec-trace/public-text checks. It rechecks head/base after inspection. It never merges or comments. The manager performs the authorized squash merge with `--match-head-commit`.
For a batch, preserve its builder's exact order in a local manifest:
```json
{"base":"BASE_SHA","batch_pr":123,"head":"BATCH_SHA","prs":[{"number":121,"head":"HEAD_121","evidence":"evidence/121.txt"},{"number":122,"head":"HEAD_122","evidence":"evidence/122.txt"}]}
```
```sh
python3 ../.github/block/scripts/safe-merge-check.py --batch batch.json
# After the authorized ordered squash merges, compare master with the printed tested tree:
python3 ../.github/block/scripts/safe-merge-check.py --verify-tree TESTED_TREE_SHA
```
The manifest and acceptance files are operator inputs from the batch builder, never files supplied by a PR. Batch readiness refuses a moved master/head, changed order or missing evidence and runs each member's base-owned local checks. Building/pushing a batch and merging remain manager operations.
## Releases
Only `seaweed-block/vX.Y.Z[-pre]` tags publish. Image tags omit the namespace and retain the existing block/CSI image names. Only block stable tags decide whether `alpha` advances. Root-context Docker recipes preserve Git revision metadata while building the nested module and retain the lab-binary refusal.
The Linux amd64 tarball contains `blockmaster`, `blockvolume` and `sw-block` copied from the exact published image digest, with `SHA256SUMS`. The GitHub release uses the namespaced tag and does not replace the shared repository's latest release. Release notes must already exist in the module. No tag, image or release is created by preparation or local tests.
## Move-window checks
This revision targets the v1.1.0 import branch. Do not edit files under `seaweed-block/` here; development stays in its source repository until the v1.1.1 history update. The root unit-group helpers project the qualified #1001 source; refresh root CI adapters against the corresponding source when that later import arrives. Run the normal Test workflow, base-owned checks and a controlled nonproduction release rehearsal before enabling real publication. Validate organization runner registration, Docker, GHCR package access, and existing repository rulesets/check names. Existing host workflows are unchanged; their broad Go filters may also select a block-only PR. The first import needs its own reviewed bootstrap evidence: a pre-import master has no block scripts, so neither the new pull_request_target gates nor the base-owned local checker can qualify that initial import from an absent base module. Once the import/port is on the trusted base, subsequent block PRs use these checks.
+408
View File
@@ -0,0 +1,408 @@
"""Local-only checks for the nested-module CI port; no Go suites or publishing."""
from pathlib import Path
import copy
import importlib.util
import os
import shutil
import re
import subprocess
import tempfile
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
class PortTests(unittest.TestCase):
def test_relative_documentation_links_are_checked(self):
text = (ROOT / ".github/workflows/block-test.yml").read_text()
marker = " - name: Relative documentation links\n"
self.assertEqual(text.count(marker), 1)
step = text.split(marker, 1)[1].split("\n - name:", 1)[0]
self.assertIn("if: matrix.suite == 'unit'", step)
self.assertIn("python3 -B ../.github/block/scripts/doc-links-check-test.py", step)
self.assertIn("python3 -I ../.github/block/scripts/doc-links-check.py .", step)
self.assertNotIn("continue-on-error", step)
self.assertNotIn("|| true", step)
def test_root_workflows_use_module_run_and_action_paths(self):
for name in ("test", "spec-trace", "post-merge-review", "known-bugs"):
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
self.assertIn("working-directory: seaweed-block", text)
if name == "post-merge-review":
self.assertIn("runs-on: ubuntu-latest", text)
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
else:
self.assertIn("vars.BLOCK_RUNNER_LABEL", text)
self.assertIn("|| 'ubuntu-latest'", text)
if "go-version-file:" in text: self.assertIn("go-version-file: seaweed-block/go.mod", text)
if name != "known-bugs":
self.assertIn('"seaweed-block/**"', text)
self.assertIn('".github/workflows/block-*.yml"', text)
test = (ROOT / ".github/workflows/block-test.yml").read_text()
self.assertIn("- master", test)
self.assertIn("git diff --relative --name-only --no-renames HEAD^1 HEAD -- .", test)
self.assertIn("go test (linux)", test)
self.assertIn("process-level tests (real binaries)", test)
scope = test.split(" - name: Docs-only pull request\n", 1)[1].split("\n", 2)[1]
self.assertEqual(scope.strip(), "if: matrix.suite == 'process' && github.event_name == 'pull_request'")
self.assertEqual(test.count("if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'"), 5)
self.assertNotRegex(test, r"if: matrix\.suite == 'process'\s*\n")
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
self.assertIn("working-directory: ${{ github.workspace }}", post)
def test_labelled_post_merge_review_refuses_host_files(self):
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
step = post.split(" - name: Check changed paths\n", 1)[1].split(" run: |\n", 1)[1].split("\n\n - name:", 1)[0]
script = "\n".join(line[10:] for line in step.splitlines())
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); module = root / "seaweed-block"
def git(*args): return subprocess.check_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false")
for name in ("post-merge-review-check.sh", "post-merge-review-allow.txt"):
source = ROOT / "seaweed-block/.github" / ("scripts/" + name if name.endswith(".sh") else name)
target = module / ".github" / ("scripts/" + name if name.endswith(".sh") else name)
target.parent.mkdir(parents=True, exist_ok=True); target.write_bytes(source.read_bytes())
(module / ".github/scripts/post-merge-review-check-test.sh").write_text("exit 0\n")
(root / ".github/block/scripts").mkdir(parents=True)
(root / ".github/block/scripts/post-merge-review-changed.sh").write_bytes((HERE / "post-merge-review-changed.sh").read_bytes())
git("add", "."); git("commit", "-m", "base"); git("remote", "add", "origin", str(root))
base = git("rev-parse", "HEAD").decode().strip()
def check(*paths):
git("reset", "-q", "--hard", base)
for path in paths: (root / path).parent.mkdir(parents=True, exist_ok=True); (root / path).write_text("changed\n")
git("add", "--", *paths); git("commit", "-m", "change")
git("update-ref", "refs/pull/1/head", "HEAD")
env = dict(os.environ, BASE=base, HEAD=git("rev-parse", "HEAD").decode().strip(), PR="1")
return subprocess.run(["bash", "-eo", "pipefail", "-c", script], cwd=module, env=env, capture_output=True, timeout=30)
self.assertEqual(check("seaweed-block/docs/a.md").returncode, 0)
for host in ("weed/example_test.go", "README.md", "docs/a.md"):
out = check("seaweed-block/docs/a.md", host)
self.assertEqual(out.returncode, 1, out)
self.assertEqual([l for l in out.stdout.splitlines() if l.startswith(b"DENY")], [b"DENY host " + host.encode() + b" (outside seaweed-block)"])
def test_known_bugs_use_the_module_verdict_helper(self):
text = (ROOT / ".github/workflows/block-known-bugs.yml").read_text()
self.assertIn("bash .github/scripts/known-bugs-test.sh", text)
self.assertIn("bash .github/scripts/known-bugs.sh <<'LIST'", text)
rows = text.split("<<'LIST'\n", 1)[1].split("\n LIST", 1)[0].split("\n")
self.assertTrue(rows)
for row in rows:
issue, pkg, test = row.split()
sources = (ROOT / "seaweed-block" / pkg).glob("*_test.go")
self.assertTrue(any("func " + test + "(" in s.read_text() for s in sources), row)
def test_release_tag_namespace_and_artifact_identity(self):
text = (ROOT / ".github/workflows/block-release.yml").read_text()
self.assertIn('"seaweed-block/v*"', text)
self.assertNotIn('tags:\n - "v*"', text)
self.assertIn("git tag -l 'seaweed-block/v*'", text)
self.assertIn('docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"', text)
self.assertIn('gh release create "$GITHUB_REF_NAME"', text)
self.assertIn('--latest=false', text)
self.assertIn('gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber', text)
publish = 'gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false'
self.assertLess(text.index("--clobber"), text.index(publish))
self.assertIn("runs-on: ubuntu-latest", text)
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
self.assertIn('sw-block-${version}-linux-amd64.tar.gz', text)
self.assertNotIn("go build", text)
self.assertLess(text.index("refusing to publish: release notes"), text.index("docker/build-push-action"))
for name in ("sw-block", "blockcsi"):
recipe = (ROOT / (".github/dockerfiles/block-" + name + ".Dockerfile")).read_text()
self.assertIn("WORKDIR /src/seaweed-block", recipe)
self.assertIn("COPY . /src", recipe)
self.assertGreater(recipe.index("RUN bash scripts/refuse-lab-binary.sh"), recipe.rindex("go build"))
built = re.findall(r"go build -o (\S+)", recipe)
refused = re.search(r"^RUN bash scripts/refuse-lab-binary\.sh (.+)$", recipe, re.M).group(1).split()
self.assertTrue(built)
self.assertEqual(sorted(built), sorted(refused))
def test_nested_git_paths_and_blobs_stay_module_relative(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); module = root / "seaweed-block"; module.mkdir()
def git(*args):
return subprocess.check_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master")
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
git("config", "commit.gpgsign", "false")
(module / "core").mkdir(); (module / "docs").mkdir()
code = module / "core/a.go"; code.write_text("package a\nconst N=1\n")
(root / "host.go").write_text("package host\n")
git("add", "."); git("commit", "-m", "base")
base = git("rev-parse", "HEAD").decode().strip()
(module / "docs/a.md").write_text("documentation\n")
git("add", "."); git("commit", "-m", "docs")
docs = git("rev-parse", "HEAD").decode().strip()
def run(name, *args):
return subprocess.check_output(["bash", str(HERE / name), *args], cwd=module, timeout=20)
self.assertEqual(run("docs-only-scope.sh", base, docs), b"docs_only 1\n")
code.write_text("package a\nconst N=2\n")
(root / "host.go").write_text("package host\nconst Changed=true\n")
git("add", "."); git("commit", "-m", "code")
head = git("rev-parse", "HEAD").decode().strip()
self.assertEqual(run("post-merge-review-changed.sh", docs, head), b"M\0core/a.go\0")
self.assertTrue(run("chunkstore-scope.sh", docs, head).startswith(b"skip 1"))
for durable in ("core/frontend/chunkstore/c.go", "core/storage/s.go", "core/frontend/durable/d.go"):
(module / durable).parent.mkdir(parents=True, exist_ok=True); (module / durable).write_text("package x\n")
git("add", "."); git("commit", "-m", "durable")
self.assertEqual(run("chunkstore-scope.sh", head, "HEAD"), b"run 1 " + durable.encode() + b"\n")
git("reset", "-q", "--hard", head)
blobs = root / "blobs"
run("changed-go-blobs.sh", docs, head, str(blobs))
self.assertEqual((blobs / "old/core/a.go").read_text(), "package a\nconst N=1\n")
self.assertEqual((blobs / "new/core/a.go").read_text(), "package a\nconst N=2\n")
self.assertFalse((blobs / "new/host.go").exists())
control = root / ".github/workflows/block-test.yml"
control.parent.mkdir(parents=True)
control.write_text("name: Block Test\n")
git("add", ".github"); git("commit", "-m", "CI control")
control_head = git("rev-parse", "HEAD").decode().strip()
self.assertIn(b".github/workflows/block-test.yml\0", run("post-merge-review-changed.sh", docs, control_head))
self.assertTrue(run("docs-only-scope.sh", base, control_head).startswith(b"run "))
checker = root / ".github/block/scripts/public-text-check.sh"
checker.parent.mkdir(parents=True)
checker.write_text("pattern='disk" + "station'\n")
git("add", ".github"); git("commit", "-m", "checker pattern")
pattern_head = git("rev-parse", "HEAD").decode().strip()
title, body = root / "title.txt", root / "body.txt"
title.write_text("CI scope"); body.write_text("Checker patterns")
self.assertEqual(run("public-text-check.sh", control_head, pattern_head, str(title), str(body)), b"public-text: clean\n")
from_root = subprocess.check_output(["bash", str(HERE / "public-text-check.sh"), control_head, pattern_head, str(title), str(body)], cwd=root, timeout=20)
self.assertEqual(from_root, b"public-text: clean\n")
artifact_path = "docs/spec/" + "recorded-example.txt"
artifact = module / artifact_path
artifact.parent.mkdir(parents=True); artifact.write_text("")
git("add", "."); git("commit", "-m", "artifact")
artifact_head = git("rev-parse", "HEAD").decode().strip()
command = ["bash", str(HERE / "public-text-check.sh"), pattern_head, artifact_head, str(title), str(body)]
for cwd in (root, module):
leak = subprocess.run(command, cwd=cwd, capture_output=True, timeout=20)
self.assertEqual(leak.returncode, 1, (cwd, leak.stdout, leak.stderr))
self.assertIn(b"artifact path: " + artifact_path.encode(), leak.stdout)
git("rm", str(artifact.relative_to(root))); git("commit", "-m", "remove artifact")
deleted = git("rev-parse", "HEAD").decode().strip()
removal = ["bash", str(HERE / "public-text-check.sh"), artifact_head, deleted, str(title), str(body)]
for cwd in (root, module):
result = subprocess.run(removal, cwd=cwd, capture_output=True, timeout=20)
self.assertEqual((result.returncode, result.stdout), (0, b"public-text: clean\n"), result.stderr)
fakebin = root / "fakebin"; fakebin.mkdir()
fakegit = fakebin / "git"
fakegit.write_text("#!/bin/sh\nfor arg; do\n if [ \"$arg\" = --diff-filter=ACMT ]; then\n printf 'docs/spec/partial.txt\\0'\n exit 23\n fi\ndone\nexec \"$PUBLIC_TEXT_REAL_GIT\" \"$@\"\n")
fakegit.chmod(0o755)
env = dict(os.environ, PUBLIC_TEXT_REAL_GIT=shutil.which("git"), PATH=str(fakebin) + os.pathsep + os.environ["PATH"])
for cwd in (root, module):
result = subprocess.run(removal, cwd=cwd, env=env, capture_output=True, timeout=20)
self.assertEqual(result.returncode, 2, (cwd, result.stdout, result.stderr))
self.assertIn(b"cannot enumerate artifact paths", result.stderr)
self.assertNotIn(b"public-text: clean", result.stdout)
def test_public_text_adapter_passes_the_module_self_test(self):
module = ROOT / "seaweed-block/.github/scripts"
pattern = lambda path: [l for l in path.read_text().splitlines() if l.startswith("pat=")]
self.assertEqual(pattern(HERE / "public-text-check.sh"), pattern(module / "public-text-check.sh"))
with tempfile.TemporaryDirectory() as tmp:
for source in (module / "public-text-check-test.sh", HERE / "public-text-check.sh"):
(Path(tmp) / source.name).write_bytes(source.read_bytes())
subprocess.run(["bash", str(Path(tmp) / "public-text-check-test.sh")], check=True, capture_output=True, timeout=60)
def test_root_block_ci_files_pass_the_public_text_scan(self):
pat = next(l for l in (HERE / "public-text-check.sh").read_text().splitlines() if l.startswith("pat='"))[5:-1]
files = [p for p in (ROOT / ".github/block").rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name != "public-text-check.sh"]
files += sorted((ROOT / ".github/workflows").glob("block-*.yml")) + sorted((ROOT / ".github/dockerfiles").glob("block-*.Dockerfile"))
hits = subprocess.run(["grep", "-E", "-i", "-n", "-H", "--", pat, *map(str, files)], capture_output=True, timeout=20)
self.assertEqual(hits.returncode, 1, hits.stdout.decode() + hits.stderr.decode())
def test_safe_merge_refuses_wrong_head_base_and_incomplete_jobs(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
run = {"path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
check.validate(pr, run, jobs, "base")
for key, value in (("head_sha", "other"), ("conclusion", "cancelled"), ("name", "Other Test")):
wrong = copy.deepcopy(run); wrong[key] = value
with self.assertRaises(ValueError): check.validate(pr, wrong, jobs, "base")
with self.assertRaises(ValueError): check.validate(pr, run, jobs, "moved")
with self.assertRaises(ValueError): check.validate(pr, run, jobs[:1], "base")
failed = copy.deepcopy(jobs); failed[0]["conclusion"] = "failure"
with self.assertRaises(ValueError): check.validate(pr, run, failed, "base")
def test_same_named_workflow_cannot_satisfy_the_gate(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
run = {"id": 1, "created_at": "1", "path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
duplicate = dict(run, id=2, created_at="2", path=".github/workflows/pretend.yml")
with self.assertRaises(ValueError): check.validate(pr, duplicate, jobs, "base")
missing = dict(run); del missing["path"]
with self.assertRaises(ValueError): check.validate(pr, missing, jobs, "base")
import json
with patch.object(check, "api", return_value={"workflow_runs": [run, duplicate]}), patch.object(check.subprocess, "check_output", return_value=json.dumps([{"jobs": jobs}]).encode()):
self.assertEqual(check.successful_run(pr, "base")["id"], 1)
with patch.object(check, "api", return_value={"workflow_runs": [duplicate]}):
with self.assertRaises(ValueError): check.successful_run(pr, "base")
def test_control_path_changes_need_independent_workflow_review(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
real_output = subprocess.check_output
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
def git(*args): return real_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false")
(root / "code.go").write_text("package example")
git("add", "."); git("commit", "-m", "base")
base = git("rev-parse", "HEAD").decode().strip()
for name in (".github/workflows/pretend.yml", ".github/block/scripts/check.py", ".github/dockerfiles/block-image.Dockerfile", "seaweed-block/.github/scripts/record-go-test.sh"):
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text("control")
git("add", "."); git("commit", "-m", "control")
added = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(base, added)
git("rm", name); git("commit", "-m", "remove")
removed = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(added, removed)
(root / "code.go").write_text("package example\nconst N=2")
git("add", "."); git("commit", "-m", "code")
head = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
check.check_control_paths(base, head)
git("checkout", "-q", "-b", "master-later", base)
(root / ".github/workflows").mkdir(parents=True, exist_ok=True)
(root / ".github/workflows/block-test.yml").write_text("master control")
git("add", "."); git("commit", "-m", "master control")
master = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
check.check_control_paths(master, head)
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(head, master)
with patch.object(check, "check_control_paths", side_effect=ValueError("workflow_review_required")), patch.object(check.subprocess, "check_output", side_effect=["base", "head"]), patch.object(check.subprocess, "run") as run:
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.local_checks({"number": 1, "body": "body", "title": "title", "head": {"sha": "head"}}, "base")
self.assertEqual(run.call_count, 1) # fetch only; no checker certification
def test_control_path_diff_refuses_multiple_merge_bases(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
real_output = subprocess.check_output
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
def git(*args): return real_output(["git", *args], cwd=root, timeout=15).decode().strip()
git("init", "-b", "master")
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
git("config", "commit.gpgsign", "false")
git("commit", "--allow-empty", "-m", "base"); base = git("rev-parse", "HEAD")
git("checkout", "-q", "-b", "left")
(root / "left.txt").write_text("left")
git("add", "."); git("commit", "-m", "left"); left = git("rev-parse", "HEAD")
git("checkout", "-q", "-b", "right", base)
(root / "right.txt").write_text("right")
git("add", "."); git("commit", "-m", "right"); right = git("rev-parse", "HEAD")
git("checkout", "-q", "left"); git("merge", "--no-ff", right, "-m", "left merge")
left_merge = git("rev-parse", "HEAD")
git("checkout", "-q", "right"); git("merge", "--no-ff", left, "-m", "right merge")
right_merge = git("rev-parse", "HEAD")
self.assertEqual(set(git("merge-base", "--all", left_merge, right_merge).splitlines()), {left, right})
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "ambiguous_merge_base"):
check.check_control_paths(left_merge, right_merge)
check.check_control_paths(left, left_merge)
def test_fork_runner_guard_is_required_not_only_the_fallback(self):
expected = "${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}"
for name in ("test", "spec-trace", "known-bugs"):
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
lines = [line.strip() for line in text.splitlines() if line.strip().startswith("runs-on:")]
self.assertEqual(lines, ["runs-on: " + expected])
def test_rerun_during_local_checks_cannot_report_ready(self):
import contextlib
import io
import json
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
def pr(number):
return {"number": number, "state": "open", "draft": False, "mergeable": True,
"base": {"ref": "master"}, "head": {"sha": str(number)}}
with tempfile.TemporaryDirectory() as tmp:
evidence = Path(tmp) / "acceptance"; evidence.write_text("accepted")
members = [pr(1), pr(2)]
manifest = {"base": "base", "head": "3", "batch_pr": 3,
"prs": [{"number": n, "head": str(n), "evidence": str(evidence)} for n in (1, 2)]}
path = Path(tmp) / "batch.json"; path.write_text(json.dumps(manifest))
for batch in (False, True):
for outcome in ("in_progress", "failed_run", "failed_job", "new_run", "success"):
with self.subTest(batch=batch, outcome=outcome):
changed = False
observations = []
number = 3 if batch else 1
def api(endpoint):
if endpoint == "git/ref/heads/master": return {"object": {"sha": "base"}}
if endpoint.startswith("pulls/"): return pr(int(endpoint.split("/")[-1]))
if endpoint == "git/commits/3": return {"tree": {"sha": "tree"}}
observations.append(("run", changed))
run = {"id": 10, "run_attempt": 2 if changed else 1, "created_at": "1",
"path": check.WORKFLOW_PATH, "name": "Block Test", "head_sha": str(number),
"status": "completed", "conclusion": "success",
"pull_requests": [{"number": number, "base": {"sha": "base"}}]}
if changed and outcome in ("in_progress", "new_run"):
run.update(status="in_progress", conclusion=None)
if outcome == "new_run": run.update(id=11, created_at="2")
if changed and outcome == "failed_run": run["conclusion"] = "failure"
return {"workflow_runs": [run]}
def jobs(*args, **kwargs):
observations.append(("jobs", changed))
result = [{"name": name, "conclusion": "success"} for name in check.JOBS]
if changed and outcome == "failed_job": result[0]["conclusion"] = "failure"
return json.dumps([{"jobs": result}]).encode()
def local(*args):
nonlocal changed
changed = True
output = io.StringIO()
with patch.object(check, "api", side_effect=api), patch.object(check.subprocess, "check_output", side_effect=jobs), patch.object(check, "fetch_review_head"), patch.object(check, "local_checks", side_effect=local), contextlib.redirect_stdout(output):
if outcome == "success":
check.main(["--batch", str(path)] if batch else ["1"])
else:
with self.assertRaises(ValueError):
check.main(["--batch", str(path)] if batch else ["1"])
if outcome == "success":
self.assertTrue(json.loads(output.getvalue())["ready"])
else:
self.assertNotIn('"ready": true', output.getvalue())
self.assertIn(("run", True), observations)
self.assertIn(("jobs", True), observations)
def test_batch_preserves_pinned_base_heads_order_and_evidence(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
with tempfile.TemporaryDirectory() as tmp:
evidence = Path(tmp) / "acceptance"; evidence.write_text("review accepted")
prs = [{"number": n, "state": "open", "draft": False, "base": {"ref": "master"}, "head": {"sha": str(n)}} for n in (1, 2)]
manifest = {"base": "base", "head": "batch", "prs": [{"number": p["number"], "head": p["head"]["sha"], "evidence": str(evidence)} for p in prs]}
check.validate_batch(manifest, prs, "base")
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "moved")
with self.assertRaises(ValueError): check.validate_batch(manifest, list(reversed(prs)), "base")
wrong = copy.deepcopy(prs); wrong[0]["head"]["sha"] = "new"
with self.assertRaises(ValueError): check.validate_batch(manifest, wrong, "base")
batch_manifest = dict(manifest, batch_pr=3)
manifest_path = Path(tmp) / "batch.json"
import json
manifest_path.write_text(json.dumps(batch_manifest))
replies = {"git/ref/heads/master": {"object": {"sha": "base"}}, "pulls/1": prs[0], "pulls/2": prs[1], "pulls/3": {"number": 3, "head": {"sha": "batch"}}}
with patch.object(check, "api", side_effect=lambda path: replies[path]), patch.object(check, "fetch_review_head", side_effect=ValueError("workflow_review_required")) as fetch, patch.object(check, "successful_run") as run:
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.main(["--batch", str(manifest_path)])
fetch.assert_called_once_with(replies["pulls/3"], "base")
run.assert_not_called()
evidence.write_text("")
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base")
if __name__ == "__main__": unittest.main()
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Writes the old and new blob of each changed non-test Go file between two
# commits under <out>/old/<path> and <out>/new/<path>, for the spec trace's
# kind DOCS (objects only; nothing from the PR is built or run).
#
# usage: changed-go-blobs.sh <merge-base> <head> <out>
#
# The paths come from the PR's tree objects, which git does not check when it
# prints a diff. A path that is absolute or has an empty, '.' or '..'
# component would write outside <out>, so it is refused before anything is
# written (exit 1).
set -euo pipefail
mb=$1 head=$2 out=$3
prefix=$(git rev-parse --show-prefix)
mkdir -p "$out"
git diff --relative --name-only --no-renames -z "$mb" "$head" -- "*.go" ":(exclude)*_test.go" >"$out/.paths"
while IFS= read -r -d "" p; do
case "/$p/" in
*//* | */./* | */../*)
printf 'changed-go-blobs: refusing path %q\n' "$p" >&2
exit 1
;;
esac
done <"$out/.paths"
while IFS= read -r -d "" p; do
mkdir -p "$out/old/$(dirname "$p")" "$out/new/$(dirname "$p")"
git show "$mb:$prefix$p" >"$out/old/$p" 2>/dev/null || rm -f "$out/old/$p"
git show "$head:$prefix$p" >"$out/new/$p" 2>/dev/null || rm -f "$out/new/$p"
done <"$out/.paths"
rm -f "$out/.paths"
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Run only from a trusted base checkout; HEAD code is inspected as Git objects.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
base=${1:?BASE}; head=${2:?HEAD}; body=${3:?BODY}; title=${4:?TITLE}
[ "$(git rev-parse HEAD)" = "$(git rev-parse "$base")" ] || { echo "refusing: checkout is not the trusted base" >&2; exit 2; }
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mb=$(git merge-base "$base" "$head")
bash "$here/post-merge-review-changed.sh" "$mb" "$head" >"$work/changed.bin"
bash "$here/changed-go-blobs.sh" "$mb" "$head" "$work/blobs"
bash .github/scripts/spec-trace-check.sh "$body" "$work/blobs" .github/model-code-trace.tsv <"$work/changed.bin"
bash "$here/public-text-check.sh" "$mb" "$head" "$title" "$body"
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# chunkstore-scope.sh BASE HEAD: decides whether a pull request runs the
# real-filer integration tests. It prints one line:
# "run N FIRST" at least one of the N changed files is under
# core/frontend/chunkstore/, core/storage/ or
# core/frontend/durable/ (FIRST is one)
# "skip N" none of the N changed files is
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
# and the caller then runs the tests: an error never selects skip.
#
# The NUL-delimited list is written to a file first and read to its end, so
# no pipe can stop early and leave a writer's error looking like an answer.
set -euo pipefail
[ "$#" -eq 2 ] || { echo "usage: chunkstore-scope.sh BASE HEAD" >&2; exit 2; }
list=$(mktemp)
trap 'rm -f "$list"' EXIT
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
echo "chunkstore-scope: git diff $1 $2 failed" >&2
exit 2
fi
n=0
hit=""
while IFS= read -r -d '' f; do
n=$((n + 1))
case $f in
core/frontend/chunkstore/* | core/storage/* | core/frontend/durable/*) [ -n "$hit" ] || hit=$f ;;
esac
done <"$list"
if [ -n "$hit" ]; then
echo "run $n $hit"
else
echo "skip $n"
fi
@@ -0,0 +1,142 @@
"""Relative Markdown links must resolve; code, anchors and URLs are not paths."""
import contextlib
import importlib.util
import io
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location("links", Path(__file__).with_name("doc-links-check.py"))
links = importlib.util.module_from_spec(spec)
spec.loader.exec_module(links)
class DocLinksTests(unittest.TestCase):
def check(self, files):
with tempfile.TemporaryDirectory() as root:
for name, text in files.items():
path = Path(root, name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
return [(source, target) for source, _, target in links.broken_links(root)]
def test_existing_targets_pass(self):
broken = self.check({
"README.md": "[guide](docs/guide.md#start) ![d](docs/d.svg) [dir](docs/) [ref][r]\n\n[r]: <docs/a b.md>\n",
"docs/guide.md": "[up](../README.md) [root](/docs/d.svg) [esc](a%20b.md)\n",
"docs/d.svg": "",
"docs/a b.md": "",
})
self.assertEqual(broken, [])
def test_missing_targets_fail(self):
broken = self.check({
"README.md": "[gone](docs/gone.md) [nested [x]](docs/x.md#a)\n\n[r]: missing.md\n",
"docs/guide.md": "[up](../nope.md)\n",
})
self.assertCountEqual(broken, [
("README.md", "docs/gone.md"),
("README.md", "docs/x.md#a"),
("README.md", "missing.md"),
("docs/guide.md", "../nope.md"),
])
def test_urls_anchors_and_code_are_not_checked(self):
broken = self.check({
"README.md": "\n".join([
"[web](https://example.invalid/x) [mail](mailto:a@example.invalid) [top](#top) [proto](//host/x)",
"`[code](gone.md)` and ``[code](gone.md)``",
"```",
"[fenced](gone.md)",
"```",
"~~~md",
"[tilde](gone.md)",
"~~~",
]) + "\n",
})
self.assertEqual(broken, [])
def test_wrapped_labels_parentheses_and_long_fences(self):
with tempfile.TemporaryDirectory() as root:
Path(root, "guide(v2).md").write_text("")
Path(root, "README.md").write_text("\n".join([
"[guide](guide(v2).md) [old](guide(v1).md)",
"",
"see the [wrapped",
"label](wrapped.md) here",
"",
"`[wrapped",
"code](gone.md)` then [after](after.md)",
"````md",
"```",
"[example](missing.md)",
"```",
"````",
]) + "\n")
broken = [(line, target) for _, line, target in links.broken_links(root)]
self.assertEqual(broken, [(1, "guide(v1).md"), (3, "wrapped.md"), (7, "after.md")])
def test_code_spans_require_complete_equal_delimiter_runs(self):
cases = [
("`unmatched\n[real](real.md) ``", [(2, "real.md")]),
("``unmatched\n[real](real.md) `", [(2, "real.md")]),
("``unmatched\n[real](real.md) ```", [(2, "real.md")]),
("`[wrapped\ncode](hidden.md)`\n[after](after.md)", [(3, "after.md")]),
("``[wrapped `\ncode](hidden.md)``\n[after](after.md)", [(3, "after.md")]),
]
for text, expected in cases:
with self.subTest(text=text), tempfile.TemporaryDirectory() as root:
Path(root, "README.md").write_text(text + "\n", encoding="utf-8")
broken = [(line, target) for _, line, target in links.broken_links(root)]
self.assertEqual(broken, expected)
def test_escaped_backticks_do_not_hide_links(self):
cases = [
("\\`\n[real](real.md)\n\\`", [(2, "real.md")]),
("\\\\`[code](hidden.md)`\n[after](after.md)", [(2, "after.md")]),
("`[code](hidden.md)\\`\n[after](after.md)", [(2, "after.md")]),
]
for text, expected in cases:
with self.subTest(text=text):
self.assertEqual(list(links.link_targets(text)), expected)
def test_masked_code_preserves_reference_line_context(self):
text = "Use `code\nmore`[r]: gone.md\n\n[r]: real.md\n"
self.assertEqual(list(links.link_targets(text)), [(4, "real.md")])
def test_code_masking_contract(self):
cases = [
("unequal runs", "`unmatched\n[real](real.md) ``", [], [(2, "real.md")]),
("escaped delimiters", "\\`\n[real](real.md)\n\\`", [], [(2, "real.md")]),
("reference context", "Use `code\nmore`[r]: gone.md\n\n[r]: real.md", [], [(4, "real.md")]),
("wrapped span", "`[code\nhere](hidden.md)`\n[after](after.md)", [], [(3, "after.md")]),
("hidden-space invalid target", "[example](`foo bar`)", [], []),
("hidden-space invalid reference", "[r]: `a b`", [], []),
("existing literal target", "[example](`foo.md`)", ["`foo.md`"], []),
("missing literal target", "[example](`foo.md`)", [], [(1, "`foo.md`")]),
]
for name, text, existing, expected in cases:
with self.subTest(name=name), tempfile.TemporaryDirectory() as root:
Path(root, "README.md").write_text(text + "\n", encoding="utf-8")
for target in existing:
Path(root, target).touch()
broken = [(line, target) for _, line, target in links.broken_links(root)]
self.assertEqual(broken, expected)
masked = links.mask_code_spans(text)
self.assertEqual(len(masked), len(text))
self.assertEqual([i for i, c in enumerate(masked) if c == "\n"],
[i for i, c in enumerate(text) if c == "\n"])
def test_main_exit_status(self):
out = io.StringIO()
with tempfile.TemporaryDirectory() as root, contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
Path(root, "README.md").write_text("[gone](gone.md)\n")
self.assertEqual(links.main(["doc-links-check.py", root]), 1)
Path(root, "gone.md").write_text("")
self.assertEqual(links.main(["doc-links-check.py", root]), 0)
self.assertEqual(links.main(["doc-links-check.py"]), 2)
self.assertIn("README.md:1: broken relative link gone.md", out.getvalue())
if __name__ == "__main__":
unittest.main()
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Fail when a Markdown file links to a relative path that does not exist.
Usage: doc-links-check.py <root>
"""
import os
import re
import sys
import urllib.parse
SKIP_DIRS = {".git", "node_modules", "vendor"}
FENCE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$")
BACKTICKS = re.compile(r"`+")
INLINE_DESTINATION = r"<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+"
REFERENCE_DESTINATION = r"<[^>]*>|\S+"
INLINE_LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\[\]]*\])*\]\(\s*(" + INLINE_DESTINATION + r")")
REFERENCE = re.compile(r"^[ \t]{0,3}\[[^\]]+\]:\s*(" + REFERENCE_DESTINATION + r")", re.M)
SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
def mask_code_spans(text):
runs = list(BACKTICKS.finditer(text))
masked = list(text)
i = 0
while i < len(runs):
opening = runs[i]
start = opening.start()
# Only prose escapes delimiters; backslashes inside code are literal.
preceding = start
while preceding > 0 and text[preceding - 1] == "\\":
preceding -= 1
if (start - preceding) % 2:
start += 1
width = opening.end() - start
if not width:
i += 1
continue
closing = next((j for j in range(i + 1, len(runs))
if len(runs[j].group()) == width), None)
if closing is None:
i += 1
continue
# Keep columns and non-whitespace line context as well as line numbers.
for pos in range(start, runs[closing].end()):
if text[pos] != "\n":
masked[pos] = "\0"
i = closing + 1
return "".join(masked)
def paragraph_targets(first, lines):
# A link label may wrap, so links are matched per paragraph.
original = "\n".join(lines)
text = mask_code_spans(original)
# Masked bytes are context only, never a synthetic filesystem destination.
found = []
for regex, syntax in ((INLINE_LINK, INLINE_DESTINATION), (REFERENCE, REFERENCE_DESTINATION)):
for match in regex.finditer(text):
target = original[match.start(1):match.end(1)]
if re.fullmatch(syntax, target):
found.append((match.start(), target))
for pos, target in sorted(found):
yield first + text.count("\n", 0, pos), target
def link_targets(text):
fence, block, first = None, [], 1
for lineno, line in enumerate(text.splitlines() + [""], 1):
m = FENCE.match(line)
if fence is not None:
# Only a fence of the same character, at least as long, closes it.
if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not m.group(2).strip():
fence = None
continue
if m or not line.strip():
yield from paragraph_targets(first, block)
block = []
if m:
fence = m.group(1)
continue
if not block:
first = lineno
block.append(line)
def local_path(target):
if target.startswith("<") and target.endswith(">"):
target = target[1:-1]
if not target or target.startswith(("#", "//")) or SCHEME.match(target):
return None
path = urllib.parse.unquote(target.split("#", 1)[0].split("?", 1)[0])
return path or None
def broken_links(root):
root = os.path.abspath(root)
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
for name in sorted(filenames):
if not name.endswith(".md"):
continue
source = os.path.join(dirpath, name)
with open(source, encoding="utf-8", errors="replace") as f:
text = f.read()
for lineno, target in link_targets(text):
path = local_path(target)
if path is None:
continue
if path.startswith("/"):
resolved = os.path.join(root, path.lstrip("/"))
else:
resolved = os.path.join(dirpath, path)
if not os.path.exists(resolved):
yield os.path.relpath(source, root), lineno, target
def main(argv):
if len(argv) != 2:
print(__doc__.strip(), file=sys.stderr)
return 2
broken = list(broken_links(argv[1]))
for source, lineno, target in broken:
print(f"{source}:{lineno}: broken relative link {target}")
return 1 if broken else 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# docs-only-scope.sh BASE HEAD: classifies the files changed between BASE and
# HEAD for the process-level suite. It prints one line:
# "docs_only N" every one of the N changed files is under docs/
# "run N [FIRST-OTHER]" no file changed, or at least one is elsewhere
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
# and the caller then runs the tests: an error never selects docs_only.
#
# The NUL-delimited list is written to a file first and read to its end, so
# no pipe can stop early and leave a writer's error looking like an answer.
set -euo pipefail
[ "$#" -eq 2 ] || { echo "usage: docs-only-scope.sh BASE HEAD" >&2; exit 2; }
list=$(mktemp)
trap 'rm -f "$list"' EXIT
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
echo "docs-only-scope: git diff $1 $2 failed" >&2
exit 2
fi
if [ -n "$(git rev-parse --show-prefix)" ]; then
git -C "$(git rev-parse --show-toplevel)" diff --name-only --no-renames -z "$1" "$2" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' >>"$list"
fi
n=0
other=""
while IFS= read -r -d '' f; do
n=$((n + 1))
case $f in
docs/*) ;;
*) [ -n "$other" ] || other=$f ;;
esac
done <"$list"
if [ "$n" -gt 0 ] && [ -z "$other" ]; then
echo "docs_only $n"
else
echo "run $n${other:+ $other}"
fi
+121
View File
@@ -0,0 +1,121 @@
"""Check that every code and test anchor of the invariants ledger exists at a git ref.
usage: python -I ledger_check.py <repo-dir> <git-ref> [<ledger path in repo>]
A ledger row is a table line whose first cell holds `INV-...`. In its cells, a
backticked token that ends in .go is a FILE; a backticked identifier (or
Type.Method) is a SYMBOL of the nearest file named before it in the same cell,
or, in the test cell, of any file named in that cell. A file must exist at the
ref; a symbol must occur in its file as a whole word (for a test: `func Name(`).
A symbol with no file in its cell is looked up in the whole tree. A file may
be a glob (`volume_lock*.go`). A lower-case token with an underscore (a build
tag, a JSON key, a reason string) is not a Go symbol and is not checked.
Prints one line per missing anchor and a summary. It reads; it changes nothing.
Exit: 0 when every anchor exists; 1 when one is missing; 2 when git fails or no
row or anchor was found (an error is never read as a pass).
"""
import re
import subprocess
import sys
def git(repo, *args):
"""git's output. A git failure ends the check with exit 2: an error must
never read as "no anchors". `git grep` finding nothing (exit 1) is not one."""
r = subprocess.run(["git", "-C", repo] + list(args), capture_output=True, text=True,
encoding="utf-8", errors="replace")
if r.returncode != 0 and not (args and args[0] == "grep" and r.returncode == 1):
print("ledger_check: git %s failed (exit %d): %s" % (" ".join(args[:2]), r.returncode, r.stderr.strip()[:300]),
file=sys.stderr)
sys.exit(2)
return r.stdout
def main():
repo, ref = sys.argv[1], sys.argv[2]
ledger = sys.argv[3] if len(sys.argv) > 3 else "docs/design/invariants.md"
text = git(repo, "show", "%s:%s" % (ref, ledger))
prefix = sys.argv[4] if len(sys.argv) > 4 else ""
files = set(git(repo, "ls-tree", "-r", "--name-only", ref, "--", prefix or ".").split("\n"))
cache = {}
def body(path):
if path not in cache:
cache[path] = git(repo, "show", "%s:%s" % (ref, path))
return cache[path]
def resolve(tok):
"""A file token may be a full path or a bare file name."""
if tok in files:
return [tok]
if "*" in tok:
rx = re.compile("^(.*/)?" + "[^/]*".join(re.escape(x) for x in tok.split("*")) + "$")
return [f for f in files if rx.match(f)]
if "/" not in tok:
return [f for f in files if f.endswith("/" + tok)]
# a path with a directory matches whole path components only
return [f for f in files if f.endswith("/" + tok)]
ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?(\(\))?$")
go_all = None
rows = missing = anchors = 0
for n, line in enumerate(text.split("\n"), 1):
if not line.startswith("|"):
continue
cells = [c.strip() for c in line.strip().strip("|").split("|")]
m = re.match(r"`(INV-[A-Z0-9-]+)`", cells[0]) if cells else None
if not m or len(cells) < 6:
continue
rows += 1
inv, status = m.group(1), cells[-1]
if "ARCHIVED" in status:
continue
for ci, kind in ((3, "code"), (4, "test")):
toks = re.findall(r"`([^`]+)`", cells[ci])
cell_files = []
for t in toks:
if t.endswith(".go"):
cell_files.append(t)
cur = None
for t in toks:
if t.endswith(".go"):
cur = t
anchors += 1
if not resolve(t):
missing += 1
print("%s (line %d, %s, %s): file %s does not exist" % (inv, n, kind, status, t))
continue
if not ident.match(t):
continue
sym = t.rstrip("()").split(".")[-1]
if sym in ("nil", "true", "false") or sym.isupper() or len(sym) < 3:
continue
if "_" in sym and sym == sym.lower():
# a build tag, a JSON key or a reason string: not a Go symbol
continue
scope = [cur] if (cur and kind == "code") else cell_files
paths = [p for f in scope for p in resolve(f)]
anchors += 1
if kind == "test" and sym.startswith(("Test", "Fuzz", "Benchmark")):
pat = re.compile(r"func %s\(" % re.escape(sym))
else:
pat = re.compile(r"\b%s\b" % re.escape(sym))
if paths:
ok = any(pat.search(body(p)) for p in paths)
else:
if go_all is None:
go_all = git(repo, "grep", "-h", "-E", r"^(func|type|var|const|\s+[A-Za-z_]+\s)", ref, "--", prefix + "*.go")
ok = bool(pat.search(go_all))
if not ok:
missing += 1
where = ", ".join(scope) if scope else "the tree"
print("%s (line %d, %s, %s): %s not found in %s" % (inv, n, kind, status, t, where))
print("%d rows, %d anchors, %d missing at %s" % (rows, anchors, missing, ref))
if rows == 0 or anchors == 0:
print("ledger_check: no ledger rows or anchors found: refusing to pass", file=sys.stderr)
sys.exit(2)
sys.exit(1 if missing else 0)
if __name__ == "__main__":
main()
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Usage: post-merge-review-changed.sh BASE HEAD
#
# Writes what a PR changes (BASE...HEAD) as NUL-separated STATUS, PATH pairs,
# unquoted, so any byte in a name reaches the check as itself. --no-renames
# reports a move as a delete of the old name and an add of the new one.
set -euo pipefail
base=${1:?usage: post-merge-review-changed.sh BASE HEAD}
head=${2:?usage: post-merge-review-changed.sh BASE HEAD}
git diff --relative -z --name-status --no-renames "$base...$head" -- .
if [ -n "$(git rev-parse --show-prefix)" ]; then
git -C "$(git rev-parse --show-toplevel)" diff -z --name-status --no-renames "$base...$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**'
fi
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# Refuses internal names in what a pull request makes public: the lines it
# adds, its commit messages, its title and its description. This repository is
# public; internal names, machine paths and raw run artifacts do not belong in it.
#
# Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE
# Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage.
#
# The patterns live only here and in this check's own test; both files are
# excluded from the scan of added lines.
set -euo pipefail
[ "$#" -eq 4 ] || { echo "usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE" >&2; exit 2; }
mb=$1; head=$2; title=$3; body=$4
for f in "$title" "$body"; do
[ -f "$f" ] && [ -r "$f" ] || { echo "public-text: cannot read $f" >&2; exit 2; }
done
git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify "$head^{commit}" >/dev/null ||
{ echo "public-text: unknown commit $mb or $head" >&2; exit 2; }
# match: a grep error fails the check instead of reading as "no hit".
match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; }
pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation|/home/[^/[:space:]]+/|(^|[^[:alnum:]_])pid[[:space:]]*[:=][[:space:]]*[0-9]+|[0-9]+[[:space:]]+cores[[:space:]]+with[[:space:]]+[0-9]+([.][0-9]+)?[[:space:]]*(KB|MB|GB|KiB|MiB|GiB)?[[:space:]]+heap|docs/spec/([^/[:space:]]+/)*recorded-[^/[:space:]]+'
out=$(mktemp); paths=; trap 'rm -f "$out" "$paths"' EXIT
paths=$(mktemp)
report() { # report WHERE < matching lines
local where=$1 line
while IFS= read -r line; do
printf 'public-text: %s: %s
' "$where" "${line:0:160}" >>"$out"
done
}
# Raw run artifacts are not public specs, even with scrubbed contents.
# Allow deletions so existing artifacts can be removed.
repo_root=$(git rev-parse --show-toplevel)
if ! (cd "$repo_root" && git diff --name-only -z --no-relative --no-renames --diff-filter=ACMT "$mb" "$head" -- docs/spec/ seaweed-block/docs/spec/) >"$paths"; then
echo 'public-text: cannot enumerate artifact paths' >&2
exit 2
fi
while IFS= read -r -d '' path; do
# Match the module's paths the same way from either entry point.
path=${path#seaweed-block/}
if [[ $path =~ ^docs/spec/(.*/)?recorded-[^/]+(/|$) ]]; then
printf '%s\n' "$path" | report "artifact path"
fi
done <"$paths"
# Added lines of the diff, with file and line number.
{
git diff --relative --no-color --no-renames -U0 "$mb" "$head" -- . \
':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh' \
':(exclude,top).github/block/scripts/public-text-check.sh'
if [ -n "$(git rev-parse --show-prefix)" ]; then
git -C "$(git rev-parse --show-toplevel)" diff --no-color --no-renames -U0 "$mb" "$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' ':(exclude).github/block/scripts/public-text-check.sh'
fi
} |
awk '
/^diff --git / { hdr = 1; next }
hdr && /^\+\+\+ / { f = substr($0, 7); next }
/^@@ / { hdr = 0; split($3, a, ","); n = substr(a[1], 2) + 0; next }
!hdr && /^\+/ { print f ":" n ": " substr($0, 2); n++ }
' | match | report "added line"
# Commit messages (subjects and bodies) of the pull request.
git log --format='%h %s%n%b' "$mb..$head" | match | report "commit message"
match "$title" | report "title"
match "$body" | report "description"
hits=$(wc -l <"$out" | tr -d ' ')
if [ "$hits" -gt 0 ]; then
cat "$out"
echo "public-text: $hits hit(s). Say what the code or test does instead of who asked for it; keep internal paths out." >&2
exit 1
fi
echo "public-text: clean"
@@ -0,0 +1,145 @@
"""Run fake recorders through the real group executor, without product tests."""
from pathlib import Path
import json
import os
import subprocess
import time
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
import importlib.util
import signal
SCRIPT = Path(__file__).with_name("run-unit-groups.py")
FAKE = r'''import json, os, sys, time
from pathlib import Path
out = Path(sys.argv[1]); group = out.parent.name
root = Path(os.environ["FIXTURE_ROOT"])
(root / (group + ".started")).write_text("started")
deadline = time.monotonic() + 5
while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()):
if time.monotonic() >= deadline: sys.exit(17)
time.sleep(.01)
flags = sys.argv[2:]
assert "-p=" + ("4" if group == "g3" else "1") in flags
assert "-short" in flags and "-count=1" in flags and "20m" in flags
if sys.platform == "linux":
wal = Path(os.environ["TMPDIR"]) / "v1.bin"
with wal.open("w") as descriptor:
assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found"
else:
assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory"
out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n")
out.with_suffix(".stderr").write_text("fixture stderr")
(root / (group + ".finished")).write_text("finished")
sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0)
'''
class GroupRunnerTests(unittest.TestCase):
def run_groups(self, fail="", empty=False, alias=False):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n")
fake = root / "fake.py"; fake.write_text(FAKE)
env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail)
scratch = root / "tmp"
if alias:
scratch.mkdir()
link = root / "runner-temp"
link.symlink_to(scratch, target_is_directory=True)
scratch = link
result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20)
self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr)
expected = ["g3"] if empty else ["g1", "g2", "g3"]
for group in expected:
self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr)
self.assertTrue((root / "evidence" / group / "go-test.stderr").exists())
self.assertTrue((root / "tmp" / group).is_dir())
events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()]
self.assertCountEqual([e["Package"] for e in events], expected)
statuses = json.loads((root / "evidence" / "unit-groups.json").read_text())
self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0)
@unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control")
def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True)
def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups()
def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2")
def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True)
def test_cancel_escalates_even_after_group_leader_exits(self):
spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT)
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
group = 12345
leader = Mock(pid=group)
leader.wait.return_value = 0
with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]):
module.terminate([leader])
self.assertIn(unittest.mock.call(group, signal.SIGTERM), killpg.call_args_list)
self.assertIn(unittest.mock.call(group, 9), killpg.call_args_list)
leader.wait.assert_called()
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
def test_cancel_kills_resistant_child_after_recorder_exits(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "")
child = root / "child.py"
child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n")
fake = root / "recorder.py"
fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n")
marker = root / "child"
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
pid = None
try:
deadline = time.monotonic() + 5
while not marker.exists():
if time.monotonic() >= deadline: self.fail("resistant child did not start")
time.sleep(.01)
pid = int(marker.read_text())
runner.terminate()
self.assertEqual(runner.wait(timeout=12), 130)
deadline = time.monotonic() + 2
while True:
stat = Path(f"/proc/{pid}/stat")
if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break
if time.monotonic() >= deadline: self.fail("resistant child survived cancellation")
time.sleep(.01)
finally:
if pid is not None:
try: os.kill(pid, signal.SIGKILL)
except ProcessLookupError: pass
if runner.poll() is None: runner.kill()
runner.communicate(timeout=5)
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
def test_cancel_joins_every_started_group(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("example/" + group + "\n")
fake = root / "held.py"
fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n")
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 5
markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")]
while not all(p.exists() for p in markers):
if time.monotonic() >= deadline: self.fail("groups did not start")
time.sleep(.01)
children = [int(p.read_text()) for p in markers]
runner.terminate()
self.assertEqual(runner.wait(timeout=10), 130)
for child in children:
with self.assertRaises(ProcessLookupError): os.kill(child, 0)
finally:
if runner.poll() is None: runner.terminate()
runner.communicate(timeout=10)
if __name__ == "__main__": unittest.main()
+123
View File
@@ -0,0 +1,123 @@
"""Run the three default unit groups concurrently on the current runner.
Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...]
The recorder accepts OUTPUT followed by go-test flags and packages. Each group
owns its logs/events; they are combined only after all group processes exit.
"""
from contextlib import ExitStack
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
def stop(_signum, _frame):
raise KeyboardInterrupt
def terminate(processes):
for process in processes:
try:
if os.name == "posix": os.killpg(process.pid, signal.SIGTERM)
elif process.poll() is None: process.terminate()
except ProcessLookupError:
pass
if os.name == "posix":
# The leader may exit on TERM while its descendants remain in the group.
# Bound the grace period by group lifetime, never by leader lifetime.
deadline = time.monotonic() + 5
remaining = list(processes)
while remaining and time.monotonic() < deadline:
alive = []
for process in remaining:
process.poll() # Reap an exited leader without forgetting its PGID.
try:
os.killpg(process.pid, 0)
alive.append(process)
except ProcessLookupError:
pass
remaining = alive
if remaining: time.sleep(.05)
for process in remaining:
try: os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError: pass
for process in processes:
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
def run(plan, evidence, temp, recorder):
groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")}
evidence.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
processes, results, times = {}, {}, {}
with ExitStack() as files:
try:
for group, packages in groups.items():
results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0}
if not packages:
print(f"{group}: no packages selected by scope", flush=True)
continue
out = evidence / group; out.mkdir(parents=True, exist_ok=True)
scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True)
# /proc/self/fd exposes resolved paths; preserve fixture identity even
# when the runner temp directory is a symlink to its data disk.
scratch = scratch.resolve(strict=True)
log = files.enter_context((out / "console.log").open("w", encoding="utf-8"))
command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages]
times[group] = time.monotonic()
processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix")
print(f"{group}: started {len(packages)} packages", flush=True)
remaining = set(processes)
while remaining:
for group in tuple(remaining):
status = processes[group].poll()
if status is not None:
results[group]["status"] = status
results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3)
remaining.remove(group)
if remaining: time.sleep(.05)
except BaseException:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
terminate(processes.values())
raise
for group in processes:
print(f"--- {group} ---", flush=True)
print((evidence / group / "console.log").read_text(errors="replace"), flush=True)
summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results}
try:
(evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
with (evidence / "go-test.json").open("ab") as combined:
for group in processes:
events = evidence / group / "go-test.json"
if events.exists(): combined.write(events.read_bytes())
except OSError as error:
print(f"test evidence unavailable: {error}", file=sys.stderr)
print(json.dumps(summary), flush=True)
return int(any(r["status"] != 0 for r in results.values()))
def main(argv):
if len(argv) < 5:
print(__doc__.strip(), file=sys.stderr)
return 2
signal.signal(signal.SIGTERM, stop)
try:
return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:])
except KeyboardInterrupt:
return 130
except (OSError, ValueError) as error:
print(f"unit groups: {error}", file=sys.stderr)
return 2
if __name__ == "__main__": sys.exit(main(sys.argv))
@@ -0,0 +1,106 @@
"""Exercise the actual pre-checkout and always-run cleanup workflow bodies."""
import contextlib
import io
import os
from pathlib import Path
import shutil
import tempfile
import textwrap
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[3]
WORKFLOWS = sorted((ROOT / ".github/workflows").glob("block-*.yml"))
def step(text, name):
marker = " - name: " + name + "\n"
if text.count(marker) != 1:
raise AssertionError("missing or duplicate " + name)
return text.split(marker, 1)[1].split("\n - name:", 1)[0]
def code(block):
return textwrap.dedent(block.split(" run: |\n", 1)[1]).split("\n", 1)[1].rsplit("\nPY", 1)[0]
def execute(source, workspace, temp, free=None):
output = io.StringIO()
with patch.dict(os.environ, {"GITHUB_WORKSPACE": str(workspace), "RUNNER_TEMP": str(temp)}), contextlib.redirect_stdout(output):
with contextlib.ExitStack() as stack:
if free is not None:
stack.enter_context(patch("shutil.disk_usage", return_value=shutil._ntuple_diskusage(100_000_000_000, 0, free)))
try:
exec(compile(source, "<workflow>", "exec"), {})
except SystemExit as err:
return err.code, output.getvalue()
return 0, output.getvalue()
class RunnerWorkspaceTests(unittest.TestCase):
def test_every_job_checks_before_checkout_and_cleans_last_even_on_failure(self):
for path in WORKFLOWS:
text = path.read_text()
before = step(text, "Runner free space")
after = step(text, "Clean job workspace")
self.assertLess(text.index("- name: Runner free space"), text.index("- name: Checkout"), path.name)
self.assertIn("if: always() && runner.environment == 'self-hosted'", after)
self.assertNotIn("continue-on-error", after)
self.assertNotIn("- name:", text.split("- name: Clean job workspace", 1)[1])
self.assertIn("working-directory: ${{ runner.temp }}", before)
self.assertIn("working-directory: ${{ runner.temp }}", after)
self.assertIn("python3 -I -", before)
self.assertIn("python3 -I -", after)
def test_low_space_refuses_and_boundary_admits(self):
for path in WORKFLOWS:
source = code(step(path.read_text(), "Runner free space"))
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
rc, out = execute(source, root, root, 9_999_999_999)
self.assertEqual(rc, 75)
self.assertIn("runner_disk_low", out)
self.assertIn("required_bytes=10000000000", out)
self.assertEqual(execute(source, root, root, 10_000_000_000)[0], 0)
with patch("shutil.disk_usage", side_effect=[shutil._ntuple_diskusage(100, 0, 10_000_000_000), shutil._ntuple_diskusage(100, 0, 1)]):
rc, out = execute(source, root / "work", root / "temp")
self.assertEqual(rc, 75)
self.assertIn("runner_disk_low", out)
with patch("shutil.disk_usage", side_effect=OSError("probe failed")):
rc, out = execute(source, root, root)
self.assertEqual(rc, 75)
self.assertIn("runner_disk_check_failed", out)
def test_cleanup_removes_hidden_and_build_files_but_not_symlink_targets(self):
for path in WORKFLOWS:
source = code(step(path.read_text(), "Clean job workspace"))
with tempfile.TemporaryDirectory() as temp:
root = Path(temp); work = root / "repo/repo"; work.mkdir(parents=True)
(work / ".git").mkdir(); (work / ".git/config").write_text("config")
(work / "binary").write_bytes(b"build")
outside = root / "outside"; outside.mkdir(); (outside / "keep").write_text("keep")
(work / "link").symlink_to(outside, target_is_directory=True)
rc, out = execute(source, work, root)
self.assertEqual(rc, 0, out)
self.assertEqual(list(work.iterdir()), [])
self.assertTrue((outside / "keep").is_file())
self.assertEqual(execute(source, root, root)[0], 1)
self.assertEqual(execute(source, Path(root.anchor), root)[0], 1)
alias = root / "alias"; alias.symlink_to(work, target_is_directory=True)
self.assertEqual(execute(source, alias, root)[0], 1)
def test_cleanup_refuses_symlinked_ancestors_and_preserves_external_sentinel(self):
for path in WORKFLOWS:
with self.subTest(workflow=path.name), tempfile.TemporaryDirectory() as temp:
base = Path(temp)
external = base / "external/repo/repo"; external.mkdir(parents=True)
sentinel = external / "keep"; sentinel.write_text("outside checkout")
alias = base / "alias"; alias.symlink_to(base / "external", target_is_directory=True)
source = code(step(path.read_text(), "Clean job workspace"))
rc, out = execute(source, alias / "repo/repo", base)
self.assertTrue(sentinel.is_file(), "cleanup followed a workspace ancestor outside the checkout")
self.assertEqual(rc, 1, out)
self.assertIn("runner_workspace_cleanup_refused", out)
if __name__ == "__main__": unittest.main()
+132
View File
@@ -0,0 +1,132 @@
"""Read-only block merge readiness check. Run from a trusted master checkout.
Usage (inside seaweed-block/): python3 ../.github/block/scripts/safe-merge-check.py PR
Never merges, posts comments, changes account config or pushes refs.
"""
import json
import subprocess
import sys
import tempfile
from pathlib import Path
REPO = "seaweedfs/seaweedfs"
WORKFLOW_PATH = ".github/workflows/block-test.yml"
JOBS = {"go test (linux)", "process-level tests (real binaries)"}
def validate(pr, run, jobs, current):
if pr["state"] != "open" or pr["draft"] or pr["mergeable"] is not True:
raise ValueError("PR must be open, ready and mergeable")
if pr["base"]["ref"] != "master": raise ValueError("expected master base")
if run.get("path") != WORKFLOW_PATH or run["name"] != "Block Test" or run["head_sha"] != pr["head"]["sha"]:
raise ValueError("wrong workflow or head")
if run["status"] != "completed" or run["conclusion"] != "success":
raise ValueError("Block Test is not successful")
bases = [p["base"]["sha"] for p in run["pull_requests"] if p["number"] == pr["number"]]
if bases != [current]: raise ValueError("tested base is not current master")
required = [j for j in jobs if j["name"] in JOBS]
if len(required) != 2 or {j["name"] for j in required} != JOBS or any(j["conclusion"] != "success" for j in required):
raise ValueError("both block test jobs must succeed")
def api(path):
return json.loads(subprocess.check_output(["gh", "api", "repos/" + REPO + "/" + path]))
def successful_run(pr, current):
runs = api("actions/runs?head_sha=" + pr["head"]["sha"] + "&event=pull_request&per_page=100")["workflow_runs"]
runs = [r for r in runs if r.get("path") == WORKFLOW_PATH and r["name"] == "Block Test"]
if not runs: raise ValueError("no Block Test run")
run = max(runs, key=lambda r: (r["created_at"], r["id"]))
pages = json.loads(subprocess.check_output(["gh", "api", "--paginate", "--slurp", "repos/" + REPO + "/actions/runs/" + str(run["id"]) + "/jobs?per_page=100"]))
validate(pr, run, [j for page in pages for j in page["jobs"]], current)
return run
def check_control_paths(base, head):
# Inspect both sides of renames and fail on enumeration errors. These PRs
# need independent workflow review; their own Actions results cannot waive it.
# Diff from the merge base: master's later control changes are not the PR's,
# and the tested merge commit already ran them.
bases = subprocess.check_output(["git", "merge-base", "--all", base, head]).decode("ascii").splitlines()
if len(bases) != 1:
raise ValueError("ambiguous_merge_base: expected exactly one merge base")
paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", bases[0], head]).split(b"\0")
controls = [p.decode("utf-8", errors="replace") for p in paths if p.startswith((b".github/workflows/", b".github/block/", b".github/dockerfiles/block-", b"seaweed-block/.github/"))]
if controls:
raise ValueError("workflow_review_required: CI controls changed: " + ", ".join(controls))
def fetch_review_head(pr, current):
if subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() != current:
raise ValueError("run from trusted current master checkout")
subprocess.run(["git", "-c", "fetch.fsckObjects=true", "fetch", "--no-tags", "origin", "+refs/pull/" + str(pr["number"]) + "/head:refs/remotes/block-review/head"], check=True)
actual = subprocess.check_output(["git", "rev-parse", "refs/remotes/block-review/head"], text=True).strip()
if actual != pr["head"]["sha"]: raise ValueError("PR head moved; recheck")
check_control_paths(current, actual)
return actual
def local_checks(pr, current):
actual = fetch_review_head(pr, current)
with tempfile.TemporaryDirectory() as tmp:
body, title = Path(tmp) / "body", Path(tmp) / "title"
body.write_text(pr["body"] or "", encoding="utf-8")
title.write_text(pr["title"], encoding="utf-8")
subprocess.run(["bash", str(Path(__file__).resolve().with_name("check-pr-base.sh")), current, actual, str(body), str(title)], check=True)
def validate_batch(manifest, prs, current):
if manifest["base"] != current: raise ValueError("master moved since batch creation")
if not manifest["head"] or len(manifest["prs"]) < 2: raise ValueError("expected pinned batch and at least two PRs")
numbers = [p["number"] for p in manifest["prs"]]
if len(set(numbers)) != len(numbers) or numbers != [p["number"] for p in prs]:
raise ValueError("batch PR order differs or repeats")
for saved, pr in zip(manifest["prs"], prs):
if pr["state"] != "open" or pr["draft"] or pr["base"]["ref"] != "master" or pr["head"]["sha"] != saved["head"]:
raise ValueError("batch member is not ready or its head changed")
if not Path(saved["evidence"]).is_file() or not Path(saved["evidence"]).read_text().strip():
raise ValueError("batch member has no acceptance evidence")
def main(args):
current = api("git/ref/heads/master")["object"]["sha"]
if len(args) == 2 and args[0] == "--verify-tree":
tree = api("git/commits/" + current)["tree"]["sha"]
if tree != args[1]: raise ValueError("master tree differs from the tested batch")
print(json.dumps({"tree_matches": True, "master": current, "tree": tree}))
return
if len(args) == 2 and args[0] == "--batch":
manifest = json.loads(Path(args[1]).read_text())
prs = [api("pulls/" + str(p["number"])) for p in manifest["prs"]]
validate_batch(manifest, prs, current)
batch = api("pulls/" + str(manifest["batch_pr"]))
if batch["head"]["sha"] != manifest["head"]: raise ValueError("batch head changed")
fetch_review_head(batch, current)
run = successful_run(batch, current)
for pr in prs: local_checks(pr, current)
if api("git/ref/heads/master")["object"]["sha"] != current: raise ValueError("master moved; recheck")
for pr in prs + [batch]:
if api("pulls/" + str(pr["number"]))["head"]["sha"] != pr["head"]["sha"]: raise ValueError("head moved; recheck")
tree = api("git/commits/" + manifest["head"])["tree"]["sha"]
# A rerun can invalidate the earlier success while local checks execute.
run = successful_run(batch, current)
print(json.dumps({"ready": True, "base": current, "head": manifest["head"], "run": run["id"], "tree": tree, "order": [p["number"] for p in prs]}))
return
if len(args) != 1 or not args[0].isdecimal(): raise ValueError("expected PR, --batch MANIFEST or --verify-tree TREE")
pr = api("pulls/" + args[0])
run = successful_run(pr, current)
local_checks(pr, current)
if api("git/ref/heads/master")["object"]["sha"] != current or api("pulls/" + args[0])["head"]["sha"] != pr["head"]["sha"]:
raise ValueError("base or head moved; recheck")
# Refresh the latest run and both jobs after every potentially slow check.
run = successful_run(pr, current)
print(json.dumps({"ready": True, "head": pr["head"]["sha"], "base": current, "run": run["id"], "merge_mode": "squash"}))
if __name__ == "__main__":
try:
main(sys.argv[1:])
except (IndexError, KeyError, ValueError, OSError, subprocess.SubprocessError) as error:
print("REFUSED: " + str(error), file=sys.stderr)
sys.exit(1)
@@ -0,0 +1,52 @@
"""Exact coverage before scope selection; old heavy-package rules afterward."""
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location("planner", Path(__file__).with_name("unit-test-shards.py"))
planner = importlib.util.module_from_spec(spec)
spec.loader.exec_module(planner)
MODULE = "example.invalid/product"
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
class UnitShardTests(unittest.TestCase):
def setUp(self):
self.packages = [MODULE + "/" + p for p in (*HEAVY, "cmd/sw-block", "core/frontend/chunkstore", "internal/newpackage", "core/storage/child")]
self.groups = planner.partition(MODULE, self.packages)
def test_exact_cover_and_stable_order(self):
flat = [p for group in self.groups.values() for p in group]
self.assertCountEqual(flat, self.packages)
self.assertEqual(len(flat), len(set(flat)))
self.assertEqual(self.groups, planner.partition(MODULE, list(reversed(self.packages))))
self.assertEqual(self.groups["g1"], [MODULE + "/core/storage"])
self.assertEqual(self.groups["g2"], [MODULE + "/" + p for p in HEAVY[1:]])
self.assertIn(MODULE + "/internal/newpackage", self.groups["g3"])
self.assertIn(MODULE + "/core/storage/child", self.groups["g3"])
def test_existing_heavy_scope_on_main_train_and_prs(self):
all_changed = [p + "/changed.go" for p in HEAVY]
for event, ref in (("push", ""), ("pull_request", "train/next")):
selected = planner.select(MODULE, self.groups, event, ref, all_changed)
self.assertEqual(selected["g1"], [])
self.assertEqual(selected["g2"], [])
self.assertEqual(selected["g3"], self.groups["g3"])
self.assertEqual(planner.select(MODULE, self.groups, "pull_request", "fix/x", all_changed), self.groups)
for path in HEAVY:
selected = planner.select(MODULE, self.groups, "pull_request", "fix/x", [path + "/x.go"])
heavy = selected["g1"] + selected["g2"]
self.assertEqual(heavy, [MODULE + "/" + path])
nested = planner.select(MODULE, self.groups, "pull_request", "fix/x", ["core/storage/child/x.go", "core/storage/"])
self.assertEqual(nested["g1"], [])
self.assertEqual(nested["g2"], [])
self.assertEqual(nested["g3"], self.groups["g3"])
def test_invalid_inventory_is_refused(self):
for packages in ([], self.packages + [self.packages[0]], self.packages[1:], self.packages + ["other/pkg"]):
with self.subTest(packages=packages), self.assertRaises(ValueError):
planner.partition(MODULE, packages)
if __name__ == "__main__":
unittest.main()
+55
View File
@@ -0,0 +1,55 @@
"""Plan the default unit groups from the full go-list inventory.
Usage: go list ./... | python3 unit-test-shards.py MODULE OUT_DIR EVENT HEAD_REF CHANGED_FILE
The complete partition covers every package exactly once. Existing scope rules
then select heavy packages only on ordinary PRs that touch their direct files.
"""
from pathlib import Path
import sys
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
def partition(module, packages):
if not module or any(c.isspace() for c in module):
raise ValueError("expected one module path")
if not packages or len(packages) != len(set(packages)):
raise ValueError("empty package list or duplicate package")
if any(p != module and not p.startswith(module + "/") for p in packages):
raise ValueError("package outside the selected module")
heavy = [module + "/" + p for p in HEAVY]
if not set(heavy) <= set(packages):
raise ValueError("required heavy packages missing from go list")
return {"g1": heavy[:1], "g2": heavy[1:], "g3": sorted(set(packages) - set(heavy))}
def select(module, groups, event, head_ref, changed):
selected = set()
if event != "push" and not head_ref.startswith("train/"):
for p in HEAVY:
if any(f.startswith(p + "/") and f[len(p) + 1:] and "/" not in f[len(p) + 1:] for f in changed):
selected.add(module + "/" + p)
return {name: [p for p in packages if name == "g3" or p in selected]
for name, packages in groups.items()}
def main(argv):
if len(argv) != 6:
print(__doc__.strip(), file=sys.stderr)
return 2
try:
groups = partition(argv[1], sys.stdin.read().split())
groups = select(argv[1], groups, argv[3], argv[4], Path(argv[5]).read_text().splitlines())
out = Path(argv[2])
out.mkdir(parents=True, exist_ok=True)
for name, packages in groups.items():
(out / (name + ".txt")).write_text("".join(p + "\n" for p in packages), encoding="utf-8")
print(f"{name}: {len(packages)} packages")
except (OSError, ValueError) as error:
print(f"unit-test-shards: {error}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -0,0 +1,27 @@
FROM golang:1.25-bookworm AS build
WORKDIR /src/seaweed-block
COPY seaweed-block/go.mod seaweed-block/go.sum ./
RUN go mod download
COPY . /src
RUN CGO_ENABLED=0 go build -o /out/blockcsi ./cmd/blockcsi
# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the
# runtime stage, so neither a build nor a push of this image can complete.
RUN bash scripts/refuse-lab-binary.sh /out/blockcsi
FROM debian:bookworm-slim
RUN apt-get update && \
apt-get install -y --no-install-recommends \
e2fsprogs \
kmod \
multipath-tools \
nvme-cli \
open-iscsi \
sg3-utils \
util-linux && \
rm -rf /var/lib/apt/lists/*
COPY --from=build /out/blockcsi /usr/local/bin/blockcsi
ENTRYPOINT ["/usr/local/bin/blockcsi"]
@@ -0,0 +1,24 @@
FROM golang:1.25-bookworm AS build
WORKDIR /src/seaweed-block
COPY seaweed-block/go.mod seaweed-block/go.sum ./
RUN go mod download
COPY . /src
RUN CGO_ENABLED=0 go build -o /out/blockmaster ./cmd/blockmaster && \
CGO_ENABLED=0 go build -o /out/blockvolume ./cmd/blockvolume && \
CGO_ENABLED=0 go build -o /out/sw-block ./cmd/sw-block
# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the
# runtime stage, so neither a build nor a push of this image can complete.
RUN bash scripts/refuse-lab-binary.sh /out/blockmaster /out/blockvolume /out/sw-block
FROM debian:bookworm-slim
RUN apt-get update && \
apt-get install -y --no-install-recommends kmod && \
rm -rf /var/lib/apt/lists/*
COPY --from=build /out/blockmaster /usr/local/bin/blockmaster
COPY --from=build /out/blockvolume /usr/local/bin/blockvolume
COPY --from=build /out/sw-block /usr/local/bin/sw-block
USER 65532:65532
+127
View File
@@ -0,0 +1,127 @@
name: Block known bugs
# Nightly: every open-issue reproduction that is skipped by default (t.Skip unless
# SEAWEED_KNOWN_BUGS=1) runs and is EXPECTED TO FAIL. If one passes, its bug is
# fixed but its skip is still in place: this job fails and names it, so the skip
# is removed in the fix PR (or right after). A fix PR removes the test's line here
# together with its skip.
on:
schedule:
- cron: "17 6 * * *"
workflow_dispatch:
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
jobs:
known-bugs:
name: known-bug reproductions still fail
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
timeout-minutes: 15
env:
CGO_ENABLED: "0"
SEAWEED_KNOWN_BUGS: "1"
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false
- 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;
# this names the runner and stops the job before it starts.
if: runner.environment == 'self-hosted'
run: |
bash .github/scripts/require-nvme-test.sh
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: seaweed-block/go.mod
cache: false
- name: Known-bug verdict controls
run: bash .github/scripts/known-bugs-test.sh
- name: Each reproduction still fails
run: |
bash .github/scripts/known-bugs.sh <<'LIST'
#186 ./cmd/blockmaster/ TestChartOptInLoopbackFlagIsAcceptedByBlockmaster
LIST
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
from pathlib import Path
import shutil
import sys
root = Path(os.environ["GITHUB_WORKSPACE"])
# Refuse aliases rather than resolving them. Open EVERY component without
# following symlinks, then keep cleanup anchored to the verified directory fd.
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
sys.exit(1)
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
fd = os.open(root.anchor, flags)
previous = os.open(".", flags)
errors = []
try:
for part in root.parts[1:]:
child = os.open(part, flags, dir_fd=fd)
os.close(fd)
fd = child
if not shutil.rmtree.avoids_symlink_attacks:
raise OSError("descriptor-safe directory removal is unavailable")
os.fchdir(fd)
for entry in os.scandir("."):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.name)
else:
os.unlink(entry.name)
except OSError as err:
errors.append(f"{entry.name}: {err}")
except OSError as err:
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
sys.exit(1)
finally:
os.fchdir(previous)
os.close(previous)
os.close(fd)
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
@@ -0,0 +1,146 @@
name: Block post-merge-review paths
# A PR labelled "post-merge-review" may merge before its full review only if
# every changed file is allowed by .github/post-merge-review-allow.txt.
# This check fails such a PR otherwise; without the label it passes.
#
# pull_request_target: the workflow, the allow list and the script all come
# from the base branch, so a PR cannot change its own check. The PR's code is
# never checked out or run: only its commit is fetched, for the file list.
on:
pull_request_target:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
# edited: a retarget changes the base, and with it the diff.
types: [opened, synchronize, reopened, labeled, unlabeled, edited]
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
concurrency:
group: block-post-merge-review-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
paths:
name: post-merge-review paths
# GitHub-hosted: on the self-hosted runners this job ended in 'Set up
# job' with no log on every runner (2026-11-29), while spec trace, on the
# same runners, passes. Unlabelled PRs only echo here, so the hosted
# queue costs little; the merge gate does not wait for it unless the PR
# is labelled.
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Not labelled
if: ${{ !contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
working-directory: ${{ github.workspace }}
run: echo "no post-merge-review label; nothing to check"
- name: Checkout base
if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
ref: ${{ github.event.pull_request.base.sha }}
fetch-depth: 0
persist-credentials: false
- name: Check changed paths
if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
env:
BASE: ${{ github.event.pull_request.base.sha }}
HEAD: ${{ github.event.pull_request.head.sha }}
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
bash .github/scripts/post-merge-review-check-test.sh
git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head"
bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
# The allow list speaks for the module only: any host file keeps the full review.
git -C .. diff -z --name-only --no-renames "$BASE...$HEAD" -- . ':(exclude)seaweed-block/' \
':(exclude).github/workflows/block-*.yml' ':(exclude).github/dockerfiles/block-*.Dockerfile' ':(exclude).github/block/**' >host.bin
host=0
while IFS= read -r -d '' path; do
printf 'DENY host %q (outside seaweed-block)\n' "$path"
host=1
done <host.bin
bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt <changed.bin
exit "$host"
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
from pathlib import Path
import shutil
import sys
root = Path(os.environ["GITHUB_WORKSPACE"])
# Refuse aliases rather than resolving them. Open EVERY component without
# following symlinks, then keep cleanup anchored to the verified directory fd.
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
sys.exit(1)
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
fd = os.open(root.anchor, flags)
previous = os.open(".", flags)
errors = []
try:
for part in root.parts[1:]:
child = os.open(part, flags, dir_fd=fd)
os.close(fd)
fd = child
if not shutil.rmtree.avoids_symlink_attacks:
raise OSError("descriptor-safe directory removal is unavailable")
os.fchdir(fd)
for entry in os.scandir("."):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.name)
else:
os.unlink(entry.name)
except OSError as err:
errors.append(f"{entry.name}: {err}")
except OSError as err:
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
sys.exit(1)
finally:
os.fchdir(previous)
os.close(previous)
os.close(fd)
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
+202
View File
@@ -0,0 +1,202 @@
name: Publish block release
on:
workflow_dispatch:
push:
tags:
- "seaweed-block/v*"
permissions:
contents: write
packages: write
env:
REGISTRY: ghcr.io
BLOCK_IMAGE: ghcr.io/seaweedfs/seaweed-block
CSI_IMAGE: ghcr.io/seaweedfs/seaweed-block-csi
jobs:
publish:
# Publish only from a version tag; a manual run from a branch must not move :alpha.
if: startsWith(github.ref, 'refs/tags/seaweed-block/v')
runs-on: ubuntu-latest
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # the tag list decides whether :alpha moves
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Compute image tags
id: tags
shell: bash
run: |
set -euo pipefail
# vX.Y.Z-pre (a release candidate) publishes only its own version tag. A stable vX.Y.Z also
# publishes sha-*, and moves :alpha only when it is the highest stable version tag, so a later
# patch on an older line never moves :alpha back.
short_sha="${GITHUB_SHA::12}"
version="${GITHUB_REF_NAME#seaweed-block/}"
if [[ ! "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then
echo "refusing to publish: tag ${version} is not vX.Y.Z or vX.Y.Z-pre" >&2
exit 1
fi
notes="seaweed-block/docs/releases/${version%%-*}.md"
if [[ ! -s "${notes}" ]]; then
echo "refusing to publish: release notes ${notes} are missing or empty" >&2
exit 1
fi
echo "notes=${notes}" >> "$GITHUB_OUTPUT"
stable=false
move_alpha=false
if [[ "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
stable=true
highest="$(git tag -l 'seaweed-block/v*' | sed 's|^seaweed-block/||' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)"
if [[ "${version}" == "${highest}" ]]; then
move_alpha=true
fi
fi
{
echo "block_tags<<EOF"
echo "${BLOCK_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${BLOCK_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${BLOCK_IMAGE}:alpha"; fi
echo "EOF"
echo "csi_tags<<EOF"
echo "${CSI_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${CSI_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${CSI_IMAGE}:alpha"; fi
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Build and push block image
id: block
uses: docker/build-push-action@v6
with:
context: .
file: .github/dockerfiles/block-sw-block.Dockerfile
platforms: linux/amd64
push: true
tags: ${{ steps.tags.outputs.block_tags }}
- name: Build and push CSI image
uses: docker/build-push-action@v6
with:
context: .
file: .github/dockerfiles/block-blockcsi.Dockerfile
platforms: linux/amd64
push: true
tags: ${{ steps.tags.outputs.csi_tags }}
- name: Publish matching binary tarball
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BLOCK_DIGEST: ${{ steps.block.outputs.digest }}
NOTES: ${{ steps.tags.outputs.notes }}
shell: bash
run: |
set -euo pipefail
version="${GITHUB_REF_NAME#seaweed-block/}"
out="$RUNNER_TEMP/block-release"
mkdir -p "$out/bin"
docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"
container=$(docker create "${BLOCK_IMAGE}@${BLOCK_DIGEST}")
trap 'docker rm "$container" >/dev/null' EXIT
for binary in blockmaster blockvolume sw-block; do
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
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$version" == *-* ]]; then prerelease=true; fi
# A rerun replaces the assets, then publishes a draft an interrupted run left.
if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber
gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false
else
gh release create "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --verify-tag --latest=false \
--prerelease="$prerelease" --title "Seaweed Block $version" --notes-file "$NOTES"
fi
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
from pathlib import Path
import shutil
import sys
root = Path(os.environ["GITHUB_WORKSPACE"])
# Refuse aliases rather than resolving them. Open EVERY component without
# following symlinks, then keep cleanup anchored to the verified directory fd.
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
sys.exit(1)
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
fd = os.open(root.anchor, flags)
previous = os.open(".", flags)
errors = []
try:
for part in root.parts[1:]:
child = os.open(part, flags, dir_fd=fd)
os.close(fd)
fd = child
if not shutil.rmtree.avoids_symlink_attacks:
raise OSError("descriptor-safe directory removal is unavailable")
os.fchdir(fd)
for entry in os.scandir("."):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.name)
else:
os.unlink(entry.name)
except OSError as err:
errors.append(f"{entry.name}: {err}")
except OSError as err:
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
sys.exit(1)
finally:
os.fchdir(previous)
os.close(previous)
os.close(fd)
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
+164
View File
@@ -0,0 +1,164 @@
name: Block spec trace
# Every PR description carries the spec trace (see the PR template); this
# check fails a PR whose description does not.
#
# pull_request_target: the workflow and the script come from the base branch,
# so a PR cannot change its own check. The PR's code is never checked out or
# run: only its commit is fetched, for the file list. The description is read
# from the event through an environment variable, never interpolated.
on:
pull_request_target:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
# edited: the check reads the description and the base.
types: [opened, synchronize, reopened, edited]
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
concurrency:
group: block-spec-trace-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
trace:
name: spec trace
# The base-owned check defaults to a disposable hosted runner. Only a
# same-repository PR may opt into the registered BLOCK_RUNNER_LABEL.
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
timeout-minutes: 5
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout base
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
# github.sha is the tip of the base branch when the event fires; the
# PR's base.sha can predate this workflow's own scripts.
ref: ${{ github.sha }}
fetch-depth: 0
persist-credentials: false
# spec-trace-check.sh builds the trusted sametokens.go; a self-hosted
# runner has no Go on its PATH unless the job sets it up.
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: seaweed-block/go.mod
cache: false
- name: Check spec trace
env:
BASE: ${{ github.event.pull_request.base.sha }}
HEAD: ${{ github.event.pull_request.head.sha }}
PR: ${{ github.event.pull_request.number }}
BODY: ${{ github.event.pull_request.body }}
TITLE: ${{ github.event.pull_request.title }}
run: |
set -euo pipefail
bash .github/scripts/spec-trace-check-test.sh
python3 -B .github/scripts/model-trace-check-test.py
bash .github/scripts/changed-go-blobs-test.sh
# fsckObjects: a PR's objects are checked as they arrive, so a tree
# with a '..' or '.git' entry is refused here.
git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head"
printf '%s' "$BODY" >body.txt
bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
# Old and new blobs of each changed non-test Go file, for kind DOCS
# (objects only; a path that would leave blobs/ is refused).
mb=$(git merge-base "$BASE" "$HEAD")
bash ../.github/block/scripts/changed-go-blobs.sh "$mb" "$HEAD" blobs
# Mapping and validator come from the trusted base checkout above.
bash .github/scripts/spec-trace-check.sh body.txt blobs .github/model-code-trace.tsv <changed.bin
# Internal names stay out of this public repository: added lines,
# commit messages, title and description (no PR code is run).
bash .github/scripts/public-text-check-test.sh
printf '%s' "$TITLE" >title.txt
bash ../.github/block/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt
- name: Invariants ledger anchors (report only)
# Every code and test anchor of docs/design/invariants.md must exist at
# the PR's commit (git objects only; nothing from the PR is run). It
# reports and does not fail the check while the known imprecise
# anchors are being corrected; then this step becomes gating.
continue-on-error: true
env:
HEAD: ${{ github.event.pull_request.head.sha }}
run: python3 -I ../.github/block/scripts/ledger_check.py "$GITHUB_WORKSPACE" "$HEAD" seaweed-block/docs/design/invariants.md seaweed-block/ || true
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
from pathlib import Path
import shutil
import sys
root = Path(os.environ["GITHUB_WORKSPACE"])
# Refuse aliases rather than resolving them. Open EVERY component without
# following symlinks, then keep cleanup anchored to the verified directory fd.
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
sys.exit(1)
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
fd = os.open(root.anchor, flags)
previous = os.open(".", flags)
errors = []
try:
for part in root.parts[1:]:
child = os.open(part, flags, dir_fd=fd)
os.close(fd)
fd = child
if not shutil.rmtree.avoids_symlink_attacks:
raise OSError("descriptor-safe directory removal is unavailable")
os.fchdir(fd)
for entry in os.scandir("."):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.name)
else:
os.unlink(entry.name)
except OSError as err:
errors.append(f"{entry.name}: {err}")
except OSError as err:
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
sys.exit(1)
finally:
os.fchdir(previous)
os.close(previous)
os.close(fd)
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
+449
View File
@@ -0,0 +1,449 @@
name: Block Test
on:
pull_request:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
# ready_for_review: a Draft runs no Go suite (below); marking it ready starts one.
types: [opened, synchronize, reopened, ready_for_review]
push:
paths:
- "seaweed-block/**"
- ".github/workflows/block-*.yml"
- ".github/block/**"
- ".github/dockerfiles/block-*.Dockerfile"
branches:
- master
defaults:
run:
working-directory: seaweed-block
permissions:
contents: read
# One run per PR (or per commit for pushes). A new push to a PR cancels the
# superseded run; a queued master run would be replaced by a newer one in a
# shared group, so each merge gets its own group and its own result.
concurrency:
group: block-test-${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
test:
# One job, two suites, one runner selection. 'unit' is the Go suite below;
# 'process' runs the process-level tests: real blockmaster, blockvolume and
# sw-block against a pinned SeaweedFS release. Those tests are named in
# .github/process-level-tests.txt, and every one must PASS, so a test that
# skips, fails, never starts or is cut off by the timeout fails the suite.
# Tests that need root or systemd are not in the list (see its header).
strategy:
fail-fast: false
matrix:
suite: [unit, process]
name: ${{ matrix.suite == 'unit' && 'go test (linux)' || 'process-level tests (real binaries)' }}
# The suite writes heavily to the runner disk (real files, fsync), so a
# Draft PR skips it; its author tests locally until the PR is ready.
if: github.event_name == 'push' || !github.event.pull_request.draft
# Hosted by default until this repository has a registered block pool.
# Set BLOCK_RUNNER_LABEL only for an available dedicated label. Forks
# always stay on disposable GitHub-hosted runners.
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
# process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence).
timeout-minutes: ${{ matrix.suite == 'unit' && 60 || 90 }}
env:
# Pure-Go build: no package in the default build needs cgo, and the
# hosted runner should not depend on a C toolchain being present.
CGO_ENABLED: "0"
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
persist-credentials: false
# Two commits: the PR merge commit and its base parent, so the test
# step can see which packages the PR touches.
fetch-depth: 2
- name: Nested module CI contracts
run: |
python3 -I ../.github/block/scripts/block-ci-port-test.py
python3 -B ../.github/block/scripts/runner-workspace-test.py
- name: Relative documentation links
if: matrix.suite == 'unit'
run: |
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;
# this names the runner and stops the job before it starts.
if: runner.environment == 'self-hosted'
run: |
bash .github/scripts/require-nvme-test.sh
bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}"
- name: Start whole-job load evidence
# Begins after checkout, before toolchain setup/build/tests. No host
# installation or privileged reads. A job-sized lifetime also bounds
# the sampler if cancellation prevents the stop step.
continue-on-error: true
env:
CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }}
run: |
echo "CI_EVIDENCE_DIR=$CI_EVIDENCE_DIR" >>"$GITHUB_ENV"
mkdir -p "$CI_EVIDENCE_DIR"
: >"$CI_EVIDENCE_DIR/go-test.json"
python3 -I .github/scripts/ci-load.py start "$CI_EVIDENCE_DIR/load.tsv" --duration ${{ matrix.suite == 'unit' && 2400 || 5400 }}
- name: Self-test evidence capture
run: |
python3 -B .github/scripts/ci-load-test.py
bash .github/scripts/record-go-test-test.sh
- name: Docs-only pull request
id: scope
if: matrix.suite == 'process' && github.event_name == 'pull_request'
# A pull request that changes only files under docs/ runs no product
# code the process-level tests could exercise, so they are skipped and
# the job still reports success. HEAD is the merge commit, HEAD^1 its
# base parent (fetch-depth 2 above). Pushes to main always run them, and
# so does any error of the check (../.github/block/scripts/docs-only-scope.sh).
run: |
set -euo pipefail
bash .github/scripts/docs-only-scope-test.sh
if out=$(bash ../.github/block/scripts/docs-only-scope.sh HEAD^1 HEAD); then
case $out in
"docs_only "*)
echo "skipped: docs only (${out#docs_only } files under docs/); the process-level tests run on the merge to main"
echo "docs_only=1" >>"$GITHUB_OUTPUT" ;;
*) echo "process-level tests run: $out" ;;
esac
else
echo "process-level tests run: the docs-only check failed"
fi
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: seaweed-block/go.mod
# The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk;
# uploading them as an Actions cache (~4 GB) in the post step
# outlasted the job timeout after every test had passed. Only the
# GitHub-hosted (fork PR) runner uses the Actions cache.
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: seaweed-block/go.sum
- name: Go version
if: matrix.suite == 'unit'
run: go version
- name: Build
if: matrix.suite == 'unit'
run: go build ./...
- name: Vet
if: matrix.suite == 'unit'
run: go vet ./...
- name: Lab build tags stay out of images and releases
if: matrix.suite == 'unit'
# swblock_lab_bigvol lifts the 1 TiB create cap and the local
# headroom refusal for scale rehearsals only; swblock_v11_format turns
# on the draft v1.1 store format. The default test run pins the
# release cap (TestReleaseBuildKeepsTheCreateCap) and the release
# format. This step checks the tags' allowlist and that every image
# Dockerfile refuses a lab binary (scripts/refuse-lab-binary.sh) after
# its build, with controls, then tests each tag alone and both.
run: |
set -euo pipefail
bash .github/scripts/lab-tag-check.sh .
bash .github/scripts/lab-tag-check-test.sh
for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do
go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'Lab|Headroom|Revision|LegacyBound' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/
done
- name: Test default configuration
if: matrix.suite == 'unit'
# Preserve the existing scope: main/train omit the four heavy packages;
# ordinary PRs add each only when its direct package files are touched.
# Three subprocesses share this ONE runner: storage, durable plus touched
# master/authority, and the remaining selected packages at -p=4.
env:
EVENT: ${{ github.event_name }}
HEAD_REF: ${{ github.head_ref }}
run: |
set -euo pipefail
python3 -I ../.github/block/scripts/unit-test-shards-test.py
python3 -I ../.github/block/scripts/run-unit-groups-test.py
plan="$RUNNER_TEMP/unit-groups"
mkdir -p "$plan"
go list ./... >"$plan/all.txt"
mod=$(go list -m)
# Main pushes need no changed-path list; a shallow initial push may
# have no parent. Ordinary PRs use the merge commit's base parent.
: >"$plan/changed.txt"
if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then
git diff --relative --name-only --no-renames HEAD^1 HEAD -- . >"$plan/changed.txt"
fi
python3 -I ../.github/block/scripts/unit-test-shards.py "$mod" "$plan" "$EVENT" "$HEAD_REF" "$plan/changed.txt" <"$plan/all.txt"
python3 -I ../.github/block/scripts/run-unit-groups.py "$plan" "$CI_EVIDENCE_DIR" "$RUNNER_TEMP/unit-group-tmp" \
bash .github/scripts/record-go-test.sh
- name: Format v3 tagged tests
if: matrix.suite == 'unit'
# The swblock_format_v3_test tests of the four packages that carry them.
# Five durable tests are skipped by name: each installs a BASE on a chunk
# store, which no production path does (its invariant row is DORMANT);
# they are rewritten at the start of the next release, then this skip
# goes.
run: |
set -euo pipefail
skip='^(TestDurableProviderV3_AttachesCompletedChunkBASE|TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD|TestDurableProviderV3_DefersBASERetirementUntilLocalPresence|TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE|TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE)$'
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -count=1 -timeout 20m -tags swblock_format_v3_test -skip "$skip" \
./core/frontend/durable/ ./core/recovery/ ./core/replication/ ./core/transport/
- name: Self-test of the required-tests gate
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# The gate must fail on a skip, a failure, a test that never ran, one
# cut off mid-run, and one that reports PASS and then exits nonzero or
# hangs; this proves it before it judges the real run.
run: |
python3 -I .github/scripts/required-tests-check-test.py
bash .github/scripts/chunkstore-scope-test.sh
bash .github/scripts/run-named-tests-test.sh
python3 -I .github/scripts/shard-named-tests-test.py
- name: Pinned SeaweedFS
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# The release archive is checked against its sha256 before every use,
# also when taken from the runner's cache; a mismatch fails the step.
# Nothing else is fetched.
env:
WEED_VERSION: "4.53"
WEED_SHA256: d1a7dec9f48d8b33895a0ea8951971defc2dc5312906dcc76fa5a5f74a6ee90d
run: |
set -euo pipefail
cache="${RUNNER_TOOL_CACHE:-$RUNNER_TEMP}/seaweedfs-weed/$WEED_VERSION"
tgz="$cache/linux_amd64.tar.gz"
mkdir -p "$cache"
if ! echo "$WEED_SHA256 $tgz" | sha256sum -c --status - 2>/dev/null; then
part="$tgz.$$.part"
curl -fsSL --retry 3 -o "$part" "https://github.com/seaweedfs/seaweedfs/releases/download/$WEED_VERSION/linux_amd64.tar.gz"
echo "$WEED_SHA256 $part" | sha256sum -c - || { rm -f "$part"; exit 1; }
mv -f "$part" "$tgz"
fi
bin="$RUNNER_TEMP/weed-$WEED_VERSION"
mkdir -p "$bin"
tar -xzf "$tgz" -C "$bin" weed
echo "CHUNKSTORE_WEED=$bin/weed" >>"$GITHUB_ENV"
- name: Real-filer integration tests
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# The chunkstore_integration tests run against the pinned weed above
# (master, volume and filer as real processes): the conditional HEAD
# writes, cut uploads and object deletes of the chunk store, and the
# layout sync crash cases of the durable provider. They fail, never
# skip, without the binary. Pushes to main and train PRs always run
# them; another PR runs them when it touches core/frontend/chunkstore/,
# core/storage/ or core/frontend/durable/.
env:
EVENT: ${{ github.event_name }}
HEAD_REF: ${{ github.head_ref }}
# ../.github/block/scripts/chunkstore-scope.sh decides; an error of that check
# runs the tests. Each filtered run must PASS at least one test, so a
# filter that matches nothing fails instead of passing empty.
run: |
set -euo pipefail
if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then
if out=$(bash ../.github/block/scripts/chunkstore-scope.sh HEAD^1 HEAD); then
case $out in
"skip "*) echo "skipped: the PR touches neither core/frontend/chunkstore/ nor core/storage/ ($out)"; exit 0 ;;
*) echo "real-filer integration tests run: $out" ;;
esac
else
echo "real-filer integration tests run: the scope check failed"
fi
fi
for spec in "./core/frontend/chunkstore/ ^TestIntegration" "./core/frontend/durable/ ^TestQD1LayoutSync"; do
pkg=${spec%% *}; filter=${spec#* }
log="$RUNNER_TEMP/integration-$(basename "$pkg").log"
bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -v -timeout 20m -tags chunkstore_integration -run "$filter" "$pkg" 2>&1 | tee "$log"
grep -q '^--- PASS: ' "$log" || { echo "no test of $pkg matched $filter"; exit 1; }
done
- name: Build the binaries and the test binary once
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
run: |
set -euo pipefail
bins="$RUNNER_TEMP/swblock-bins"
mkdir -p "$bins"
for b in blockmaster blockvolume sw-block; do go build -o "$bins/$b" "./cmd/$b"; done
go test -c -tags 'subprocess chunkstore_integration' -o "$bins/blockvolume.test" ./cmd/blockvolume
go test -c -o "$bins/blockcsi.test" ./cmd/blockcsi
# The known-zero acceptance's first-start crash step holds a test-only
# blockvolume (build tag kzhold, never released) at a chosen point.
go build -tags kzhold -o "$RUNNER_TEMP/blockvolume-kzhold" ./cmd/blockvolume
echo "SWBLOCK_TEST_BINS=$bins" >>"$GITHUB_ENV"
echo "KZ_HOLD_BIN=$RUNNER_TEMP/blockvolume-kzhold" >>"$GITHUB_ENV"
- name: Run the named process-level tests
if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'
# Each named test in its own process of the one test binary, in
# sequence, so a panic or a hang in one cannot hide the others; each
# is bounded (TEST_TIMEOUT, then killed) and its exit status is kept:
# the gate needs a PASS event AND exit 0 for every named test. The known-zero acceptance
# runs its small shape (1 GiB, user-space client, no device); the
# 1 TiB run is lab only.
env:
KZ_RUN: "1"
KZ_SIZE: 1G
F1_RUN: "1"
TEST_TIMEOUT: 15m
# A failed test copies each daemon's whole log here (keepFullLog);
# the step below keeps them as the run's artifact.
SWBLOCK_TEST_LOG_DIR: ${{ env.CI_EVIDENCE_DIR }}/daemon-logs
run: |
set -euo pipefail
# SHARDS parallel shards, balanced by their last measured times
# (.github/process-level-seconds.txt). Each shard is its own sequence
# of test processes with its own slice of the test port ranges
# (SWBLOCK_TEST_PORT_SHARD) and its own TMPDIR; the gate judges every
# named test from all the shards together.
names=.github/process-level-tests.txt
# The manifest tags CSI entries; every other name uses blockvolume.test.
# The final checker still requires the complete, unsplit manifest.
awk '!/# package=blockcsi/' "$names" > "$RUNNER_TEMP/blockvolume-names.txt"
awk '/# package=blockcsi/ {sub(/#.*/, ""); if ($0 ~ /[^[:space:]]/) print}' "$names" > "$RUNNER_TEMP/blockcsi-names.txt"
test -s "$RUNNER_TEMP/blockcsi-names.txt"
shards=4
python3 -I .github/scripts/shard-named-tests.py "$RUNNER_TEMP/blockvolume-names.txt" .github/process-level-seconds.txt "$shards" "$RUNNER_TEMP/shard"
pids=()
for k in $(seq 1 "$shards"); do
mkdir -p "$RUNNER_TEMP/tmp-$k"
SWBLOCK_TEST_PORT_SHARD=$k SWBLOCK_TEST_PORT_SHARDS=$shards TMPDIR="$RUNNER_TEMP/tmp-$k" \
bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockvolume.test" "$RUNNER_TEMP/shard/$k.txt" \
"$RUNNER_TEMP/process-level-$k.json" "$RUNNER_TEMP/process-level-$k.status" "$TEST_TIMEOUT" cmd/blockvolume \
>"$RUNNER_TEMP/process-level-$k.log" 2>&1 &
pids+=($!)
done
for p in "${pids[@]}"; do wait "$p" || true; done
for k in $(seq 1 "$shards"); do sed "s/^/[shard $k] /" "$RUNNER_TEMP/process-level-$k.log"; done
# CSI uses the same per-case isolation, timeout and verdict as the shards.
TEST_PKG=github.com/seaweedfs/seaweed-block/cmd/blockcsi \
bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockcsi.test" "$RUNNER_TEMP/blockcsi-names.txt" \
"$RUNNER_TEMP/process-level-csi.json" "$RUNNER_TEMP/process-level-csi.status" "$TEST_TIMEOUT" cmd/blockcsi \
>"$RUNNER_TEMP/process-level-csi.log" 2>&1 || true
cat "$RUNNER_TEMP/process-level-csi.log"
cat "$RUNNER_TEMP"/process-level-*.status >"$RUNNER_TEMP/process-level.status"
python3 -I .github/scripts/required-tests-check.py --status "$RUNNER_TEMP/process-level.status" \
"$names" "$RUNNER_TEMP"/process-level-*.json
- name: Stop load evidence and collect raw process events
if: always()
continue-on-error: true
env:
SUITE: ${{ matrix.suite }}
run: |
if [ -z "${CI_EVIDENCE_DIR:-}" ]; then exit 0; fi
python3 -I .github/scripts/ci-load.py stop "$CI_EVIDENCE_DIR/load.tsv" || true
if [ "$SUITE" = process ]; then
mkdir -p "$CI_EVIDENCE_DIR/shards"
shopt -s nullglob
for file in "$RUNNER_TEMP"/process-level-*.json "$RUNNER_TEMP"/process-level-*.log "$RUNNER_TEMP"/process-level*.status; do
cp "$file" "$CI_EVIDENCE_DIR/shards/"
done
for file in "$CI_EVIDENCE_DIR"/shards/*.json; do cat "$file" >>"$CI_EVIDENCE_DIR/go-test.json"; done
fi
- name: Keep failed-job tests, load, daemon logs and shard results
# Both suites retain timed events and whole-job load. Process evidence
# also retains the original shard receipts and full daemon logs.
if: failure()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ env.CI_EVIDENCE_DIR }}
retention-days: 14
if-no-files-found: warn
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 -I - <<'PY'
import os
from pathlib import Path
import shutil
import sys
root = Path(os.environ["GITHUB_WORKSPACE"])
# Refuse aliases rather than resolving them. Open EVERY component without
# following symlinks, then keep cleanup anchored to the verified directory fd.
if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]):
print(f"runner_workspace_cleanup_refused path={str(root)!r}")
sys.exit(1)
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
fd = os.open(root.anchor, flags)
previous = os.open(".", flags)
errors = []
try:
for part in root.parts[1:]:
child = os.open(part, flags, dir_fd=fd)
os.close(fd)
fd = child
if not shutil.rmtree.avoids_symlink_attacks:
raise OSError("descriptor-safe directory removal is unavailable")
os.fchdir(fd)
for entry in os.scandir("."):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.name)
else:
os.unlink(entry.name)
except OSError as err:
errors.append(f"{entry.name}: {err}")
except OSError as err:
print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}")
sys.exit(1)
finally:
os.fchdir(previous)
os.close(previous)
os.close(fd)
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
+2
View File
@@ -9,6 +9,7 @@ on:
- 'weed/storage/volume_vacuum*.go'
- 'weed/storage/volume_loading.go'
- 'weed/storage/disk_location.go'
- 'weed/server/filer_grpc_server_rename.go'
- 'test/winfsp/**'
- '.github/workflows/mount-windows.yml'
# No base branch filter: this is the only thing that runs the Windows mount,
@@ -20,6 +21,7 @@ on:
- 'weed/storage/volume_vacuum*.go'
- 'weed/storage/volume_loading.go'
- 'weed/storage/disk_location.go'
- 'weed/server/filer_grpc_server_rename.go'
- 'test/winfsp/**'
- '.github/workflows/mount-windows.yml'
+57 -10
View File
@@ -1,17 +1,21 @@
name: "release: bump version and cut the release"
# One entry point for a SeaweedFS release:
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, commit to master
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, point the
# chart's cosi.image at the newest COSI driver release, commit to master
# 2. push the <appVersion> tag, which fans out to the workflows that trigger on
# `push: tags` (binaries_release*, container_release_unified, helm_manual_release)
# 3. create the GitHub release, with GitHub's generated notes
# 4. dispatch "Prepare release" in seaweedfs-csi-driver and seaweedfs-operator,
# which pick up the new master through `go get -u`, and wait for both
# 4. dispatch "Prepare release" in seaweedfs-csi-driver, seaweedfs-operator and
# seaweedfs-cosi-driver, which pick up the new master through `go get`, and
# wait for all three. The COSI driver image cut here reaches the chart at
# the next release, through step 1.
#
# Events raised by the default GITHUB_TOKEN do not start other workflows, and it
# cannot reach the other two repositories at all. Add a repo secret RELEASE_PAT
# with `contents: write` here and `actions: write` on the csi-driver and operator
# repos. Without it the tag is still pushed, but nothing downstream of it runs.
# cannot reach the other repositories at all. Add a repo secret RELEASE_PAT
# with `contents: write` here and `actions: write` on the csi-driver, operator
# and cosi-driver repos. Without it the tag is still pushed, but nothing
# downstream of it runs.
on:
workflow_dispatch:
@@ -28,7 +32,7 @@ on:
type: string
required: false
downstream:
description: "Also release the CSI driver and the operator"
description: "Also release the CSI driver, the operator and the COSI driver"
type: boolean
default: true
dry_run:
@@ -134,6 +138,43 @@ jobs:
sed -i -E "s/^version:.*/version: ${CHART_VERSION}/" "$CHART"
cat "$CHART"
- name: Point the chart at the newest COSI driver release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: seaweedfs/seaweedfs-cosi-driver
run: |
set -euo pipefail
VALUES=k8s/charts/seaweedfs/values.yaml
IMAGE="ghcr.io/${REPO}"
CUR=$(grep -oP "^ image: \"${IMAGE}:\K[^\"]+" "$VALUES" || true)
if [ -z "$CUR" ]; then
echo "::warning::no ${IMAGE} image line in ${VALUES}; cosi.image is left alone"
exit 0
fi
# Not worth failing a release over: keep the current image instead.
if ! NEW=$(timeout 60 gh release view -R "$REPO" --json tagName --jq .tagName); then
echo "::warning::could not read the latest ${REPO} release; cosi.image stays ${CUR}"
exit 0
fi
if [ "$NEW" = "$CUR" ]; then
echo "cosi.image is already ${CUR}"
exit 0
fi
if [ "$(printf '%s\n%s\n' "${CUR#v}" "${NEW#v}" | sort -V | tail -n1)" != "${NEW#v}" ]; then
echo "::warning::the latest ${REPO} release ${NEW} is older than ${CUR}; cosi.image stays ${CUR}"
exit 0
fi
# A release without its image would break every chart install with cosi.enabled.
TOKEN=$(curl -sf --connect-timeout 10 --max-time 30 "https://ghcr.io/token?scope=repository:${REPO}:pull" | jq -r .token || true)
if ! curl -sfI -o /dev/null --connect-timeout 10 --max-time 30 -H "Authorization: Bearer ${TOKEN}" \
-H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \
"https://ghcr.io/v2/${REPO}/manifests/${NEW}"; then
echo "::warning::${IMAGE}:${NEW} is not pullable; cosi.image stays ${CUR}"
exit 0
fi
sed -i -E "s|^( image: \"${IMAGE}:)[^\"]+\"|\1${NEW}\"|" "$VALUES"
grep -n "^ image: \"${IMAGE}:" "$VALUES"
- name: Commit, and push the tag
id: tag
env:
@@ -156,7 +197,7 @@ jobs:
if git diff --quiet; then
echo "::warning::Version files are already at ${TAG}; tagging the current HEAD."
else
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml k8s/charts/seaweedfs/values.yaml
git commit -m "${TAG}"
git push
fi
@@ -187,14 +228,20 @@ jobs:
include:
- repo: seaweedfs/seaweedfs-csi-driver
workflow: prepare_release.yaml
ref: master
- repo: seaweedfs/seaweedfs-operator
workflow: prepare_release.yml
ref: master
- repo: seaweedfs/seaweedfs-cosi-driver
workflow: prepare_release.yaml
ref: main
steps:
- name: Release ${{ matrix.repo }}
env:
GH_TOKEN: ${{ secrets.RELEASE_PAT }}
REPO: ${{ matrix.repo }}
WORKFLOW: ${{ matrix.workflow }}
REF: ${{ matrix.ref }}
SHA: ${{ needs.release.outputs.sha }}
MODULE: github.com/seaweedfs/seaweedfs
run: |
@@ -204,7 +251,7 @@ jobs:
exit 1
fi
# The dispatched workflow pins seaweedfs with `go get -u ...@latest`, so
# The dispatched workflow pins seaweedfs with `go get ...@latest`, so
# wait until the proxy serves the release commit as the tip. Asking for
# the commit by name is what makes the proxy fetch it. The proxy can
# take longer than five minutes to refresh @latest after a new tag.
@@ -231,7 +278,7 @@ jobs:
BEFORE=$(released)
# A minute early, so runner clock skew cannot hide the run.
DISPATCHED_AT=$(date -u -d '1 minute ago' '+%Y-%m-%dT%H:%M:%SZ')
gh workflow run -R "$REPO" "$WORKFLOW" --ref master -f bump=patch -f update_seaweedfs=true
gh workflow run -R "$REPO" "$WORKFLOW" --ref "$REF" -f bump=patch -f update_seaweedfs=true
RUN_ID=""
for _ in $(seq 12); do
+20
View File
@@ -56,6 +56,26 @@ 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
+47
View File
@@ -722,6 +722,53 @@ The chart does not enable `runAsNonRoot` by default because its default `hostPat
Security contexts configured for a component also apply to the chart-managed helper containers for that component. User-provided init containers and sidecars must define their own container security context and writable mounts.
### Run as a non-root user with PVC storage
The standard SeaweedFS image creates a `seaweed` user and group with UID/GID `1000`. Configure the pod security context so kubelet gives that user access to the mounted volumes. kubelet applies `fsGroup` to claims and `emptyDir`, but not to `hostPath`, which the master, volume and filer data and logs use by default, so move those off `hostPath` as well:
```yaml
master:
data:
type: "persistentVolumeClaim"
size: "1Gi"
logs:
type: "emptyDir"
podSecurityContext:
enabled: true
runAsUser: 1000
runAsGroup: 1000
runAsNonRoot: true
fsGroup: 1000
volume:
dataDirs:
- name: data1
type: "persistentVolumeClaim"
size: "100Gi"
maxVolumes: 0
podSecurityContext:
enabled: true
runAsUser: 1000
runAsGroup: 1000
runAsNonRoot: true
fsGroup: 1000
filer:
data:
type: "persistentVolumeClaim"
size: "25Gi"
logs:
type: "emptyDir"
podSecurityContext:
enabled: true
runAsUser: 1000
runAsGroup: 1000
runAsNonRoot: true
fsGroup: 1000
```
Apply the same `podSecurityContext` to every other enabled workload, such as `s3`, `admin`, `worker`, or `sftp`, and set `s3.logs` and `sftp.logs` to `emptyDir`; for an all-in-one deployment, use the `allInOne` values key. If you use a custom image with a different UID/GID, replace `1000` with the values for that image. Storage classes that do not support `fsGroup` may need permissions adjusted on the storage backend. A release that already runs on `hostPath` cannot switch its claims in place; see [Master data](#master-data-hostpath-vs-a-claim).
## OpenShift Support
SeaweedFS can be deployed on OpenShift or any cluster enforcing the Kubernetes "restricted" Pod Security Standard. By default, OpenShift blocks containers that run as root or use `hostPath` volumes.
+1030 -1042
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 53 KiB

+6 -4
View File
@@ -11,14 +11,14 @@ cmd/sw-block/volume_backup.go RestoreCommand.Abort
cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify
cmd/sw-block/volume_backup.go RestoreCommand.Run
cmd/sw-block/volume_backup.go RestoreCommand.Start
cmd/sw-block/volume_start_release.go StopAndRestart.CrashRestart
cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean
cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean
cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen
cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
cmd/sw-block/volume_verbs.go CutTime.Poll
cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
core/authority/authority.go DeleteRetire.Retire
core/authority/authority_store_file.go DeleteRetire.Retire
core/authority/authority.go DeleteRetire.RetireLine
core/authority/authority_store_file.go DeleteRetire.RetireLine
core/authority/workspace.go HolderInterface.ForcedMove
core/authority/workspace.go HolderInterface.PlannedMove
core/authority/workspace.go MoveAdmission.Ack
@@ -36,7 +36,7 @@ core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
core/authority/workspace_lease_view.go HolderInterface.Grant
core/authority/workspace_lease_view.go HolderInterface.Regrant
core/authority/workspace_retirement.go DeleteRetire.Retire
core/authority/workspace_retirement.go DeleteRetire.RetireLine
core/engine/apply.go ReplicationPeer.Reconcile
core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
core/frontend/chunkstore/catalog_b.go CleanBatch.Request
@@ -187,6 +187,7 @@ core/frontend/durable/provider_layout.go EngineAdapter.SettleDown
core/frontend/durable/provider_layout.go StopAndRestart.SettleDown
core/frontend/durable/provider_preempt.go CutTime.Preempt
core/frontend/durable/provider_preempt.go CutTime.Settle
core/frontend/durable/provider_seal_replay.go PlainSealReplay.Reply
core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite
core/frontend/durable/storage_adapter.go HolderInterface.Write
core/frontend/durable/storage_adapter.go WALHold.Resubmit
@@ -206,6 +207,7 @@ core/host/master/product_loop.go FencingRound.Decide
core/host/master/product_loop.go Promotion.Decide
core/host/master/services.go FormatGate.Report
core/host/master/spec_retirement.go DeleteRetire.ReadOK
core/host/master/spec_retirement.go DeleteRetire.RetirePlace
core/host/master/store_attestation.go ReplicationPeer.Attest
core/host/master/workspace_binding.go FormatGate.Grant
core/host/master/workspace_binding.go MoveAdmission.Ack
1 # Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
11 cmd/sw-block/volume_backup.go
12 cmd/sw-block/volume_backup.go
13 cmd/sw-block/volume_backup.go
14 cmd/sw-block/volume_start_release.go
15 cmd/sw-block/volume_start_release.go
16 cmd/sw-block/volume_start_release.go
cmd/sw-block/volume_start_release.go
17 cmd/sw-block/volume_verbs.go
18 cmd/sw-block/volume_verbs.go
19 cmd/sw-block/workspace_show.go
20 core/authority/authority.go
21 core/authority/authority_store_file.go
22 core/authority/workspace.go
23 core/authority/workspace.go
24 core/authority/workspace.go
36 core/authority/workspace_delete_reservation.go
37 core/authority/workspace_lease_view.go
38 core/authority/workspace_lease_view.go
39 core/authority/workspace_retirement.go
40 core/engine/apply.go
41 core/frontend/chunkstore/catalog_b.go
42 core/frontend/chunkstore/catalog_b.go
187 core/frontend/durable/provider_layout.go
188 core/frontend/durable/provider_preempt.go
189 core/frontend/durable/provider_preempt.go
190 core/frontend/durable/provider_seal_replay.go
191 core/frontend/durable/storage_adapter.go
192 core/frontend/durable/storage_adapter.go
193 core/frontend/durable/storage_adapter.go
207 core/host/master/product_loop.go
208 core/host/master/services.go
209 core/host/master/spec_retirement.go
210 core/host/master/spec_retirement.go
211 core/host/master/store_attestation.go
212 core/host/master/workspace_binding.go
213 core/host/master/workspace_binding.go
+8
View File
@@ -97,3 +97,11 @@ 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,6 +7,41 @@ 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:
@@ -23,6 +58,7 @@ class ReleaseAssets(unittest.TestCase):
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
+3 -1
View File
@@ -33,9 +33,11 @@ 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
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block sw-block.tmpfiles.conf
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$tag" == *-* ]]; then prerelease=true; fi
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
# Draft PR skips it; its author tests locally until the PR is ready.
if: github.event_name == 'push' || !github.event.pull_request.draft
# Pull requests run on GitHub-hosted runners (free for this public repo, many
# jobs in parallel); pushes to main keep the team's tp04 runner (seaweed.slice,
# jobs in parallel); pushes to main keep the team's self-hosted runner (seaweed.slice,
# capped at 8 cores / 8 GiB) as the self-hosted signal. A train PR (branch
# train/* of this repository, a few a day) also runs on the team's runners:
# it is the merge gate, and the organization's shared GitHub-hosted queue held
+10 -8
View File
@@ -116,23 +116,25 @@ TAG=v1.1.1
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
export PATH="$PWD:$PATH" # so the sw-block commands that mini prints run as shown
# 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
# blockvolume keeps one lock per volume here, so only one live process serves a volume on a host:
sudo install -d -m 0755 -o root -g root /run/sw-block
sudo install -d -m 0755 -o "$USER" -g "$(id -gn)" /run/sw-block/locks
./sw-block mini --dir ./swb-mini --weed /path/to/weed
```
A failed start leaves `--dir` behind: start again with a new `--dir`, or on the same one with `--reuse`.
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 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. A scheduled
`sched-<time>` snapshot also appears soon after the start. A restore into a new volume does not run inside `mini`
yet; use the standalone setup for it.
- 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.
**Next:**
@@ -0,0 +1,91 @@
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
// Re-importing the same declarative spec must preserve the durable records,
// including the registration observation time. This checks replacement, not
// just equal JSON: an identical rewrite still pays the durability barriers.
func TestUnchangedSpecRestartKeepsAll999ImportRecords(t *testing.T) {
const count = 999
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
open := func() *master.Host {
t.Helper()
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir})
if err != nil {
t.Fatal(err)
}
return h
}
closeHost := func(h *master.Host) {
t.Helper()
h.Start()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.Close(ctx); err != nil {
t.Fatal(err)
}
}
nodes := make([]lifecycle.NodeRegistration, count)
intents := make([]lifecycle.PlacementIntent, count)
for i := range nodes {
id := fmt.Sprintf("n%04d", i)
nodes[i] = lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"}
intents[i] = lifecycle.PlacementIntent{VolumeID: fmt.Sprintf("v%04d", i), DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: id, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}
}
importSpec := func(h *master.Host) {
t.Helper()
if err := importLifecycleNodeInventory(h, nodes); err != nil {
t.Fatal(err)
}
if err := importLifecyclePlacementIntents(h, intents); err != nil {
t.Fatal(err)
}
}
h := open()
importSpec(h)
closeHost(h)
before := make(map[string]os.FileInfo, 2*count)
for _, kind := range []string{"nodes", "placements"} {
entries, err := os.ReadDir(filepath.Join(lifecycleDir, kind))
if err != nil {
t.Fatal(err)
}
if len(entries) != count {
t.Fatalf("%s records=%d, want %d", kind, len(entries), count)
}
for _, entry := range entries {
path := filepath.Join(lifecycleDir, kind, entry.Name())
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
before[path] = info
}
}
h = open()
importSpec(h)
closeHost(h)
rewritten := map[string]int{}
for path, info := range before {
after, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if !os.SameFile(info, after) || !info.ModTime().Equal(after.ModTime()) {
rewritten[filepath.Base(filepath.Dir(path))]++
}
}
if rewritten["nodes"] != 0 || rewritten["placements"] != 0 {
t.Fatalf("unchanged restart replaced records: nodes=%d placements=%d; want zero", rewritten["nodes"], rewritten["placements"])
}
}
@@ -71,3 +71,19 @@ func layoutTargetCreator(cat *chunkstore.BCatalog) func(context.Context, lifecyc
return err
}
}
// newRetirementHeadReader opens only a read transport. The serving catalog has
// already validated the endpoint; retirement must not repeat its write probes
// or start another probe-cleanup worker.
func newRetirementHeadReader(cfg chunkstore.SWFSConfig) (func(context.Context, lifecycle.VolumeSpec) (layout.Head, error), *chunkstore.SWFS, error) {
client, err := chunkstore.DialSWFS(cfg)
if err != nil {
return nil, nil, err
}
cat, err := chunkstore.NewBCatalog(client, client, cfg.AssignPath)
if err != nil {
_ = client.Close()
return nil, nil, err
}
return layoutHeadReader(cat), client, nil
}
+24 -15
View File
@@ -274,6 +274,7 @@ func run(f flags) int {
fmt.Fprintln(os.Stderr, "blockmaster: dynamic lifecycle topology enabled by cluster-spec node inventory; assignments will be derived from verified placement intents")
}
cfg := master.Config{
FailStopLifecycleWrites: true,
EphemeralLauncherState: (f.launcherManifestDir != "" || f.launcherKubernetesApply) && f.launcherStateHostPath == "",
AuthorityStoreDir: f.authorityStore,
LifecycleStoreDir: f.lifecycleStore,
@@ -295,8 +296,8 @@ func run(f flags) int {
return 1
}
cfg.Auth, cfg.ServerOptions = authn, serverOpts
// The layout catalog is the master's one HEAD source (create, restore and
// the workspace reader all read through it).
// Foreground catalog operations share their serving connection. Retirement
// owns a separate connection so outage reads do not alter its backoff.
var layoutCat *chunkstore.BCatalog
if f.workspaceRPC {
cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{
@@ -311,6 +312,17 @@ func run(f flags) int {
cfg.LayoutCreateVolume = layoutVolumeCreator(cat)
cfg.LayoutReadVolume = layoutVolumeReader(cat)
cfg.LayoutReadHead = layoutHeadReader(cat)
retirementRead, retirementClient, err := newRetirementHeadReader(chunkstore.SWFSConfig{
FilerGRPC: f.chunkFiler, Collection: f.chunkCollection,
Replication: f.chunkReplication, AssignPath: f.chunkPath,
})
if err != nil {
fmt.Fprintln(os.Stderr, "blockmaster: retirement filer:", err)
return 1
}
// Host.Close cancels and joins retirement before these clients close.
defer retirementClient.Close()
cfg.LayoutRetirementReadHead = retirementRead
cfg.LayoutCreateTarget = layoutTargetCreator(cat)
layoutCat = cat
}
@@ -339,6 +351,9 @@ func run(f flags) int {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
return 1
}
if st := h.Lifecycle(); st != nil {
fmt.Fprintf(os.Stderr, "blockmaster: lifecycle import durability: nodes %s; placements %s\n", st.Nodes.ImportDurabilityMode(), st.Placements.ImportDurabilityMode())
}
// Every promotion decides on the probe round's answers: each candidate
// answers a fresh round over its authenticated node stream.
h.SetPromotionEvidenceProvider(h.NewRoundPromotionEvidenceProvider(f.launcherReplicationAck, nil))
@@ -389,12 +404,6 @@ func run(f flags) int {
}
}
if err := h.ReconcileDeletedSpecVolumes(context.Background()); err != nil {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
_ = h.Close(context.Background())
return 1
}
if f.printReadyLine {
_ = json.NewEncoder(os.Stdout).Encode(readyLine{
Component: "blockmaster",
@@ -478,10 +487,8 @@ func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistra
if stores == nil {
return fmt.Errorf("lifecycle node import requires --lifecycle-store")
}
for _, node := range nodes {
if _, err := stores.Nodes.RegisterNode(node); err != nil {
return fmt.Errorf("register lifecycle node %s: %w", node.ServerID, err)
}
if err := stores.Nodes.ImportNodes(nodes); err != nil {
return fmt.Errorf("import lifecycle nodes: %w", err)
}
return nil
}
@@ -510,6 +517,7 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
if stores == nil {
return fmt.Errorf("lifecycle placement import requires --lifecycle-store")
}
plans := make([]lifecycle.PlacementPlan, 0, len(intents))
for _, intent := range intents {
if stores.Deletions.Reserved(intent.VolumeID) {
continue // never placed again (see importLifecycleVolumes)
@@ -528,9 +536,10 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
Source: slot.Source,
})
}
if _, err := stores.Placements.ApplyPlan(plan); err != nil {
return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err)
}
plans = append(plans, plan)
}
if err := stores.Placements.ImportPlans(plans); err != nil {
return fmt.Errorf("import lifecycle placement seeds: %w", err)
}
return nil
}
@@ -19,7 +19,7 @@ import (
// only a host that holds no volume: a retired id is then unregistered, so a
// holder RPC under it is refused (refuseWorkspaceHolderHost) and the checks
// only get stricter. This guard fails when any other non-test caller of
// RegisterNode or RemoveNode appears anywhere.
// RegisterNode, ImportNodes or RemoveNode appears anywhere.
func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
@@ -56,7 +56,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
if !ok {
return true
}
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "RemoveNode") {
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "ImportNodes" || sel.Sel.Name == "RemoveNode") {
sites = append(sites, filepath.ToSlash(rel)+":"+fn.Name.Name+"."+sel.Sel.Name)
}
return true
@@ -68,7 +68,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
t.Fatal(err)
}
sort.Strings(sites)
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.ImportNodes", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
if strings.Join(sites, ",") != strings.Join(want, ",") {
t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want)
}
@@ -0,0 +1,113 @@
//go:build linux
package main
import (
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
func TestMasterImportPersistenceFailureExitsAndRecovers(t *testing.T) {
root := t.TempDir()
nodeDir := filepath.Join(root, "lifecycle", "nodes")
store, err := lifecycle.OpenNodeInventoryStore(nodeDir)
if err != nil {
t.Fatal(err)
}
old := lifecycle.NodeRegistration{ServerID: "kept", Addr: "127.0.0.1:19001"}
old, err = store.RegisterNode(old)
if err != nil {
t.Fatal(err)
}
// A real rename failure, even as root; the preceding committed record
// stays untouched. Directories are not parsed as JSON records on reload.
block := filepath.Join(nodeDir, "new.json")
if err := os.Mkdir(block, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil {
t.Fatal(err)
}
spec := filepath.Join(root, "spec.yaml")
if err := os.WriteFile(spec, []byte("nodes:\n - server_id: new\n addr: 127.0.0.1:19002\n"), 0600); err != nil {
t.Fatal(err)
}
args := []string{"--listen", "127.0.0.1:0", "--authority-store", filepath.Join(root, "authority"), "--lifecycle-store", filepath.Join(root, "lifecycle"), "--cluster-spec", spec}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep))
out, runErr := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != authority.ExitDurabilityUnknown {
t.Fatalf("master did not fail-stop with exit74: %v context=%v\n%s", runErr, ctx.Err(), out)
}
text := string(out)
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "reason=lifecycle_persist_failed") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
t.Fatalf("missing single persistence ERROR: %s", text)
}
oldRaw, err := json.Marshal(old)
if err != nil {
t.Fatal(err)
}
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMasterImportPersistenceRecoveryChild$", "-test.timeout=8s")
recovery.Env = append(os.Environ(), "MASTER_RECOVERY_ROOT="+root, "MASTER_RECOVERY_OLD="+string(oldRaw))
if out, err := recovery.CombinedOutput(); err != nil {
t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out)
}
}
func TestMasterImportPersistenceRecoveryChild(t *testing.T) {
root := os.Getenv("MASTER_RECOVERY_ROOT")
if root == "" {
t.Skip("bounded recovery subprocess")
}
nodeDir := filepath.Join(root, "lifecycle", "nodes")
var old lifecycle.NodeRegistration
if err := json.Unmarshal([]byte(os.Getenv("MASTER_RECOVERY_OLD")), &old); err != nil {
t.Fatal(err)
}
// A new master must load the complete committed record, not a speculative
// new registration or partial JSON from the failed write.
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle")})
if err != nil {
t.Fatal(err)
}
h.Start()
t.Cleanup(func() {
closeCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
if err := h.Close(closeCtx); err != nil {
t.Error(err)
}
})
if got, ok := h.Lifecycle().Nodes.GetNodeSnapshot("kept"); !ok || got.ServerID != old.ServerID || got.Addr != old.Addr || !got.SeenAt.Equal(old.SeenAt) {
t.Fatalf("committed record lost on restart: %+v %v", got, ok)
}
if _, ok := h.Lifecycle().Nodes.GetNodeSnapshot("new"); ok {
t.Fatal("failed record appeared on restart")
}
entries, err := os.ReadDir(nodeDir)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {
raw, err := os.ReadFile(filepath.Join(nodeDir, entry.Name()))
if err != nil || !json.Valid(raw) {
t.Fatalf("partial record %s: %v", entry.Name(), err)
}
}
}
}
@@ -0,0 +1,86 @@
package main
import (
"context"
"errors"
"net"
"sync"
"testing"
"time"
"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/lifecycle"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
type retirementTransportFiler struct {
filerpb.UnimplementedSeaweedFilerServer
mu sync.Mutex
peers []string
}
func (f *retirementTransportFiler) LookupDirectoryEntry(ctx context.Context, _ *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) {
p, _ := peer.FromContext(ctx)
f.mu.Lock()
f.peers = append(f.peers, p.Addr.String())
f.mu.Unlock()
return nil, status.Error(codes.NotFound, "absent")
}
// Exercise actual transports: retirement opens a different HTTP/2 connection,
// performs no conditional write probe, and leaves the serving client usable
// after its own connection closes.
func TestRetirementCatalogOwnsItsConnection(t *testing.T) {
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
f := &retirementTransportFiler{}
srv := grpc.NewServer()
filerpb.RegisterSeaweedFilerServer(srv, f)
go srv.Serve(lis)
defer srv.Stop()
cfg := chunkstore.SWFSConfig{FilerGRPC: lis.Addr().String(), AssignPath: "/blocks"}
serving, err := chunkstore.DialSWFS(cfg)
if err != nil {
t.Fatal(err)
}
defer serving.Close()
cat, err := chunkstore.NewBCatalog(serving, serving, cfg.AssignPath)
if err != nil {
t.Fatal(err)
}
retireRead, retireClient, err := newRetirementHeadReader(cfg)
if err != nil {
t.Fatal(err)
}
defer retireClient.Close()
id, err := layout.NewVolumeID()
if err != nil {
t.Fatal(err)
}
spec := lifecycle.VolumeSpec{VolumeID: "v", LayoutID: id.String()}
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
for _, read := range []func(context.Context, lifecycle.VolumeSpec) (layout.Head, error){layoutHeadReader(cat), retireRead} {
if _, err := read(ctx, spec); !errors.Is(err, layout.ErrHeadAbsent) {
t.Fatalf("read: %v", err)
}
}
if err := retireClient.Close(); err != nil {
t.Fatal(err)
}
if _, err := layoutHeadReader(cat)(ctx, spec); !errors.Is(err, layout.ErrHeadAbsent) {
t.Fatalf("serving read after retirement close: %v", err)
}
f.mu.Lock()
defer f.mu.Unlock()
if len(f.peers) != 3 || f.peers[0] == f.peers[1] || f.peers[0] != f.peers[2] {
t.Fatalf("serving, retirement, serving connections: %v", f.peers)
}
}
@@ -26,6 +26,13 @@ import (
// refuses an interval above half the freshness window (a longer loop gap
// reads as the master's own pause), so the window is 60 s: the dead
// primary's loss then comes at most a window after its last report.
//
// The failover is predicted within gapLoop + gapWindow + gapLoop of the
// kill: the tick that ends creation comes at most a loop after it, the
// loss a window after that tick's silence floor, and the tick that reads
// the loss at most a loop later. The test waits twice that.
const gapLoop, gapWindow = 30 * time.Second, 60 * time.Second
func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
bins := buildG54Binaries(t)
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
@@ -48,8 +55,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
}
master := h.start(t, "blockmaster", bins.master,
"--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s",
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", gapLoop.String(),
"--freshness-window", gapWindow.String(), "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
for _, b := range hosts {
lockDir := b.root + ".locks"
@@ -84,7 +91,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
// 3. The next tick reads the survivors' write: creation ended, and the
// gate fails the volume over.
var p2 *host
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
predicted := gapLoop + gapWindow + gapLoop
poll(t, 2*predicted, fmt.Sprintf("no survivor became primary at epoch 2 within %v, twice the predicted %v (the volume held as creating, or the gate's replace not acted on: see the master's 'decision=replace' lines)", 2*predicted, predicted), func() bool {
for _, b := range survivors {
if statusIsPrimaryAt(b.status, 2) {
p2 = b
+4 -4
View File
@@ -129,8 +129,8 @@ type flags struct {
durableBlockSize uint
durableWALMultiBlockRecords bool
durableWALRecoveryTestDisableFlusher bool
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden,
// test-only; refused under systemd).
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden, for
// tests and sw-block mini's one-user trial; 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 test-only 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 for tests and trial runs 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 a test override: the one-process-per-host guarantee does not hold\n", 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)
}
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: workspace move: missing or changed authority/lease" {
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" {
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)
}
}
@@ -0,0 +1,111 @@
//go:build linux && subprocess && chunkstore_integration
package main_test
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
)
// A master restart must not replace live holders while rebuilding its
// heartbeat view. Registration time is deliberately older than the window;
// only the new process's received heartbeats make its node evidence fresh.
func TestMasterImportRestartKeepsLiveHoldersAcrossFreshnessWindow(t *testing.T) {
const window = 6 * time.Second
env := startHandoffEnvVolumes(t, 1, []string{"v2"}, "--freshness-window", window.String(), "--lifecycle-product-loop-interval", "100ms")
env.volExtra = append(env.volExtra, "--heartbeat-interval", "250ms")
for id, volume := range map[string]string{"s1": "v1", "n-v2": "v2"} {
host := env.hosts[id]
host.volume, host.replica = volume, "r1"
env.hosts[id] = host
}
first, second := f1Up(t, env, "s1"), f1Up(t, env, "n-v2")
epochs := map[string]uint64{}
for volume, holder := range map[string]*daemon{"v1": first, "v2": second} {
epoch, err := adoptedEpochOf(volume, holder.line("blockvolume: volume "+volume+" adopted as PRIMARY at r1@"))
if err != nil {
t.Fatal(err)
}
epochs[volume] = epoch
}
// Both durable registrations now age beyond freshness while holders keep
// reporting; a restart must not renew these durable observation times.
time.Sleep(window + 100*time.Millisecond)
env.masterProcess.term(t, 10*time.Second)
started := time.Now()
env.masterProcess = env.h.start(t, "blockmaster-import-restarted", env.h.master, env.masterArgs...)
conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
client := control.NewClusterEvidenceServiceClient(conn)
fresh := map[string]bool{}
verified := map[string]bool{}
observed := map[string]bool{}
samples := 0
for time.Since(started) < window {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
status, err := client.GetClusterStatus(ctx, &control.GetClusterStatusRequest{})
cancel()
if err == nil {
samples++
for _, node := range status.Nodes {
if at := node.GetLastHeartbeatAt(); at != nil && at.AsTime().After(started) {
fresh[node.GetNodeName()] = true
}
}
for _, volume := range status.Volumes {
if epoch, ok := epochs[volume.VolumeId]; ok && volume.Epoch != 0 {
observed[volume.VolumeId] = true
if volume.Epoch != epoch {
t.Fatalf("%s changed epoch after restart: %d -> %d", volume.VolumeId, epoch, volume.Epoch)
}
}
}
for _, event := range status.Events {
if event.EventType == "placement_verified" {
verified[event.VolumeId] = true
}
}
}
for _, bad := range []string{"primary lost:", "decision=replace("} {
if env.masterProcess.has(bad) {
t.Fatalf("live-holder restart made a loss/replacement decision: %s", bad)
}
}
for id, d := range map[string]*daemon{"s1": first, "n-v2": second} {
select {
case <-d.done:
t.Fatalf("live holder %s exited during master restart: %v", id, d.err)
default:
}
}
time.Sleep(100 * time.Millisecond)
}
if samples == 0 {
t.Fatal("no successful status sample in the freshness window")
}
for _, id := range []string{"s1", "n-v2"} {
if !fresh[id] {
t.Fatalf("live node %s never became fresh after restart", id)
}
}
for id := range epochs {
if !observed[id] {
t.Fatalf("volume %s never showed its authoritative epoch again", id)
}
if !verified[id] {
t.Fatalf("placement %s did not verify again within one window", id)
}
}
for _, id := range []string{"s1", "n-v2"} {
block := pattern("restart-live-io!")
env.writeBlock(t, id, 0, block)
}
t.Logf("master restart: %d status samples, both nodes fresh, both placements verified, no loss/replacement or holder exit within %s", samples, window)
}
@@ -0,0 +1,220 @@
//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)
}
}
@@ -0,0 +1,615 @@
//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())
}
}
@@ -169,6 +169,21 @@ func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) {
}
}
func TestRunCLIPreservesTheHarnessTLSIdentity(t *testing.T) {
env := startTLSEnv(t, 1, nil, nil)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if out, errOut, code, err := runCLI(ctx, env.h, env.show...); err != nil || code != 0 {
t.Fatalf("CLI with the harness identity: exit %d, error %v:\n%s\n%s", code, err, out, errOut)
}
admin := env.h.cliEnv
defer func() { env.h.cliEnv = admin }()
env.h.cliEnv = []string{"SW_BLOCK_TLS_CERT=", "SW_BLOCK_TLS_KEY=", "SW_BLOCK_TLS_CA="}
if _, errOut, code, err := runCLI(ctx, env.h, env.show...); err != nil || code != 5 {
t.Fatalf("CLI with the identity explicitly cleared: exit %d, error %v, stderr %q; want 5", code, err, errOut)
}
}
// fencedHolderThenForcedMove is T6/T7's flow: s1 serves and publishes block 0
// (seal), then lose() takes its certificate away. s1 fences and exits; when
// operatorFirst, an operator's forced move is refused as not authorized; the
@@ -10,6 +10,7 @@ import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"testing"
@@ -535,6 +536,9 @@ func (env *handoffEnv) hydrate(t *testing.T, target string) {
func runCLI(ctx context.Context, h *plannedHandoffHarness, args ...string) (string, string, int, error) {
cmd := exec.CommandContext(ctx, h.cli, args...)
cmd.Dir = h.dir
if len(h.cliEnv) > 0 {
cmd.Env = append(os.Environ(), h.cliEnv...)
}
cmd.WaitDelay = 5 * time.Second
var stdout, stderr strings.Builder
cmd.Stdout, cmd.Stderr = &stdout, &stderr
@@ -1,6 +1,6 @@
# The wrong-size local store a 1.0 first start left (3402e0dd, the 1.0 RC):
# v2 restored with a 65536-block record, started with --durable-blocks 32768;
# captured from that run on tp04 (archive sha256
# captured from that run on a lab host (archive sha256
# 0905c3af83b3a1dc226b417fa5acf7071907cc3e53478bc14a531481b717c5c1).
# "file <name> <size> <octal mode>", then "<offset> <hex>" for each run of
# non-zero bytes; every other byte is zero.
@@ -6,6 +6,8 @@ import (
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// The test lock directory override is refused under systemd
@@ -50,3 +52,42 @@ 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)
}
}
@@ -0,0 +1,250 @@
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)
}
}
}
@@ -0,0 +1,29 @@
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)
}
})
}
}
@@ -0,0 +1,87 @@
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,6 +11,7 @@ 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"
)
@@ -18,7 +19,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", status.Error(codes.Unavailable, "connection refused"))
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")))
}
func TestOpsChunkCatalogUnavailableIsTyped(t *testing.T) {
@@ -97,14 +98,14 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
code string
retry bool
}{
{"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},
{"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},
{"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"), "internal", false},
{"permission", status.Error(codes.PermissionDenied, "refused"), "not_authorized", false},
{"unknown", errors.New("unexpected implementation error"), "internal", false},
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "internal", false},
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "bad_request", false},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
@@ -114,6 +115,15 @@ 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 chunkTransportFailure(err) || chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) {
if knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if err != nil {
+46 -32
View File
@@ -25,6 +25,7 @@ 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 (
@@ -67,6 +68,15 @@ 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) {
@@ -76,7 +86,7 @@ func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunks
switch {
case err == nil:
return -1
case chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) || chunkTransportFailure(err):
case knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled):
return chunkResult(name, nil, err, stdout, stderr)
case errors.Is(err, chunkstore.ErrNotSingleFiler):
return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
@@ -177,25 +187,32 @@ 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 := chunkHTTPClient.Do(req)
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.Unsent)
if err != nil {
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
return chunkResult(name, nil, err, stdout, stderr)
}
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 chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "read the response: "+err.Error(), true)
return responseFailure(err)
}
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 chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI,
fmt.Sprintf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit), false)
return responseFailure(fmt.Errorf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit))
}
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 chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid snapshot operation admission", false)
return responseFailure(fmt.Errorf("snapshot request %v: invalid operation admission; retry with the same --request-id against the original status address", body["requestID"]))
}
a.Raw = append([]byte(nil), out...)
a.Location = resp.Header.Get("Location")
@@ -216,15 +233,20 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
}
var e chunkErrBody
if json.Unmarshal(out, &e) != nil || e.Code == "" {
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))), false)
return responseFailure(fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))))
}
// The route's error body is already the CLI's error body: relay it.
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, chunkErrorAdvice(e.Code, e.Retryable, e.Message))
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)
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 chunkErrorExit(chunkExitFailed, e.Code, e.Retryable)
return policy.Exit
}
func chunkCut(args []string, stdout, stderr io.Writer) int {
@@ -367,27 +389,12 @@ 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 {
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)
contract := answer.Chunk
if name == "verify" {
contract = answer.ChunkVerify
}
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 {
@@ -422,6 +429,11 @@ 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
@@ -449,13 +461,15 @@ 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 {
return 75
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, "")))
return policy.Exit
}
return exit
}
func chunkErrorAdvice(code string, retryable bool, message string) string {
if code == codeUnavailableCLI && retryable {
return message + "; retry the same operation when the remote is reachable"
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, message)))
return policy.Cure
}
return message
}
@@ -0,0 +1,74 @@
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
}
+17 -19
View File
@@ -17,6 +17,7 @@ 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"
@@ -36,15 +37,16 @@ var restoreCreateRPC = func(ctx context.Context, master string, req *control.Cre
}
// bCatalog dials the filer and opens the volume catalog; a command that
// writes first passes the single-filer start check. It returns exit -1 on
// success, else the exit code after reporting.
// writes first passes the single-filer start check, then runs the chunk
// condition probe; each runs within timeout. It returns exit -1 on success,
// else the exit code after reporting.
func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.BCatalog, func() error, int) {
if filer == "" {
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false)
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
return nil, nil, chunkResult(name, nil, err, stdout, stderr)
}
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
@@ -67,6 +69,11 @@ func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdo
if err != nil {
return fail(err.Error())
}
if writes {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
cat.ProbeChunkGuard(ctx)
cancel()
}
return cat, closeFn, -1
}
@@ -145,7 +152,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 chunkCanceled(err) || chunkTransportFailure(err) {
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
return chunkResult(name, nil, err, c.stdout, c.stderr)
}
if status.Code(err) == codes.NotFound { // the master does not know the volume
@@ -354,7 +361,9 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int {
c.bindVolume(&vol, "volume", "volume")
var ref chunkstore.VolumeRef
return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
return cat.Usage(ctx, ref)
u, err := cat.Usage(ctx, ref)
u.MetadataGuard = ""
return u, err
})
}
@@ -385,21 +394,10 @@ func chunkRestore(args []string, stdout, stderr io.Writer) int {
VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID,
})
if err != nil {
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)
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)
}
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)
+1 -1
View File
@@ -176,7 +176,7 @@ func TestOpsChunk_CatalogCommands(t *testing.T) {
if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 || !strings.Contains(out, tgt.Dir()) {
t.Fatalf("restore: %d %q %q", code, out, errs)
}
if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) {
if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) || strings.Contains(out, "metadata_guard") {
t.Fatalf("target usage: %d %q", code, out)
}
if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" {
@@ -4,7 +4,10 @@ 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"
@@ -12,13 +15,47 @@ 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 := grpc.NewClient("127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial("127.0.0.1:1")
if err != nil {
t.Fatal(err)
}
@@ -1,7 +1,6 @@
package main
import (
"context"
"io"
"net"
"net/http"
@@ -13,28 +12,30 @@ import (
"testing/synctest"
)
// 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 {
// 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 {
t.Helper()
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}
}}
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)
}
old := chunkHTTPClient
chunkHTTPClient = &http.Client{Transport: transport}
t.Cleanup(func() { transport.CloseIdleConnections(); chunkHTTPClient = old })
return calls
chunkHTTPClient = &http.Client{}
t.Cleanup(func() { chunkHTTPClient = old })
return "http://" + addr
}
func TestPlainDetachRefusedDialIsRemoteUnavailable(t *testing.T) {
calls := installRefusedHolderDial(t)
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder")
addr := installRefusedHolderDial(t)
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", addr)
e := chunkErrorOut(t, out)
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)
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)
}
}
@@ -15,6 +15,7 @@ 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"
)
@@ -32,7 +33,7 @@ func TestChunkErrorFamilyAnswerTable(t *testing.T) {
advice string
only string
}{
{"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", ""},
{"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", ""},
{"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(), ""},
@@ -156,7 +157,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 != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
if exit != 3 || answer.Code != "outcome_unknown" || !answer.Retryable {
t.Fatalf("exit=%d answer=%+v", exit, answer)
}
retained, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
@@ -176,8 +177,20 @@ 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; 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" {
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" {
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)
}
}
@@ -0,0 +1,214 @@
package main
import (
"bytes"
"context"
"errors"
"io"
"path"
"strings"
"testing"
"time"
"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"
)
// A command that changes chunk metadata runs the chunk condition probe on
// the catalog it opens, so its adoptions and marks send the filer's chunk
// condition as blockvolume's do; a read-only command writes nothing.
func TestOpsChunkWritingCatalogRunsTheChunkConditionProbe(t *testing.T) {
mem := newMemChunkStore()
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
for _, tc := range []struct {
writes bool
guard string
}{{true, chunkstore.MetadataGuardChunks}, {false, chunkstore.MetadataGuardReread}} {
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", tc.writes, time.Minute, io.Discard, io.Discard)
if exit >= 0 {
t.Fatalf("writes=%v: catalog open exited %d", tc.writes, exit)
}
_ = closeFn()
if got := cat.MetadataGuard(); got != tc.guard {
t.Fatalf("writes=%v: metadata guard %q, want %q", tc.writes, got, tc.guard)
}
left, err := mem.ListEntries(context.Background(), "/blocks", "", "", 100)
if err != nil || len(left) != 0 {
t.Fatalf("writes=%v: %d entries left under the catalog base (%v)", tc.writes, len(left), err)
}
}
}
// stalledProbeFiler stalls the probe's disposable HEAD create until its
// context ends.
type stalledProbeFiler struct{ *memChunkStore }
func (f stalledProbeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
if inStartupProbe(dir, e.GetName()) {
<-ctx.Done()
return ctx.Err()
}
return f.memChunkStore.CreateEntry(ctx, dir, e, oExcl)
}
// The probe runs within the command's --timeout: after a passing census, a
// probe stalled on its filer ends at the timeout, leaves the guard off and
// refuses nothing.
func TestOpsChunkWritingCatalogProbeIsBoundedByTheTimeout(t *testing.T) {
mem := newMemChunkStore()
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
return stalledProbeFiler{mem}, func() error { return nil }, nil
}
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
start := time.Now()
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", true, 200*time.Millisecond, io.Discard, io.Discard)
if exit >= 0 {
t.Fatalf("a stalled probe refused the command: exit %d", exit)
}
_ = closeFn()
if took := time.Since(start); took > 5*time.Second {
t.Fatalf("a stalled probe held the command %v past its 200ms --timeout", took)
}
if got := cat.MetadataGuard(); got != chunkstore.MetadataGuardReread {
t.Fatalf("metadata guard %q after a stalled probe, want %q", got, chunkstore.MetadataGuardReread)
}
}
// betweenLookupAndUpdate runs before, once it is set, ahead of the next
// update: what other writers do while a stale one is between its lookup and
// its update.
type betweenLookupAndUpdate struct {
*memChunkStore
before func()
}
func (f *betweenLookupAndUpdate) runBefore() {
if b := f.before; b != nil {
f.before = nil
b()
}
}
func (f *betweenLookupAndUpdate) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
f.runBefore()
return f.memChunkStore.UpdateEntry(ctx, dir, e, expected)
}
func (f *betweenLookupAndUpdate) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
f.runBefore()
return f.memChunkStore.UpdateEntryIfChunks(ctx, dir, e, expected, fids)
}
// A writing command's adoption that paused between its lookup and its update
// does not land on an object a cleaner deleted and another executor created
// again in between, through the store of the catalog bCatalog opens. An
// unchanged object is still adopted; a catalog that ran no probe lets the
// stale write through.
func TestOpsChunkStaleCLIAdoptionDoesNotOverwriteARecreatedObject(t *testing.T) {
for _, tc := range []struct {
name string
writes, recreate bool
}{
{"probed catalog, recreated object", true, true},
{"probed catalog, unchanged object", true, false},
{"catalog without the probe, recreated object", false, true},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
mem := newMemChunkStore()
hooked := &betweenLookupAndUpdate{memChunkStore: mem}
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return hooked, func() error { return nil }, nil }
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil }
cat, closeFn, exit := bCatalog("snapshot-delete", "filer:18888", "/blocks", tc.writes, time.Minute, io.Discard, io.Discard)
if exit >= 0 {
t.Fatalf("catalog open exited %d", exit)
}
defer closeFn()
id, err := layout.NewVolumeID()
if err != nil {
t.Fatal(err)
}
ref := chunkstore.VolumeRef{Name: "v", ID: id}
stale, err := cat.Store(ref)
if err != nil {
t.Fatal(err)
}
others, err := chunkstore.NewLayoutStore(mem, mem, path.Join("/blocks", ref.Dir()), id)
if err != nil {
t.Fatal(err)
}
data := bytes.Repeat([]byte{0x5a}, 4096)
rel := layout.NameChunk(1, data).Path()
obj := path.Join("/blocks", ref.Dir(), rel)
fid := func() string {
e, err := mem.LookupEntry(ctx, path.Dir(obj), path.Base(obj))
if err != nil || len(e.Chunks) != 1 {
t.Fatalf("lookup %s: %+v %v", rel, e, err)
}
return e.Chunks[0].FileId
}
if err := others.Create(ctx, rel, data, "producer-1"); err != nil {
t.Fatal(err)
}
first := fid()
meta, found, err := others.Stat(ctx, rel)
if err != nil || !found {
t.Fatalf("stat: %v %v", found, err)
}
second := first
if tc.recreate {
hooked.before = func() {
if err := others.Mark(ctx, rel, meta, "clean-1"); err != nil {
t.Errorf("mark: %v", err)
}
if err := others.DeleteMarked(ctx, rel, "clean-1"); err != nil {
t.Errorf("delete: %v", err)
}
if err := others.Create(ctx, rel, data, "producer-1"); err != nil {
t.Errorf("re-create: %v", err)
}
second = fid()
}
}
err = stale.Reuse(ctx, rel, meta, "writer-1")
if tc.recreate && second == first {
t.Fatalf("fixture: the object was not re-created with a new chunk (%s)", first)
}
switch {
case tc.writes && tc.recreate:
if !errors.Is(err, layout.ErrPrecondition) {
t.Fatalf("the stale CLI adoption over a re-created object answered %v, want ErrPrecondition", err)
}
if got := fid(); got != second {
t.Fatalf("the stale CLI adoption wrote chunk %s over the re-created object's %s", got, second)
}
case tc.recreate:
if err != nil || fid() != first {
t.Fatalf("control: without the probe the stale adoption should land (err %v, chunk %s, first %s)", err, fid(), first)
}
default:
if err != nil {
t.Fatalf("adoption of an unchanged object: %v", err)
}
if m, _, err := others.Stat(ctx, rel); err != nil || m.Session != "writer-1" {
t.Fatalf("after adoption: %+v %v", m, err)
}
}
})
}
}
// inStartupProbe reports whether dir/name lies in a catalog probe's
// disposable directory: a fake that stalls object deletes lets the probe's
// own cleanup through, as a real filer deletes its inline HEAD at once.
func inStartupProbe(dir, name string) bool {
return strings.Contains(path.Join(dir, name), "/.startup-head-probe-")
}
+2 -1
View File
@@ -13,6 +13,7 @@ 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.
@@ -184,7 +185,7 @@ func chunkStats(statusAddr, volumeID string, deadline time.Time) (chunkStagedSta
if err != nil {
return chunkStagedStats{}, false
}
resp, err := chunkHTTPClient.Do(req)
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
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, chunkExitFailed, codeInternalCLI, "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation", false)
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)
}
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 != 75 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
if code := run(args, &out, &errs); code != 3 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), "outcome_unknown") {
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) {
installRefusedHolderDial(t)
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://holder"); code != 75 {
addr := installRefusedHolderDial(t)
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", addr); 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)
+11 -12
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"
"net"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -29,17 +29,9 @@ func chunkTransportFailure(err error) bool {
if layoutCode(err) != "" && !errors.Is(err, layout.ErrHolderActive) {
return false
}
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)
kind, listed := answer.ErrorKind(err)
return listed && (kind == answer.Connection || kind == answer.PlaintextConnection || kind == answer.DNS || kind == answer.Timeout)
}
// gRPC cancellation does not wrap context.Canceled. Keep it distinct from an
@@ -54,3 +46,10 @@ 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,6 +14,7 @@ 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"
@@ -56,6 +57,7 @@ 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")
@@ -84,18 +86,18 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
case "resolve":
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) {
calls.Add(1)
return layout.VolumeID{}, failure.err
return layout.VolumeID{}, fixtureErr
}
case "dial":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, failure.err }
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, fixtureErr }
case "census":
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
calls.Add(1)
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, failure.err)
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, fixtureErr)
}
case "read":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
return transportLookupStore{mem, failure.err, &calls}, func() error { return nil }, nil
return transportLookupStore{mem, fixtureErr, &calls}, func() error { return nil }, nil
}
case "restore":
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
@@ -110,6 +112,11 @@ 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 (any other resolve
// transport failure is retryable remote_unavailable).
// volume the master does not know is volume_not_found. A resolve failure
// without admission evidence requires recovery of the same operation.
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"), 75, codeUnavailableCLI},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 3, "outcome_unknown"},
} {
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{}, c.err }
var out, errs bytes.Buffer
+8 -14
View File
@@ -14,6 +14,7 @@ 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
@@ -21,8 +22,9 @@ 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; 1: it could not complete (the partial
// result is printed with the reason); 2: usage.
// 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.
func chunkVerify(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("verify", stderr)
var (
@@ -114,7 +116,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
if knownChunkFailure(err) {
return verifyIncomplete(layout.VerifyResult{}, err, stdout, stderr)
}
return usage(err.Error())
@@ -290,17 +292,9 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ
chunkErrBody
Verify layout.VerifyResult `json:"verify"`
}{Verify: res}
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)
policy, detail := chunkAnswerFor(err, answer.ChunkVerify)
body.Code, body.Message, body.Retryable = policy.Code, detail, policy.Retryable
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
chunkResult("verify", body, nil, stdout, stderr)
return chunkErrorExit(chunkExitFailed, body.Code, body.Retryable)
return policy.Exit
}
@@ -14,6 +14,7 @@ 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"
)
@@ -95,15 +96,7 @@ 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 {
// 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
return leaseRefusal(err, false)
}
func deleteLeaseBarrierDetail(err error) bool {
@@ -118,6 +111,12 @@ 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
@@ -127,7 +126,15 @@ func finalLeaseBarrierErr(err error) 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 {
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)}
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)}
}
}
}
@@ -227,7 +234,10 @@ func deleteVolumeWithProgress(ctx context.Context, cat *chunkstore.BCatalog, ref
}
return all, nil
}
transient := errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Unavailable
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))
if !transient {
return nil, err
}
@@ -10,6 +10,7 @@ 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"
)
@@ -40,7 +41,11 @@ func (f *transientDeleteFiler) DeleteEntry(ctx context.Context, dir, name string
return err
}
}
return status.Error(f.code, "object deadline")
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 f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
}
@@ -100,6 +105,9 @@ type waitingDeleteFiler struct {
}
func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
if inStartupProbe(dir, name) {
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
}
f.calls++
if f.calls == 1 {
timer := time.NewTimer(f.bound / 2)
@@ -116,7 +124,7 @@ func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string,
return err
}
if f.stall {
return status.Error(codes.Unavailable, "stalled after first removal")
return answer.Record(answer.Unsent, status.Error(codes.Unavailable, "stalled after first removal"))
}
if !f.waited {
f.waited = true
@@ -166,6 +174,9 @@ func TestVolumeDeleteRefreshesAnExpiredSweepAndWaitsFromLastRemoval(t *testing.T
type blockedDeleteFiler struct{ *memChunkStore }
func (f *blockedDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
if inStartupProbe(dir, name) {
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
}
<-ctx.Done()
return ctx.Err()
}
@@ -6,6 +6,7 @@ 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"
@@ -40,7 +41,8 @@ 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", authorityErr(status.Error(codes.Unavailable, "connection refused")), 75, "remote_unavailable", true},
{"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},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
+35 -16
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,7 +152,8 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
@@ -164,15 +165,15 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
if reason == "" {
reason = status.Code(err).String()
}
switch status.Code(err) {
case codes.FailedPrecondition:
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" {
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("failed", reason, msg, finalizeExitFailed)
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
}
answer.FormatLevel = resp.GetFormatLevel()
for _, u := range resp.GetUnconfirmed() {
@@ -289,7 +290,8 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
answer.Server = *server
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
@@ -300,14 +302,14 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
if reason == "" {
reason = status.Code(err).String()
}
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)
p, check := policy.PolicyOf(policy.EnsureEvidence(policy.PossiblyAdmitted, err), policy.Cluster)
if check != nil {
return fail("failed", reason, check.Error(), finalizeExitFailed)
}
return fail("failed", reason, msg, finalizeExitFailed)
if p.Code == "not_admitted" {
answer.Volumes = retireVolumes(md)
}
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
}
answer.Result, answer.Message = "retired", "host retired from the node inventory"
if !jsonMode {
@@ -316,6 +318,23 @@ 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,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"reflect"
"sort"
"testing"
@@ -50,12 +51,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: 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"},
{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"},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
return tc.resp, tc.err
return tc.resp, answer.Record(answer.Unsent, tc.err)
}}
withClusterMaster(t, f)
if tc.dialErr != nil {
@@ -179,8 +180,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: 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: "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: "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) {
@@ -188,7 +189,7 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
calls++
if tc.err != nil {
return nil, tc.err
return nil, answer.Record(answer.Unsent, tc.err)
}
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
}}
@@ -4,16 +4,15 @@ 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
@@ -84,15 +83,16 @@ func chunkObserveHandle(name, route, addr string, window time.Duration, deadline
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
phase := answer.Unsent
if id != "" {
phase = answer.PossiblyAdmitted
}
resp, err := answer.DoHTTP(&client, req, phase)
var raw []byte
if err != nil && id == "" {
cancel()
// 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)
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)
}
return unknown(name + " admission answer was not received (" + err.Error() + "); no second one was started")
}
+17 -32
View File
@@ -2,7 +2,6 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
@@ -11,9 +10,8 @@ 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"
@@ -51,10 +49,12 @@ 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 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).
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.
`
func runOpsFailover(args []string, stdout, stderr io.Writer) int {
@@ -93,11 +93,13 @@ 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 {
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, err)
return 2
p, detail := operatorAnswer(err, answer.Failover)
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, detail)
return p.Exit
} 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)
return 2
p, _ := operatorAnswer(answer.LocalCredential(fmt.Errorf("admin client certificate is required")), answer.Failover)
return p.Exit
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
@@ -119,14 +121,15 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
EvidenceRefs: []string{"sw-block ops failover", "operator_confirmed_old_node_off=" + volume},
})
if err != nil {
if failoverOutcomeUnknown(err) {
policy, detail := operatorAnswer(err, answer.Failover)
if policy.Retry == answer.Recover {
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 3
return policy.Exit
}
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch)
fmt.Fprintf(stderr, "%s: refused: %v (no line published; a refused fencing round may have fenced the survivors)\n", opsFailoverName, err)
return 1
fmt.Fprintf(stderr, "%s: %v (a refused fencing round may have fenced the survivors)\n", opsFailoverName, detail)
return policy.Exit
}
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",
@@ -150,21 +153,3 @@ 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
}
+64 -2
View File
@@ -11,6 +11,7 @@ import (
"encoding/pem"
"errors"
"math/big"
"net"
"os"
"os/exec"
"path/filepath"
@@ -19,6 +20,7 @@ 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"
@@ -169,6 +171,42 @@ 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.
@@ -202,8 +240,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 != 2 {
t.Fatalf("rc=%d; want 2", rc)
if c.calls == 0 && rc != 78 {
t.Fatalf("rc=%d; want 78", rc)
}
if c.calls == 1 && rc != 0 {
t.Fatalf("rc=%d stderr %q; want 0", rc, errb.String())
@@ -288,3 +326,27 @@ 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 findings, 1 incomplete; --depth data needs --timeout)")
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, " 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>")
+57 -57
View File
@@ -250,11 +250,11 @@ func TestOpsOperatorStatusDryRunFromBundle(t *testing.T) {
},
Replicas: []ops.ReplicaFact{{
ReplicaID: "r1",
KubernetesNode: "m02",
KubernetesNode: "node-b",
Role: "primary",
Observed: true,
}},
CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}},
CSIStages: []ops.CSIStageFact{{NodeName: "node-b", Target: "192.168.1.184:3260"}},
Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true},
})}
raw, err := ops.MarshalObservationJSON(cluster)
@@ -296,11 +296,11 @@ func TestOpsOperatorStatusWritesCRDStatusWhenDryRunDisabled(t *testing.T) {
},
Replicas: []ops.ReplicaFact{{
ReplicaID: "r1",
KubernetesNode: "m02",
KubernetesNode: "node-b",
Role: "primary",
Observed: true,
}},
CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}},
CSIStages: []ops.CSIStageFact{{NodeName: "node-b", Target: "192.168.1.184:3260"}},
Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true},
})}
raw, err := ops.MarshalObservationJSON(cluster)
@@ -1894,7 +1894,7 @@ func TestOpsClusterMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing
}
out := stdout.String()
for _, want := range []string{
`"kubernetes_node": "m02"`,
`"kubernetes_node": "node-b"`,
`"ready": false`,
`"reason": "node_not_ready"`,
} {
@@ -1926,7 +1926,7 @@ func TestOpsReportMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.
}
out := string(raw)
for _, want := range []string{
`"kubernetes_node": "m02"`,
`"kubernetes_node": "node-b"`,
`"ready": false`,
`"reason": "node_not_ready"`,
} {
@@ -1956,7 +1956,7 @@ func TestLoadObservationVolumeUsesSharedInClusterNodeEvidenceEnrichment(t *testi
if code != ops.VolumeStatusExitOK {
t.Fatalf("exit=%d stderr=%s cluster=%+v", code, stderr.String(), cluster)
}
if len(cluster.Nodes) != 1 || cluster.Nodes[0].KubernetesNode != "m02" {
if len(cluster.Nodes) != 1 || cluster.Nodes[0].KubernetesNode != "node-b" {
t.Fatalf("cluster nodes=%+v", cluster.Nodes)
}
if !cmdConditionReason(cluster.Nodes[0].Conditions, ops.ReasonNodeNotReady) {
@@ -2051,7 +2051,7 @@ func TestOpsDashboardMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testi
}()
body := waitForHTTPContains(t, "http://"+addr+"/cluster-evidence.json", `"reason": "node_not_ready"`)
if !strings.Contains(body, `"kubernetes_node": "m02"`) || !strings.Contains(body, `"ready": false`) {
if !strings.Contains(body, `"kubernetes_node": "node-b"`) || !strings.Contains(body, `"ready": false`) {
t.Fatalf("dashboard cluster evidence missing enriched node:\n%s", body)
}
select {
@@ -2123,8 +2123,8 @@ type fakeNodeEvidenceEnricher struct{}
func (fakeNodeEvidenceEnricher) EnrichNodeEvidence(_ context.Context, _ string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) {
cluster.Nodes = []ops.NodeEvidence{{
NodeName: "m02",
KubernetesNode: "m02",
NodeName: "node-b",
KubernetesNode: "node-b",
Ready: false,
Schedulable: true,
Conditions: []ops.ObservationCondition{{
@@ -2538,7 +2538,7 @@ func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values",
"--out", outPath,
"--target-node", "m02",
"--target-node", "node-b",
"--node-limit", "1",
"--image", "ghcr.io/seaweedfs/seaweed-block:sha-test",
"--csi-image", "ghcr.io/seaweedfs/seaweed-block-csi:sha-test",
@@ -2551,7 +2551,7 @@ func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) {
"network_mode=loopback",
"ready_kubernetes_nodes=1",
"discovered_kubernetes_nodes=3",
"target_node=m02",
"target_node=node-b",
"restart_persistence_mode=hostpath",
"state_hostpath=/var/lib/sw-block/k8s",
} {
@@ -2575,8 +2575,8 @@ func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) {
"stateHostPath: /var/lib/sw-block/k8s",
"expectedSlotsPerVolume: 1",
"enabled: false",
"name: m02",
"kubernetesNode: m02",
"name: node-b",
"kubernetesNode: node-b",
"internalIP: 127.0.0.1",
"dataPort: 19101",
"controlPort: 19102",
@@ -2641,15 +2641,15 @@ func TestOpsGenerateHelmValuesMultiNodeExternalISCSI(t *testing.T) {
"stateHostPath: /var/lib/sw-block/k8s",
"enabled: true",
"secret: fixed-chap-secret",
"name: m01",
"name: node-a",
"internalIP: 192.168.1.181",
"dataPort: 19101",
"controlPort: 19102",
"name: m02",
"name: node-b",
"internalIP: 192.168.1.184",
"dataPort: 19103",
"controlPort: 19104",
"name: tp01",
"name: node-c",
"internalIP: 192.168.1.188",
"dataPort: 19105",
"controlPort: 19106",
@@ -2709,11 +2709,11 @@ func TestOpsGenerateHelmValuesMultiNodeExternalNVMe(t *testing.T) {
"enabled: false",
"create: false",
"secret: \"\"",
"name: m01",
"name: node-a",
"internalIP: 192.168.1.181",
"name: m02",
"name: node-b",
"internalIP: 192.168.1.184",
"name: tp01",
"name: node-c",
"internalIP: 192.168.1.188",
} {
if !strings.Contains(string(values), want) {
@@ -2739,7 +2739,7 @@ func TestOpsGenerateHelmValuesMultiNodeNVMeFrontendIPMap(t *testing.T) {
"--out", outPath,
"--replication-factor", "3",
"--protocol", "nvme",
"--frontend-ip-map", "m01=10.0.0.181,m02=10.0.0.184,tp01=10.0.0.188",
"--frontend-ip-map", "node-a=10.0.0.181,node-b=10.0.0.184,node-c=10.0.0.188",
"--frontend-network-class", "100gbe_tcp",
}, &stdout, &stderr)
if code != ops.VolumeStatusExitOK {
@@ -2747,7 +2747,7 @@ func TestOpsGenerateHelmValuesMultiNodeNVMeFrontendIPMap(t *testing.T) {
}
for _, want := range []string{
"network_mode=external-nvme",
"frontend_ip_map=m01=10.0.0.181,m02=10.0.0.184,tp01=10.0.0.188",
"frontend_ip_map=node-a=10.0.0.181,node-b=10.0.0.184,node-c=10.0.0.188",
"frontend_network_class=100gbe_tcp",
} {
if !strings.Contains(stdout.String(), want) {
@@ -2759,16 +2759,16 @@ func TestOpsGenerateHelmValuesMultiNodeNVMeFrontendIPMap(t *testing.T) {
t.Fatal(err)
}
for _, want := range []string{
"name: m01",
"name: node-a",
"internalIP: 192.168.1.181",
"managementIP: 192.168.1.181",
"frontendIP: 10.0.0.181",
"frontendNetworkClass: 100gbe_tcp",
"name: m02",
"name: node-b",
"internalIP: 192.168.1.184",
"managementIP: 192.168.1.184",
"frontendIP: 10.0.0.184",
"name: tp01",
"name: node-c",
"internalIP: 192.168.1.188",
"managementIP: 192.168.1.188",
"frontendIP: 10.0.0.188",
@@ -2791,7 +2791,7 @@ func TestPhase165_OpsGenerateHelmValuesNVMERDMA(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values", "--out", outPath, "--replication-factor", "1",
"--protocol", "nvme", "--nvme-transport", "rdma",
"--frontend-ip-map", "m01=10.0.0.181,m02=10.0.0.184,tp01=10.0.0.188",
"--frontend-ip-map", "node-a=10.0.0.181,node-b=10.0.0.184,node-c=10.0.0.188",
"--frontend-network-class", "100gbe_roce",
}, &stdout, &stderr)
if code != ops.VolumeStatusExitOK {
@@ -2817,7 +2817,7 @@ func TestPhase165_OpsGenerateHelmValuesNVMERDMARequiresRoCEMap(t *testing.T) {
for _, args := range [][]string{
{"--protocol", "iscsi", "--nvme-transport", "rdma"},
{"--protocol", "nvme", "--nvme-transport", "rdma"},
{"--protocol", "nvme", "--nvme-transport", "rdma", "--frontend-ip-map", "m01=10.0.0.181", "--frontend-network-class", "100gbe_tcp"},
{"--protocol", "nvme", "--nvme-transport", "rdma", "--frontend-ip-map", "node-a=10.0.0.181", "--frontend-network-class", "100gbe_tcp"},
} {
var stdout, stderr bytes.Buffer
base := []string{"ops", "generate-helm-values", "--out", filepath.Join(t.TempDir(), "values.yaml")}
@@ -2841,20 +2841,20 @@ func TestOpsGenerateHelmValuesRejectsIncompleteFrontendIPMap(t *testing.T) {
"--out", filepath.Join(t.TempDir(), "values.yaml"),
"--replication-factor", "3",
"--protocol", "nvme",
"--frontend-ip-map", "m01=10.0.0.181,m02=10.0.0.184",
"--frontend-ip-map", "node-a=10.0.0.181,node-b=10.0.0.184",
"--frontend-network-class", "100gbe_tcp",
}, &stdout, &stderr)
if code != ops.VolumeStatusExitInvalid {
t.Fatalf("exit=%d want invalid stdout=%s stderr=%s", code, stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), `--frontend-ip-map missing selected node "tp01"`) {
if !strings.Contains(stderr.String(), `--frontend-ip-map missing selected node "node-c"`) {
t.Fatalf("stderr=%s", stderr.String())
}
}
func TestNodeEvidenceFromWirePreservesFrontendAddress(t *testing.T) {
node := nodeEvidenceFromWire(&control.NodeEvidence{
NodeName: "m01",
NodeName: "node-a",
InternalIp: "192.168.1.181",
FrontendIp: "10.0.0.1",
FrontendNetworkClass: "100gbe_tcp",
@@ -2887,7 +2887,7 @@ func TestOpsGenerateHelmValuesRestartPersistenceHostPath(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values",
"--out", outPath,
"--target-node", "m02",
"--target-node", "node-b",
"--node-limit", "1",
"--restart-persistence", "hostpath",
"--state-hostpath", "/var/lib/sw-block",
@@ -2945,7 +2945,7 @@ func TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values",
"--out", filepath.Join(t.TempDir(), "values.yaml"),
"--target-node", "m02",
"--target-node", "node-b",
"--replication-factor", "3",
}, &stdout, &stderr)
if code != ops.VolumeStatusExitInvalid {
@@ -2966,7 +2966,7 @@ func TestOpsDescribeVolumeFromBundle(t *testing.T) {
for _, want := range []string{
"cluster status=degraded volumes=1",
"volume pvc-observed status=ok rf=3 ack=sync-quorum",
"primary r2 on m02 frontend=192.168.1.184:3260",
"primary r2 on node-b frontend=192.168.1.184:3260",
} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout missing %q:\n%s", want, stdout.String())
@@ -2984,7 +2984,7 @@ func TestOpsDescribeVolumeFromBundlePrefersProductClusterEvidence(t *testing.T)
for _, want := range []string{
"cluster status=ok volumes=1 nodes=1",
"volume pvc-product status=ok rf=3 ack=sync-quorum",
"primary r2 on m02 frontend=192.168.1.184:3260",
"primary r2 on node-b frontend=192.168.1.184:3260",
} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout missing %q:\n%s", want, stdout.String())
@@ -3341,7 +3341,7 @@ func TestOpsReportFromBundleSkipsCorruptClusterEvidenceCandidate(t *testing.T) {
ReplicationFactor: 1,
Status: ops.ObservationStatusOK,
PrimaryReplica: "r1",
PrimaryNode: "m02",
PrimaryNode: "node-b",
PublishTarget: "192.168.1.184:3260",
}}
raw, err := ops.MarshalObservationJSON(cluster)
@@ -3513,7 +3513,7 @@ func TestOpsExplainVolumeFromBundleBlockedImagePull(t *testing.T) {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "demo", ops.KubeSystemPodsDeploysArtifact), []byte(`NAME READY STATUS RESTARTS AGE IP NODE
pod/sw-block-csi-node-n948t 0/2 Init:ErrImagePull 0 2m3s 192.168.1.184 m02
pod/sw-block-csi-node-n948t 0/2 Init:ErrImagePull 0 2m3s 192.168.1.184 node-b
deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:local
`), 0o644); err != nil {
t.Fatal(err)
@@ -3525,7 +3525,7 @@ deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:loca
}
for _, want := range []string{
"volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed",
"waiting=ImagePullBackOff on node m02 image sw-block-csi:local",
"waiting=ImagePullBackOff on node node-b image sw-block-csi:local",
} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout missing %q:\n%s", want, stdout.String())
@@ -3551,7 +3551,7 @@ func TestOpsDescribeVolumeLiveInventory(t *testing.T) {
"cluster status=ok volumes=1 nodes=0",
"volume pvc-live status=ok rf=1 ack=best-effort",
"pvc default/app-live",
"primary r1 on m02 frontend=127.0.0.1:3260",
"primary r1 on node-b frontend=127.0.0.1:3260",
} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout missing %q:\n%s", want, stdout.String())
@@ -3583,7 +3583,7 @@ func TestOpsClusterAndVolumesLiveInventory(t *testing.T) {
if code != ops.VolumeStatusExitOK {
t.Fatalf("volumes exit=%d stderr=%s stdout=%s", code, volumesErr.String(), volumesOut.String())
}
if !strings.Contains(volumesOut.String(), "volume pvc-live status=ok rf=1 primary=r1 node=m02 frontend=127.0.0.1:3260") {
if !strings.Contains(volumesOut.String(), "volume pvc-live status=ok rf=1 primary=r1 node=node-b frontend=127.0.0.1:3260") {
t.Fatalf("volumes output missing evidence:\n%s", volumesOut.String())
}
}
@@ -3601,9 +3601,9 @@ func cleanCmdResidueCommand(_ context.Context, name string, args ...string) ([]b
}
}
const cmdHelmNodeWide = `m01 Ready worker 10d v1.34.4+k3s1 192.168.1.181 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
m02 Ready control-plane 10d v1.34.4+k3s1 192.168.1.184 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
tp01 Ready worker 10d v1.34.4+k3s1 192.168.1.188 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
const cmdHelmNodeWide = `node-a Ready worker 10d v1.34.4+k3s1 192.168.1.181 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
node-b Ready control-plane 10d v1.34.4+k3s1 192.168.1.184 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
node-c Ready worker 10d v1.34.4+k3s1 192.168.1.188 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
bad1 Ready,SchedulingDisabled worker 10d v1.34.4+k3s1 192.168.1.199 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
bad2 NotReady worker 10d v1.34.4+k3s1 192.168.1.200 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
bad3 Ready worker 10d v1.34.4+k3s1 127.0.0.1 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
@@ -3630,7 +3630,7 @@ const cmdSingleDeploymentListJSON = `{
"labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-live","sw-block.seaweedfs.com/replica":"r1"},
"ownerReferences":[{"kind":"PersistentVolumeClaim","name":"app-live","uid":"uid-live"}]
},
"spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"m02"},"containers":[{"name":"blockvolume","args":["--server-id=m02","--volume-id=pvc-live","--replica-id=r1","--data-addr=127.0.0.1:19101","--ctrl-addr=127.0.0.1:19102","--status-addr=127.0.0.1:23260","--iscsi-listen=127.0.0.1:3260","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-live"]}]}}},
"spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"node-b"},"containers":[{"name":"blockvolume","args":["--server-id=node-b","--volume-id=pvc-live","--replica-id=r1","--data-addr=127.0.0.1:19101","--ctrl-addr=127.0.0.1:19102","--status-addr=127.0.0.1:23260","--iscsi-listen=127.0.0.1:3260","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-live"]}]}}},
"status":{"replicas":1,"readyReplicas":1}
}
]
@@ -3655,7 +3655,7 @@ func writeCmdObservationBundle(t *testing.T) string {
{
ReplicaID: "r2",
ServerID: "node-loss-r2",
NodeName: "m02",
NodeName: "node-b",
Observed: true,
Protocol: "iscsi",
FrontendAddress: "192.168.1.184:3260",
@@ -3677,7 +3677,7 @@ func writeCmdObservationBundle(t *testing.T) string {
{
ReplicaID: "r3",
ServerID: "node-loss-r3",
NodeName: "tp01",
NodeName: "node-c",
Observed: true,
Protocol: "iscsi",
FrontendAddress: "192.168.1.188:3260",
@@ -3705,7 +3705,7 @@ func writeCmdObservationBundle(t *testing.T) string {
if err := os.WriteFile(filepath.Join(dir, "demo", ops.NodeLossRecoverySummaryArtifact), []byte(strings.Join([]string{
"result=promoted",
"ack_profile=sync-quorum",
"promoted=r2@m02",
"promoted=r2@node-b",
"before_frontend=192.168.1.181:3260",
"after_frontend=192.168.1.184:3260",
"reader_verified=true",
@@ -3731,7 +3731,7 @@ func writeCmdProductClusterBundle(t *testing.T) string {
cluster.ProductRevision = "product-cluster-rev"
cluster.Status = ops.ObservationStatusOK
cluster.Nodes = []ops.NodeEvidence{{
NodeName: "m02",
NodeName: "node-b",
InternalIP: "192.168.1.184",
Schedulable: true,
Ready: true,
@@ -3748,11 +3748,11 @@ func writeCmdProductClusterBundle(t *testing.T) string {
ObservedReplicas: 3,
Status: ops.ObservationStatusOK,
PrimaryReplica: "r2",
PrimaryNode: "m02",
PrimaryNode: "node-b",
PublishTarget: "192.168.1.184:3260",
Replicas: []ops.ReplicaEvidence{{
ReplicaID: "r2",
KubernetesNode: "m02",
KubernetesNode: "node-b",
Observed: true,
Role: "primary",
FrontendAddr: "192.168.1.184:3260",
@@ -3796,7 +3796,7 @@ func writeCmdReturnedReplicaBundle(t *testing.T) string {
ReplicationFactor: 2,
Status: ops.ObservationStatusRecovering,
PrimaryReplica: "r2",
PrimaryNode: "m02",
PrimaryNode: "node-b",
PublishTarget: "192.168.1.184:3260",
Epoch: 2,
EndpointVersion: 1,
@@ -3804,7 +3804,7 @@ func writeCmdReturnedReplicaBundle(t *testing.T) string {
RequiredFrontierLSN: 4241,
Replicas: []ops.ReplicaEvidence{{
ReplicaID: "r1",
KubernetesNode: "m01",
KubernetesNode: "node-a",
Observed: true,
Role: "previous_primary",
ReplicationRole: "replica_ready",
@@ -3818,7 +3818,7 @@ func writeCmdReturnedReplicaBundle(t *testing.T) string {
SupportBundlePath: "returned-replica-summary.txt",
}, {
ReplicaID: "r2",
KubernetesNode: "m02",
KubernetesNode: "node-b",
Observed: true,
Role: "primary",
Healthy: true,
@@ -3856,7 +3856,7 @@ func writeCmdReturnedReplicaRebuildBundle(t *testing.T) string {
ReplicationFactor: 3,
Status: ops.ObservationStatusRecovering,
PrimaryReplica: "r2",
PrimaryNode: "m02",
PrimaryNode: "node-b",
PublishTarget: "192.168.1.184:3260",
Epoch: 3,
EndpointVersion: 7,
@@ -3864,7 +3864,7 @@ func writeCmdReturnedReplicaRebuildBundle(t *testing.T) string {
RequiredFrontierLSN: 4241,
Replicas: []ops.ReplicaEvidence{{
ReplicaID: "r1",
KubernetesNode: "m01",
KubernetesNode: "node-a",
Observed: true,
Role: "previous_primary",
ReplicationRole: "replica_behind",
@@ -3878,7 +3878,7 @@ func writeCmdReturnedReplicaRebuildBundle(t *testing.T) string {
SupportBundlePath: "returned-replica-rebuild-summary.txt",
}, {
ReplicaID: "r2",
KubernetesNode: "m02",
KubernetesNode: "node-b",
Observed: true,
Role: "primary",
Healthy: true,
@@ -4004,7 +4004,7 @@ func (cmdFakeClusterEvidenceServer) GetClusterStatus(context.Context, *control.G
ObservedReplicas: 3,
Status: ops.ObservationStatusOK,
PrimaryReplica: "r2",
PrimaryNode: "m02",
PrimaryNode: "node-b",
PublishTarget: "192.168.1.184:3260",
Epoch: 2,
EndpointVersion: 1,
@@ -4014,7 +4014,7 @@ func (cmdFakeClusterEvidenceServer) GetClusterStatus(context.Context, *control.G
EventTime: timestamppb.Now(),
VolumeId: "v1",
ReplicaId: "r2",
NodeName: "m02",
NodeName: "node-b",
EventType: ops.EventTypeCSIReattachObserved,
Severity: "info",
Message: "CSI staged volume on node",
+130 -31
View File
@@ -18,6 +18,7 @@ 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
@@ -83,6 +84,9 @@ 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
@@ -98,6 +102,23 @@ 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 {
@@ -118,6 +139,20 @@ 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)
@@ -186,9 +221,16 @@ 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.
// 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).
func miniVolumeArgs(c miniConfig, chunk bool, layoutID string) []string {
return miniVolumeSpec(c, chunk, layoutID).args()
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
}
// miniVolumeSpec is mini's v1: the same settings volume start writes for a
@@ -268,13 +310,25 @@ 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) {
fmt.Fprintf(r.out, "+ %s %s\n", bin, strings.Join(args, " "))
words := []string{shQuote(bin)}
for _, a := range args {
words = append(words, shQuote(a))
}
fmt.Fprintf(r.out, "+ %s\n", strings.Join(words, " "))
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)
@@ -292,6 +346,7 @@ 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)
@@ -300,6 +355,7 @@ 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
}
@@ -309,16 +365,40 @@ 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)", c.name, miniStartWait, ports, c.name)
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))
}
select {
case <-ctx.Done():
return ctx.Err()
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
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 {
@@ -411,10 +491,26 @@ 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 == "" {
weed, _ = exec.LookPath("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 = ""
}
} 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 {
@@ -482,7 +578,11 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
return 1, err
}
}
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol")} {
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")} {
if err := os.MkdirAll(d, 0o755); err != nil {
return 1, err
}
@@ -491,6 +591,8 @@ 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 {
@@ -519,26 +621,9 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
}
layoutID := ""
if chunk {
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):
}
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)
}
}
vc, err := r.start("blockvolume", volume, miniVolumeArgs(cfg, chunk, layoutID))
@@ -598,9 +683,18 @@ 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 "sw-block mini --dir " + shQuote(c.Dir) + " --reuse"
return miniSelf(c) + " mini --dir " + shQuote(c.Dir) + " --reuse"
}
// miniNextSteps prints what to run next; mini runs none of it.
@@ -616,9 +710,14 @@ func miniNextSteps(w io.Writer, c miniConfig, chunk bool) {
return
}
cmds := miniCommands(c, chunk)
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))
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))
}
// miniBeforeStop reminds the user, before the target goes away, to have
+142 -4
View File
@@ -3,6 +3,7 @@ package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
@@ -57,6 +58,9 @@ 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
}
@@ -145,7 +149,9 @@ func TestMiniWalstoreFlagsAreThePage(t *testing.T) {
}
}
for f := range got {
if _, ok := page[f]; !ok {
// 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" {
t.Errorf("%s: mini passes %s; the page's swb_start does not", c.binary, f)
}
}
@@ -328,7 +334,7 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
}
})
waitOutput(t, out, "sw-block mini: running")
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",
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",
"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())
@@ -344,7 +350,12 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
case <-time.After(30 * time.Second):
t.Fatal("mini did not stop")
}
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"} {
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"} {
if !strings.Contains(out.String(), want) {
t.Fatalf("at stop, output lacks %q:\n%s", want, out.String())
}
@@ -442,7 +453,8 @@ 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"},
"--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"},
}
}
@@ -577,6 +589,52 @@ 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
@@ -800,3 +858,83 @@ 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())
}
}
@@ -0,0 +1,219 @@
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)
}
}
@@ -0,0 +1,75 @@
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"))
}
})
}
}
@@ -0,0 +1,187 @@
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)
}
})
}
}
+4 -2
View File
@@ -13,6 +13,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
type inspectionShell struct {
@@ -207,8 +208,9 @@ func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int {
defer cancel()
cluster, err := readMasterClusterEvidence(ctx, s.master)
if err != nil {
fmt.Fprintf(stderr, "%s: %v\n", name, err)
return 1
policy, detail := operatorAnswer(err, answer.Shell)
fmt.Fprintf(stderr, "%s: %v\n", name, detail)
return policy.Exit
}
var value any = cluster
text := ops.RenderClusterEvidenceText(cluster)
+7 -1
View File
@@ -14,6 +14,7 @@ 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"
@@ -191,6 +192,11 @@ 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 {
@@ -297,7 +303,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 := client.Do(req)
resp, err := answer.DoHTTP(client, req, answer.Unsent)
if err != nil {
return err
}
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"net/url"
@@ -44,9 +45,16 @@ 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 chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
return unobserved(fmt.Errorf("operation has no result"))
}
if err := writeAll(stdout, a.Answer.Result); err != nil {
return chunkExitFailed
@@ -59,16 +67,19 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
}
origin, err := url.Parse(base)
if err != nil {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeBadRequestCLI, err.Error(), false)
return unobserved(fmt.Errorf("invalid original operation origin"))
}
loc, err := url.Parse(a.Location)
if err != nil {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid operation handle URI", false)
return unobserved(fmt.Errorf("invalid operation handle URI"))
}
handle := origin.ResolveReference(loc)
if handle.Scheme != origin.Scheme || handle.Host != origin.Host || handle.User != nil {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation handle changed origin", false)
return unobserved(fmt.Errorf("operation handle changed origin"))
}
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 {
@@ -76,32 +87,28 @@ 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 chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
return unobserved(fmt.Errorf("invalid operation status request"))
}
resp, err := chunkHTTPClient.Do(req)
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
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 = fmt.Errorf("operation status HTTP %d", resp.StatusCode)
err = answer.HTTPStatusFailure(resp.StatusCode, 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 chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
return unobserved(err)
}
if current.ID != a.Answer.ID {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation status changed identity", false)
return unobserved(fmt.Errorf("operation status changed identity"))
}
switch current.State {
case "succeeded":
if len(current.Result) == 0 || !json.Valid(current.Result) {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false)
return unobserved(fmt.Errorf("operation has no result"))
}
if err := writeAll(stdout, current.Result); err != nil {
return chunkExitFailed
@@ -117,7 +124,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 chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "unknown operation state", false)
return unobserved(fmt.Errorf("unknown operation state"))
}
timer := time.NewTimer(100 * time.Millisecond)
select {
@@ -125,7 +132,7 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
if !timer.Stop() {
<-timer.C
}
return chunkExitFailed
return unobserved(ctx.Err())
case <-timer.C:
}
}
@@ -4,7 +4,9 @@ package main
import (
"context"
"crypto/x509"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
@@ -22,11 +24,37 @@ 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
@@ -88,6 +116,9 @@ func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
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)
@@ -113,8 +144,9 @@ func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
if err := cmd.Process.Signal(os.Interrupt); err != nil {
t.Fatal(err)
}
var observerErr error
select {
case <-done:
case observerErr = <-done:
joined = true
case <-ctx.Done():
t.Fatal("interrupt did not stop the observer")
@@ -128,6 +160,18 @@ func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) {
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()
@@ -0,0 +1,197 @@
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)
}
}
@@ -49,7 +49,7 @@ func TestEphemeralStateIsAnOptInThatSaysItLosesData(t *testing.T) {
t.Helper()
var stdout, stderr bytes.Buffer
path := filepath.Join(t.TempDir(), "values.yaml")
args := append([]string{"ops", "generate-helm-values", "--out", path, "--target-node", "m02", "--node-limit", "1",
args := append([]string{"ops", "generate-helm-values", "--out", path, "--target-node", "node-b", "--node-limit", "1",
"--image", "ghcr.io/seaweedfs/seaweed-block:sha-test", "--csi-image", "ghcr.io/seaweedfs/seaweed-block-csi:sha-test"}, extra...)
if code := run(args, &stdout, &stderr); code != ops.VolumeStatusExitOK {
t.Fatalf("generate %v: %d %s", extra, code, stderr.String())
@@ -64,7 +64,7 @@ func TestEphemeralStateIsAnOptInThatSaysItLosesData(t *testing.T) {
if !strings.Contains(out, "restart_persistence_mode=hostpath") || !strings.Contains(out, "master_state_hostpath=/var/lib/sw-block/k8s/master") || !strings.Contains(out, "volume_state_hostpath=/var/lib/sw-block/k8s/volumes") || strings.Contains(out, sentence) {
t.Fatalf("default generate output:\n%s", out)
}
if !strings.Contains(vals, "stateHostPath: /var/lib/sw-block/k8s/master") || !strings.Contains(vals, "stateHostPath: /var/lib/sw-block/k8s/volumes") || !strings.Contains(vals, "kubernetes.io/hostname: m02") {
if !strings.Contains(vals, "stateHostPath: /var/lib/sw-block/k8s/master") || !strings.Contains(vals, "stateHostPath: /var/lib/sw-block/k8s/volumes") || !strings.Contains(vals, "kubernetes.io/hostname: node-b") {
t.Fatalf("default values do not pin blockmaster with its state path:\n%s", vals)
}
out, vals = gen("--restart-persistence", "ephemeral")
@@ -0,0 +1,52 @@
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
}
+27 -38
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,8 +130,9 @@ 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 {
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
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(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))
@@ -163,8 +164,13 @@ 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) (snapshotAnswer, *snapshotRefusal, error) {
return snapshotAnswer{}, nil, fmt.Errorf("the snapshot's outcome is unknown (%s)", why)
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
}
rctx, cancel := context.WithTimeout(ctx, timeout)
req, err := http.NewRequestWithContext(rctx, http.MethodPost, "http://"+status+"/chunk/snapshot", bytes.NewReader(body))
@@ -174,16 +180,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 := client.Do(req)
resp, err := answer.DoHTTP(&client, req, answer.Unsent)
if err != nil {
cancel()
return unknown(err.Error())
return unknown("snapshot admission answer not received", err)
}
b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
resp.Body.Close()
cancel()
if err != nil {
return unknown("answer unreadable: " + err.Error())
return unknown("snapshot answer unreadable", err)
}
if resp.StatusCode == http.StatusAccepted {
var adm snapshotOperationIdentity
@@ -191,7 +197,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(err.Error())
return unknown("snapshot observation failed", err)
}
var op struct {
State string `json:"state"`
@@ -272,7 +278,7 @@ func observeSnapshotOperation(ctx context.Context, env verbEnv, client http.Clie
cancel()
return nil, err
}
resp, err := client.Do(req)
resp, err := answer.DoHTTP(&client, req, answer.PossiblyAdmitted)
var b []byte
if err == nil {
b, err = io.ReadAll(io.LimitReader(resp.Body, 64<<10))
@@ -402,8 +408,9 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
return ops.VolumeStatusExitInvalid
}
unknown := func(step string, err error) int {
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, err, ways)
return 1
policy, detail := operatorAnswer(err, answer.VolumeJob)
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, detail, ways)
return policy.Exit
}
src, err := readEnvFile(filepath.Join(env.EtcDir, o.Source+".env"))
if err != nil {
@@ -425,10 +432,11 @@ 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 code := restoreRefusal(err); code != "" {
return refuse("restore", code+": "+err.Error())
if policy, detail := operatorAnswer(err, answer.VolumeJob); !policy.Retryable {
fmt.Fprintf(stderr, "sw-block volume restore: restore: %v\n", detail)
return policy.Exit
}
return unknown("restore", fmt.Errorf("the outcome is unknown (%v)", err))
return unknown("restore", err)
}
if resp.GetVolumeId() != v.VolumeID || !resp.GetStoreReady() {
return unknown("restore", errors.New("the master did not confirm the new volume store-ready"))
@@ -476,10 +484,10 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
break
}
}
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
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
}
return unknown(step, err)
}
@@ -631,25 +639,6 @@ 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,17 +28,23 @@ 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 {
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
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
}
func newSnapHolder(t *testing.T) *snapHolder {
@@ -79,14 +85,12 @@ func newSnapHolder(t *testing.T) *snapHolder {
http.NotFound(w, r)
return
}
var q struct {
VolumeID, Name, RequestID string
Labels map[string]string
}
var q backupWireRequest
_ = 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)
@@ -386,7 +390,7 @@ func (m *restoreMaster) QueryVolumeStatus(_ context.Context, q *control.StatusRe
return out, nil
}
func serveRestoreMaster(t *testing.T) (*restoreMaster, string) {
func serveRestoreMaster(t *testing.T, options ...grpc.ServerOption) (*restoreMaster, string) {
t.Helper()
for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} {
t.Setenv(key, "")
@@ -406,7 +410,7 @@ func serveRestoreMaster(t *testing.T) (*restoreMaster, string) {
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
server := grpc.NewServer(options...)
control.RegisterLifecycleServiceServer(server, m)
control.RegisterWorkspaceServiceServer(server, m)
control.RegisterEvidenceServiceServer(server, m)
@@ -503,12 +507,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) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
func restoreSetup(t *testing.T, options ...grpc.ServerOption) (*fakeHost, verbEnv, *restoreMaster, *[]string) {
h := newFakeHost(t)
h.name = "vol-r"
env := h.env(t)
base := env.Systemctl
m, master := serveRestoreMaster(t)
m, master := serveRestoreMaster(t, options...)
// 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
@@ -590,6 +594,9 @@ 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
}
@@ -617,7 +624,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 != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
if code != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
t.Fatalf("missing %s: %d %s %s", f, code, out, errs)
}
sh.setMode("")
@@ -720,7 +727,11 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
}
m.failNext = r.fail
code, _, errs := runRestore(env, restoreArgs(h)...)
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") ||
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") ||
!strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("interrupted restore: %d\n%s", code, errs)
}
@@ -786,7 +797,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 != 2 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
t.Fatalf("restore after abort: %d %s", code, errs)
}
})
@@ -822,7 +833,11 @@ 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"},
} {
if code, _, errs := runRestore(env, c.args...); code != 2 || !strings.Contains(errs, c.want) {
wantExit := 2
if c.name == "missing snapshot" {
wantExit = 1
}
if code, _, errs := runRestore(env, c.args...); code != wantExit || !strings.Contains(errs, c.want) {
t.Errorf("%s: %d %s", c.name, code, errs)
}
}
@@ -831,11 +846,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 != 2 || !strings.Contains(errs, "restore_source_not_own") {
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 1 || !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 != 2 || !strings.Contains(errs, "target_exists") {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "target_exists") {
t.Errorf("target of another request: %d %s", code, errs)
}
delete(m.vols, "vol-r")
@@ -853,7 +868,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 != 2 || !strings.Contains(errs, "to undo it: "+abortCmd) {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("refused placement: %d %s", code, errs)
}
if h.called("enable") != 0 {
@@ -994,7 +1009,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 != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
if code != 3 || !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 {
@@ -1066,7 +1081,7 @@ func TestVolumeRestoreRefusesAMalformedLayoutAnswer(t *testing.T) {
h, env, m, _ := restoreSetup(t)
m.failNext = "create-badlayout"
code, _, errs := runRestore(env, restoreArgs(h)...)
if code != 1 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
if code != 3 || !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 {
+14 -8
View File
@@ -11,6 +11,7 @@ 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"
@@ -53,20 +54,25 @@ func runOpsVolumeCreate(args []string, stdout, stderr io.Writer) int {
}
conn, err := link.DialMasterFromEnv(*master)
if err != nil {
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", err)
return 2
policy, detail := operatorAnswer(err, answer.VolumeCreate)
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", detail)
return policy.Exit
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
fail := func(step string, err error) int {
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"
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
}
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
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
}
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)
+5 -10
View File
@@ -8,8 +8,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// runOpsVolume exposes the same master name binding used by ops chunk.
@@ -38,15 +37,11 @@ func runOpsVolume(args []string, stdout, stderr io.Writer) int {
defer cancel()
id, err := resolveVolumeID(ctx, *master, fs.Arg(0))
if err != nil {
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
}
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)
return 78
}
fmt.Fprintln(stdout, id.String())
@@ -6,7 +6,6 @@ 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."
@@ -73,13 +72,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 1
return workspaceErrorExit(err)
}
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 workspaceExit(wsclient.OutcomeOf(err))
return workspaceErrorExit(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")
+25 -8
View File
@@ -21,6 +21,7 @@ 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
@@ -386,7 +387,7 @@ func getJSON(ctx context.Context, env verbEnv, url string, into any) error {
if err != nil {
return err
}
resp, err := env.HTTP.Do(req)
resp, err := answer.DoHTTP(env.HTTP, req, answer.Unsent)
if err != nil {
return err
}
@@ -633,20 +634,32 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
payload["deadlineNs"] = deadline.UnixNano()
}
body, _ := json.Marshal(payload)
unknown := func(why string) (cutAnswer, error) {
return cutAnswer{}, fmt.Errorf("the cut's outcome is unknown (%s): it may have published", why)
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
}
client := *env.HTTP
client.Timeout = timeout + slack
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
id, seen, last := "", uint64(0), time.Now()
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; cut id " + id)
return unknown("no progress within the window, or the deadline passed")
}
method, url := http.MethodPost, "http://"+status+"/chunk/cut"
var reqBody io.Reader = bytes.NewReader(body)
@@ -662,11 +675,15 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
phase := answer.Unsent
if id != "" {
phase = answer.PossiblyAdmitted
}
resp, err := answer.DoHTTP(&client, req, phase)
if err != nil {
cancel()
if id == "" {
return unknown(err.Error())
return unknown("cut admission answer not received", err)
}
time.Sleep(min(env.Poll, time.Until(until)))
continue
@@ -675,7 +692,7 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
resp.Body.Close()
cancel()
if err != nil {
return unknown("answer unreadable: " + err.Error())
return unknown("cut answer unreadable", err)
}
// 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
Loaded 100 of 720 files, more files were not shown because too many files have changed in this diff. Show more