Compare commits

...
Author SHA1 Message Date
pingqiuandClaude Opus 5.5 bbbc613c3e seaweed-block: a rack outage test asserts the detach's settlement (review round 1)
The plain detach answered during the outage settles as a stop-abort: with
the filer answering, a guest write completes within 30 s (tried every 2 s)
and HEAD, as "ops chunk show" reads it, is live with the holder, claim and
epoch it had before the detach, its generation past the baseline's and its
committed image unchanged. The header comment now states this claim.

The repeated plain detach after recovery leaves HEAD detached with the
same holder, claim and epoch, at a position no older than the newest LSN
the holder reports written (HeadLSN in /status/durable) after the last
outage-time guest write.

The recovery steps are numbered in the order they run: 9 restart, 10 the
snapshot resumed, 11 the plain detach repeated, 12 the restore repeated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 02:54:47 -08:00
pingqiuandClaude Opus 5.5 8024a15577 seaweed-block: a rack outage test repeats retryable answers after recovery
After the outage, the snapshot resume and the plain detach are repeated every
5 s for at most 5 min while they answer retryable, as a client does; the first
and the last answers are recorded. The guest write after the detach's answer is
recorded, not asserted: serving resumes once the holder settles the stop as
aborted, so a completed write there is the settled outcome.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 02:35:46 -08:00
pingqiuandClaude Opus 5.5 b4b13fdf2e seaweed-block: a rack outage test asserts the model's answers and its recovery
During the outage the snapshot stops at its resumable stalled state and
the CLI asked again with the same request id answers no_progress,
retryable; the restore answers outcome_unknown, retryable, with its target
listed as a dependent of the source snapshot; the plain detach answers 503
cut_stalled, retryable, "I/O stays stopped", and a guest write after it
does not complete.

A recovery phase follows: the stopped volume server restarts with its
directory, port and rack, and once a placement of three copies is writable
each interrupted request is repeated as it was asked. The snapshot resumes
by its request id before the plain detach (a detached volume admits no
snapshot), the repeated plain detach answers 200, and the repeated restore
succeeds. The final checks before recovery report and continue, so the
recovery is always measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 02:19:45 -08:00
pingqiuandClaude Opus 5.5 f3755af25e seaweed-block: a rack outage measurement records every step
Steps 4 to 7 report a contradiction with t.Errorf instead of stopping, so one
step that disagrees with the model still leaves the later steps and the final
HEAD check measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:59:32 -08:00
pingqiuandClaude Opus 5.5 87c933c43e seaweed-block: record a snapshot and a restore during a rack outage
The rack-outage measurement now also asks, during the outage and after
the cut, for a snapshot (an operation read by its handle) and a restore
of a snapshot taken before the outage into a new volume, then the plain
detach last. Each answer is recorded with its typed code and time to it;
the test asserts only that each answers within the bound and does not
succeed. The pre-outage snapshot's root joins HEAD's committed image in
the unchanged check, and every step logs the snapshot list. The master
asks for the same replication, since it writes a restore target's
objects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:59:00 -08:00
pingqiuandClaude Opus 5.5 27586ee303 seaweed-block: measure a rack outage under a released SeaweedFS
A subprocess integration test of the block on a weed cluster with one
volume server in each of three racks, the chunk store asking for
replication 020. After a baseline cut, rackC's server is stopped; a
released SeaweedFS (no degraded volume growth) can then neither write nor
grow any 020 volume.

Each step logs one "E9-OUTAGE step N" line: the baseline HEAD and orphan
count; guest write and flush latency (p50/p99/max over NVMe/TCP) for 20 s
with every rack up and for 60 s with rackC down; the answer (HTTP status,
answer code, retryable) and time to it of a cut and then a plain detach
asked for during the outage, each with a 90 s no-progress window; HEAD and
the orphan count after them.

Asserted: neither the cut nor the plain detach succeeds; the detach
answers detach_aborted, outcome_unknown or plain_detach_busy; HEAD's
committed image (current root and position) is the baseline's. Latency
and the orphan count are recorded, not asserted. The per-attempt upload
timeout has no typed surface and is not observed.

The weed harness's options take a volume topology (data center, rack and
-max per volume server); a cluster without one starts as before.

No red commit: the test measures released behaviour; there is no fake or
missing hook whose absence would make a meaningful red.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:55:00 -08:00
pingqiuandClaude Opus 5.5 94b90440af seaweed-block: filer contract suite: degraded growth needs a placement of three copies
Degraded growth never leaves fewer than two copies: degradedPlacements
tries totals from copies-1 down to degradedGrowthMinCopies (2), so for a
two-copy placement such as 010 it tries nothing, and a 010 assign with a
rack down fails even on a master with degraded growth. The E9 rack-loss
store asked for 010, so its degraded-growth expectation could never hold.

The E9 stores now use one volume server in each of three racks and
placement 020. With every rack up the copies land in three racks; with
rackC stopped, a store with degraded growth places exactly two copies,
one in rackA and one in rackB (010, the first relaxed placement), and a
store without it refuses, as before. The slot-capacity twin moves to 020
over the same three racks with one 1 MB slot per server, so the first
volume takes every slot.

MemFiler's topology mode takes the copy count and follows the same
order and floor; a new test asserts that a 010 placement with a rack down
never degrades and that 020 degrades to rackA and rackB.

No red commit: this corrects the cells' design, not a fake or product
behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:38:20 -08:00
pingqiuandClaude Opus 5.5 f48591a9d3 seaweed-block: filer contract suite slice 2: parent directories, deadline proxy, degraded growth
MemFiler, as the filer:
- Creating an entry makes its missing parent directories (a directory
  with the child's permission bits plus 0111, its owner, times set), as
  ensureParentDirectoryEntry does. A non-recursive delete of a directory
  with children is refused with the filer's text.
- SetTopology/CopyRacks: puts ask for one copy in each of two racks. With
  too few racks a put is refused as unplaceable (not a full store), or,
  under degraded growth, placed with both copies in the racks left.

TestMemFiler_Contract now expects the made directory sub among /d's
children and asserts that it is a directory and the grandchild is not
listed.

Real-filer target (chunkstore_integration):
- A filer gRPC proxy that applies an armed mutation and holds its reply
  past the caller's deadline, so the apply-after-deadline cells run on a
  real filer.
- weedtest Options.Volumes (data center, rack and -max per volume
  server), Cluster.VolumeURLs and Cluster.StopVolume, for the E9 stores:
  two servers in rackA, one in rackB, replication 010.
- CHUNKSTORE_WEED_DEGRADED_GROWTH=1 states that the binary's source
  contains degraded volume growth (#13178). No release up to 4.56 does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:20:23 -08:00
pingqiuandClaude Opus 5.5 f397468403 seaweed-block: filer contract suite, slice 2 red cells
New cells:
- C_ParentDirectories: creating an entry makes its missing parent
  directories as the filer does (directory, the child's permission bits
  plus 0111, its owner, times set). A non-recursive delete of a directory
  with children is refused; an empty one is deleted and its parent kept.
- E9_RackLossAssign: with one of two racks down, an assign asking for a
  copy in each rack is refused by a store without degraded growth. The
  typed outcome the product gives is recorded, not asserted. A store
  with degraded growth places it with at least two copies in the racks
  still up.
- E9_SlotCapacityTwin: a placement that fits but finds no free slot is a
  full store, storage.ErrChunkRemoteFull.

The listing cell now expects the made parent directory in the listing.
The E5 cell logs the full refusal text.

Red on MemFiler: it makes no parent directories and has no topology
mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:08:51 -08:00
pingqiuandClaude Opus 5.5 945223e882 seaweed-block: filer contract suite and fake modes
MemFiler now passes the filer contract suite the real filer is held to:

- An unconditional delete of a missing entry succeeds and a conditional
  one is ErrPrecondition, as the Filer interface and the filer say (it
  returned ErrNotFound for both).
- A listed directory's one trailing slash is trimmed, as the filer's
  listing does.
- Blobs: chunk payloads by fid (Put, Get, DeleteBlob), returned by
  Blobs() so the filer's own method set is unchanged. Chunks an entry
  drops (delete, an update, a plain create over it) are freed.
- SetFreeDelay/FlushFrees: the free is late, as the filer's deletion
  queue; a read by fid succeeds until it runs.
- ApplyAfterDeadline: a mutation applies while its caller gets the
  context's gRPC status, as a reply lost after the filer applied it.
- SetCap: a byte or object cap refused with the filer's full-store text,
  which matches storage.ErrChunkRemoteFull.

Every mode is off by default, so existing callers see the old behaviour
apart from the delete and listing fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:03:53 -08:00
pingqiuandClaude Opus 5.5 65f5744e08 seaweed-block: filer contract suite, red cells
One table of cells for the layer below the block, run on every target:
"mem" (MemFiler) always, "weed" (a real filer) under the
chunkstore_integration tag with CHUNKSTORE_WEED. A divergence is a defect
of the fake. Cells cover the seam's shape (lookup, create, list, the
missing-entry delete and update, the absent-key rule), CAS on expected
extended values, IF_CHUNKS_EQUAL, late chunk free after a delete or a
dropping update, a full store's typed refusal and a mutation applied after
its caller's deadline.

Red on MemFiler: an unconditional delete of a missing entry fails, a
trailing slash on the listed directory lists nothing, and the fake has no
blobs, late-free queue, capacity cap or apply-after-deadline mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:01:47 -08:00
8 changed files with 2533 additions and 36 deletions

No files matched your search

@@ -0,0 +1,867 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/internal/weedtest"
)
// A rack outage under a released SeaweedFS (no degraded volume growth): the
// chunk store asks for replication 020 (one copy in each of three racks) on
// three volume servers in rackA, rackB and rackC, and rackC's server is
// stopped. No 020 volume stays writable and none can be grown, so every
// chunk upload is refused while the guest keeps writing to its local WAL.
//
// Every outcome is the product's typed answer: guest I/O over NVMe/TCP, the
// holder's /chunk/cut, /chunk/snapshot (an operation read by its handle) and
// /chunk/detach HTTP status and answer code, the restore's answer as
// "ops chunk restore" prints it, HEAD as "ops chunk show" reads it, the
// snapshot list as "ops chunk snapshots" prints it, and orphans as
// "ops chunk verify --orphans" reports them. The master writes a restore
// target's objects, so it asks for 020 too.
//
// Order: a baseline cut and a snapshot with every rack up; guest load; the
// outage; guest load; then, during the outage, a cut, a snapshot, a restore
// of the pre-outage snapshot into a new volume, and a plain detach last.
// Then recovery: rackC's server restarts, and each interrupted request is
// repeated as it was asked: the snapshot resumed by its request id (before
// the plain detach, since a detached volume admits no snapshot), the plain
// detach, the restore.
//
// Asserted (the model's answers): during the outage the cut, the snapshot,
// the restore and the plain detach each answer within the bound and none
// succeeds; the snapshot stops at its resumable "stalled" state and the
// CLI resuming it answers no_progress, retryable; the restore answers
// outcome_unknown, retryable, with its target listed as a dependent of the
// source snapshot; the plain detach answers 503 cut_stalled, retryable,
// "I/O stays stopped", and then settles as a stop-abort: with the filer
// answering, a guest write completes within 30 s and HEAD is live with the
// same holder, claim and epoch, its generation past the baseline's and its
// committed image unchanged; HEAD's committed image (current root and
// position) and the pre-outage snapshot's root are unchanged. After
// recovery the same requests complete: the snapshot succeeds and is
// listed; the plain detach answers 200 and HEAD is detached with the same
// holder, claim and epoch at a position no older than the newest LSN the
// holder reported written after the last outage-time guest write; the
// restore succeeds. Recorded, one grep-able "E9-OUTAGE step N"
// line per step: guest write and flush latency before and during the
// outage, each answer and the time to it, HEAD, the snapshot list and the
// orphan count.
//
// The cut and the detach run with a 90 s no-progress window (timeoutMs on
// the request, as "ops chunk cut --timeout 90s" sends it), not the 5 min
// default. A snapshot's timeoutMs bounds only its admission; the snapshot
// operation itself runs under the product's default cut window (5 min).
// Per-attempt upload timing (the 30 s CutRequestTimeout of each chunk
// upload) has no typed surface; only the final answer is observed.
//
// About 15-25 minutes, at most about 60: go test -timeout 75m.
const (
e9Window = 90 * time.Second
e9IOBound = 20 * time.Second // one guest command's answer bound
e9AnswerBound = 8 * time.Minute // a cut or detach must answer within this
e9RepeatBound = 5 * time.Minute // a client repeats a retryable answer for this long after the outage
)
func TestE9RackOutageOnAReleasedStore(t *testing.T) {
racks := []string{"rackA", "rackB", "rackC"}
var vols []weedtest.Volume
for _, r := range racks {
vols = append(vols, weedtest.Volume{DataCenter: "dc1", Rack: r, Max: 16})
}
cluster := startWorkspaceWeedWith(t, t.TempDir(), w4WeedOpts{VolumeSizeLimitMB: 256, Volumes: vols})
// The harness's readiness probe asks for the default placement; wait
// until a 020 placement is writable too (every server registered).
await020 := func(within time.Duration) (time.Duration, error) {
start := time.Now()
probe, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: cluster.filerGRPC, Collection: "swblock", Replication: "020", AssignPath: "/swblock/vols/probe"})
if err != nil {
return 0, err
}
defer probe.Close()
for end := start.Add(within); ; time.Sleep(500 * time.Millisecond) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := probe.Put(ctx, []byte("probe-020"))
cancel()
if err == nil {
return time.Since(start), nil
}
if time.Now().After(end) {
return time.Since(start), err
}
}
}
if _, err := await020(60 * time.Second); err != nil {
t.Fatalf("no 020 placement writable within 60s of the cluster start: %v", err)
}
// No mutual TLS: the test speaks to the holder's chunk control over HTTP.
env := startHandoffEnvOnCluster(t, 1, []string{"v2"}, nil, false, cluster, "--chunk-replication", "020")
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off", "--chunk-replication", "020"}
holder := env.start(t, "blockvolume-e9", "s1")
env.adopt(t, holder, "s1")
status := env.hosts["s1"].status
head := func() layoutHeadRecord {
out, _ := env.h.command(t, env.chunkShow()...)
hd, err := parseLayoutHead(out)
if err != nil {
t.Fatal(err)
}
return hd
}
image := func(h layoutHeadRecord) string { return fmt.Sprintf("%s@%d", h.Current, h.Position) }
snapList := func() string {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
list, err := env.listSnapshots(ctx, "v1", "")
if err != nil {
return "unreadable: " + firstLine(err.Error())
}
var parts []string
for _, s := range list {
parts = append(parts, fmt.Sprintf("%s root=%s dependents=%v", s.Name, s.Root, s.Dependents))
}
return fmt.Sprintf("%d [%s]", len(list), strings.Join(parts, "; "))
}
const baseSnap = "e9-base"
// 1. A volume with a committed image: baseline written, one cut, one
// snapshot (the restore source).
env.writeCutCrashImage(t, 'A')
snaps0 := snapList()
baseCut := e9Handle(t, status, "/chunk/cut", map[string]any{"volumeID": "v1", "timeoutMs": e9Window.Milliseconds()})
if baseCut.status != http.StatusOK {
t.Fatalf("baseline cut with every rack up: HTTP %d %s: %s", baseCut.status, baseCut.code, baseCut.message)
}
baseSnapshot := e9Snapshot(t, status, baseSnap)
if baseSnapshot.state != "succeeded" {
t.Fatalf("baseline snapshot with every rack up: HTTP %d state %q %s: %s", baseSnapshot.status, baseSnapshot.state, baseSnapshot.code, baseSnapshot.message)
}
h1 := head()
if h1.State != "" || len(h1.Current) == 0 || string(h1.Current) == "null" {
t.Fatalf("baseline HEAD %+v: want a live HEAD with a committed image", h1)
}
baseRoot := e9SnapshotRoot(t, env, baseSnap)
orphans1 := e9Orphans(t, env)
t.Logf("E9-OUTAGE step 1 baseline cut HTTP %d in %s; snapshot %s HTTP %d in %s root=%s; HEAD gen=%d epoch=%d position=%d state=%q image=%s; orphans=%s; snapshots before=%s after=%s",
baseCut.status, baseCut.at.Round(time.Millisecond), baseSnap, baseSnapshot.status, baseSnapshot.at.Round(time.Millisecond), baseRoot,
h1.Gen, h1.Epoch, h1.Position, h1.State, image(h1), orphans1, snaps0, snapList())
// 2. Guest write latency with every rack up.
before := e9GuestLoad(t, env, 20*time.Second, 'B')
t.Logf("E9-OUTAGE step 2 racks up %s", before)
// 3. rackC's server stops; guest write latency during the outage.
cluster.stopProc(t, w4VolumeProc(len(racks)-1))
downAt := time.Now()
during := e9GuestLoad(t, env, 60*time.Second, 'C')
lsn3 := e9WrittenLSN(t, status)
t.Logf("E9-OUTAGE step 3 rackC down %s; holder written LSN %s", during, lsn3)
// 4. A cut during the outage.
snaps4 := snapList()
cut := e9Handle(t, status, "/chunk/cut", map[string]any{"volumeID": "v1", "timeoutMs": e9Window.Milliseconds()})
t.Logf("E9-OUTAGE step 4 cut window=%s: HTTP %d code=%q retryable=%v after %s (outage age %s): %s; snapshots before=%s after=%s",
e9Window, cut.status, cut.code, cut.retryable, cut.at.Round(time.Millisecond), time.Since(downAt).Round(time.Second), firstLine(cut.message), snaps4, snapList())
if cut.status == http.StatusOK {
t.Errorf("step 4: a cut succeeded while no 020 placement can be written (HEAD gen %v)", cut.headGen)
}
if cut.status == 0 {
t.Errorf("step 4: the cut gave no typed answer within %s", e9AnswerBound)
}
// 5. A snapshot during the outage: its operation stops at the
// resumable "stalled" state; the CLI asked again with the same request
// id answers no_progress, retryable.
const outageSnap = "e9-outage"
snaps5 := snapList()
snap := e9Snapshot(t, status, outageSnap)
snapCLIArgs := []string{"ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", status, "--name", outageSnap, "--request-id", e9SnapshotRequestID(outageSnap)}
snapCLI := e9CLI(t, env, snapCLIArgs...)
t.Logf("E9-OUTAGE step 5 snapshot: HTTP %d code=%q state=%q after %s (outage age %s): %s; CLI same request id: exit %d code=%q retryable=%v after %s: %s; snapshots before=%s after=%s",
snap.status, snap.code, snap.state, snap.at.Round(time.Millisecond), time.Since(downAt).Round(time.Second), firstLine(snap.message),
snapCLI.exit, snapCLI.code, snapCLI.retryable, snapCLI.at.Round(time.Millisecond), firstLine(snapCLI.message), snaps5, snapList())
if snap.state != "stalled" {
t.Errorf("step 5: the snapshot answered HTTP %d state %q code %q within %s, not the resumable \"stalled\"", snap.status, snap.state, snap.code, e9AnswerBound)
}
if snapCLI.exit == 0 || snapCLI.code != "no_progress" || !snapCLI.retryable {
t.Errorf("step 5: the CLI resuming the snapshot answered exit %d code %q retryable %v; want no_progress, retryable", snapCLI.exit, snapCLI.code, snapCLI.retryable)
}
// 6. A restore of the pre-outage snapshot into a new volume during the
// outage (the product restores into a new volume, never in place).
snaps6 := snapList()
restoreArgs := []string{"ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", baseSnap, "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
restore := e9CLI(t, env, restoreArgs...)
deps6 := e9SnapshotDependents(t, env, baseSnap)
t.Logf("E9-OUTAGE step 6 restore %s -> v2: exit %d code=%q retryable=%v after %s (outage age %s): %s; %s dependents=%v; snapshots before=%s after=%s",
baseSnap, restore.exit, restore.code, restore.retryable, restore.at.Round(time.Millisecond), time.Since(downAt).Round(time.Second), firstLine(restore.message), baseSnap, deps6, snaps6, snapList())
switch {
case restore.exit == 0:
t.Errorf("step 6: a restore succeeded while no 020 placement can be written: %s", restore.message)
case restore.exit < 0:
t.Errorf("step 6: the restore gave no answer within %s: %s", e9AnswerBound, restore.message)
case restore.code != "outcome_unknown" || !restore.retryable:
t.Errorf("step 6: the restore answered exit %d code %q retryable %v; want outcome_unknown, retryable", restore.exit, restore.code, restore.retryable)
}
if !e9HasDependent(deps6, "v2") {
t.Errorf("step 6: snapshot %s lists dependents %v; want the pending target v2", baseSnap, deps6)
}
// 7. A plain detach during the outage, last.
hPre := head()
snaps7 := snapList()
detach := e9Handle(t, status, "/chunk/detach", map[string]any{"volumeID": "v1", "plain": true, "timeoutMs": e9Window.Milliseconds()})
t.Logf("E9-OUTAGE step 7 plain detach window=%s: HTTP %d code=%q retryable=%v after %s: %s; snapshots before=%s after=%s",
e9Window, detach.status, detach.code, detach.retryable, detach.at.Round(time.Millisecond), firstLine(detach.message), snaps7, snapList())
switch {
case detach.status == http.StatusOK:
t.Errorf("step 7: a plain detach succeeded while no 020 placement can be written (HEAD gen %v)", detach.headGen)
case detach.status == 0:
t.Errorf("step 7: the plain detach gave no typed answer within %s", e9AnswerBound)
case detach.status != http.StatusServiceUnavailable || detach.code != "cut_stalled" || !detach.retryable || !strings.Contains(detach.message, "I/O stays stopped"):
t.Errorf("step 7: the plain detach answered HTTP %d %q retryable %v %q; want 503 cut_stalled, retryable, \"I/O stays stopped\"", detach.status, detach.code, detach.retryable, detach.message)
}
// The detach settles as a stop-abort: I/O stays stopped only while the
// stop is unsettled; with the filer answering, the holder writes a
// stop-abort HEAD (nothing published) and serving resumes. A guest write
// is tried every 2 s until one completes or 30 s pass.
settleStart := time.Now()
var probes []string
completed := false
for !completed && time.Since(settleStart) < 30*time.Second {
bound := min(10*time.Second, 30*time.Second-time.Since(settleStart))
r := e9WriteProbe(env, bound)
probes = append(probes, r)
if completed = r == "completed"; !completed {
time.Sleep(2 * time.Second)
}
}
lsn7 := e9WrittenLSN(t, status)
h7 := head()
t.Logf("E9-OUTAGE step 7 guest write after the detach: completed=%v after %s, %d tries %v; holder written LSN %s; HEAD gen=%d epoch=%d holder=%q claim=%q position=%d state=%q image=%s (before the detach gen=%d epoch=%d holder=%q claim=%q)",
completed, time.Since(settleStart).Round(time.Millisecond), len(probes), probes, lsn7, h7.Gen, h7.Epoch, h7.Holder, h7.ClaimID, h7.Position, h7.State, image(h7),
hPre.Gen, hPre.Epoch, hPre.Holder, hPre.ClaimID)
if !completed {
t.Errorf("step 7: no guest write completed within 30s of the detach's answer: %v", probes)
}
if h7.State != "" || h7.Holder != hPre.Holder || h7.ClaimID != hPre.ClaimID || h7.Epoch != hPre.Epoch || h7.Gen <= h1.Gen || image(h7) != image(h1) {
t.Errorf("step 7: HEAD after the detach is state %q holder %q claim %q epoch %d gen %d image %s; want the stop-abort settlement: live, holder %q claim %q epoch %d, gen past %d, image %s",
h7.State, h7.Holder, h7.ClaimID, h7.Epoch, h7.Gen, image(h7), hPre.Holder, hPre.ClaimID, hPre.Epoch, h1.Gen, image(h1))
}
// 8. HEAD's committed image is the baseline's and the pre-outage
// snapshot names the same root; orphans recorded.
h8 := head()
root8 := e9SnapshotRoot(t, env, baseSnap)
orphans8 := e9Orphans(t, env)
t.Logf("E9-OUTAGE step 8 HEAD gen=%d epoch=%d position=%d state=%q image=%s (baseline gen=%d image=%s); snapshot %s root=%s (baseline %s); orphans=%s (baseline %s); snapshots=%s",
h8.Gen, h8.Epoch, h8.Position, h8.State, image(h8), h1.Gen, image(h1), baseSnap, root8, baseRoot, orphans8, orphans1, snapList())
if image(h8) != image(h1) {
t.Errorf("step 8: HEAD's committed image moved during the outage: %s -> %s", image(h1), image(h8))
}
if root8 != baseRoot {
t.Errorf("step 8: snapshot %s's root moved during the outage: %s -> %s", baseSnap, baseRoot, root8)
}
// 9. Recovery: rackC's server restarts (same data directory, port and
// rack) and a 020 placement is writable again.
cluster.restartProc(t, w4VolumeProc(len(racks)-1))
took, err := await020(3 * time.Minute)
t.Logf("E9-OUTAGE step 9 rackC restarted after an outage of %s; 020 writable after %s (err %v)", time.Since(downAt).Round(time.Second), took.Round(time.Millisecond), err)
if err != nil {
t.Fatalf("step 9: no 020 placement writable within 3m of rackC's restart: %v", err)
}
// 10. The stalled snapshot resumed with its request id succeeds (before
// the detach: a detached volume admits no snapshot, a resumed one
// included).
// A client repeats a retryable answer: every 5 s for at most 5 min.
snaps10 := snapList()
start10 := time.Now()
var resumed e9CLIAnswer
var first10 string
tries10 := 0
for {
tries10++
resumed = e9CLI(t, env, snapCLIArgs...)
if tries10 == 1 {
first10 = fmt.Sprintf("exit %d code=%q: %s", resumed.exit, resumed.code, firstLine(resumed.message))
}
if resumed.exit == 0 || !resumed.retryable || time.Since(start10) > e9RepeatBound {
break
}
time.Sleep(5 * time.Second)
}
listed := e9SnapshotListed(t, env, outageSnap)
t.Logf("E9-OUTAGE step 10 snapshot resumed with its request id: %d tries over %s, first %s; last exit %d code=%q: %s; %s listed=%v; snapshots before=%s after=%s",
tries10, time.Since(start10).Round(time.Millisecond), first10, resumed.exit, resumed.code, firstLine(resumed.message), outageSnap, listed, snaps10, snapList())
if resumed.exit != 0 || !listed {
t.Errorf("step 10: the resumed snapshot answered exit %d code %q, listed %v; want success and %s listed", resumed.exit, resumed.code, listed, outageSnap)
}
// 11. The same plain detach, repeated, completes: HEAD is detached with
// the holder, claim and epoch it had, at a position no older than the
// newest LSN written after the last outage-time guest write.
snaps11 := snapList()
start11 := time.Now()
var detached e9Answer
var first11 string
tries11 := 0
for {
tries11++
detached = e9Handle(t, status, "/chunk/detach", map[string]any{"volumeID": "v1", "plain": true, "timeoutMs": e9Window.Milliseconds()})
if tries11 == 1 {
first11 = fmt.Sprintf("HTTP %d code=%q", detached.status, detached.code)
}
if detached.status == http.StatusOK || !detached.retryable || time.Since(start11) > e9RepeatBound {
break
}
time.Sleep(5 * time.Second)
}
h11 := head()
t.Logf("E9-OUTAGE step 11 plain detach repeated: %d tries over %s, first %s; last HTTP %d code=%q retryable=%v after %s: %s; HEAD gen=%d epoch=%d holder=%q claim=%q position=%d state=%q image=%s (written LSN after step 3 %s, after step 7 %s); snapshots before=%s after=%s",
tries11, time.Since(start11).Round(time.Millisecond), first11, detached.status, detached.code, detached.retryable, detached.at.Round(time.Millisecond), firstLine(detached.message),
h11.Gen, h11.Epoch, h11.Holder, h11.ClaimID, h11.Position, h11.State, image(h11), lsn3, lsn7, snaps11, snapList())
if detached.status != http.StatusOK {
t.Errorf("step 11: the repeated plain detach answered HTTP %d %q retryable %v; want 200", detached.status, detached.code, detached.retryable)
}
if h11.State != "detached" || h11.Holder != hPre.Holder || h11.ClaimID != hPre.ClaimID || h11.Epoch != hPre.Epoch {
t.Errorf("step 11: HEAD after the detach is state %q holder %q claim %q epoch %d; want detached, holder %q claim %q epoch %d",
h11.State, h11.Holder, h11.ClaimID, h11.Epoch, hPre.Holder, hPre.ClaimID, hPre.Epoch)
}
if !lsn7.known || h11.Position < lsn7.head {
t.Errorf("step 11: HEAD position %d; want at least the holder's written LSN after the last outage-time guest write (%s)", h11.Position, lsn7)
}
// 12. The same restore, repeated, completes: v2 is store-ready.
snaps12 := snapList()
restored := e9CLI(t, env, restoreArgs...)
t.Logf("E9-OUTAGE step 12 restore repeated %s -> v2: exit %d code=%q retryable=%v after %s: %s; %s dependents=%v; snapshots before=%s after=%s",
baseSnap, restored.exit, restored.code, restored.retryable, restored.at.Round(time.Millisecond), firstLine(restored.message), baseSnap, e9SnapshotDependents(t, env, baseSnap), snaps12, snapList())
if restored.exit != 0 {
t.Errorf("step 12: the repeated restore answered exit %d code %q retryable %v; want success", restored.exit, restored.code, restored.retryable)
}
}
// e9LSN is the holder's newest written LSN for v1 as /status/durable
// reports it (HeadLSN, valid when FrontierKnown).
type e9LSN struct {
head uint64
known bool
operational bool
}
func (l e9LSN) String() string {
return fmt.Sprintf("HeadLSN=%d frontierKnown=%v operational=%v", l.head, l.known, l.operational)
}
// e9WrittenLSN reads v1's HeadLSN (the newest LSN written) from the
// holder's /status/durable.
func e9WrittenLSN(t *testing.T, addr string) e9LSN {
t.Helper()
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Get("http://" + addr + "/status/durable?volume=v1")
if err != nil {
t.Fatalf("durable status: %v", err)
}
defer resp.Body.Close()
var st struct {
Volumes []struct {
VolumeID string
FrontierKnown bool
HeadLSN uint64
Operational bool
}
}
b, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil || resp.StatusCode != http.StatusOK || json.Unmarshal(b, &st) != nil {
t.Fatalf("durable status: HTTP %d %v: %.200q", resp.StatusCode, err, b)
}
for _, v := range st.Volumes {
if v.VolumeID == "v1" {
return e9LSN{head: v.HeadLSN, known: v.FrontierKnown, operational: v.Operational}
}
}
t.Fatalf("durable status lists no v1: %.200q", b)
return e9LSN{}
}
// e9SnapshotListed reports whether "ops chunk snapshots" lists v1's
// snapshot name.
func e9SnapshotListed(t *testing.T, env *handoffEnv, name string) bool {
t.Helper()
for _, s := range env.snapshots(t, "v1", name) {
if s.Name == name {
return true
}
}
return false
}
// e9SnapshotDependents is the dependents "ops chunk snapshots" lists for
// v1's snapshot name.
func e9SnapshotDependents(t *testing.T, env *handoffEnv, name string) []string {
t.Helper()
for _, s := range env.snapshots(t, "v1", name) {
if s.Name == name {
return s.Dependents
}
}
t.Fatalf("snapshot %s is not listed for v1", name)
return nil
}
// e9HasDependent reports whether deps names volume vol (its directory is
// the name, a dash and the layout id's prefix).
func e9HasDependent(deps []string, vol string) bool {
for _, d := range deps {
if strings.HasPrefix(d, vol+"-") {
return true
}
}
return false
}
// e9WriteProbe connects to the volume's NVMe/TCP target and writes one
// block within bound. It answers "completed", or how the write did not
// complete: the connect's error, the write's typed error, or no answer
// within bound.
func e9WriteProbe(env *handoffEnv, bound time.Duration) string {
done := make(chan string, 1)
var conn struct {
sync.Mutex
c []net.Conn
}
go func() {
c, err := e9DialNVMe(env.hosts["s1"].nvme, plannedHandoffNQN, func(nc net.Conn) {
conn.Lock()
conn.c = append(conn.c, nc)
conn.Unlock()
})
if err != nil {
done <- "connect: " + err.Error()
return
}
if err := c.tryWrite(0, cutCrashBlock('D', 0)); err != nil {
done <- "write: " + err.Error()
return
}
done <- "completed"
}()
select {
case r := <-done:
conn.Lock()
for _, c := range conn.c {
_ = c.Close()
}
conn.Unlock()
return r
case <-time.After(bound):
conn.Lock()
for _, c := range conn.c {
_ = c.Close()
}
conn.Unlock()
<-done
return fmt.Sprintf("no answer within %s", bound)
}
}
// e9DialNVMe is dialNVMe answering its error instead of failing the test:
// the admin and the I/O queue connected to subNQN. opened sees each
// connection as it opens.
func e9DialNVMe(addr, subNQN string, opened func(net.Conn)) (*nvmeInitiator, error) {
c := &nvmeInitiator{}
cd := nvme.ConnectData{HostID: [16]byte{0x5e, 0xa1}, SubNQN: subNQN, HostNQN: "nqn.2026-11.io.seaweedfs:handoff-test"}
var cntlID uint16
for qid := uint32(0); qid <= 1; qid++ {
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
return nil, err
}
opened(conn)
// Bounded even when the probe's close comes before this connection
// opened; the write then bounds itself (nvmeIODeadline).
_ = conn.SetDeadline(time.Now().Add(15 * time.Second))
r, w := nvme.NewReader(conn), nvme.NewWriter(conn)
if err := w.SendHeaderOnly(0x0, &nvme.ICRequest{PDUMaxR2T: 1}, 120); err != nil {
return nil, fmt.Errorf("ICReq: %w", err)
}
if ch, err := r.Dequeue(); err != nil || ch.Type != 0x1 {
return nil, fmt.Errorf("ICResp: type %v: %w", ch, err)
}
if err := r.Receive(&nvme.ICResponse{}); err != nil {
return nil, fmt.Errorf("ICResp body: %w", err)
}
cd.CNTLID = 0xFFFF
if qid == 1 {
cd.CNTLID = cntlID
}
buf := make([]byte, 1024)
cd.Marshal(buf)
c.cid++
cmd := nvme.CapsuleCommand{OpCode: 0x7F, FCType: 0x01, CID: c.cid, D10: qid << 16}
if err := w.SendWithData(0x4, 0, &cmd, 64, buf); err != nil {
return nil, fmt.Errorf("Connect qid %d: %w", qid, err)
}
ch, err := r.Dequeue()
if err != nil || ch.Type != 0x5 {
return nil, fmt.Errorf("Connect qid %d response: type %v: %w", qid, ch, err)
}
var resp nvme.CapsuleResponse
if err := r.Receive(&resp); err != nil {
return nil, fmt.Errorf("Connect qid %d response body: %w", qid, err)
}
if resp.Status != 0 {
return nil, fmt.Errorf("Connect qid %d status 0x%04x", qid, resp.Status)
}
if qid == 0 {
c.admin, cntlID = conn, uint16(resp.DW0&0xFFFF)
} else {
c.io, c.r, c.w = conn, r, w
}
}
return c, nil
}
// e9SnapshotRoot is the root "ops chunk snapshots" lists for v1's snapshot
// name; the test fails when the list is unreadable or lacks it.
func e9SnapshotRoot(t *testing.T, env *handoffEnv, name string) string {
t.Helper()
for _, s := range env.snapshots(t, "v1", name) {
if s.Name == name {
return s.Root
}
}
t.Fatalf("snapshot %s is not listed for v1", name)
return ""
}
// e9SnapAnswer is a snapshot operation's answer: its state ("succeeded",
// "refused", the resumable "stalled", or how the admission or the handle
// read was refused) and status: 200 when it succeeded, else the refusal's
// HTTP status (the admission's, or the one the operation records), 0 when
// it stalled or none came within e9AnswerBound.
type e9SnapAnswer struct {
status int
code string
state string
message string
at time.Duration
}
func e9SnapshotRequestID(name string) string { return "e9-" + name }
// e9Snapshot asks the holder for a snapshot of v1 as an operation
// (Prefer: respond-async) and reads its handle until it succeeds, is
// refused or stalls, as "ops chunk snapshot" does.
func e9Snapshot(t *testing.T, addr, name string) e9SnapAnswer {
t.Helper()
start := time.Now()
payload, err := json.Marshal(map[string]any{"volumeID": "v1", "name": name, "requestID": e9SnapshotRequestID(name), "timeoutMs": e9Window.Milliseconds()})
if err != nil {
t.Fatal(err)
}
client := &http.Client{Timeout: e9Window + time.Minute}
type reply struct {
Handle string `json:"handle"`
State string `json:"state"`
Code string `json:"code"`
Message string `json:"message"`
Status int `json:"status"`
}
read := func(resp *http.Response) (reply, error) {
defer resp.Body.Close()
var r reply
b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return r, err
}
if err := json.Unmarshal(b, &r); err != nil {
return r, fmt.Errorf("HTTP %d answer is not JSON: %q", resp.StatusCode, b)
}
return r, nil
}
req, err := http.NewRequest(http.MethodPost, "http://"+addr+"/chunk/snapshot", bytes.NewReader(payload))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Prefer", "respond-async")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("snapshot %s admission: %v", name, err)
}
httpStatus := resp.StatusCode
location := resp.Header.Get("Location")
r, err := read(resp)
if err != nil {
t.Fatalf("snapshot %s admission: %v", name, err)
}
if httpStatus != http.StatusAccepted && httpStatus != http.StatusOK {
return e9SnapAnswer{status: httpStatus, code: r.Code, state: "admission refused", message: r.Message, at: time.Since(start)}
}
if location == "" {
location = r.Handle
}
for r.State != "succeeded" && r.State != "refused" && r.State != "stalled" {
if location == "" {
t.Fatalf("snapshot %s: state %q without a handle", name, r.State)
}
if time.Since(start) > e9AnswerBound {
return e9SnapAnswer{code: "no_answer", state: r.State, message: "still " + r.State, at: time.Since(start)}
}
time.Sleep(time.Second)
resp, err := client.Get("http://" + addr + location)
if err != nil {
t.Fatalf("snapshot %s: read handle: %v", name, err)
}
httpStatus = resp.StatusCode
if r, err = read(resp); err != nil {
t.Fatalf("snapshot %s: read handle: %v", name, err)
}
if httpStatus != http.StatusOK {
return e9SnapAnswer{status: httpStatus, code: r.Code, state: "handle refused", message: r.Message, at: time.Since(start)}
}
}
a := e9SnapAnswer{status: http.StatusOK, code: "ok", state: r.State, message: r.Message, at: time.Since(start)}
if r.State == "stalled" {
a.status, a.code = 0, r.Code
}
if r.State == "refused" {
a.status, a.code = r.Status, r.Code
if a.status == 0 {
a.status = http.StatusConflict // a refusal recorded without its status is still not a success
}
}
return a
}
// e9CLIAnswer is an ops command's answer: its exit status (-1: none within
// e9AnswerBound) and, on failure, the typed code it prints.
type e9CLIAnswer struct {
exit int
code string
message string
retryable bool
at time.Duration
}
// e9CLI runs one ops command as an operator does ("ops chunk restore"
// through the master, "ops chunk snapshot" against the holder) and reads
// its answer within e9AnswerBound.
func e9CLI(t *testing.T, env *handoffEnv, args ...string) e9CLIAnswer {
t.Helper()
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), e9AnswerBound)
defer cancel()
out, errOut, rc, err := runCLI(ctx, env.h, args...)
if ctx.Err() != nil {
return e9CLIAnswer{exit: -1, code: "no_answer", message: fmt.Sprintf("%v %s", err, firstLine(strings.TrimSpace(errOut))), at: time.Since(start)}
}
if err != nil {
t.Fatalf("%q: %v", args, err)
}
a := e9CLIAnswer{exit: rc, message: strings.TrimSpace(out), at: time.Since(start)}
var body struct {
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
}
if rc != 0 {
if json.Unmarshal([]byte(out), &body) == nil && body.Code != "" {
a.code, a.message, a.retryable = body.Code, body.Message, body.Retryable
} else {
a.message = fmt.Sprintf("%s %s", strings.TrimSpace(out), firstLine(strings.TrimSpace(errOut)))
}
}
return a
}
// e9Answer is the holder's final answer to one handle (a cut or a plain
// detach): its HTTP status (0: none within e9AnswerBound) and answer code
// ("ok" for a 200).
type e9Answer struct {
status int
code string
message string
retryable bool
headGen *uint64
at time.Duration
}
// e9Handle starts a handle at route on the holder's status address and
// reads it by its id on /chunk/cut until it answers other than in_progress,
// as "ops chunk cut" and "ops chunk detach --plain" do, keeping the HTTP
// status the CLI does not print.
func e9Handle(t *testing.T, addr, route string, body map[string]any) e9Answer {
t.Helper()
start := time.Now()
payload, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
// The admission holds its reply up to the handle's window.
client := &http.Client{Timeout: e9Window + time.Minute}
type reply struct {
Code string `json:"code"`
Message string `json:"message"`
CutID string `json:"cutID"`
Retryable bool `json:"retryable"`
HeadGen *uint64 `json:"headGen"`
}
read := func(resp *http.Response) (reply, error) {
defer resp.Body.Close()
var r reply
b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return r, err
}
if err := json.Unmarshal(b, &r); err != nil {
return r, fmt.Errorf("HTTP %d answer is not JSON: %q", resp.StatusCode, b)
}
return r, nil
}
resp, err := client.Post("http://"+addr+route, "application/json", bytes.NewReader(payload))
if err != nil {
t.Fatalf("%s admission: %v", route, err)
}
httpStatus := resp.StatusCode
r, err := read(resp)
if err != nil {
t.Fatalf("%s admission: %v", route, err)
}
id := r.CutID
for httpStatus == http.StatusAccepted && r.Code == "in_progress" {
if id == "" {
t.Fatalf("%s: in_progress without a handle id", route)
}
if time.Since(start) > e9AnswerBound {
return e9Answer{code: "no_answer", message: "still in_progress", at: time.Since(start)}
}
time.Sleep(time.Second)
q := url.Values{"volumeID": {"v1"}, "cutID": {id}}
resp, err := client.Get("http://" + addr + "/chunk/cut?" + q.Encode())
if err != nil {
t.Fatalf("%s: read handle %s: %v", route, id, err)
}
httpStatus = resp.StatusCode
if r, err = read(resp); err != nil {
t.Fatalf("%s: read handle %s: %v", route, id, err)
}
}
a := e9Answer{status: httpStatus, code: r.Code, message: r.Message, retryable: r.Retryable, headGen: r.HeadGen, at: time.Since(start)}
if httpStatus == http.StatusOK {
a.code = "ok"
}
return a
}
// e9GuestLoad writes 4 KiB blocks over NVMe/TCP for d, a flush after every
// 8 writes, and summarises each command's latency. A command that does not
// answer within e9IOBound ends the load (its connection is unusable).
func e9GuestLoad(t *testing.T, env *handoffEnv, d time.Duration, img byte) string {
t.Helper()
c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN)
defer c.close()
var writes, flushes []time.Duration
var errs, timeouts int
var firstErr error
op := func(f func() error) (time.Duration, error) {
start := time.Now()
_ = c.io.SetDeadline(start.Add(e9IOBound))
err := f()
return time.Since(start), err
}
end := time.Now().Add(d)
for n := 0; time.Now().Before(end); n++ {
ch, i := (n/cutCrashPer)%cutCrashChunks, n%cutCrashPer
lba := uint64(ch*ladderChunkBlocks + i)
took, err := op(func() error { return c.tryWrite(lba, cutCrashBlock(img, lba)) })
if err == nil {
writes = append(writes, took)
}
if err == nil && n%8 == 7 {
took, err = op(c.tryFlush)
if err == nil {
flushes = append(flushes, took)
}
}
if err != nil {
errs++
if firstErr == nil {
firstErr = err
}
var ne interface{ Timeout() bool }
if errors.As(err, &ne) && ne.Timeout() {
timeouts++
break
}
}
time.Sleep(5 * time.Millisecond)
}
return fmt.Sprintf("guest load %s: writes %s; flushes %s; errors %d (timeouts %d) first error %v",
d, e9Latency(writes), e9Latency(flushes), errs, timeouts, firstErr)
}
func e9Latency(ds []time.Duration) string {
if len(ds) == 0 {
return "n=0"
}
s := append([]time.Duration(nil), ds...)
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
p := func(q int) time.Duration { return s[min(len(s)-1, len(s)*q/100)] }
return fmt.Sprintf("n=%d p50=%s p99=%s max=%s", len(s), p(50).Round(time.Microsecond), p(99).Round(time.Microsecond), s[len(s)-1].Round(time.Microsecond))
}
// e9Orphans is "ops chunk verify --orphans" for v1: the count of the
// volume's own names no reachable root names, or why the pass did not
// complete.
func e9Orphans(t *testing.T, env *handoffEnv) string {
t.Helper()
args := []string{"ops", "chunk", "verify", "--master", env.h.masterAddr, "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC,
"--chunk-path", env.chunkPath, "--depth", "bindings", "--orphans", "--timeout", "2m"}
out, errOut, rc := env.h.run(t, args...)
var res struct {
Complete bool
Incomplete string
OrphansChecked bool
Findings []struct{ Class, Path string }
Code string `json:"code"`
}
if err := json.Unmarshal([]byte(out), &res); err != nil {
return fmt.Sprintf("unreadable (exit %d: %s)", rc, firstLine(strings.TrimSpace(errOut)))
}
if res.Code != "" || !res.Complete || !res.OrphansChecked {
return fmt.Sprintf("incomplete (exit %d code %q: %s)", rc, res.Code, res.Incomplete)
}
orphans, other := 0, 0
for _, f := range res.Findings {
if f.Class == "ORPHAN" {
orphans++
} else {
other++
}
}
return fmt.Sprintf("%d (other findings %d, exit %d)", orphans, other, rc)
}
@@ -95,6 +95,21 @@ type w4WeedOpts struct {
// The one real filer binds a private loopback address; no second filer is registered.
FilerBind string
FilerFront func(*w4WeedCluster)
// Volumes, when set, replaces the one volume server with one per
// element, each in its data center and rack with its own -max
// (VolumeMax is then unused). Their process names are w4VolumeProc(i):
// the first stays "volume".
Volumes []weedtest.Volume
}
// w4VolumeProc is the process name of the i-th volume server of a cluster
// started with w4WeedOpts.Volumes ("volume" for the first, as a cluster with
// one volume server has always named it).
func w4VolumeProc(i int) string {
if i == 0 {
return "volume"
}
return fmt.Sprintf("volume%d", i)
}
// weedStarts is how many times a cluster that does not start (a server
@@ -192,7 +207,15 @@ func startWorkspaceWeedOnce(t *testing.T, dir, weed string, o w4WeedOpts) (*w4We
})
registerWeedReport(t, &c.reported, func() bool { return c.discarded }, c.servers)
}
for _, d := range []string{"m", "v", "f"} {
vols := o.Volumes
if len(vols) == 0 {
vols = []weedtest.Volume{{Max: o.VolumeMax}}
}
dirs := []string{"m", "f"}
for i := range vols {
dirs = append(dirs, w4VolumeDir(i))
}
for _, d := range dirs {
if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
t.Fatal(err)
}
@@ -204,8 +227,17 @@ func startWorkspaceWeedOnce(t *testing.T, dir, weed string, o w4WeedOpts) (*w4We
if err := c.exitedEarly("master"); err != nil {
return c, err
}
vp := w4PickPortPair(t, used, "volume")
run("volume", "volume", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax))
for i, v := range vols {
vp := w4PickPortPair(t, used, "volume")
args := []string{"volume", "-ip=" + testListenHost(), fmt.Sprintf("-port=%d", vp), "-dir=" + filepath.Join(dir, w4VolumeDir(i)), "-master=" + c.master, fmt.Sprintf("-max=%d", v.Max)}
if v.DataCenter != "" {
args = append(args, "-dataCenter="+v.DataCenter)
}
if v.Rack != "" {
args = append(args, "-rack="+v.Rack)
}
run(w4VolumeProc(i), args...)
}
fp := w4PickPortPair(t, used, "filer")
c.filerHTTP = fmt.Sprintf("%s:%d", testListenHost(), fp)
c.filerGRPC = fmt.Sprintf("%s:%d", testListenHost(), fp+10000)
@@ -251,6 +283,15 @@ func startWorkspaceWeedOnce(t *testing.T, dir, weed string, o w4WeedOpts) (*w4We
return c, nil
}
// w4VolumeDir is the i-th volume server's data directory ("v" for the
// first, as before).
func w4VolumeDir(i int) string {
if i == 0 {
return "v"
}
return fmt.Sprintf("v%d", i)
}
// exitedEarly reports a server of this start that has already exited: its
// port answered, but for another process.
func (c *w4WeedCluster) exitedEarly(name string) error {
@@ -0,0 +1,822 @@
package chunkstore
// The filer contract suite: one table of cells, each a behaviour of the layer
// below that the block relies on, run on every target that claims to be that
// layer. Target "mem" (MemFiler) runs always; target "weed" (a real filer)
// runs under the chunkstore_integration tag with CHUNKSTORE_WEED set
// (contract_suite_weed_integration_test.go). A divergence between the two is
// a defect of the fake: it is fixed before a test that uses the fake counts
// as evidence for the row.
//
// Each cell names the environment row it covers:
// - C: the seam's shape (lookup, create, update, list, delete, the
// missing-entry and absent-key rules), remote.go Filer;
// - CAS: UpdateEntry/DeleteEntry with expected extended values;
// - E1: late chunk free; the entry is the only liveness truth;
// - E2: a mutation applied after its caller's deadline;
// - E5: a full store answers a typed capacity refusal;
// - E8: the IF_CHUNKS_EQUAL write condition;
// - E9: an assign whose replica placement the topology cannot hold.
//
// A cell that needs a mode the target lacks fails on a fake (a fake without
// the mode is "fake: immediate" and proves nothing for the row) and skips on
// a real target that cannot provide it yet.
import (
"context"
"errors"
"fmt"
"os"
"sort"
"strings"
"testing"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// contractTarget is one implementation of the layer below plus the hooks the
// cells need to drive its timing and capacity.
type contractTarget struct {
name string
// fake: an in-repo stand-in. A fake must provide every mode below.
fake bool
filer Filer
// cond is the IF_CHUNKS_EQUAL side (nil: the target cannot send it).
cond ChunkConditionFiler
// blobs stores the chunk payloads the entries reference (nil: none).
blobs Blobs
// flushFrees frees every chunk the target has queued for a late free.
// nil on a real filer: cells poll a bounded time instead.
flushFrees func()
// lateFreeHeld: a dropped chunk stays readable until flushFrees, so the
// late-free window can be shown, not only allowed.
lateFreeHeld bool
// applyAfterDeadline arms the next n mutations to be applied while the
// caller only sees its deadline pass (nil: not available).
applyAfterDeadline func(n int)
// capped returns blobs of a separate store with a small capacity, so a
// few puts fill it (nil: not available).
capped func(t *testing.T) Blobs
// topology returns a separate store on three volume servers, one in each
// of rackA, rackB and rackC, whose puts ask for placement 020: one copy
// in each of three racks (nil: not available).
topology func(t *testing.T, kind topologyKind) contractTopology
}
type topologyKind int
const (
// topologyRackLoss: free slots on every server; rackC can be stopped.
topologyRackLoss topologyKind = iota
// topologySlotFull: the placement fits but few slots: a few puts take
// every slot.
topologySlotFull
)
// contractTopology is a store whose puts ask for one copy in each of three
// racks (replication 020).
//
// Three copies, because degraded growth never goes below two copies
// (weed/topology/volume_growth_degraded.go degradedGrowthMinCopies, and
// degradedPlacements tries totals from copies-1 down to that minimum): a
// placement of two copies, such as 010, can never degrade. With rackC
// down, 020 degrades to 010 over rackA and rackB.
type contractTopology struct {
blobs Blobs
// copyRacks names the rack of each copy of fid's volume, read until it
// names want copies (a replica registers by heartbeat) or a bound.
copyRacks func(t *testing.T, fid string, want int) []string
// stopRackC stops rackC's only volume server.
stopRackC func(t *testing.T)
// degradedGrowth: the store grows a volume with fewer copies (at least
// two) when the topology cannot hold the placement (SeaweedFS #13178,
// in no release up to 4.56). Decided by the store's ancestry, never by
// a version string.
degradedGrowth bool
}
type contractCell struct {
name string
run func(t *testing.T, tg contractTarget, dir string)
}
// contractCells is the table. Keep each cell's name prefixed with its row.
var contractCells = []contractCell{
{"C_LookupCreateList", cellLookupCreateList},
{"C_ParentDirectories", cellParentDirectories},
{"C_UpdateMissing", cellUpdateMissing},
{"C_DeleteMissing", cellDeleteMissing},
{"CAS_ExpectedExtended", cellExpectedExtended},
{"E8_IfChunksEqual", cellIfChunksEqual},
{"E1_LateFreeAfterDelete", cellLateFreeAfterDelete},
{"E1_LateFreeAfterDroppingUpdate", cellLateFreeAfterDroppingUpdate},
{"E5_CapacityRefusal", cellCapacityRefusal},
{"E2_UpdateAppliedAfterDeadline", cellUpdateAppliedAfterDeadline},
{"E2_DeleteAppliedAfterDeadline", cellDeleteAppliedAfterDeadline},
{"E9_RackLossAssign", cellRackLossAssign},
{"E9_SlotCapacityTwin", cellSlotCapacityTwin},
}
// runContractSuite runs every cell on targets built by open, one target per
// cell, each cell in its own directory.
func runContractSuite(t *testing.T, open func(t *testing.T) contractTarget) {
runContractCells(t, "", open)
}
// runContractCells runs the cells whose name starts with prefix.
func runContractCells(t *testing.T, prefix string, open func(t *testing.T) contractTarget) {
for _, c := range contractCells {
if !strings.HasPrefix(c.name, prefix) {
continue
}
t.Run(c.name, func(t *testing.T) {
tg := open(t)
c.run(t, tg, "/contract/"+tg.name+"/"+c.name)
})
}
}
// memContractTarget is MemFiler as a contract target. The modes are found
// by their method sets so the suite reports a missing mode as a cell failure.
func memContractTarget(t *testing.T) contractTarget {
return memContractTargetWith(t, false)
}
// memTopology is the fake's topology mode, found by its method set.
type memTopology interface {
SetTopology(racks []string, copies int, degradedGrowth bool)
CopyRacks(fid string) []string
}
// memContractTargetWith is the mem target; degradedGrowth sets its
// topology mode to grow with fewer racks, as a store with #13178.
func memContractTargetWith(t *testing.T, degradedGrowth bool) contractTarget {
m := NewMemFiler()
tg := contractTarget{name: "mem", fake: true, filer: m}
var x any = m
if c, ok := x.(ChunkConditionFiler); ok {
tg.cond = c
}
if b, ok := x.(interface{ Blobs() Blobs }); ok {
tg.blobs = b.Blobs()
}
if lf, ok := x.(interface {
SetFreeDelay(time.Duration)
FlushFrees()
}); ok {
lf.SetFreeDelay(-1) // held until flushed
tg.flushFrees = lf.FlushFrees
tg.lateFreeHeld = true
}
if a, ok := x.(interface{ ApplyAfterDeadline(n int) }); ok {
tg.applyAfterDeadline = a.ApplyAfterDeadline
}
if _, ok := x.(interface{ SetCap(int64, int) }); ok {
tg.capped = func(t *testing.T) Blobs {
c := NewMemFiler()
var y any = c
y.(interface{ SetCap(int64, int) }).SetCap(1<<20, 0)
return y.(interface{ Blobs() Blobs }).Blobs()
}
}
if _, ok := x.(memTopology); ok {
tg.topology = func(t *testing.T, kind topologyKind) contractTopology {
var y any = NewMemFiler()
mt := y.(memTopology)
mt.SetTopology([]string{"rackA", "rackB", "rackC"}, 3, degradedGrowth)
if kind == topologySlotFull {
y.(interface{ SetCap(int64, int) }).SetCap(1<<20, 0)
}
return contractTopology{
blobs: y.(interface{ Blobs() Blobs }).Blobs(),
copyRacks: func(_ *testing.T, fid string, _ int) []string { return mt.CopyRacks(fid) },
stopRackC: func(*testing.T) { mt.SetTopology([]string{"rackA", "rackB"}, 3, degradedGrowth) },
degradedGrowth: degradedGrowth,
}
}
}
return tg
}
func TestFilerContract_Mem(t *testing.T) {
runContractSuite(t, memContractTarget)
}
// The E9 cells again on a fake that grows with fewer racks, as a store
// built with #13178 does.
func TestFilerContract_MemDegradedGrowth(t *testing.T) {
runContractCells(t, "E9_", func(t *testing.T) contractTarget {
tg := memContractTargetWith(t, true)
tg.name = "mem-degraded"
return tg
})
}
// needMode fails a fake that lacks a mode and skips a real target.
func needMode(t *testing.T, tg contractTarget, mode string) {
t.Helper()
if tg.fake {
t.Fatalf("%s: the fake lacks the %s mode; without it the fake is \"fake: immediate\" and no evidence for this row", tg.name, mode)
}
t.Skipf("%s: %s is not available on this target", tg.name, mode)
}
func ctCtx(t *testing.T) context.Context {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
return ctx
}
// ctEntry is a file entry with extended values and one chunk per fid, laid
// end to end so no chunk covers another.
func ctEntry(name string, ext map[string]string, fids ...string) *filerpb.Entry {
e := &filerpb.Entry{Name: name, Attributes: &filerpb.FuseAttributes{FileMode: 0o644, Mtime: time.Now().Unix(), Crtime: time.Now().Unix()}}
if ext != nil {
e.Extended = map[string][]byte{}
for k, v := range ext {
e.Extended[k] = []byte(v)
}
}
var off int64
for _, f := range fids {
e.Chunks = append(e.Chunks, &filerpb.FileChunk{FileId: f, Offset: off, Size: 8})
off += 8
}
e.Attributes.FileSize = uint64(off)
return e
}
func ctExp(kv ...string) map[string][]byte {
m := map[string][]byte{}
for i := 0; i+1 < len(kv); i += 2 {
m[kv[i]] = []byte(kv[i+1])
}
return m
}
func ctMustCreate(t *testing.T, tg contractTarget, dir string, e *filerpb.Entry) {
t.Helper()
if err := tg.filer.CreateEntry(ctCtx(t), dir, e, true); err != nil {
t.Fatalf("create %s/%s: %v", dir, e.GetName(), err)
}
}
func ctLookupExt(t *testing.T, tg contractTarget, dir, name, key string) string {
t.Helper()
e, err := tg.filer.LookupEntry(ctCtx(t), dir, name)
if err != nil {
t.Fatalf("lookup %s/%s: %v", dir, name, err)
}
return string(e.GetExtended()[key])
}
func ctNames(es []*filerpb.Entry) []string {
out := make([]string, 0, len(es))
for _, e := range es {
out = append(out, e.GetName())
}
return out
}
// ctPut stores 8 bytes and returns the fid.
func ctPut(t *testing.T, tg contractTarget, tag string) string {
t.Helper()
fid, err := tg.blobs.Put(ctCtx(t), []byte(fmt.Sprintf("%-8.8s", tag)))
if err != nil {
t.Fatalf("put %s: %v", tag, err)
}
return fid
}
// ctFreed waits until a read of fid answers ErrBlobNotFound: on a fake by
// flushing its queue, on a real filer by polling its deletion loop (1123 ms
// a round) for a bounded time.
func ctFreed(t *testing.T, tg contractTarget, fid string) {
t.Helper()
if tg.flushFrees != nil {
tg.flushFrees()
}
deadline := time.Now().Add(60 * time.Second)
for {
_, err := tg.blobs.Get(ctCtx(t), fid)
if errors.Is(err, ErrBlobNotFound) {
return
}
if tg.flushFrees != nil || time.Now().After(deadline) {
t.Fatalf("%s: the dropped chunk %s was never freed: read answered %v", tg.name, fid, err)
}
time.Sleep(500 * time.Millisecond)
}
}
// ctLive asserts fid reads back.
func ctLive(t *testing.T, tg contractTarget, fid, why string) {
t.Helper()
if _, err := tg.blobs.Get(ctCtx(t), fid); err != nil {
t.Fatalf("%s: %s: read of %s: %v", tg.name, why, fid, err)
}
}
// ctIsDeadline is how the product recognises a request that ran out of
// time (maintenance_request.go): the context's error or gRPC's code.
func ctIsDeadline(err error) bool {
return errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded
}
// C: lookup, exclusive and plain create, and name-ordered listing of one
// directory's children (remote.go Filer).
func cellLookupCreateList(t *testing.T, tg contractTarget, dir string) {
ctx := ctCtx(t)
f := tg.filer
if _, err := f.LookupEntry(ctx, dir, "a"); !errors.Is(err, ErrNotFound) {
t.Fatalf("lookup of a missing entry: %v, want ErrNotFound", err)
}
if l, err := f.ListEntries(ctx, dir, "", "", 0); err != nil || len(l) != 0 {
t.Fatalf("list of a missing directory: %v %v, want empty", ctNames(l), err)
}
for _, n := range []string{"b", "a", "c", "xa"} {
ctMustCreate(t, tg, dir, ctEntry(n, map[string]string{"k": "1"}))
}
ctMustCreate(t, tg, dir+"/sub", ctEntry("y", nil))
if err := f.CreateEntry(ctx, dir, ctEntry("a", map[string]string{"k": "2"}), true); !errors.Is(err, ErrExists) {
t.Fatalf("exclusive create over an entry: %v, want ErrExists", err)
}
if got := ctLookupExt(t, tg, dir, "a", "k"); got != "1" {
t.Fatalf("a refused exclusive create changed the entry: k=%q", got)
}
// A plain create is an upsert on the filer.
if err := f.CreateEntry(ctx, dir, ctEntry("a", map[string]string{"k": "2"}), false); err != nil {
t.Fatalf("plain create over an entry: %v", err)
}
if got := ctLookupExt(t, tg, dir, "a", "k"); got != "2" {
t.Fatalf("plain create over an entry: k=%q, want 2", got)
}
// The filer made sub, the parent of y, a directory entry of dir.
l, err := f.ListEntries(ctx, dir, "", "", 0)
if got := strings.Join(ctNames(l), ","); err != nil || got != "a,b,c,sub,xa" {
t.Fatalf("list: %q %v, want a,b,c,sub,xa (children only, name order, the made parent included)", got, err)
}
l, err = f.ListEntries(ctx, dir, "", "a", 2)
if got := strings.Join(ctNames(l), ","); err != nil || got != "b,c" {
t.Fatalf("list after a, limit 2: %q %v, want b,c", got, err)
}
l, err = f.ListEntries(ctx, dir, "x", "", 0)
if got := strings.Join(ctNames(l), ","); err != nil || got != "xa" {
t.Fatalf("list prefix x: %q %v, want xa", got, err)
}
// The filer trims one trailing slash from the listed directory
// (weed/filer/filer_search.go StreamListDirectoryEntries).
l, err = f.ListEntries(ctx, dir+"/", "", "", 0)
if got := strings.Join(ctNames(l), ","); err != nil || got != "a,b,c,sub,xa" {
t.Fatalf("list %s/: %q %v, want a,b,c,sub,xa", dir, got, err)
}
}
// C: an update of a missing entry is ErrNotFound, with or without an
// expectation (the filer answers NotFound before it checks expected).
func cellUpdateMissing(t *testing.T, tg contractTarget, dir string) {
ctx := ctCtx(t)
if err := tg.filer.UpdateEntry(ctx, dir, ctEntry("m", nil), nil); !errors.Is(err, ErrNotFound) {
t.Fatalf("unconditional update of a missing entry: %v, want ErrNotFound", err)
}
if err := tg.filer.UpdateEntry(ctx, dir, ctEntry("m", nil), ctExp("k", "1")); !errors.Is(err, ErrNotFound) {
t.Fatalf("conditional update of a missing entry: %v, want ErrNotFound", err)
}
if _, err := tg.filer.LookupEntry(ctx, dir, "m"); !errors.Is(err, ErrNotFound) {
t.Fatalf("a refused update created the entry: %v", err)
}
}
// C: remote.go DeleteEntry: an unconditional delete of a missing entry
// succeeds; a conditional one (any non-empty expected, even an expected
// empty value) is ErrPrecondition (the filer cannot read the entry it is
// asked to check).
func cellDeleteMissing(t *testing.T, tg contractTarget, dir string) {
ctx := ctCtx(t)
if err := tg.filer.DeleteEntry(ctx, dir, "m", nil); err != nil {
t.Fatalf("unconditional delete of a missing entry: %v, want success", err)
}
if err := tg.filer.DeleteEntry(ctx, dir, "m", ctExp("k", "1")); !errors.Is(err, ErrPrecondition) {
t.Fatalf("conditional delete of a missing entry: %v, want ErrPrecondition", err)
}
if err := tg.filer.DeleteEntry(ctx, dir, "m", ctExp("k", "")); !errors.Is(err, ErrPrecondition) {
t.Fatalf("delete of a missing entry expecting an absent key: %v, want ErrPrecondition", err)
}
// Deleting twice: the second, unconditional, still succeeds.
ctMustCreate(t, tg, dir, ctEntry("d", nil))
for i := 0; i < 2; i++ {
if err := tg.filer.DeleteEntry(ctx, dir, "d", nil); err != nil {
t.Fatalf("unconditional delete #%d: %v", i+1, err)
}
}
}
// CAS: UpdateEntry and DeleteEntry apply only when every expected extended
// value holds (layout_store.go writes HEAD this way). The absent-key rule:
// an expected empty value matches an absent key, a non-empty one does not
// (weed/server/filer_grpc_server.go validateUpdateEntryPreconditions).
func cellExpectedExtended(t *testing.T, tg contractTarget, dir string) {
ctx := ctCtx(t)
f := tg.filer
ctMustCreate(t, tg, dir, ctEntry("h", map[string]string{"gen": "1", "mark": ""}))
next := ctEntry("h", map[string]string{"gen": "2", "mark": ""})
if err := f.UpdateEntry(ctx, dir, next, ctExp("gen", "9")); !errors.Is(err, ErrPrecondition) {
t.Fatalf("update expecting a wrong value: %v, want ErrPrecondition", err)
}
if got := ctLookupExt(t, tg, dir, "h", "gen"); got != "1" {
t.Fatalf("a refused update applied: gen=%q", got)
}
if err := f.UpdateEntry(ctx, dir, next, ctExp("gen", "1")); err != nil {
t.Fatalf("update expecting the stored value: %v", err)
}
if got := ctLookupExt(t, tg, dir, "h", "gen"); got != "2" {
t.Fatalf("update expecting the stored value: gen=%q, want 2", got)
}
cases := []struct {
why string
expected map[string][]byte
ok bool
}{
{"an absent key expected empty", ctExp("gen", "2", "absent", ""), true},
{"an absent key expected non-empty", ctExp("gen", "2", "absent", "x"), false},
{"a present empty value expected empty", ctExp("gen", "2", "mark", ""), true},
{"a present non-empty value expected empty", ctExp("gen", ""), false},
}
for _, c := range cases {
err := f.UpdateEntry(ctx, dir, next, c.expected)
if c.ok && err != nil {
t.Fatalf("update with %s: %v, want applied", c.why, err)
}
if !c.ok && !errors.Is(err, ErrPrecondition) {
t.Fatalf("update with %s: %v, want ErrPrecondition", c.why, err)
}
}
if err := f.DeleteEntry(ctx, dir, "h", ctExp("gen", "1")); !errors.Is(err, ErrPrecondition) {
t.Fatalf("delete expecting a wrong value: %v, want ErrPrecondition", err)
}
if _, err := f.LookupEntry(ctx, dir, "h"); err != nil {
t.Fatalf("a refused delete removed the entry: %v", err)
}
if err := f.DeleteEntry(ctx, dir, "h", ctExp("gen", "2", "absent", "")); err != nil {
t.Fatalf("delete expecting the stored values: %v", err)
}
if _, err := f.LookupEntry(ctx, dir, "h"); !errors.Is(err, ErrNotFound) {
t.Fatalf("lookup after delete: %v, want ErrNotFound", err)
}
}
// E8: UpdateEntryIfChunks applies only when the stored chunk fids equal the
// given ones as a multiset and every expected value holds; the open-time
// probe's deliberately failing write is one of the refused cases.
func cellIfChunksEqual(t *testing.T, tg contractTarget, dir string) {
if tg.cond == nil {
needMode(t, tg, "IF_CHUNKS_EQUAL")
}
if tg.blobs == nil {
needMode(t, tg, "blobs")
}
ctx := ctCtx(t)
a, b := ctPut(t, tg, "a"), ctPut(t, tg, "b")
ctMustCreate(t, tg, dir, ctEntry("h", map[string]string{"gen": "1"}, a))
next := ctEntry("h", map[string]string{"gen": "2"}, b)
refused := []struct {
why string
expected map[string][]byte
fids []string
}{
{"other chunks", ctExp("gen", "1"), []string{b}},
{"no chunks", ctExp("gen", "1"), nil},
{"one chunk too many", ctExp("gen", "1"), []string{a, a}},
{"equal chunks but a wrong expected value", ctExp("gen", "9"), []string{a}},
}
for _, c := range refused {
if err := tg.cond.UpdateEntryIfChunks(ctx, dir, next, c.expected, c.fids); !errors.Is(err, ErrPrecondition) {
t.Fatalf("IF_CHUNKS_EQUAL with %s: %v, want ErrPrecondition", c.why, err)
}
e, err := tg.filer.LookupEntry(ctx, dir, "h")
if err != nil || string(e.GetExtended()["gen"]) != "1" || !fidsEqual(entryFids(e), []string{a}) {
t.Fatalf("a refused IF_CHUNKS_EQUAL (%s) changed the entry: %v %v", c.why, e, err)
}
}
if err := tg.cond.UpdateEntryIfChunks(ctx, dir, next, ctExp("gen", "1"), []string{a}); err != nil {
t.Fatalf("IF_CHUNKS_EQUAL with the stored chunks: %v", err)
}
e, err := tg.filer.LookupEntry(ctx, dir, "h")
if err != nil || string(e.GetExtended()["gen"]) != "2" || !fidsEqual(entryFids(e), []string{b}) {
t.Fatalf("IF_CHUNKS_EQUAL with the stored chunks did not apply: %v %v", e, err)
}
if err := tg.cond.UpdateEntryIfChunks(ctx, dir, ctEntry("missing", nil), nil, nil); !errors.Is(err, ErrNotFound) {
t.Fatalf("IF_CHUNKS_EQUAL on a missing entry: %v, want ErrNotFound", err)
}
}
// E1: a deleted entry is gone at once, but its chunks are freed later: a
// read by fid may still succeed in between, so it never proves a chunk live.
// The entry is the liveness truth.
func cellLateFreeAfterDelete(t *testing.T, tg contractTarget, dir string) {
if tg.blobs == nil {
needMode(t, tg, "blobs")
}
if tg.flushFrees == nil && tg.fake {
needMode(t, tg, "late free")
}
ctx := ctCtx(t)
a := ctPut(t, tg, "a")
ctMustCreate(t, tg, dir, ctEntry("o", nil, a))
if err := tg.filer.DeleteEntry(ctx, dir, "o", nil); err != nil {
t.Fatalf("delete: %v", err)
}
if _, err := tg.filer.LookupEntry(ctx, dir, "o"); !errors.Is(err, ErrNotFound) {
t.Fatalf("lookup right after delete: %v, want ErrNotFound (the entry goes at once)", err)
}
if tg.lateFreeHeld {
ctLive(t, tg, a, "a deleted entry's chunk before the free queue runs (the late-free window)")
}
ctFreed(t, tg, a)
}
// E1: chunks an UpdateEntry (or a plain create over an entry) drops are
// queued and freed later too; the chunks the entry keeps stay live.
func cellLateFreeAfterDroppingUpdate(t *testing.T, tg contractTarget, dir string) {
if tg.blobs == nil {
needMode(t, tg, "blobs")
}
if tg.flushFrees == nil && tg.fake {
needMode(t, tg, "late free")
}
ctx := ctCtx(t)
a, b, c := ctPut(t, tg, "a"), ctPut(t, tg, "b"), ctPut(t, tg, "c")
ctMustCreate(t, tg, dir, ctEntry("o", nil, a, b))
if err := tg.filer.UpdateEntry(ctx, dir, ctEntry("o", nil, b), nil); err != nil {
t.Fatalf("update dropping a chunk: %v", err)
}
e, err := tg.filer.LookupEntry(ctx, dir, "o")
if err != nil || !fidsEqual(entryFids(e), []string{b}) {
t.Fatalf("lookup after the dropping update: %v %v, want chunks [%s]", e, err, b)
}
if tg.lateFreeHeld {
ctLive(t, tg, a, "a dropped chunk before the free queue runs (the late-free window)")
}
ctFreed(t, tg, a)
ctLive(t, tg, b, "a chunk the entry still lists")
// A plain create over the entry replaces its chunk list the same way.
if err := tg.filer.CreateEntry(ctx, dir, ctEntry("o", nil, c), false); err != nil {
t.Fatalf("plain create over the entry: %v", err)
}
if tg.lateFreeHeld {
ctLive(t, tg, b, "a chunk a create replaced, before the free queue runs")
}
ctFreed(t, tg, b)
ctLive(t, tg, c, "a chunk the entry still lists")
}
// E5: a full store refuses a put with storage.ErrChunkRemoteFull, the typed
// capacity answer, carrying the filer's own text, not a timeout.
func cellCapacityRefusal(t *testing.T, tg contractTarget, dir string) {
if tg.capped == nil {
needMode(t, tg, "capacity cap")
}
b := tg.capped(t)
obj := make([]byte, 256<<10)
deadline := time.Now().Add(2 * time.Minute)
var others []string
for i := 0; ; i++ {
if time.Now().After(deadline) || i > 4096 {
t.Fatalf("%s: the store never answered full after %d objects; other errors: %q", tg.name, i, others)
}
obj[0], obj[1] = byte(i), byte(i>>8)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := b.Put(ctx, obj)
cancel()
if err == nil {
continue
}
if errors.Is(err, storage.ErrChunkRemoteFull) {
if !strings.Contains(strings.ToLower(err.Error()), seaweedNoFreeVolumes) {
t.Fatalf("a full store's refusal lacks the filer's text %q: %v", seaweedNoFreeVolumes, err)
}
if ctIsDeadline(err) {
t.Fatalf("a full store's refusal reads as a timeout: %v", err)
}
// The full text, recorded per weed version.
t.Logf("E5 refusal after %d objects, full text: %q", i, err.Error())
return
}
if len(others) < 8 {
others = append(others, err.Error())
}
}
}
// E2: a mutation whose caller saw its deadline pass may still be applied: a
// timeout is UNKNOWN until a read names its effect, and the same conditional
// write repeated is refused by the effect it already had.
func cellUpdateAppliedAfterDeadline(t *testing.T, tg contractTarget, dir string) {
if tg.applyAfterDeadline == nil {
needMode(t, tg, "apply-after-deadline")
}
ctMustCreate(t, tg, dir, ctEntry("h", map[string]string{"gen": "1"}))
tg.applyAfterDeadline(1)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
err := tg.filer.UpdateEntry(ctx, dir, ctEntry("h", map[string]string{"gen": "2"}), ctExp("gen", "1"))
if !ctIsDeadline(err) {
t.Fatalf("an update applied after its deadline: the caller saw %v, want DeadlineExceeded", err)
}
if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) {
t.Fatalf("a timed-out update reads as a verdict: %v", err)
}
if got := ctLookupExt(t, tg, dir, "h", "gen"); got != "2" {
t.Fatalf("the read after a timed-out update: gen=%q, want 2 (applied)", got)
}
if err := tg.filer.UpdateEntry(ctCtx(t), dir, ctEntry("h", map[string]string{"gen": "2"}), ctExp("gen", "1")); !errors.Is(err, ErrPrecondition) {
t.Fatalf("repeating the timed-out conditional update: %v, want ErrPrecondition", err)
}
}
// E2: the same for a conditional delete.
func cellDeleteAppliedAfterDeadline(t *testing.T, tg contractTarget, dir string) {
if tg.applyAfterDeadline == nil {
needMode(t, tg, "apply-after-deadline")
}
ctMustCreate(t, tg, dir, ctEntry("h", map[string]string{"gen": "1"}))
tg.applyAfterDeadline(1)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
err := tg.filer.DeleteEntry(ctx, dir, "h", ctExp("gen", "1"))
if !ctIsDeadline(err) {
t.Fatalf("a delete applied after its deadline: the caller saw %v, want DeadlineExceeded", err)
}
if _, err := tg.filer.LookupEntry(ctCtx(t), dir, "h"); !errors.Is(err, ErrNotFound) {
t.Fatalf("the read after a timed-out delete: %v, want ErrNotFound (applied)", err)
}
if err := tg.filer.DeleteEntry(ctCtx(t), dir, "h", ctExp("gen", "1")); !errors.Is(err, ErrPrecondition) {
t.Fatalf("repeating the timed-out conditional delete: %v, want ErrPrecondition", err)
}
}
// C: creating an entry makes every missing parent directory, as the filer
// does (weed/filer/filer.go ensureParentDirectoryEntry): a directory entry
// with the child's permission bits plus 0111, the child's owner, and its
// own times. A directory with children is not deleted by a non-recursive
// delete; an empty one is, and its parent stays.
func cellParentDirectories(t *testing.T, tg contractTarget, dir string) {
ctx := ctCtx(t)
f := tg.filer
child := ctEntry("f", nil)
child.Attributes.FileMode = 0o640
child.Attributes.Uid, child.Attributes.Gid = 1000, 1001
ctMustCreate(t, tg, dir+"/p/q", child)
wantMode := uint32(os.ModeDir | 0o751)
for _, d := range []struct{ dir, name string }{{dir + "/p", "q"}, {dir, "p"}} {
e, err := f.LookupEntry(ctx, d.dir, d.name)
if err != nil {
t.Fatalf("lookup of the made parent %s/%s: %v", d.dir, d.name, err)
}
a := e.GetAttributes()
if !e.GetIsDirectory() || a.GetFileMode() != wantMode || a.GetUid() != 1000 || a.GetGid() != 1001 || a.GetMtime() == 0 || a.GetCrtime() == 0 || len(e.GetChunks()) != 0 {
t.Fatalf("the made parent %s/%s: dir=%v mode=%o uid=%d gid=%d mtime=%d crtime=%d chunks=%d, want a directory, mode %o, owner 1000:1001, times set, no chunks",
d.dir, d.name, e.GetIsDirectory(), a.GetFileMode(), a.GetUid(), a.GetGid(), a.GetMtime(), a.GetCrtime(), len(e.GetChunks()), wantMode)
}
}
l, err := f.ListEntries(ctx, dir, "", "", 0)
if got := strings.Join(ctNames(l), ","); err != nil || got != "p" || !l[0].GetIsDirectory() {
t.Fatalf("list %s: %q %v, want the directory p", dir, got, err)
}
// A second child does not remake its parent.
other := ctEntry("g", nil)
other.Attributes.FileMode = 0o600
ctMustCreate(t, tg, dir+"/p/q", other)
if e, err := f.LookupEntry(ctx, dir+"/p", "q"); err != nil || e.GetAttributes().GetFileMode() != wantMode {
t.Fatalf("the parent after a second child: %v %v, want mode %o kept", e, err, wantMode)
}
err = f.DeleteEntry(ctx, dir+"/p", "q", nil)
if err == nil || errors.Is(err, ErrNotFound) || errors.Is(err, ErrPrecondition) {
t.Fatalf("non-recursive delete of a directory with children: %v, want a refusal", err)
}
t.Logf("non-recursive delete of a directory with children, full text: %q", err.Error())
if _, err := f.LookupEntry(ctx, dir+"/p", "q"); err != nil {
t.Fatalf("a refused directory delete removed it: %v", err)
}
for _, n := range []string{"f", "g"} {
if err := f.DeleteEntry(ctx, dir+"/p/q", n, nil); err != nil {
t.Fatalf("delete %s: %v", n, err)
}
}
if err := f.DeleteEntry(ctx, dir+"/p", "q", nil); err != nil {
t.Fatalf("delete of an empty directory: %v", err)
}
if _, err := f.LookupEntry(ctx, dir+"/p", "q"); !errors.Is(err, ErrNotFound) {
t.Fatalf("lookup of a deleted directory: %v, want ErrNotFound", err)
}
if e, err := f.LookupEntry(ctx, dir, "p"); err != nil || !e.GetIsDirectory() {
t.Fatalf("the parent of a deleted directory: %v %v, want it kept", e, err)
}
}
// E9: with rackC down, an assign asking for one copy in each of three racks
// cannot be placed. A store without degraded growth (every release up to
// 4.56) refuses it: the cell asserts the refusal and records the typed
// outcome the product gives (remote_full or not), never asserting which.
// A store with degraded growth (#13178) places it with exactly two copies,
// one in rackA and one in rackB (degradedPlacements tries two copies in two
// racks, 010, first). The expectation flips when a pinned release contains
// #13178.
func cellRackLossAssign(t *testing.T, tg contractTarget, dir string) {
if tg.topology == nil {
needMode(t, tg, "topology")
}
tp := tg.topology(t, topologyRackLoss)
put := func(tag string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
return tp.blobs.Put(ctx, []byte(fmt.Sprintf("%-8.8s", tag)))
}
fid, err := put("whole")
if err != nil {
t.Fatalf("an assign with every rack up: %v", err)
}
racks := tp.copyRacks(t, fid, 3)
sort.Strings(racks)
if strings.Join(racks, ",") != "rackA,rackB,rackC" {
t.Fatalf("an assign with every rack up: copies in racks %v, want one in each of rackA, rackB, rackC", racks)
}
tp.stopRackC(t)
deadline := time.Now().Add(90 * time.Second)
if !tp.degradedGrowth {
// Volumes grown before the stop leave the writable list once the
// master drops rackC's server: wait for three refusals in a row.
var last error
for refused := 0; refused < 3; {
if time.Now().After(deadline) {
t.Fatalf("%s: an assign whose placement the topology cannot hold kept succeeding (last refusal %v); a store with degraded growth (#13178) does that, so check the binary's ancestry", tg.name, last)
}
_, err := put(fmt.Sprintf("r%d", refused))
if err == nil {
refused = 0
time.Sleep(500 * time.Millisecond)
continue
}
refused++
last = err
}
t.Logf("E9 (no degraded growth): the unplaceable assign is refused; remote_full=%v deadline=%v full text: %q",
errors.Is(last, storage.ErrChunkRemoteFull), ctIsDeadline(last), last.Error())
return
}
var last error
for {
if time.Now().After(deadline) {
t.Fatalf("%s: with degraded growth no assign succeeded after rackC stopped: %v", tg.name, last)
}
fid, err := put("degraded")
if err != nil {
last = err
time.Sleep(500 * time.Millisecond)
continue
}
racks := tp.copyRacks(t, fid, 2)
sort.Strings(racks)
if strings.Join(racks, ",") != "rackA,rackB" {
t.Fatalf("a degraded assign: copies in racks %v, want exactly two, one in rackA and one in rackB", racks)
}
t.Logf("E9 (degraded growth): placed with copies in racks %v after earlier refusal %v", racks, last)
return
}
}
// E9/E5: a placement the topology can hold but no slot is free for is a
// full store, storage.ErrChunkRemoteFull, with or without degraded growth.
func cellSlotCapacityTwin(t *testing.T, tg contractTarget, dir string) {
if tg.topology == nil {
needMode(t, tg, "topology")
}
tp := tg.topology(t, topologySlotFull)
obj := make([]byte, 256<<10)
deadline := time.Now().Add(2 * time.Minute)
var others []string
for i := 0; ; i++ {
if time.Now().After(deadline) || i > 4096 {
t.Fatalf("%s: the placed store never answered full after %d objects; other errors: %q", tg.name, i, others)
}
obj[0], obj[1] = byte(i), byte(i>>8)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
_, err := tp.blobs.Put(ctx, obj)
cancel()
if err == nil {
continue
}
if errors.Is(err, storage.ErrChunkRemoteFull) {
t.Logf("E9 slot-capacity refusal after %d objects, full text: %q", i, err.Error())
return
}
if len(others) < 8 {
others = append(others, err.Error())
}
}
}
@@ -0,0 +1,260 @@
//go:build chunkstore_integration
package chunkstore
import (
"context"
"errors"
"io"
"net"
"os"
"strings"
"sync"
"testing"
"time"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/internal/weedtest"
)
// TestIntegration_FilerContract_Weed runs the filer contract suite
// (contract_suite_test.go) on a real filer: one cluster for the suite, each
// cell in its own directory, reached through a deadline proxy (below) so the
// apply-after-deadline cells run too; a separate tiny store (-max 2 volumes
// of 1 MB) for the capacity cell; and separate three-server, three-rack stores
// for the topology cells. The weed binary is CHUNKSTORE_WEED; without it the
// suite skips.
//
// CHUNKSTORE_WEED_DEGRADED_GROWTH=1 states that the binary's source contains
// SeaweedFS #13178 (degraded volume growth; decided by git ancestry of the
// commit the binary was built from, not by a version string). No release up
// to 4.56 contains it, so leave it unset for a pinned release.
func TestIntegration_FilerContract_Weed(t *testing.T) {
c := startWeed(t) // skips without CHUNKSTORE_WEED
proxy := startDeadlineProxy(t, c.filerGRPC)
cl, err := DialSWFS(SWFSConfig{FilerGRPC: proxy.addr, Collection: "swblock", AssignPath: "/swblock/vols/contract"})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = cl.Close() })
degraded := os.Getenv("CHUNKSTORE_WEED_DEGRADED_GROWTH") == "1"
runContractSuite(t, func(*testing.T) contractTarget {
return contractTarget{
name: "weed",
filer: cl,
cond: cl,
blobs: cl,
applyAfterDeadline: proxy.arm,
capped: func(t *testing.T) Blobs {
full := startWeedSized(t, "", 1, 2)
return full.client(t, "/swblock/vols/contract-full")
},
topology: func(t *testing.T, kind topologyKind) contractTopology {
return weedTopology(t, kind, degraded)
},
}
})
}
// weedRacks is the topology of the E9 stores: one volume server in each of
// rackA, rackB and rackC, all in one data center. rackC's server is the
// last.
var weedRacks = []string{"rackA", "rackB", "rackC"}
// weedTopology starts a store on weedRacks whose puts ask for 020 (one copy
// in each of the three racks). For topologyRackLoss every server holds up
// to 8 volumes of 64 MB. For topologySlotFull every server holds one volume
// of 1 MB: a 020 volume takes one slot on each of the three servers, so the
// first volume (grown by the readiness probe) takes all 3 x 1 slots, and
// once its 1 MB is filled no slot is left to grow another.
func weedTopology(t *testing.T, kind topologyKind, degradedGrowth bool) contractTopology {
t.Helper()
o := weedtest.Options{SizeMB: 64}
maxes := []int{8, 8, 8}
if kind == topologySlotFull {
o.SizeMB, maxes = 1, []int{1, 1, 1}
}
for i, r := range weedRacks {
o.Volumes = append(o.Volumes, weedtest.Volume{DataCenter: "dc1", Rack: r, Max: maxes[i]})
}
c := startWeedOptions(t, "020", o)
cl, err := DialSWFS(SWFSConfig{FilerGRPC: c.filerGRPC, Collection: "swblock", Replication: "020", AssignPath: "/swblock/vols/contract-topology"})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = cl.Close() })
rackOf := map[string]string{}
for i, u := range c.VolumeURLs {
rackOf[u] = weedRacks[i]
}
return contractTopology{
blobs: cl,
// A fresh lookup of the fid's volume, polled until it names want
// copies (a replica registers with the master by heartbeat) or 10 s.
copyRacks: func(t *testing.T, fid string, want int) []string {
t.Helper()
vid, _, _ := strings.Cut(fid, ",")
var racks []string
deadline := time.Now().Add(10 * time.Second)
for {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
resp, err := cl.fc.LookupVolume(ctx, &filerpb.LookupVolumeRequest{VolumeIds: []string{vid}})
cancel()
if err != nil {
t.Fatalf("lookup volume %s: %v", vid, err)
}
racks = nil
for _, l := range resp.GetLocationsMap()[vid].GetLocations() {
r, ok := rackOf[l.GetUrl()]
if !ok {
r = "unknown:" + l.GetUrl()
}
racks = append(racks, r)
}
if len(racks) >= want || time.Now().After(deadline) {
t.Logf("volume %s copies: %v", vid, racks)
return racks
}
time.Sleep(500 * time.Millisecond)
}
},
stopRackC: func(t *testing.T) {
t.Helper()
if err := c.StopVolume(len(weedRacks) - 1); err != nil {
t.Fatal(err)
}
},
degradedGrowth: degradedGrowth,
}
}
// deadlineProxy is a filer gRPC front that forwards every call. An armed
// mutation (create, update, delete) is forwarded under its own context, so
// the filer applies it, and its reply is held until the caller's deadline
// has passed: the caller sees DeadlineExceeded for a write that landed.
// Calls are forwarded one at a time, so a read issued after the caller gave
// up waits until the held write has landed.
type deadlineProxy struct {
filerpb.UnimplementedSeaweedFilerServer
addr string
up filerpb.SeaweedFilerClient
order sync.Mutex // one forwarded call at a time
armMu sync.Mutex
armed int
}
func startDeadlineProxy(t *testing.T, filerGRPC string) *deadlineProxy {
t.Helper()
conn, err := link.Dial(filerGRPC, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(64<<20), grpc.MaxCallSendMsgSize(64<<20)))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
p := &deadlineProxy{addr: lis.Addr().String(), up: filerpb.NewSeaweedFilerClient(conn)}
srv := grpc.NewServer(grpc.MaxRecvMsgSize(64<<20), grpc.MaxSendMsgSize(64<<20))
filerpb.RegisterSeaweedFilerServer(srv, p)
go func() { _ = srv.Serve(lis) }()
t.Cleanup(srv.Stop)
return p
}
// arm makes the next n mutations apply with their reply held.
func (p *deadlineProxy) arm(n int) {
p.armMu.Lock()
defer p.armMu.Unlock()
p.armed = n
}
func (p *deadlineProxy) take() bool {
p.armMu.Lock()
defer p.armMu.Unlock()
if p.armed > 0 {
p.armed--
return true
}
return false
}
// mutate forwards one mutation; held, it is applied under a context the
// caller cannot cancel and answered only after the caller's context ends.
func mutate[R any](p *deadlineProxy, ctx context.Context, call func(context.Context) (R, error)) (R, error) {
if !p.take() {
p.order.Lock()
defer p.order.Unlock()
return call(ctx)
}
p.order.Lock()
applyCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
r, err := call(applyCtx)
cancel()
p.order.Unlock()
<-ctx.Done()
return r, err
}
func forward[R any](p *deadlineProxy, ctx context.Context, call func(context.Context) (R, error)) (R, error) {
p.order.Lock()
defer p.order.Unlock()
return call(ctx)
}
func (p *deadlineProxy) CreateEntry(ctx context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) {
return mutate(p, ctx, func(c context.Context) (*filerpb.CreateEntryResponse, error) { return p.up.CreateEntry(c, r) })
}
func (p *deadlineProxy) UpdateEntry(ctx context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) {
return mutate(p, ctx, func(c context.Context) (*filerpb.UpdateEntryResponse, error) { return p.up.UpdateEntry(c, r) })
}
func (p *deadlineProxy) DeleteEntry(ctx context.Context, r *filerpb.DeleteEntryRequest) (*filerpb.DeleteEntryResponse, error) {
return mutate(p, ctx, func(c context.Context) (*filerpb.DeleteEntryResponse, error) { return p.up.DeleteEntry(c, r) })
}
func (p *deadlineProxy) LookupDirectoryEntry(ctx context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) {
return forward(p, ctx, func(c context.Context) (*filerpb.LookupDirectoryEntryResponse, error) {
return p.up.LookupDirectoryEntry(c, r)
})
}
func (p *deadlineProxy) AssignVolume(ctx context.Context, r *filerpb.AssignVolumeRequest) (*filerpb.AssignVolumeResponse, error) {
return forward(p, ctx, func(c context.Context) (*filerpb.AssignVolumeResponse, error) { return p.up.AssignVolume(c, r) })
}
func (p *deadlineProxy) LookupVolume(ctx context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) {
return forward(p, ctx, func(c context.Context) (*filerpb.LookupVolumeResponse, error) { return p.up.LookupVolume(c, r) })
}
func (p *deadlineProxy) GetFilerConfiguration(ctx context.Context, r *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) {
return forward(p, ctx, func(c context.Context) (*filerpb.GetFilerConfigurationResponse, error) {
return p.up.GetFilerConfiguration(c, r)
})
}
func (p *deadlineProxy) ListEntries(r *filerpb.ListEntriesRequest, ss grpc.ServerStreamingServer[filerpb.ListEntriesResponse]) error {
p.order.Lock()
defer p.order.Unlock()
stream, err := p.up.ListEntries(ss.Context(), r)
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
if err := ss.Send(resp); err != nil {
return err
}
}
}
@@ -2,16 +2,41 @@ package chunkstore
// MemFiler is an in-memory Filer for development and for tests outside this
// package: exclusive create, conditional update and delete on extended
// attributes, and name-ordered listing of one directory's children. It has
// no fault injection; this package's own tests use their own fake.
// attributes, and name-ordered listing of one directory's children.
//
// It is a fake of the layer below and passes the filer contract suite
// (contract_suite_test.go) that a real filer passes. By default it behaves
// as it always has; these modes model what a real filer does and a test can
// switch on:
// - Blobs: chunk payloads stored by fid, so it can serve a LayoutStore's
// blobs. Chunks an entry drops (delete, an update or a plain create over
// it) are freed, as the filer's deletion queue frees them.
// - SetFreeDelay / FlushFrees: the free happens later, not at once (the
// filer polls its deletion queue); a read by fid in between succeeds.
// - ApplyAfterDeadline: a mutation is applied but its caller only sees its
// deadline pass (a reply lost after the filer applied the request).
// - SetCap: a byte or object cap; a put past it is refused with the
// filer's full-store text, as storage.ErrChunkRemoteFull.
// - SetTopology / CopyRacks: puts ask for a number of copies, each in its
// own rack, on servers in the given racks; with too few racks a put is
// refused, or placed with fewer copies (at least two) under degraded
// growth.
//
// As the filer, creating an entry makes its missing parent directories, and
// a non-recursive delete of a directory with children is refused.
import (
"context"
"errors"
"fmt"
"os"
"path"
"sort"
"strings"
"sync"
"time"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
@@ -20,16 +45,266 @@ import (
type MemFiler struct {
mu sync.Mutex
e map[string]*filerpb.Entry
// blobs holds chunk payloads by fid; used is their total size.
blobs map[string][]byte
used int64
needle uint64
// freeDelay: 0 frees a dropped chunk at once, > 0 after that long,
// < 0 only on FlushFrees. frees is the queue of dropped chunks.
freeDelay time.Duration
frees []memFree
// lateReplies: how many next mutations apply but answer only the
// caller's deadline.
lateReplies int
// capBytes, capObjects: the store's capacity (0: none).
capBytes int64
capObjects int
// topoRacks: the rack of each volume server up (nil: no placement);
// degradedGrowth: place with fewer racks when they are too few.
topoRacks []string
topoCopies int
degradedGrowth bool
copies map[string][]string
}
type memFree struct {
fid string
due time.Time // zero: only on FlushFrees
}
// NewMemFiler returns an empty MemFiler.
func NewMemFiler() *MemFiler { return &MemFiler{e: map[string]*filerpb.Entry{}} }
func NewMemFiler() *MemFiler {
return &MemFiler{e: map[string]*filerpb.Entry{}, blobs: map[string][]byte{}}
}
var _ Filer = (*MemFiler)(nil)
var (
_ Filer = (*MemFiler)(nil)
_ ChunkConditionFiler = (*MemFiler)(nil)
_ Blobs = memBlobs{}
)
// memFullText is the text a filer answers an assign with when the store has
// no writable volume and no free slot to grow one (SeaweedFS master,
// weed/server/master_grpc_server_assign.go, relayed by the filer).
const memFullText = "assign volume: No writable volumes and no free volumes left for {\"replication\":\"000\"}"
// memUnplaceableText stands for a master's answer to an assign whose replica
// placement the topology cannot hold, without free-slot exhaustion (the
// master's growth reports e.g. "Only has 2 racks, not enough for 3."; the
// exact relayed text differs by version, which the contract suite records).
const memUnplaceableText = "assign volume: No writable volumes: Only has too few racks for the replica placement"
// restorableModeBits are the permission bits a made parent directory takes
// from its child (weed/filer/filer.go).
const restorableModeBits = os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky
// memDegradedMinCopies is the fewest copies degraded growth leaves
// (weed/topology/volume_growth_degraded.go degradedGrowthMinCopies).
const memDegradedMinCopies = 2
// SetTopology makes every later put ask for copies copies, each in its own
// rack (placement 0(copies-1)0: 010 for two, 020 for three), on volume
// servers in racks (one element per server up; nil: no placement, the
// default). When the racks cannot hold it the put is refused as unplaceable
// (not a full store), unless degradedGrowth finds a placement with fewer
// copies, never fewer than two, as a master with degraded growth does: so a
// two-copy placement never degrades.
func (m *MemFiler) SetTopology(racks []string, copies int, degradedGrowth bool) {
m.mu.Lock()
defer m.mu.Unlock()
m.topoRacks = append([]string(nil), racks...)
m.topoCopies = copies
m.degradedGrowth = degradedGrowth
}
// CopyRacks names the rack of each copy of fid placed under SetTopology.
func (m *MemFiler) CopyRacks(fid string) []string {
m.mu.Lock()
defer m.mu.Unlock()
return append([]string(nil), m.copies[fid]...)
}
// placeLocked picks the racks of a put's copies (nil: no topology).
func (m *MemFiler) placeLocked() ([]string, error) {
if len(m.topoRacks) == 0 {
return nil, nil
}
var order []string
servers := map[string]int{}
for _, r := range m.topoRacks {
if servers[r] == 0 {
order = append(order, r)
}
servers[r]++
}
// place puts one copy in each of 1+otherRacks racks plus sameRack more
// in the first rack with room, as a placement of DiffRackCount
// otherRacks and SameRackCount sameRack.
place := func(otherRacks, sameRack int) []string {
if len(order) < otherRacks+1 {
return nil
}
for i, main := range order {
if servers[main] < sameRack+1 {
continue
}
out := make([]string, 0, otherRacks+sameRack+1)
for k := 0; k <= sameRack; k++ {
out = append(out, main)
}
for j, r := range order {
if len(out) == otherRacks+sameRack+1 {
break
}
if j != i {
out = append(out, r)
}
}
return out
}
return nil
}
if out := place(m.topoCopies-1, 0); out != nil {
return out, nil
}
if m.degradedGrowth {
// degradedPlacements: fewer copies first by count, then the most
// racks, never below the minimum.
for total := m.topoCopies - 1; total >= memDegradedMinCopies; total-- {
for other := total - 1; other >= 0; other-- {
if out := place(other, total-1-other); out != nil {
return out, nil
}
}
}
}
return nil, assignErr("chunkstore: assign", errors.New(memUnplaceableText))
}
// SetFreeDelay sets when a chunk an entry drops is freed: 0 at once (the
// default), d > 0 after d (checked on every call), d < 0 only on FlushFrees.
func (m *MemFiler) SetFreeDelay(d time.Duration) {
m.mu.Lock()
defer m.mu.Unlock()
m.freeDelay = d
}
// FlushFrees frees every queued chunk now, as the filer's deletion loop does
// when it runs.
func (m *MemFiler) FlushFrees() {
m.mu.Lock()
defer m.mu.Unlock()
for _, f := range m.frees {
m.dropBlob(f.fid)
}
m.frees = nil
}
// ApplyAfterDeadline arms the next n mutations (create, update, delete): each
// is applied, then its reply is held until the caller's context ends and the
// caller gets the context's gRPC status (DeadlineExceeded), as a filer whose
// reply arrives after the caller's deadline. A context with no deadline gets
// DeadlineExceeded at once.
func (m *MemFiler) ApplyAfterDeadline(n int) {
m.mu.Lock()
defer m.mu.Unlock()
m.lateReplies = n
}
// SetCap sets the store's capacity in bytes and in objects (0: no limit). A
// put that would pass it is refused with the filer's full-store answer,
// which matches storage.ErrChunkRemoteFull. A freed chunk gives its room
// back only when it is freed.
func (m *MemFiler) SetCap(maxBytes int64, maxObjects int) {
m.mu.Lock()
defer m.mu.Unlock()
m.capBytes, m.capObjects = maxBytes, maxObjects
}
// Blobs returns the chunk store that goes with this filer: its fids are the
// ones the filer frees when an entry drops them.
func (m *MemFiler) Blobs() Blobs { return memBlobs{m} }
// reapLocked frees the queued chunks whose delay has passed.
func (m *MemFiler) reapLocked() {
if len(m.frees) == 0 {
return
}
now := time.Now()
kept := m.frees[:0]
for _, f := range m.frees {
if !f.due.IsZero() && !now.Before(f.due) {
m.dropBlob(f.fid)
continue
}
kept = append(kept, f)
}
m.frees = kept
}
func (m *MemFiler) dropBlob(fid string) {
if b, ok := m.blobs[fid]; ok {
m.used -= int64(len(b))
delete(m.blobs, fid)
}
delete(m.copies, fid)
}
// dropChunksLocked queues for freeing the chunks of old that next does not
// list (next nil: all of them), as the filer's garbage of an update.
func (m *MemFiler) dropChunksLocked(old, next *filerpb.Entry) {
if old == nil {
return
}
keep := map[string]int{}
for _, f := range entryFids(next) {
keep[f]++
}
for _, f := range entryFids(old) {
if keep[f] > 0 {
keep[f]--
continue
}
switch {
case m.freeDelay == 0:
m.dropBlob(f)
case m.freeDelay < 0:
m.frees = append(m.frees, memFree{fid: f})
default:
m.frees = append(m.frees, memFree{fid: f, due: time.Now().Add(m.freeDelay)})
}
}
}
// beginLocked starts a mutation: it reaps due frees and reports whether this
// mutation's reply is to be lost.
func (m *MemFiler) beginLocked() (late bool) {
m.reapLocked()
if m.lateReplies > 0 {
m.lateReplies--
return true
}
return false
}
// lateReply waits out the caller's context and returns what a gRPC client
// returns then, wrapped as the SWFS client wraps an unclassified error.
func lateReply(ctx context.Context, op, dir, name string) error {
if _, ok := ctx.Deadline(); ok {
<-ctx.Done()
}
cause := ctx.Err()
if cause == nil {
cause = context.DeadlineExceeded
}
return fmt.Errorf("chunkstore: %s %s/%s: %w", op, dir, name, status.FromContextError(cause).Err())
}
func (m *MemFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.Entry, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
e, ok := m.e[path.Join(dir, name)]
if !ok {
return nil, ErrNotFound
@@ -37,52 +312,100 @@ func (m *MemFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.En
return proto.Clone(e).(*filerpb.Entry), nil
}
func (m *MemFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
func (m *MemFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
m.mu.Lock()
defer m.mu.Unlock()
late := m.beginLocked()
err := m.createLocked(dir, e, oExcl)
m.mu.Unlock()
if late {
return lateReply(ctx, "create", dir, e.GetName())
}
return err
}
func (m *MemFiler) createLocked(dir string, e *filerpb.Entry, oExcl bool) error {
p := path.Join(dir, e.GetName())
if _, ok := m.e[p]; ok && oExcl {
old, ok := m.e[p]
if ok && oExcl {
return ErrExists
}
m.e[p] = proto.Clone(e).(*filerpb.Entry)
m.dropChunksLocked(old, e)
m.ensureParentsLocked(path.Dir(p), e)
return nil
}
func (m *MemFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
// ensureParentsLocked makes every missing directory from d up, as the
// filer's ensureParentDirectoryEntry: a directory entry with the child's
// permission bits plus 0111, the child's owner and the current time.
func (m *MemFiler) ensureParentsLocked(d string, child *filerpb.Entry) {
ca := child.GetAttributes()
now := time.Now().Unix()
for ; d != "/" && d != "." && d != ""; d = path.Dir(d) {
if _, ok := m.e[d]; ok {
return
}
m.e[d] = &filerpb.Entry{Name: path.Base(d), IsDirectory: true, Attributes: &filerpb.FuseAttributes{
Mtime: now, Crtime: now,
FileMode: uint32(os.ModeDir | os.FileMode(ca.GetFileMode())&restorableModeBits | 0o111),
Uid: ca.GetUid(),
Gid: ca.GetGid(),
}}
}
}
func (m *MemFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
m.mu.Lock()
defer m.mu.Unlock()
p := path.Join(dir, e.GetName())
cur, ok := m.e[p]
if !ok {
return ErrNotFound
late := m.beginLocked()
err := m.updateLocked(dir, e, expected, nil)
m.mu.Unlock()
if late {
return lateReply(ctx, "update", dir, e.GetName())
}
if !extendedMatch(cur, expected) {
return ErrPrecondition
}
m.e[p] = proto.Clone(e).(*filerpb.Entry)
return nil
return err
}
// UpdateEntryIfChunks is UpdateEntry that also requires the stored chunk
// fids to equal fids as a multiset, as the filer's IF_CHUNKS_EQUAL does.
func (m *MemFiler) UpdateEntryIfChunks(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
func (m *MemFiler) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
if fids == nil {
fids = []string{}
}
m.mu.Lock()
defer m.mu.Unlock()
late := m.beginLocked()
err := m.updateLocked(dir, e, expected, fids)
m.mu.Unlock()
if late {
return lateReply(ctx, "update", dir, e.GetName())
}
return err
}
// updateLocked applies e if expected holds and, when fids is not nil, the
// stored chunk fids equal fids.
func (m *MemFiler) updateLocked(dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
p := path.Join(dir, e.GetName())
cur, ok := m.e[p]
if !ok {
return ErrNotFound
}
if !extendedMatch(cur, expected) || !fidsEqual(entryFids(cur), fids) {
if !extendedMatch(cur, expected) || (fids != nil && !fidsEqual(entryFids(cur), fids)) {
return ErrPrecondition
}
m.e[p] = proto.Clone(e).(*filerpb.Entry)
m.dropChunksLocked(cur, e)
return nil
}
func (m *MemFiler) ListEntries(_ context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
// The filer trims one trailing slash from the listed directory
// (weed/filer/filer_search.go StreamListDirectoryEntries).
if len(dir) > 1 {
dir = strings.TrimSuffix(dir, "/")
}
var names []string
for p := range m.e {
if name := path.Base(p); path.Dir(p) == dir && strings.HasPrefix(name, prefix) && name > startAfter {
@@ -100,18 +423,43 @@ func (m *MemFiler) ListEntries(_ context.Context, dir, prefix, startAfter string
return out, nil
}
func (m *MemFiler) DeleteEntry(_ context.Context, dir, name string, expected map[string][]byte) error {
// DeleteEntry follows Filer: an unconditional delete of a missing entry
// succeeds; a conditional one (expected not empty) is ErrPrecondition, as
// the filer cannot read the entry it is asked to check.
func (m *MemFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
m.mu.Lock()
defer m.mu.Unlock()
late := m.beginLocked()
err := m.deleteLocked(dir, name, expected)
m.mu.Unlock()
if late {
return lateReply(ctx, "delete", dir, name)
}
return err
}
func (m *MemFiler) deleteLocked(dir, name string, expected map[string][]byte) error {
p := path.Join(dir, name)
cur, ok := m.e[p]
if !ok {
return ErrNotFound
if len(expected) > 0 {
return ErrPrecondition
}
return nil
}
if !extendedMatch(cur, expected) {
return ErrPrecondition
}
if cur.GetIsDirectory() {
for k := range m.e {
if path.Dir(k) == p {
// The filer's answer in DeleteEntryResponse.Error, as SWFS
// reports it.
return fmt.Errorf("chunkstore: delete %s/%s: fail to delete non-empty folder: %s", dir, name, p)
}
}
}
delete(m.e, p)
m.dropChunksLocked(cur, nil)
return nil
}
@@ -123,3 +471,60 @@ func extendedMatch(e *filerpb.Entry, expected map[string][]byte) bool {
}
return true
}
// memBlobs is MemFiler's chunk store (Blobs plus DeleteBlob, as SWFS).
type memBlobs struct{ m *MemFiler }
// Put stores data under a new fid, or refuses past the cap as a full
// SeaweedFS store answers the assign.
func (b memBlobs) Put(_ context.Context, data []byte) (string, error) {
m := b.m
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
if (m.capObjects > 0 && len(m.blobs)+1 > m.capObjects) || (m.capBytes > 0 && m.used+int64(len(data)) > m.capBytes) {
return "", assignErr("chunkstore: assign", errors.New(memFullText))
}
racks, err := m.placeLocked()
if err != nil {
return "", err
}
if m.blobs == nil {
m.blobs = map[string][]byte{}
}
m.needle++
fid := fmt.Sprintf("1,%x00000000", m.needle)
m.blobs[fid] = append([]byte(nil), data...)
if racks != nil {
if m.copies == nil {
m.copies = map[string][]string{}
}
m.copies[fid] = racks
}
m.used += int64(len(data))
return fid, nil
}
// Get returns the payload; a freed or unknown fid is ErrBlobNotFound, as a
// volume server's 404.
func (b memBlobs) Get(_ context.Context, fid string) ([]byte, error) {
m := b.m
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
d, ok := m.blobs[fid]
if !ok {
return nil, fmt.Errorf("chunkstore: read %s: %w", fid, &blobNotFoundError{&blobStatusError{code: 404, host: "memfiler"}})
}
return append([]byte(nil), d...), nil
}
// DeleteBlob removes a needle at once (a direct needle delete, not the
// filer's queue); an absent one is not an error.
func (b memBlobs) DeleteBlob(_ context.Context, fid string) error {
m := b.m
m.mu.Lock()
defer m.mu.Unlock()
m.dropBlob(fid)
return nil
}
@@ -6,6 +6,7 @@ import (
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestMemFiler_Contract(t *testing.T) {
@@ -25,9 +26,17 @@ func TestMemFiler_Contract(t *testing.T) {
if err := m.CreateEntry(ctx, "/d/sub", ent("x", "1"), true); err != nil {
t.Fatal(err)
}
// The filer makes parent directory entries on create (weed/filer/filer.go
// ensureParentDirectoryEntry), so the create of /d/sub/x made the
// directory /d/sub: a child of /d. Its own child x is not.
list, err := m.ListEntries(ctx, "/d", "", "a", 10)
if err != nil || len(list) != 2 || list[0].Name != "b" || list[1].Name != "c" {
t.Fatalf("list after a: %v %v (children only, in name order)", list, err)
if err != nil || len(list) != 3 || list[0].Name != "b" || list[1].Name != "c" || list[2].Name != "sub" || !list[2].GetIsDirectory() {
t.Fatalf("list after a: %v %v (children only, in name order, the made directory sub included)", list, err)
}
for _, e := range list {
if e.Name == "x" {
t.Fatalf("list after a: %v lists the grandchild x", list)
}
}
if err := m.UpdateEntry(ctx, "/d", ent("a", "3"), map[string][]byte{"k": []byte("9")}); !errors.Is(err, ErrPrecondition) {
t.Fatalf("update with a wrong expectation: %v", err)
@@ -48,3 +57,33 @@ func TestMemFiler_Contract(t *testing.T) {
t.Fatalf("lookup after delete: %v", err)
}
}
// Degraded growth never goes below two copies (degradedGrowthMinCopies in
// weed/topology/volume_growth_degraded.go; degradedPlacements tries totals
// from copies-1 down to it), so a two-copy placement such as 010 never
// degrades: with a rack down it is refused even with degraded growth on.
// A three-copy placement (020) with a rack down degrades to two copies in
// the racks left.
func TestMemFiler_TwoCopyPlacementNeverDegrades(t *testing.T) {
ctx := context.Background()
m := NewMemFiler()
b := m.Blobs()
m.SetTopology([]string{"rackA", "rackA", "rackB"}, 2, true)
fid, err := b.Put(ctx, []byte("x"))
if got := m.CopyRacks(fid); err != nil || len(got) != 2 || got[0] == got[1] {
t.Fatalf("010 with two racks up: %v %v, want one copy in each rack", got, err)
}
m.SetTopology([]string{"rackA", "rackA"}, 2, true)
if fid, err := b.Put(ctx, []byte("x")); err == nil || errors.Is(err, storage.ErrChunkRemoteFull) {
t.Fatalf("010 with one rack up and degraded growth on: fid %q err %v, want an unplaceable refusal (no degradation below two copies)", fid, err)
}
m.SetTopology([]string{"rackA", "rackB"}, 3, true)
fid, err = b.Put(ctx, []byte("x"))
if got := m.CopyRacks(fid); err != nil || len(got) != 2 || got[0] != "rackA" || got[1] != "rackB" {
t.Fatalf("020 with rackC down and degraded growth on: %v %v, want [rackA rackB]", got, err)
}
m.SetTopology([]string{"rackA", "rackB"}, 3, false)
if _, err := b.Put(ctx, []byte("x")); err == nil {
t.Fatal("020 with rackC down, no degraded growth: placed, want refused")
}
}
@@ -37,16 +37,23 @@ func startWeedWith(t *testing.T, security string) *weedCluster {
// max x sizeMB. A start that fails (a server cannot bind a port another
// process took) is started again on fresh ports.
func startWeedSized(t *testing.T, security string, sizeMB, max int) *weedCluster {
t.Helper()
return startWeedOptions(t, "", weedtest.Options{SizeMB: sizeMB, Max: max, Security: security})
}
// startWeedOptions starts the cluster o shapes, ready once an assign with
// replication (empty: the master's default) succeeds. o.Ready is set here.
func startWeedOptions(t *testing.T, replication string, o weedtest.Options) *weedCluster {
t.Helper()
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
t.Skip("CHUNKSTORE_WEED not set")
}
c := weedtest.Start(t, weed, t.TempDir(), weedtest.Options{
SizeMB: sizeMB, Max: max, Security: security,
SizeMB: o.SizeMB, Max: o.Max, Security: o.Security, Volumes: o.Volumes,
// Ready once an assign succeeds (volume registered, volumes growable).
Ready: func(filerGRPC string) error {
cl, err := DialSWFS(SWFSConfig{FilerGRPC: filerGRPC, Collection: "swblock", AssignPath: "/swblock/vols/probe"})
cl, err := DialSWFS(SWFSConfig{FilerGRPC: filerGRPC, Collection: "swblock", Replication: replication, AssignPath: "/swblock/vols/probe"})
if err != nil {
return err
}
+61 -5
View File
@@ -35,11 +35,20 @@ const host = "127.0.0.1"
// Options shape a cluster: the master's volume size limit (MB), the volume
// server's volume count (-max), the contents of a security.toml in the
// cluster's directory ("" for none), and Ready, which reports whether the
// started cluster serves (nil: its filer's gRPC port listens).
// started cluster serves (nil: its filer's gRPC port listens). Volumes, when
// set, replaces the one volume server with one per element, each in its
// data center and rack with its own -max.
type Options struct {
SizeMB, Max int
Security string
Ready func(filerGRPC string) error
Volumes []Volume
}
// Volume is one volume server of a cluster with a topology.
type Volume struct {
DataCenter, Rack string
Max int
}
// Cluster is one started weed cluster.
@@ -47,7 +56,11 @@ type Cluster struct {
Master, FilerHTTP, FilerGRPC string
Dir string // this start's directory (server logs: <role>.log)
Starts []string // the directory of every start, the discarded ones first
procs []*proc
// VolumeURLs are the volume servers' host:port, in Options.Volumes
// order (one element without a topology).
VolumeURLs []string
procs []*proc
volumes []*proc
}
type proc struct {
@@ -87,7 +100,15 @@ func Start(t testing.TB, weed, dir string, o Options) *Cluster {
func startOnce(t testing.TB, weed, dir string, o Options) (*Cluster, error) {
t.Helper()
c := &Cluster{Dir: dir}
for _, d := range []string{"m", "v", "f"} {
vols := o.Volumes
if len(vols) == 0 {
vols = []Volume{{Max: o.Max}}
}
dirs := []string{"m", "f"}
for i := range vols {
dirs = append(dirs, volumeDir(i))
}
for _, d := range dirs {
if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
t.Fatal(err)
}
@@ -104,8 +125,22 @@ func startOnce(t testing.TB, weed, dir string, o Options) (*Cluster, error) {
if err := c.listening(m, c.Master, 20*time.Second); err != nil {
return c, err
}
vp := PickPair(t, used, "volume")
c.start(t, weed, "volume", "volume", "-ip="+host, fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.Master, fmt.Sprintf("-max=%d", o.Max))
for i, v := range vols {
vp := PickPair(t, used, "volume")
role := "volume"
if i > 0 {
role = fmt.Sprintf("volume%d", i)
}
args := []string{"volume", "-ip=" + host, fmt.Sprintf("-port=%d", vp), "-dir=" + filepath.Join(dir, volumeDir(i)), "-master=" + c.Master, fmt.Sprintf("-max=%d", v.Max)}
if v.DataCenter != "" {
args = append(args, "-dataCenter="+v.DataCenter)
}
if v.Rack != "" {
args = append(args, "-rack="+v.Rack)
}
c.volumes = append(c.volumes, c.start(t, weed, role, args...))
c.VolumeURLs = append(c.VolumeURLs, fmt.Sprintf("%s:%d", host, vp))
}
fp := PickPair(t, used, "filer")
c.FilerHTTP = fmt.Sprintf("%s:%d", host, fp)
c.FilerGRPC = fmt.Sprintf("%s:%d", host, fp+10000)
@@ -136,6 +171,27 @@ func startOnce(t testing.TB, weed, dir string, o Options) (*Cluster, error) {
return c, c.exited()
}
// volumeDir is the i-th volume server's directory ("v" for the first, as
// a cluster without a topology has always used).
func volumeDir(i int) string {
if i == 0 {
return "v"
}
return fmt.Sprintf("v%d", i)
}
// StopVolume kills the i-th volume server (Options.Volumes order) and waits
// for its exit. It stays stopped; the cluster's cleanup still reaps it.
func (c *Cluster) StopVolume(i int) error {
if i < 0 || i >= len(c.volumes) {
return fmt.Errorf("weedtest: no volume server %d (have %d)", i, len(c.volumes))
}
if !c.volumes[i].stop() {
return fmt.Errorf("weedtest: volume server %d did not exit after kill", i)
}
return nil
}
// start launches one server of this start; it is stopped when t ends.
func (c *Cluster) start(t testing.TB, weed, role string, args ...string) *proc {
t.Helper()