mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
006ea07e5e | ||
|
|
fe2d016c41 | ||
|
|
cf3eda7e57 | ||
|
|
68d56d8ff8 | ||
|
|
39f568f614 | ||
|
|
4a58968439 | ||
|
|
f9febc7ee5 | ||
|
|
0ce344d559 | ||
|
|
63c50b8cfe |
No files matched your search
+5
-4
@@ -11,14 +11,14 @@ cmd/sw-block/volume_backup.go RestoreCommand.Abort
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.Run
|
||||
cmd/sw-block/volume_backup.go RestoreCommand.Start
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.CrashRestart
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean
|
||||
cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen
|
||||
cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
|
||||
cmd/sw-block/volume_verbs.go CutTime.Poll
|
||||
cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
|
||||
core/authority/authority.go DeleteRetire.Retire
|
||||
core/authority/authority_store_file.go DeleteRetire.Retire
|
||||
core/authority/authority.go DeleteRetire.RetireLine
|
||||
core/authority/authority_store_file.go DeleteRetire.RetireLine
|
||||
core/authority/workspace.go HolderInterface.ForcedMove
|
||||
core/authority/workspace.go HolderInterface.PlannedMove
|
||||
core/authority/workspace.go MoveAdmission.Ack
|
||||
@@ -36,7 +36,7 @@ core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
|
||||
core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
|
||||
core/authority/workspace_lease_view.go HolderInterface.Grant
|
||||
core/authority/workspace_lease_view.go HolderInterface.Regrant
|
||||
core/authority/workspace_retirement.go DeleteRetire.Retire
|
||||
core/authority/workspace_retirement.go DeleteRetire.RetireLine
|
||||
core/engine/apply.go ReplicationPeer.Reconcile
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
|
||||
core/frontend/chunkstore/catalog_b.go CleanBatch.Request
|
||||
@@ -187,6 +187,7 @@ core/frontend/durable/provider_layout.go EngineAdapter.SettleDown
|
||||
core/frontend/durable/provider_layout.go StopAndRestart.SettleDown
|
||||
core/frontend/durable/provider_preempt.go CutTime.Preempt
|
||||
core/frontend/durable/provider_preempt.go CutTime.Settle
|
||||
core/frontend/durable/provider_seal_replay.go PlainSealReplay.Reply
|
||||
core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite
|
||||
core/frontend/durable/storage_adapter.go HolderInterface.Write
|
||||
core/frontend/durable/storage_adapter.go WALHold.Resubmit
|
||||
|
||||
|
@@ -12,7 +12,6 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -26,7 +25,7 @@ import (
|
||||
type storeRecordMaster struct {
|
||||
control.UnimplementedLifecycleServiceServer
|
||||
mu sync.Mutex
|
||||
mode string // "creating", "ended", "older", "unreadable", "unavailable"
|
||||
mode string // "creating", "ended", "older", "unavailable"
|
||||
}
|
||||
|
||||
func (m *storeRecordMaster) set(mode string) { m.mu.Lock(); m.mode = mode; m.mu.Unlock() }
|
||||
@@ -43,8 +42,6 @@ func (m *storeRecordMaster) GetReplicaStore(_ context.Context, q *control.GetRep
|
||||
return &control.GetReplicaStoreResponse{Listed: true, CreationEnded: true}, nil
|
||||
case "older":
|
||||
return nil, status.Error(codes.Unimplemented, "unknown method GetReplicaStore")
|
||||
case "unreadable":
|
||||
return nil, status.Error(codes.FailedPrecondition, "the replica's store record is unreadable")
|
||||
}
|
||||
return nil, status.Error(codes.Unavailable, "lifecycle store unavailable")
|
||||
}
|
||||
@@ -105,10 +102,7 @@ func runHolder(t *testing.T, bin, master, root, locks string, until func() bool,
|
||||
// the volume is creating an empty state directory creates the store; once
|
||||
// creation ended, a store other than the recorded one, and a wiped state
|
||||
// directory, exit 78 store_lost; an older master (no GetReplicaStore) and an
|
||||
// unreadable record exit 75 with an empty state directory left empty. A
|
||||
// master that gives no reply is waited out inside the process, writing
|
||||
// nothing, so a start during an outage does not burn the unit's start limit;
|
||||
// once it answers creating, the same process creates its store.
|
||||
// unreadable record exit 75 with an empty state directory left empty.
|
||||
func TestBlockvolumeAsksTheMasterBeforeCreatingItsStore(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("builds and runs the blockvolume binary")
|
||||
@@ -190,64 +184,11 @@ func TestBlockvolumeAsksTheMasterBeforeCreatingItsStore(t *testing.T) {
|
||||
}
|
||||
empty(t)
|
||||
|
||||
for mode, reason := range map[string]string{"older": "master_too_old", "unreadable": "store_record_unreadable"} {
|
||||
for mode, reason := range map[string]string{"older": "master_too_old", "unavailable": "store_record_unreadable"} {
|
||||
m.set(mode)
|
||||
if code, _, out := runHolder(t, bin, ln.Addr().String(), root, locks, nil, 60*time.Second); code != exitWorkspaceRetry || !strings.Contains(out, reason) {
|
||||
t.Fatalf("%s master, empty state: exit %d, want 75 %s\n%s", mode, code, reason, out)
|
||||
}
|
||||
empty(t)
|
||||
}
|
||||
|
||||
// No reply for longer than the old 10 s read bound plus the unit's 5 s
|
||||
// restart delay: the process stays, writes nothing, and creates its
|
||||
// store once the master answers creating.
|
||||
m.set("unavailable")
|
||||
start, answered := time.Now(), false
|
||||
answer := func() bool {
|
||||
if !answered && time.Since(start) > 25*time.Second {
|
||||
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
|
||||
t.Errorf("the waiting holder wrote into its state directory: %v %v", entries, err)
|
||||
}
|
||||
m.set("creating")
|
||||
answered = true
|
||||
}
|
||||
return created()
|
||||
}
|
||||
if code, running, out := runHolder(t, bin, ln.Addr().String(), root, locks, answer, 90*time.Second); !running || !created() || !strings.Contains(out, "waiting for the master at "+ln.Addr().String()) {
|
||||
t.Fatalf("a master with no reply, then creating: exit %d running %v created %v\n%s", code, running, created(), out)
|
||||
}
|
||||
|
||||
// A stop during the wait is a clean stop: exit 0, nothing created.
|
||||
if runtime.GOOS == "windows" {
|
||||
return // no SIGTERM to another process
|
||||
}
|
||||
if err := os.RemoveAll(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.set("unavailable")
|
||||
var buf bytes.Buffer
|
||||
cmd := exec.Command(bin, "--master", ln.Addr().String(), "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
|
||||
"--data-addr", "127.0.0.1:0", "--ctrl-addr", "127.0.0.1:0", "--durable-root", root, "--durable-impl", "walstore",
|
||||
"--durable-blocks", "64", "--"+volumeLockDirTestOnlyFlag, locks)
|
||||
cmd.Stdout, cmd.Stderr = &buf, &buf
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
time.Sleep(5 * time.Second)
|
||||
_ = cmd.Process.Signal(syscall.SIGTERM)
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil || !strings.Contains(buf.String(), "stopped while waiting for the master") {
|
||||
t.Fatalf("SIGTERM during the wait: %v\n%s", err, buf.String())
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
killAndJoin(cmd, done)
|
||||
t.Fatalf("SIGTERM did not end the wait\n%s", buf.String())
|
||||
}
|
||||
empty(t)
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
@@ -927,24 +926,9 @@ func runVolume(f flags, exits *processExit) int {
|
||||
if xErr == nil && f.durableImpl != "walstore-chunk" {
|
||||
// A plain walstore store is the volume's only copy: ask the master
|
||||
// before anything is created or written (GetReplicaStore).
|
||||
var storeWait atomic.Bool
|
||||
if status != nil {
|
||||
status.SetStartupWait(storeWait.Load)
|
||||
}
|
||||
rec, qerr := readReplicaStore(exits.parent, f.masterAddr, h.ReplicaStoreRecord, log.Printf, storeWait.Store)
|
||||
if exits.parent.Err() != nil {
|
||||
// Stopped while waiting for the master: nothing was opened or
|
||||
// created, and a stop is not a failure.
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: stopped while waiting for the master's store record; nothing was created")
|
||||
_ = closeProviderAfterSnapshotOperations(status, dp.Close)
|
||||
if status != nil {
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = status.Close(shutCtx)
|
||||
shutCancel()
|
||||
}
|
||||
_ = h.Close()
|
||||
return 0
|
||||
}
|
||||
qctx, qcancel := context.WithTimeout(context.Background(), replicaStoreQueryTimeout)
|
||||
rec, qerr := h.ReplicaStoreRecord(qctx)
|
||||
qcancel()
|
||||
admission, refuse := decideStoreAdmission(rec, qerr, exists)
|
||||
if refuse != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockvolume: durable storage open refused:", refuse.reason, refuse.detail)
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
//go:build linux && subprocess && chunkstore_integration && systemd_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A plain walstore holder started under the shipped unit's restart policy and
|
||||
// start limit while blockmaster gives no reply (nothing listens on its
|
||||
// address) waits inside the process for its store record: through a
|
||||
// 5-minute outage the unit stays active with no restart, /status says
|
||||
// waiting_for_master and the journal names the wait; once blockmaster
|
||||
// starts, the volume serves with no restart. Before, the start exited 75 at
|
||||
// once, the unit restarted every RestartSec, and after StartLimitBurst
|
||||
// starts it stayed failed even once the master came back.
|
||||
//
|
||||
// A runtime unit file (/run/systemd/system) stands for the installed unit.
|
||||
func TestWalstoreUnitWaitsForAnUnreachableMasterWithoutBurningItsStartLimit(t *testing.T) {
|
||||
if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" {
|
||||
t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof")
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
t.Fatal("systemd qualification needs root")
|
||||
}
|
||||
shipped := gap1ShippedPolicy(t)
|
||||
interval, burst := shippedStartLimit(t)
|
||||
|
||||
exe := filepath.Join(t.TempDir(), "blockvolume")
|
||||
if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" {
|
||||
exe = filepath.Join(d, "blockvolume")
|
||||
} else {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
out, err := exec.CommandContext(ctx, "go", "build", "-o", exe, "github.com/seaweedfs/seaweed-block/cmd/blockvolume").CombinedOutput()
|
||||
cancel()
|
||||
if err != nil {
|
||||
t.Fatalf("build blockvolume: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
masterBin := filepath.Join(filepath.Dir(exe), "blockmaster")
|
||||
if os.Getenv("SWBLOCK_TEST_BINS") == "" {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
out, err := exec.CommandContext(ctx, "go", "build", "-o", masterBin, "github.com/seaweedfs/seaweed-block/cmd/blockmaster").CombinedOutput()
|
||||
cancel()
|
||||
if err != nil {
|
||||
t.Fatalf("build blockmaster: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
master, data, ctrl, statusAddr, nvme := handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t)
|
||||
// nothing listens at master until blockmaster starts below
|
||||
|
||||
unit := fmt.Sprintf("swb-c04-walstore-wait-%d.service", os.Getpid())
|
||||
writeRuntimeUnit(t, unit, exe, []string{"--master", master, "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
|
||||
"--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--durable-impl", "walstore",
|
||||
"--durable-blocks", "64", "--nvme-listen", nvme, "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"}, []string{
|
||||
"StartLimitIntervalSec=" + interval,
|
||||
"StartLimitBurst=" + burst,
|
||||
}, []string{
|
||||
"Restart=on-failure",
|
||||
"RestartSec=" + shipped["RestartSec"],
|
||||
"RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"],
|
||||
"TimeoutStopSec=" + shipped["TimeoutStopSec"],
|
||||
})
|
||||
if out, err := runSystemctl("start", unit); err != nil {
|
||||
t.Fatalf("start %s: %v %s", unit, err, out)
|
||||
}
|
||||
// A 5-minute outage: on the old behaviour the unit has failed after
|
||||
// StartLimitBurst starts RestartSec apart, well before this.
|
||||
window := 5 * time.Minute
|
||||
started := time.Now()
|
||||
var state map[string]string
|
||||
for time.Since(started) < window {
|
||||
time.Sleep(2 * time.Second)
|
||||
s, err := gap1ReadUnit(unit)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
state = s
|
||||
if s["ActiveState"] == "failed" {
|
||||
t.Fatalf("the unit gave up %v into the master outage: NRestarts %s Result %s; journal: %s",
|
||||
time.Since(started).Round(time.Second), s["NRestarts"], s["Result"], lastLines(unitJournal(unit), 15))
|
||||
}
|
||||
}
|
||||
journal := unitJournal(unit)
|
||||
t.Logf("walstore unit after %v with no master: ActiveState %s NRestarts %s", window, state["ActiveState"], state["NRestarts"])
|
||||
if state["ActiveState"] != "active" || state["NRestarts"] != "0" {
|
||||
t.Fatalf("after %v: ActiveState %s NRestarts %s; want active with no restart; journal: %s", window, state["ActiveState"], state["NRestarts"], lastLines(journal, 15))
|
||||
}
|
||||
if !strings.Contains(journal, "waiting for the master at "+master+" to answer this replica's store record: no reply for") {
|
||||
t.Fatalf("the journal does not name the wait: %s", lastLines(journal, 15))
|
||||
}
|
||||
if reason := statusNotReadyReason(statusAddr, "v1"); reason != "waiting_for_master" {
|
||||
t.Fatalf("/status NotReadyReason %q during the wait; want waiting_for_master", reason)
|
||||
}
|
||||
|
||||
// blockmaster starts: the waiting process goes on and serves, with no restart.
|
||||
dir := t.TempDir()
|
||||
topo := filepath.Join(dir, "topology.yaml")
|
||||
nl := string(rune(10))
|
||||
if err := os.WriteFile(topo, []byte("volumes:"+nl+" - volume_id: v1"+nl+" slots:"+nl+" - replica_id: r1"+nl+" server_id: s1"+nl), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mlog, err := os.Create(filepath.Join(dir, "blockmaster.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc := exec.Command(masterBin, "--authority-store", filepath.Join(dir, "master"), "--listen", master, "--topology", topo, "--expected-slots-per-volume", "1")
|
||||
mc.Stdout, mc.Stderr = mlog, mlog
|
||||
if err := mc.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = mc.Process.Kill(); _ = mc.Wait(); mlog.Close() })
|
||||
back := time.Now()
|
||||
for !volumeFrontendReady(statusAddr, "v1") {
|
||||
if time.Since(back) > 2*time.Minute {
|
||||
b, _ := os.ReadFile(mlog.Name())
|
||||
t.Fatalf("v1 never served after blockmaster started; journal: %s; blockmaster: %s", lastLines(unitJournal(unit), 15), lastLines(string(b), 10))
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
s, _ := gap1ReadUnit(unit)
|
||||
t.Logf("walstore unit served %v after blockmaster started: ActiveState %s NRestarts %s", time.Since(back).Round(time.Second), s["ActiveState"], s["NRestarts"])
|
||||
if s["ActiveState"] != "active" || s["NRestarts"] != "0" {
|
||||
t.Fatalf("after serving: ActiveState %s NRestarts %s; want active with no restart", s["ActiveState"], s["NRestarts"])
|
||||
}
|
||||
}
|
||||
|
||||
// statusNotReadyReason is /status's NotReadyReason for vol ("" when unreadable).
|
||||
func statusNotReadyReason(statusAddr, vol string) string {
|
||||
resp, err := http.Get("http://" + statusAddr + "/status?volume=" + vol)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var p struct{ NotReadyReason string }
|
||||
if json.NewDecoder(resp.Body).Decode(&p) != nil {
|
||||
return ""
|
||||
}
|
||||
return p.NotReadyReason
|
||||
}
|
||||
|
||||
func lastLines(s string, n int) string {
|
||||
lines := strings.Split(strings.TrimSpace(s), string(rune(10)))
|
||||
if len(lines) > n {
|
||||
lines = lines[len(lines)-n:]
|
||||
}
|
||||
return strings.Join(lines, " | ")
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -15,57 +13,6 @@ import (
|
||||
// its durable open.
|
||||
const replicaStoreQueryTimeout = 10 * time.Second
|
||||
|
||||
// replicaStoreRetryEvery paces the store record read while blockmaster gives
|
||||
// no reply, and replicaStoreWaitLogEvery its log line. Vars only so a test
|
||||
// can shorten them.
|
||||
var (
|
||||
replicaStoreRetryEvery = 2 * time.Second
|
||||
replicaStoreWaitLogEvery = 30 * time.Second
|
||||
)
|
||||
|
||||
// readReplicaStore reads the master's record of this replica's store. While
|
||||
// blockmaster gives no reply (volume.MasterCallClass: neither contact nor a
|
||||
// credentials refusal) the process waits and reads again, with no bound, so
|
||||
// a start during a master outage does not exit and burn the unit's start
|
||||
// limit. It runs before the store is opened or created, so nothing is
|
||||
// written meanwhile; waiting reports the wait (for /status) and the log
|
||||
// repeats it every replicaStoreWaitLogEvery with the master's address and the
|
||||
// time waited. Any answer, a credentials refusal, or ctx's end returns the
|
||||
// last result.
|
||||
func readReplicaStore(ctx context.Context, master string, read func(context.Context) (*control.GetReplicaStoreResponse, error), logf func(string, ...any), waiting func(bool)) (*control.GetReplicaStoreResponse, error) {
|
||||
var since, logged time.Time
|
||||
defer func() {
|
||||
if !since.IsZero() {
|
||||
waiting(false)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
qctx, cancel := context.WithTimeout(ctx, replicaStoreQueryTimeout)
|
||||
rec, err := read(qctx)
|
||||
cancel()
|
||||
contact, credentials := volume.MasterCallClass(err)
|
||||
if contact || credentials || ctx.Err() != nil {
|
||||
if !since.IsZero() && ctx.Err() == nil {
|
||||
logf("blockvolume: the master at %s answered this replica's store record after %s", master, time.Since(since).Round(time.Second))
|
||||
}
|
||||
return rec, err
|
||||
}
|
||||
if since.IsZero() {
|
||||
since = time.Now()
|
||||
waiting(true)
|
||||
}
|
||||
if logged.IsZero() || time.Since(logged) >= replicaStoreWaitLogEvery {
|
||||
logged = time.Now()
|
||||
logf("blockvolume: waiting for the master at %s to answer this replica's store record: no reply for %s (%v); nothing is created or written meanwhile", master, time.Since(since).Round(time.Second), err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return rec, err
|
||||
case <-time.After(replicaStoreRetryEvery):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// storeAdmission is how the durable open may treat the local store: with
|
||||
// mustExist it never creates one (a missing store is refused at the open
|
||||
// itself), and a nonzero id is the store it must find.
|
||||
@@ -80,8 +27,7 @@ type storeAdmission struct {
|
||||
// exists:
|
||||
//
|
||||
// answer store present store absent
|
||||
// no reply (waited out in-process by readReplicaStore; only a shutdown ends the wait)
|
||||
// other error refuse 75 refuse 75
|
||||
// error / timeout refuse 75 refuse 75
|
||||
// older master (Unimplemented) open as before refuse 75 master_too_old
|
||||
// not listed open as before refuse 75 volume_not_listed
|
||||
// listed, replicated, non-primary open or create (peer rebuild path, as before)
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// The store record read waits inside the process while blockmaster gives no
|
||||
// reply (Unavailable, DeadlineExceeded, a timed-out read), logging once, and
|
||||
// returns the first answer; any other result returns at once (a credentials
|
||||
// refusal, an older master, an answered error), and so does a shutdown.
|
||||
func TestReadReplicaStoreWaitsOnlyWhileTheMasterGivesNoReply(t *testing.T) {
|
||||
prev := replicaStoreRetryEvery
|
||||
replicaStoreRetryEvery = time.Millisecond
|
||||
t.Cleanup(func() { replicaStoreRetryEvery = prev })
|
||||
want := &control.GetReplicaStoreResponse{Listed: true}
|
||||
script := func(errs ...error) (func(context.Context) (*control.GetReplicaStoreResponse, error), *int) {
|
||||
calls := 0
|
||||
return func(context.Context) (*control.GetReplicaStoreResponse, error) {
|
||||
calls++
|
||||
if calls <= len(errs) {
|
||||
return nil, errs[calls-1]
|
||||
}
|
||||
return want, nil
|
||||
}, &calls
|
||||
}
|
||||
logs := 0
|
||||
logf := func(string, ...any) { logs++ }
|
||||
var states []bool
|
||||
waiting := func(w bool) { states = append(states, w) }
|
||||
|
||||
read, calls := script(status.Error(codes.Unavailable, "connection refused"), status.Error(codes.DeadlineExceeded, "deadline"), context.DeadlineExceeded)
|
||||
if rec, err := readReplicaStore(context.Background(), "127.0.0.1:9180", read, logf, waiting); err != nil || rec != want || *calls != 4 || logs != 2 {
|
||||
t.Fatalf("no reply three times, then an answer: rec %v err %v calls %d logs %d (want the answer after 4 reads, 2 log lines)", rec, err, *calls, logs)
|
||||
}
|
||||
if len(states) != 2 || !states[0] || states[1] {
|
||||
t.Fatalf("the wait was reported %v; want waiting, then not", states)
|
||||
}
|
||||
// The log line repeats at its cadence, not at every read.
|
||||
prevLog := replicaStoreWaitLogEvery
|
||||
replicaStoreWaitLogEvery = 50 * time.Millisecond
|
||||
t.Cleanup(func() { replicaStoreWaitLogEvery = prevLog })
|
||||
logs, slow := 0, 0
|
||||
slowRead := func(context.Context) (*control.GetReplicaStoreResponse, error) {
|
||||
slow++
|
||||
if slow > 60 {
|
||||
return want, nil
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
return nil, status.Error(codes.Unavailable, "down")
|
||||
}
|
||||
if _, err := readReplicaStore(context.Background(), "m", slowRead, logf, func(bool) {}); err != nil || logs < 3 || logs > 12 {
|
||||
t.Fatalf("about 300 ms of no reply at a 50 ms cadence logged %d lines (err %v); want a few, not one per read", logs, err)
|
||||
}
|
||||
for _, e := range []error{status.Error(codes.Unauthenticated, "bad cert"), status.Error(codes.Unimplemented, "older"), status.Error(codes.Internal, "boom"), errors.New("plain")} {
|
||||
read, calls := script(e)
|
||||
if _, err := readReplicaStore(context.Background(), "m", read, logf, func(bool) {}); !errors.Is(err, e) || *calls != 1 {
|
||||
t.Fatalf("%v: waited (%d reads) instead of returning it", e, *calls)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
never := func(context.Context) (*control.GetReplicaStoreResponse, error) {
|
||||
cancel()
|
||||
return nil, status.Error(codes.Unavailable, "down")
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := readReplicaStore(ctx, "m", never, logf, func(bool) {}); done <- err }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if status.Code(err) != codes.Unavailable {
|
||||
t.Fatalf("a shutdown during the wait: %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("a shutdown did not end the wait")
|
||||
}
|
||||
}
|
||||
@@ -68,8 +68,8 @@ func TestGetReplicaStoreAnswersFromTheMastersCreationFact(t *testing.T) {
|
||||
}
|
||||
for _, bad := range []string{"zz", "00000000000000000000000000000000"} {
|
||||
seed(&attestedStores{Stores: map[string]string{"r1": bad}})
|
||||
if r, err := ask("vol"); status.Code(err) != codes.FailedPrecondition {
|
||||
t.Fatalf("an invalid recorded id %q: %+v %v, want FailedPrecondition (an answer, never creating)", bad, r, err)
|
||||
if r, err := ask("vol"); status.Code(err) != codes.Unavailable {
|
||||
t.Fatalf("an invalid recorded id %q: %+v %v, want Unavailable (never creating)", bad, r, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -609,7 +609,7 @@ func (s *services) GetReplicaStore(ctx context.Context, q *control.GetReplicaSto
|
||||
state, id := s.host.ReplicaStoreState(q.GetVolumeId(), q.GetReplicaId())
|
||||
switch state {
|
||||
case replicaStoreUnknown:
|
||||
return nil, status.Error(codes.FailedPrecondition, "the replica's store record is unreadable (an invalid recorded store id)")
|
||||
return nil, status.Error(codes.Unavailable, "the replica's store record is unreadable (an invalid recorded store id)")
|
||||
case replicaStoreEnded:
|
||||
out.CreationEnded = true
|
||||
if !id.IsZero() {
|
||||
|
||||
@@ -65,11 +65,11 @@ func newMasterWait(now func() time.Time, logf func(string, ...any)) *masterWait
|
||||
return &masterWait{now: now, logf: logf}
|
||||
}
|
||||
|
||||
// MasterCallClass sorts a call result: a reply produced by blockmaster's
|
||||
// masterCallClass sorts a call result: a reply produced by blockmaster's
|
||||
// handler (any status but the transport codes) is contact; Unavailable,
|
||||
// DeadlineExceeded and Canceled are no reply; Unauthenticated and
|
||||
// PermissionDenied are a credentials refusal.
|
||||
func MasterCallClass(err error) (contact, credentials bool) {
|
||||
func masterCallClass(err error) (contact, credentials bool) {
|
||||
if err == nil {
|
||||
return true, false
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func MasterCallClass(err error) (contact, credentials bool) {
|
||||
// assignment to accept). The heartbeat does not check identity, so its
|
||||
// answers alone do not end it sooner.
|
||||
func (w *masterWait) call(err error) {
|
||||
contact, credentials := MasterCallClass(err)
|
||||
contact, credentials := masterCallClass(err)
|
||||
identity := ""
|
||||
r := leaseRefusalDetail(err)
|
||||
if r != nil && r.GetKind() == control.WorkspaceLeaseRefusal_IDENTITY {
|
||||
|
||||
@@ -485,21 +485,3 @@ func TestRecordedRevocationFinalRequiresTypedFailedPrecondition(t *testing.T) {
|
||||
t.Fatal("log text became a terminal verdict")
|
||||
}
|
||||
}
|
||||
|
||||
// While the start waits for blockmaster's first answer, /status says
|
||||
// waiting_for_master, ahead of any other reason, and is not ready.
|
||||
func TestStatusSaysWaitingForMasterDuringTheStartupWait(t *testing.T) {
|
||||
p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}}
|
||||
view := NewAdapterProjectionView(p, "v1", "r1", nil)
|
||||
s := NewStatusServer(view)
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{VolumeID: "v1", Operational: true}}})
|
||||
waiting := true
|
||||
s.SetStartupWait(func() bool { return waiting })
|
||||
if got := s.statusProjection(); got.FrontendPrimaryReady || got.NotReadyReason != NotReadyWaitingForMaster {
|
||||
t.Fatalf("during the wait: ready %v reason %q", got.FrontendPrimaryReady, got.NotReadyReason)
|
||||
}
|
||||
waiting = false
|
||||
if got := s.statusProjection(); got.NotReadyReason == NotReadyWaitingForMaster {
|
||||
t.Fatalf("after the wait: reason %q", got.NotReadyReason)
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,6 @@ type StatusServer struct {
|
||||
peerSource peerStatusSource
|
||||
durableSource durableStatusSource
|
||||
masterWait func() *MasterWait // why a workspace primary holds no grant; nil: not wired
|
||||
startupWait func() bool // true while the start waits for blockmaster's first answer; nil: not wired
|
||||
nvmeSource nvmeStatusSource
|
||||
guestSources map[string]func() int // frontend -> guests connected now
|
||||
ublkSource ublkStatusSource
|
||||
@@ -620,17 +619,6 @@ func (s *StatusServer) handleStatusNVMe(w http.ResponseWriter, r *http.Request)
|
||||
// the lease-readiness gate (no claim, no listen, not ready).
|
||||
const NotReadyLeaseNotHeld = "lease_not_held"
|
||||
|
||||
// NotReadyWaitingForMaster: the start waits for blockmaster to answer before
|
||||
// it opens or creates the volume's store (blockmaster gives no reply).
|
||||
const NotReadyWaitingForMaster = "waiting_for_master"
|
||||
|
||||
// SetStartupWait wires whether the start is waiting for blockmaster's answer.
|
||||
func (s *StatusServer) SetStartupWait(f func() bool) {
|
||||
s.mu.Lock()
|
||||
s.startupWait = f
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *StatusServer) statusProjection() StatusProjection {
|
||||
p := s.authorityProjection()
|
||||
authorityReady := p.FrontendPrimaryReady
|
||||
@@ -640,7 +628,6 @@ func (s *StatusServer) statusProjection() StatusProjection {
|
||||
p.FrontendPrimaryReady = p.FrontendPrimaryReady && !nvmePending
|
||||
src := s.durableSource
|
||||
masterWait := s.masterWait
|
||||
startupWait := s.startupWait
|
||||
s.mu.Unlock()
|
||||
// INV-FE-PRIMARY-READY-OPERATIONAL-001: not FrontendPrimaryReady while the
|
||||
// local backend admits no I/O (before the storage claim of a chunk volume,
|
||||
@@ -672,14 +659,8 @@ func (s *StatusServer) statusProjection() StatusProjection {
|
||||
if backendReason != "" || leaseNotHeld || profileRefusal != "" {
|
||||
p.FrontendPrimaryReady = false
|
||||
}
|
||||
waiting := startupWait != nil && startupWait()
|
||||
if waiting {
|
||||
p.FrontendPrimaryReady = false
|
||||
}
|
||||
if !p.FrontendPrimaryReady {
|
||||
switch {
|
||||
case waiting:
|
||||
p.NotReadyReason = NotReadyWaitingForMaster
|
||||
case profileRefusal != "":
|
||||
p.NotReadyReason = profileRefusal
|
||||
case leaseNotHeld:
|
||||
|
||||
@@ -547,8 +547,6 @@ Tests: `TestMaintenanceKickRunsAPassNow`, `TestMaintenanceKickedBusyPassRetriesS
|
||||
`TestDefaultConfigCleansAfterEachSnapshotDelete`. Detach/fence/Close cancels and joins before
|
||||
catalog/storage release; only a still-current handle may re-arm after safe abort.
|
||||
A pass has no total deadline. Its one-minute no-progress window renews only on a strict advance of this pass's finite (phase, cursor) work position; a stalled pass answers `no_progress`. Each remote request has a separate 30 s deadline; request attempts never renew the window. The existing cursor resumes later; retention failure skips cleaning.
|
||||
A scoped GC pass traces the whole catalog but mutates only its target volume,
|
||||
with a separate scope/config-bound mark. Incomplete marks carry no coverage.
|
||||
|
||||
The scheduled-snapshot worker runs beside it under the same owner and join, on
|
||||
in-process monotonic time: `Armed -> Due -> Running -> Armed`. A success sets the
|
||||
@@ -1038,7 +1036,7 @@ Notes:
|
||||
| `INV-WS-HEAD-KEY-PROVENANCE-001` | RETIRED at the cut-over to the content-named store: intents are gone and a content name may be written again. Replaced by `INV-SNAPK-COMMIT-REACH-001`. | M5 Manifest → CAS | — (`PrepareManifest` and `core/frontend/chunkstore/manifest.go` were deleted) | — | — | ARCHIVED |
|
||||
| `INV-WS-REOPEN-FENCE-001` | Retired: the legacy same-holder reopen replaced HEAD generation. B fences by claim id and local-root lineage (`INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-CLAIM-001`, `INV-SNAPK-STALE-HOLDER-001`); an ordinary same-root reopen may leave HEAD unchanged. | legacy M4 | — | — | — | ARCHIVED |
|
||||
| `INV-WS-SEALED-REOPEN-001` | A same-epoch Start cannot reactivate a detached HEAD: it refuses before another HEAD update or serving, preserving its current root, position and detached state for a higher-epoch claimant. | M9 detached → higher-epoch idle | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition` (`core/frontend/chunkstore/layout/detached_test.go`); `TestRestoreEqualOwnerDetachedHEADStaysSealed` (`core/frontend/durable/provider_seed_order_test.go`) | `INV-SNAPK-DETACHED-001` | ACTIVE |
|
||||
| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after a same-epoch detached restart, succeeds only from a fresh B HEAD with exact epoch, holder and local claim id. It returns that HEAD/frontier without a new generation. An unreadable or mismatched proof cannot be answered from process memory. | B detached HEAD read | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`, `readLayoutSeal`; `cmd/blockvolume/workspace_lease.go` `workspaceLayoutDetachedGeneration` | `TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory` (`core/frontend/durable/provider_layout_plain_replay_test.go`); `TestWorkspaceLayoutDetachedProof` (`cmd/blockvolume/workspace_layout_proof_test.go`) | K1: detached proof belongs to the exact claim | ACTIVE |
|
||||
| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after a same-epoch detached restart, succeeds only from a fresh B HEAD with exact epoch, holder and local claim id. It returns that HEAD/frontier without a new generation. An unreadable or mismatched proof cannot be answered from process memory. | B detached HEAD read | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`, `readLayoutSeal`; `cmd/blockvolume/workspace_lease.go` `workspaceLayoutDetachedGeneration` | `TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory` (`core/frontend/durable/provider_layout_plain_replay_test.go`); `TestWorkspaceLayoutDetachedProof` (`cmd/blockvolume/workspace_layout_proof_test.go`) | K1: detached proof belongs to the exact claim; `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` (mutants `PlainSealReplay_memory`, `PlainSealReplay_no_exact`, `PlainSealReplay_layer`) | ACTIVE |
|
||||
| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its session stays open; settlement replays the same commit in it. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/frontend/chunkstore/layout_remote.go` | `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestSession_UncertainCommitIsNotAbortedUntilSettled` (`core/storage/chunk_layer_session_test.go`); `TestLayoutRemote_LostReplyOfTheFirstCutIsNotAFence`, `TestLayoutRemote_LostReplyOfALaterCutWithAnInheritedChunkIsNotAFence`, `TestLayoutRemote_LostReplyOfANoOpCutIsNotAFence` (`core/frontend/chunkstore/layout_remote_same_proposal_test.go`); `TestLevelZeroCutRefusalDoesNotBecomeAnUnresolvedPublication` (`core/frontend/chunkstore/layout_format_refusal_test.go`); `TestARefusedReproposalDoesNotSettleAnEarlierUnknownWrite`, `TestARefusedConfirmationReadDoesNotUnpublishTheSuccessfulWrite` (`core/storage/chunk_head_refusal_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new B holder claims HEAD at its issued epoch only after the local root is validated against the HEAD it updates; an older epoch or another holder at the same epoch is refused, and guest writes stay closed until assignment and claim. | M9 Start → Claim → Serving | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/durable/provider_layout.go` `startLayoutRoot` | `TestStart_ValidatesAgainstTheHeadItUpdates`, `TestStart_Refusals` (`core/frontend/chunkstore/layout/start_test.go`); `TestStart_TheClaimRechecksTheSeedRule` (`core/frontend/chunkstore/layout/start_seed_test.go`); `TestFreshStoreRefusesWriteBeforeAssignmentThenPublishesAfterClaim` (`core/frontend/durable/provider_restore_schedule_test.go`) | `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-CLAIM-001` | ACTIVE |
|
||||
| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go`; `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal`; `core/frontend/chunkstore/layout/volume.go`, `start.go`, `create.go`; `core/frontend/chunkstore/catalog_b.go` | `TestGeometryFlagsRefusalComparesTheRecord`, `TestVolumeRequiresGeometry`, `TestVolumeGeometryChecksAndIsImmutable`, `TestStartGeometryMismatchPrecedesClaim`, `TestBCatalogRestoreCopiesVolumeGeometry`, `TestVolumeGeometryLivesOnlyInVolume` | K3: immutable required VOLUME geometry; Start checks the local persisted shape before claim; restores copy source geometry; no resize or compatibility path. | ACTIVE |
|
||||
@@ -1083,7 +1081,7 @@ Notes:
|
||||
| `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE |
|
||||
| `INV-ATTACH-ASSIGNMENT-BOUND-001` | Without a master wait, the assignment allowance is checked between attach attempts; it never cancels a granted attempt's manifest read. Per-fetch bounds, recovery progress and provider Close still apply. | M1 Recovering to Serving (wait scheduling only) | `DurableProvider.chunkAuthorityWait` | `TestDefaultAttachAt262144EntriesOutlivesAssignmentWait`, `TestDefaultGrantedAttachFailureEndsAtAssignmentAllowance` (`core/frontend/durable/default_attach_attempt_test.go`); `TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose` (`core/frontend/durable/provider_assignment_test.go`) | none (scheduling; authority guards unchanged) | ACTIVE |
|
||||
| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. Newer HEAD/store format: 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_startup.go` `ChunkStartupIdentityRefused`, `ChunkStartupNewerVersion`, `endChunkStartup`; `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`, `durableOpenFatalExit` | `TestANewerHeadVersionExits78NotRestartable`, `TestAStoreOfANewerFormatExits78` (`cmd/blockvolume/newer_version_exit_test.go`); `TestChunkStartupNewerVersionIsGenerationBound` (`core/frontend/durable/provider_startup_internal_test.go`); `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE |
|
||||
| `INV-WALSTORE-NO-EMPTY-STORE-001` | A plain walstore holder (single replica, or a replicated volume's line primary) creates its store only on the master's creating answer. Once its store is recorded, or its volume predates attestation, a missing store exits 78 store_lost; an unreadable record exits 75. Neither writes anything. | Holder startup, before the durable open | `cmd/blockvolume/store_admission.go` `decideStoreAdmission`; `cmd/blockvolume/main.go` `runVolume` (before `InitReplicaFloor`); `core/host/master/store_attestation.go` `GetReplicaStore`, `ReplicaStoreState`; `core/frontend/durable/provider.go` `openOrCreate` (`ErrLostStore`) | `TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost` (`cmd/blockvolume/rf1_store_lost_test.go`, process-level); `TestBlockvolumeAsksTheMasterBeforeCreatingItsStore` (`cmd/blockvolume/lost_store_exit_test.go`); `TestReadReplicaStoreWaitsOnlyWhileTheMasterGivesNoReply` (`cmd/blockvolume/store_record_wait_test.go`); `TestStoreAdmissionCreatesOnlyOnAnExplicitCreatingAnswer` (`cmd/blockvolume/store_admission_test.go`); `TestRF3WipedPrimaryRefusesAndASurvivorServesItsData` (`cmd/blockvolume/rf3_primary_store_lost_test.go`, process-level); `TestGetReplicaStoreAnswersFromTheMastersCreationFact` (`core/host/master/get_replica_store_test.go`); `TestGetReplicaStoreAnswersAReplicatedPrimaryFromItsOwnStore` (`core/host/master/primary_store_answer_test.go`); `TestAnEndedVolumeWithoutItsStoreRefusesAndCreatesNothing` (`core/frontend/durable/lost_store_test.go`) | MasterCreate NoEmptyHeadOverLineage projected onto the holder's local store (mutant RecreateWhenReady, here recreate_when_ended); CreateEvid2 creation fact; KnownZero (walstore has no HEAD to hydrate from). A replicated volume's non-primary replica keeps the peer rebuild: a fresh store has no durable LSN and is not the recorded store, so it never counts as a survivor or a promotion candidate | STUB |
|
||||
| `INV-WALSTORE-NO-EMPTY-STORE-001` | A plain walstore holder (single replica, or a replicated volume's line primary) creates its store only on the master's creating answer. Once its store is recorded, or its volume predates attestation, a missing store exits 78 store_lost; an unreadable record exits 75. Neither writes anything. | Holder startup, before the durable open | `cmd/blockvolume/store_admission.go` `decideStoreAdmission`; `cmd/blockvolume/main.go` `runVolume` (before `InitReplicaFloor`); `core/host/master/store_attestation.go` `GetReplicaStore`, `ReplicaStoreState`; `core/frontend/durable/provider.go` `openOrCreate` (`ErrLostStore`) | `TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost` (`cmd/blockvolume/rf1_store_lost_test.go`, process-level); `TestBlockvolumeAsksTheMasterBeforeCreatingItsStore` (`cmd/blockvolume/lost_store_exit_test.go`); `TestStoreAdmissionCreatesOnlyOnAnExplicitCreatingAnswer` (`cmd/blockvolume/store_admission_test.go`); `TestRF3WipedPrimaryRefusesAndASurvivorServesItsData` (`cmd/blockvolume/rf3_primary_store_lost_test.go`, process-level); `TestGetReplicaStoreAnswersFromTheMastersCreationFact` (`core/host/master/get_replica_store_test.go`); `TestGetReplicaStoreAnswersAReplicatedPrimaryFromItsOwnStore` (`core/host/master/primary_store_answer_test.go`); `TestAnEndedVolumeWithoutItsStoreRefusesAndCreatesNothing` (`core/frontend/durable/lost_store_test.go`) | MasterCreate NoEmptyHeadOverLineage projected onto the holder's local store (mutant RecreateWhenReady, here recreate_when_ended); CreateEvid2 creation fact; KnownZero (walstore has no HEAD to hydrate from). A replicated volume's non-primary replica keeps the peer rebuild: a fresh store has no durable LSN and is not the recorded store, so it never counts as a survivor or a promotion candidate | STUB |
|
||||
| `INV-WS-SERVE-AFTER-OWN-STORE-001` | A new volume's primary acknowledges no write until the master has recorded every initial replica's store, its own included (a single-replica volume waits for its own). So a replica's recorded store precedes every write it acknowledges. | Volume creation: stores awaited, then Serving | `core/host/master/store_attestation.go` `awaited`; `core/host/master/services.go` `assignmentFact`; `core/host/volume/workspace_startup.go` `ReplicaStoresAwaited`; `core/host/volume/projection_bridge.go` `replicaStoresAwaited` | `TestAnRF1PrimaryAwaitsItsOwnStoreBeforeServing` (`core/host/master/primary_store_answer_test.go`); `TestNewVolumeAssignmentWaitsForReplicaAttestations` (`core/host/master/store_record_wait_test.go`); `TestNewVolumePrimaryServesNothingBeforeReplicaAttestations` (`core/host/volume/replica_stores_wait_test.go`) | CreateEvid2: a recorded store may hold acknowledged data, which is what lets `INV-WALSTORE-NO-EMPTY-STORE-001` read a recorded store as creation ended | ACTIVE |
|
||||
| `INV-WS-MASTER-WAIT-001` | Startup waits without a bound while the master gives no reply or refuses credentials or identity; after contact it ends 30 s beyond the later of recovery's first reply or the master barrier. Typed MOVED or DELETED ends it with 78, including a confirmed moved source without an own assignment. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace.go` `WorkspaceSourceMoved`; `core/host/master/services.go` `SubscribeAssignments`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until just past the barrier time, jittered, at most 2 min; then a 200 ms poll for 5 s); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait`, `TestCredentialsRefusedForAnHourWaitsAndLogs`, `TestHeartbeatLogsTheMasterWait`, `TestFlappingMasterNeverExpiresEarly` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait`, `TestChunkAuthorityWaitPassesItsOwnStart`, `TestChunkGrantedAttachThatKeepsFailingIsBounded`, `TestChunkAuthorityWaitAttachesAGrantOnTheBoundsTick` (`core/frontend/durable/provider_master_wait_test.go`); `TestIdentityRefusalWaitsVisibly`, `TestChunkAuthorityWaitAfterASlowOpenGetsItsFullLimit`, `TestIdentityRefusalEndsAndDecays` (`core/host/volume/master_wait_test.go`); `TestIdentityRefusalEndsOnADeliveredAssignment` (`cmd/blockvolume/process_exit_authority_test.go`); `TestIdentityRefusalIsTyped` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestLeaseRefusalKinds`, `TestRenewalReplicaMismatchAtOlderLineEpochIsOther` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestChunkStartupExitFinalGives78`, `TestRestartedMovedSourceExits78WithoutAnOwnLine` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceSourceMovedProof`, `TestMovedSourceProofCallers`, `TestMasterWaitFinalSites`, `TestMovedAssignmentStreamIsFinalWithoutAnyOwnAssignment`; also in `core/authority/workspace_source_moved_test.go`, `core/host/master/workspace_moved_source_guard_test.go` | Real systemd moved-source and prestarted-target controls remain qualification gates. | ACTIVE |
|
||||
|
||||
@@ -1208,7 +1206,7 @@ Notes:
|
||||
| `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused for held host slots, pending urgent work or an earlier ticket is a wait, not a failure: no backoff or minimum spacing; it retries at the next poll in ticket order, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitEndsTheWait`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestCutPolicy_TicketOrderWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
|
||||
| `INV-SNAPSHOT-ANSWER-COUNT-001` | Newly produced snapshot creation and listing answers omit the uncomputed chunk count; no manifest scan is added to answer a snapshot. | M9 snapshot answer projection (no transition change) | `core/frontend/chunkstore/control_types.go`, `api.go`; `core/host/volume/chunk_control.go` | `TestSnapshotAfter200MiBWritesOmitsUncomputedChunkCount` (`core/host/volume/snapshot_chunk_count_test.go`) | NONE (pure projection of the published snapshot; no authority or persisted format change) | STUB |
|
||||
| `INV-SPEC-DELETE-RETIRE-001` | Retire spec-removed metadata only under a permanent reservation after no-live-lease and a subsequent HEAD read proves deleted or absent. Read errors, live HEAD and deleting HEAD keep the records. Retirement never removes the reservation or store data. | M4 delete retirement | `core/host/master/spec_retirement.go`; `core/authority/workspace_retirement.go`, `authority_store_file.go` | `TestSpecRetirementReadsHeadOnlyAfterLeaseAndKeepsTombstone`, `TestSpecRetirementRequiresDeletedOrAbsentAndReadableHead`, `TestSpecRetirementDoesNotUseAbsentHeadWithoutReservation`, `TestRetirementKeepsReservationAndWaitsForLiveLease`, `TestFileAuthorityRetirementSurvivesReloadAndKeepsOtherRecords`, `TestSpecRetirementBackgroundBoundsReadsAndCachesTerminalProof`, `TestSpecRetirementLocalFailureDoesNotStopOtherVolumesOrProductTick` | DeleteRetire.ReadOK; DeleteRetire.Retire; DeleteRetire.HostRetire | STUB |
|
||||
| `INV-SPEC-DELETE-RETIRE-001` | Retire spec-removed metadata only under a permanent reservation after no-live-lease and a subsequent HEAD read proves deleted or absent. Read errors, live HEAD and deleting HEAD keep the records. Retirement never removes the reservation or store data. | M4 delete retirement | `core/host/master/spec_retirement.go`; `core/authority/workspace_retirement.go`, `authority_store_file.go` | `TestSpecRetirementReadsHeadOnlyAfterLeaseAndKeepsTombstone`, `TestSpecRetirementRequiresDeletedOrAbsentAndReadableHead`, `TestSpecRetirementDoesNotUseAbsentHeadWithoutReservation`, `TestRetirementKeepsReservationAndWaitsForLiveLease`, `TestFileAuthorityRetirementSurvivesReloadAndKeepsOtherRecords`, `TestSpecRetirementBackgroundBoundsReadsAndCachesTerminalProof`, `TestSpecRetirementLocalFailureDoesNotStopOtherVolumesOrProductTick` | DeleteRetire.ReadOK; DeleteRetire.RetireLine; DeleteRetire.RetirePlace; DeleteRetire.HostRetire | STUB |
|
||||
| `INV-SPEC-DELETE-RETRY-001` | Startup lease barriers schedule one more retirement pass after the latest observed barrier, independently of the product loop. The pass rechecks every lease and HEAD guard, logs skipped volumes, and is cancelled and joined before stores close. | M4 delete retirement scheduling | `core/host/master/host.go` `Start`, `Close`; `spec_retirement.go` `startPostFloorRetirement` | `TestStandaloneRestartRetriesSpecRetirementAfterLeaseFloor`, `TestRetirementLeaseBarrierIsOnlyASchedulingHint`, `TestPostFloorRetirementTimerJoinsOnCancellation` | DeleteRetire.ReadOK; DeleteRetire.Retire | STUB |
|
||||
| `INV-SPEC-UNUSED-PLACEMENT-001` | A spec startup prunes an undesired placement only before serving and with no volume record, authority line, binding or deletion reservation, and no skipped authority recovery. The desired spec and seed are one keep set. | M4 registration input | `cmd/blockmaster/main.go`; `core/host/master/spec_retirement.go` | `TestClusterSpecImportRemovesUnusedPlacementMissingFromSpec`, `TestClusterSpecCleanupKeepsRecordsBindingsAuthorityAndSeed` | NONE (registration-only cleanup before controller activity) | STUB |
|
||||
| `INV-CHECK-DELETING-001` | A post-lease reserved volume with HEAD deleting, deleted or absent holds no serving work. Its status is informational and checks issue no lease or holder requests for it. Another volume's failures remain visible. | M9 delete observation | `core/host/master/observation_snapshot.go`, `journal_isolation.go`; `cmd/sw-block/shell_check.go` | `TestSpecRetirementRequiresDeletedOrAbsentAndReadableHead`, `TestSpecRetirementReadsHeadOnlyAfterLeaseAndKeepsTombstone`, `TestClusterCheckDoesNotProbeDeletingOrDeletedVolumes` | DeleteRetire.HostRetire | STUB |
|
||||
@@ -1529,7 +1527,7 @@ One row per wait in the data and control paths. Guest-visible rows on one path m
|
||||
|
||||
| Site | Waits for | Bound | Owner that ends it | On expiry | Lock held while waiting | Guest-visible |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `cmd/blockvolume/store_admission.go` `readReplicaStore` (from `runVolume`, before the durable open of a plain walstore holder) | the master's `GetReplicaStore` answer | none while blockmaster gives no reply (`volume.MasterCallClass`); each read `replicaStoreQueryTimeout` (10 s), reads `replicaStoreRetryEvery` (2 s) apart | the master's answer, or a signal (`processExit.parent`) | none: an answer goes to `decideStoreAdmission` (an unreadable record exits 75 `store_record_unreadable`), nothing written while waiting | none | no (no frontend has started) |
|
||||
| `cmd/blockvolume/main.go` `runVolume`, `Host.ReplicaStoreRecord` (one call before the durable open of a plain walstore holder) | the master's `GetReplicaStore` answer | `replicaStoreQueryTimeout` (10 s) | the call's own context | exit 75 `store_record_unreadable`, nothing written; the supervisor restarts the unit | none | no (no frontend has started) |
|
||||
| `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) |
|
||||
| `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (from `runVolume`, before any frontend starts) | the backend's first admitted I/O (`StorageBackend.FirstServing`), or the process's stop waiter returning | none of its own: it ends on the stop waiter, which INV-WS-STARTUP-RETRY-001 bounds (a refused or timed-out claim latches exit 75/78) | `runVolume` (`INV-FE-PRIMARY-READY-OPERATIONAL-001`) | no frontend starts; shutdown as after the frontends | none | no (no target listens yet) |
|
||||
| `cmd/blockvolume/frontend_gate.go` `firstAdmitted` (one goroutine from `runVolume`, workspace chunk primaries only) | the backend's first admitted I/O (`FirstServing`), then `AdmitsIO` passing, re-checked every 50 ms (the backend has no projection-change signal) | until first served or the process outcome (`e.done`), whichever comes first | the process exit owner (`superviseProcess`) through `e.done` | none: it ends without starting the frontends | none | no (no target listens yet) |
|
||||
|
||||
@@ -14,6 +14,38 @@ v1.1.1 is a fix release of the v1.1 line. None of its changes alters a stored fo
|
||||
- The `sw-block` commands that `mini` prints assume it is on `PATH`: in the extracted directory, run
|
||||
`export PATH="$PWD:$PATH"`. Its `weed shell` hint needs the full path of the `weed` binary given to `--weed`.
|
||||
|
||||
## Known issue: restarting blockmaster with many declared volumes
|
||||
|
||||
- **What happens:** when blockmaster restarts, it rewrites every declared volume's node and placement records to disk, one by one, before it answers again. With a few hundred declared volumes this can take longer than a running volume's lease. Running volumes then stop (`lease_expired`, exit 75), and the guest sees I/O errors on those volumes while they are stopped.
|
||||
- In our test with 999 declared volumes, blockmaster answered again after about 45 s; the 8 running volumes stopped 12–20 s after the restart.
|
||||
- With 33 declared volumes, nothing stopped.
|
||||
- No acknowledged data is lost.
|
||||
- **Recovery:** a stopped volume comes back only if it is supervised. The shipped systemd unit restarts a volume that exits 75; in our test the volumes were serving again within a minute. Otherwise, start the volume again yourself.
|
||||
- **Where it starts:** we estimate around 150 declared volumes; it depends on the disk under blockmaster's state directory.
|
||||
- **What to do:** restart blockmaster in a maintenance window if a cluster declares more than about 150 volumes. A fix is planned for v1.1.2; in our test with it, 999 volumes restarted in under 6 s including the stop, and no volume stopped.
|
||||
|
||||
## Known issue: blockmaster needs its filer to start
|
||||
|
||||
- blockmaster checks that its SeaweedFS filer answers before it starts. If the filer is unreachable, blockmaster stops with an error after about 60 s instead of starting.
|
||||
- While blockmaster cannot start, running volumes stop when their leases run out.
|
||||
- Start or fix the filer first, then start blockmaster.
|
||||
|
||||
## Known issue: `sw-block ops chunk detach --plain` waits for a scheduled periodic cut
|
||||
|
||||
- A scheduled periodic cut is not interrupted by `sw-block ops chunk detach --plain`. A detach issued while such a cut is capturing waits until the cut finishes, so on a volume with a long cut the detach takes correspondingly longer.
|
||||
- No data is lost. A fix is planned for a later v1.1.x release.
|
||||
|
||||
## Known issue: a walstore volume unit can reach its systemd start limit while blockmaster is unreachable
|
||||
|
||||
- Affects volumes on the walstore engine run by `sw-blockvolume.service`, `sw-blockvolume@.service` or `sw-blockvolume-ublk.service` (`StartLimitBurst=10` in 600 s, `RestartSec=5s`). Chunk-store volumes wait for blockmaster in process and are not affected.
|
||||
- A walstore volume that starts while blockmaster is unreachable exits with 75 after about 10 s and is restarted by systemd. After about 10 attempts (about 150 s) the unit stays failed, even once blockmaster is back.
|
||||
- No data is lost. Recover with `systemctl reset-failed <unit>`, then `systemctl start <unit>`. A fix is planned for v1.1.2.
|
||||
|
||||
## Known issue: startup retirement reads can delay blockmaster
|
||||
|
||||
- At startup blockmaster checks volumes that are reserved for deletion and hold no workspace lease, one at a time, before it serves. Each check reads the filer, so a slow filer delays the start: in our test, 100 such volumes with a 100 ms filer delay added about 20 s. Volumes in normal use are skipped without a read.
|
||||
- No data is lost. A fix is planned for v1.1.2.
|
||||
|
||||
## Upgrade notes
|
||||
|
||||
- **Order: the CLI first, then blockmaster, then each holder**, as in
|
||||
|
||||
@@ -103,7 +103,7 @@ cmd/sw-block/volume_release.go releaseLease context.WithTimeout 1 per-call NONE:
|
||||
cmd/sw-block/volume_release.go releaseLease context.WithTimeout 2 availability-contract NONE: no model row maps this file yet the wait for the recorded release: one lease validity plus slack, since the holder acknowledges at its next renewal within the lease
|
||||
cmd/sw-block/volume_release.go releaseLease time.After 1 control-timer NONE: no model row maps this file yet lease record poll during the release wait
|
||||
cmd/sw-block/volume_resolve.go runOpsVolume context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
|
||||
cmd/sw-block/volume_start_release.go prepareVolumeStart context.WithTimeout 1 availability-contract StopAndRestart.IssueClean; StopAndRestart.ReadClean; StopAndRestart.SameEpochReopen lease-query/clean-move setup (10 s), before enabling the unit; no volume data is processed
|
||||
cmd/sw-block/volume_start_release.go prepareVolumeStart context.WithTimeout 1 availability-contract StopAndRestart.IssueClean; StopAndRestart.ReadClean; StopAndRestart.CrashRestart lease-query/clean-move setup (10 s), before enabling the unit; no volume data is processed
|
||||
cmd/sw-block/volume_verbs.go runVolume http.Client.Timeout 1 per-call CutTime.Poll one HTTP request
|
||||
cmd/sw-block/volume_verbs.go volumeStart time.Now().Add 1 per-call CutTime.Poll volume start: the operator's --wait for it to serve
|
||||
cmd/sw-block/volume_verbs.go volumeStart time.After 1 control-timer CutTime.Poll volume start poll
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 49 and column 123.
|
@@ -86,19 +86,16 @@ type MasterOptions struct {
|
||||
// standalone weed master.
|
||||
shutdownCtx context.Context
|
||||
// releaseAllocOnFirstReport lifts the post-mint allocation hold as soon as
|
||||
// one full volume-server inventory has been applied. weed mini sets it in
|
||||
// single-master mode, with singleReporterAddr pinning the embedded volume
|
||||
// server as the only admitted reporter: any other volume server is refused,
|
||||
// so the warmup window after a fresh topology id is dead time.
|
||||
// Standalone weed master can face late-arriving veterans and must keep
|
||||
// the window; a single-master weed server releases on its embedded
|
||||
// volume server's clean report through expectedReporterAddr instead.
|
||||
// one full volume-server inventory has been applied, with
|
||||
// singleReporterAddr pinning the only admitted reporter: any other volume
|
||||
// server is refused, so the warmup window after a fresh topology id is
|
||||
// dead time.
|
||||
releaseAllocOnFirstReport bool
|
||||
singleReporterAddr string
|
||||
// expectedReporterAddr names the reporter whose first clean inventory
|
||||
// collapses the post-mint allocation hold to a confirm pulse without
|
||||
// refusing others: a single-master weed server points it at its
|
||||
// embedded volume server.
|
||||
// refusing others: a single-master weed server or weed mini points it at
|
||||
// its embedded volume server.
|
||||
expectedReporterAddr string
|
||||
}
|
||||
|
||||
|
||||
+16
-17
@@ -606,6 +606,20 @@ func miniMqBrokerAddress() string {
|
||||
return util.JoinHostPort(*miniIp, *miniMqBrokerOptions.port)
|
||||
}
|
||||
|
||||
// setMiniExpectedReporter mirrors a single-master weed server: the embedded
|
||||
// volume server's first clean inventory collapses the post-mint allocation
|
||||
// hold to a confirm pulse, while volume servers started later against this
|
||||
// master are still admitted. Multi-master minis keep the regular hold.
|
||||
// Re-derived on every run: the package-level options survive in-process
|
||||
// reruns, so a multi-master mini after a single-master one must not inherit
|
||||
// the expected reporter.
|
||||
func setMiniExpectedReporter() {
|
||||
miniMasterOptions.expectedReporterAddr = ""
|
||||
if isSingleMasterMode(*miniMasterOptions.peers) {
|
||||
miniMasterOptions.expectedReporterAddr = util.JoinHostPort(*miniIp, *miniOptions.v.port)
|
||||
}
|
||||
}
|
||||
|
||||
// initMiniWebDAVFlags initializes WebDAV server flag options
|
||||
func initMiniWebDAVFlags() {
|
||||
miniWebDavOptions.port = cmdMini.Flag.Int("webdav.port", 7333, "webdav server http listen port")
|
||||
@@ -1698,23 +1712,8 @@ func runMini(cmd *Command, args []string) bool {
|
||||
// tear those services down too. On Ctrl+C they rely on their own
|
||||
// OnInterrupt hooks (see grace's LIFO ordering).
|
||||
miniMasterOptions.shutdownCtx = MiniClusterCtx
|
||||
// In single-master mode mini's embedded volume server is the only reporter
|
||||
// of prior cluster state; its first heartbeat already carries the full
|
||||
// inventory, so the post-mint allocation hold ends there instead of
|
||||
// running the whole warmup window on every fresh start. The master pins
|
||||
// the embedded address and refuses any other volume server, keeping the
|
||||
// single-reporter assumption true. Multi-master minis can field
|
||||
// late-reporting volume servers and keep the regular hold.
|
||||
// Both fields are re-derived on every run: the package-level options
|
||||
// survive in-process reruns, so a multi-master mini after a
|
||||
// single-master one must not inherit the release or the stale pin.
|
||||
singleMaster := isSingleMasterMode(*miniMasterOptions.peers)
|
||||
miniMasterOptions.releaseAllocOnFirstReport = singleMaster
|
||||
miniMasterOptions.singleReporterAddr = ""
|
||||
miniFilerOptions.skipEmptyMembershipConfirm = singleMaster
|
||||
if singleMaster {
|
||||
miniMasterOptions.singleReporterAddr = util.JoinHostPort(*miniIp, *miniOptions.v.port)
|
||||
}
|
||||
setMiniExpectedReporter()
|
||||
miniFilerOptions.skipEmptyMembershipConfirm = isSingleMasterMode(*miniMasterOptions.peers)
|
||||
miniOptions.v.shutdownCtx = MiniClusterCtx
|
||||
miniFilerOptions.shutdownCtx = MiniClusterCtx
|
||||
// Mini is a small/dev setup with short-lived RPCs; cap the filer's
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package command
|
||||
|
||||
import "testing"
|
||||
|
||||
// A single-master mini names its embedded volume server only as the reporter
|
||||
// whose inventory lifts the post-mint hold; it must not pin it as the only
|
||||
// admitted one, or volume servers added to the mini are refused.
|
||||
func TestMiniSingleMasterAdmitsOutsideVolumeServers(t *testing.T) {
|
||||
oldPeers, oldIp, oldPort := *miniMasterOptions.peers, *miniIp, *miniOptions.v.port
|
||||
oldExpected := miniMasterOptions.expectedReporterAddr
|
||||
defer func() {
|
||||
*miniMasterOptions.peers, *miniIp, *miniOptions.v.port = oldPeers, oldIp, oldPort
|
||||
miniMasterOptions.expectedReporterAddr = oldExpected
|
||||
}()
|
||||
*miniIp, *miniOptions.v.port = "10.0.0.1", 8080
|
||||
|
||||
*miniMasterOptions.peers = "none"
|
||||
setMiniExpectedReporter()
|
||||
if miniMasterOptions.releaseAllocOnFirstReport || miniMasterOptions.singleReporterAddr != "" {
|
||||
t.Fatalf("single-master mini pins its embedded volume server: release=%v reporter=%q", miniMasterOptions.releaseAllocOnFirstReport, miniMasterOptions.singleReporterAddr)
|
||||
}
|
||||
if got := miniMasterOptions.expectedReporterAddr; got != "10.0.0.1:8080" {
|
||||
t.Fatalf("expected reporter = %q, want 10.0.0.1:8080", got)
|
||||
}
|
||||
|
||||
*miniMasterOptions.peers = "10.0.0.1:9333,10.0.0.2:9333,10.0.0.3:9333"
|
||||
setMiniExpectedReporter()
|
||||
if got := miniMasterOptions.expectedReporterAddr; got != "" {
|
||||
t.Fatalf("multi-master mini kept expected reporter %q", got)
|
||||
}
|
||||
}
|
||||
@@ -202,12 +202,10 @@ func (store *UniversalRedisStore) ListDirectoryEntries(ctx context.Context, dirP
|
||||
}
|
||||
break
|
||||
} else {
|
||||
if entry.TtlSec > 0 {
|
||||
if entry.Attr.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
|
||||
store.Client.Del(ctx, string(path)).Result()
|
||||
store.Client.SRem(ctx, dirListKey, fileName).Result()
|
||||
continue
|
||||
}
|
||||
if expiresAt, ok := entry.ExpiresAt(); ok && expiresAt.Before(time.Now()) {
|
||||
store.Client.Del(ctx, string(path)).Result()
|
||||
store.Client.SRem(ctx, dirListKey, fileName).Result()
|
||||
continue
|
||||
}
|
||||
|
||||
count++
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -329,3 +331,37 @@ func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) {
|
||||
t.Fatalf("listed %v, want [replaced]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A listing removes the entries it finds expired, so it has to judge them as
|
||||
// the filer does. An overwrite keeps an S3 object's Crtime and moves its mtime,
|
||||
// which its TTL counts from, and a directory never expires.
|
||||
func TestListDirectoryEntriesExpiresAnEntryAsTheFilerDoes(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
old, recent := time.Now().Add(-2*time.Hour), time.Now().Add(-time.Minute)
|
||||
s3Object := map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
|
||||
for _, entry := range []*filer.Entry{
|
||||
{FullPath: dir.Child("expired-file"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}},
|
||||
{FullPath: dir.Child("expired-object"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("overwritten-object"), Attr: filer.Attr{Crtime: old, Mtime: recent, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("subdir"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: os.ModeDir | 0755, TtlSec: 3600}},
|
||||
} {
|
||||
if err := store.InsertEntry(ctx, entry); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
names := listNames(t, store, dir)
|
||||
if len(names) != 2 || names[0] != "overwritten-object" || names[1] != "subdir" {
|
||||
t.Fatalf("listed %v, want [overwritten-object subdir]", names)
|
||||
}
|
||||
for name, kept := range map[string]bool{"expired-file": false, "expired-object": false, "overwritten-object": true, "subdir": true} {
|
||||
_, err := store.FindEntry(ctx, dir.Child(name))
|
||||
if kept && err != nil {
|
||||
t.Fatalf("%s is gone after the listing: %v", name, err)
|
||||
}
|
||||
if !kept && err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("%s after the listing: %v, want it removed", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -369,8 +369,10 @@ func (store *UniversalRedis2Store) existsOnMaster(ctx context.Context, key strin
|
||||
return runScript(ctx, store.Client, existsScript, existsScriptSHA1, []string{key}).Int64()
|
||||
}
|
||||
|
||||
// isLogicallyExpired applies the filer's own rule, since a listing removes what it finds expired.
|
||||
func isLogicallyExpired(entry *filer.Entry) bool {
|
||||
return entry.TtlSec > 0 && entry.Attr.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now())
|
||||
expiresAt, ok := entry.ExpiresAt()
|
||||
return ok && expiresAt.Before(time.Now())
|
||||
}
|
||||
|
||||
// deletes the value only when it still holds exactly the bytes the expiry decision was made on;
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -566,6 +567,40 @@ func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A listing removes the entries it finds expired, so it has to judge them as
|
||||
// the filer does. An overwrite keeps an S3 object's Crtime and moves its mtime,
|
||||
// which its TTL counts from, and a directory never expires.
|
||||
func TestListDirectoryEntriesExpiresAnEntryAsTheFilerDoes(t *testing.T) {
|
||||
store, dir := newTestStore(t, "")
|
||||
ctx := context.Background()
|
||||
old, recent := time.Now().Add(-2*time.Hour), time.Now().Add(-time.Minute)
|
||||
s3Object := map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
|
||||
for _, entry := range []*filer.Entry{
|
||||
{FullPath: dir.Child("expired-file"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}},
|
||||
{FullPath: dir.Child("expired-object"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("overwritten-object"), Attr: filer.Attr{Crtime: old, Mtime: recent, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("subdir"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: os.ModeDir | 0755, TtlSec: 3600}},
|
||||
} {
|
||||
if err := store.InsertEntry(ctx, entry); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
names := listNames(t, store, dir)
|
||||
if len(names) != 2 || names[0] != "overwritten-object" || names[1] != "subdir" {
|
||||
t.Fatalf("listed %v, want [overwritten-object subdir]", names)
|
||||
}
|
||||
for name, kept := range map[string]bool{"expired-file": false, "expired-object": false, "overwritten-object": true, "subdir": true} {
|
||||
_, err := store.FindEntry(ctx, dir.Child(name))
|
||||
if kept && err != nil {
|
||||
t.Fatalf("%s is gone after the listing: %v", name, err)
|
||||
}
|
||||
if !kept && err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("%s after the listing: %v, want it removed", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A lookup can miss an entry the master holds, on a lagging replica. Its list
|
||||
// is then not touched at all: removing the member and putting it back would
|
||||
// reset the score given to it here.
|
||||
|
||||
@@ -113,7 +113,10 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
}
|
||||
|
||||
// case 2.3
|
||||
x := nl.NodeInnerPosition(prevNodeReference, name)
|
||||
x, err := nl.NodeInnerPosition(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
y := nodeSize - x
|
||||
addToX := x <= y
|
||||
// add to a new node
|
||||
@@ -124,6 +127,12 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
return nil
|
||||
}
|
||||
if addToX {
|
||||
// current Y keeps the names after name and is keyed by the smallest of them,
|
||||
// read before anything is changed
|
||||
minName, err := nl.NodeMin(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// collect names before name, add them to X
|
||||
namesToX, err := nl.NodeRangeBeforeExclusive(prevNodeReference, name)
|
||||
if err != nil {
|
||||
@@ -144,7 +153,7 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
}
|
||||
|
||||
// point skip list to current Y
|
||||
if err := nl.ItemAdd(lookupKey, prevNodeReference.ElementPointer); err != nil {
|
||||
if err := nl.ItemAdd([]byte(minName), prevNodeReference.ElementPointer); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -170,7 +179,10 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
|
||||
// case 2.4
|
||||
if nextNode != nil {
|
||||
nodeSize := nl.NodeSize(nextNode.Reference())
|
||||
nodeSize, err := nl.NodeSize(nextNode.Reference())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if nodeSize < nl.batchSize {
|
||||
if id, err := nl.skipList.DeleteByKey(nextNode.Key); err != nil {
|
||||
return err
|
||||
@@ -245,7 +257,10 @@ func (nl *ItemList) DeleteName(name string) error {
|
||||
if err := nl.NodeDeleteMember(nextNode.Reference(), name); err != nil {
|
||||
return err
|
||||
}
|
||||
minName := nl.NodeMin(nextNode.Reference())
|
||||
minName, err := nl.NodeMin(nextNode.Reference(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if minName == "" {
|
||||
return nl.NodeDelete(nextNode.Reference())
|
||||
}
|
||||
@@ -271,22 +286,28 @@ func (nl *ItemList) DeleteName(name string) error {
|
||||
// case 2.1
|
||||
return nil
|
||||
}
|
||||
if !nl.NodeContainsItem(prevNode.Reference(), name) {
|
||||
return nil
|
||||
if contains, err := nl.NodeContainsItem(prevNode.Reference(), name); err != nil || !contains {
|
||||
return err
|
||||
}
|
||||
|
||||
// case 3
|
||||
if err := nl.NodeDeleteMember(prevNode.Reference(), name); err != nil {
|
||||
return err
|
||||
}
|
||||
prevSize := nl.NodeSize(prevNode.Reference())
|
||||
prevSize, err := nl.NodeSize(prevNode.Reference())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if prevSize == 0 {
|
||||
if _, err := nl.skipList.DeleteByKey(prevNode.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
nextSize := nl.NodeSize(nextNode.Reference())
|
||||
nextSize, err := nl.NodeSize(nextNode.Reference())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if nextSize > 0 && prevSize+nextSize < nl.batchSize {
|
||||
// case 3.1 merge nextNode and prevNode
|
||||
if _, err := nl.skipList.DeleteByKey(nextNode.Key); err != nil {
|
||||
@@ -315,6 +336,11 @@ func (nl *ItemList) ListNames(startFrom string, visitNamesFn func(name string) b
|
||||
}
|
||||
if found && bytes.Compare(nextNode.Key, lookupKey) == 0 {
|
||||
prevNode = nil
|
||||
} else if found {
|
||||
// the names from startFrom up to the next node's key are in the node before it
|
||||
if prevNode, err = nl.skipList.LoadElement(nextNode.Prev); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
prevNode, err = nl.skipList.GetLargestNode()
|
||||
@@ -342,6 +368,28 @@ func (nl *ItemList) ListNames(startFrom string, visitNamesFn func(name string) b
|
||||
return nil
|
||||
}
|
||||
|
||||
// ContainsName reports whether name is in the list, reading only the node that would hold it.
|
||||
func (nl *ItemList) ContainsName(name string) (bool, error) {
|
||||
lookupKey := []byte(name)
|
||||
_, nextNode, found, err := nl.skipList.FindGreaterOrEqual(lookupKey)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if found && bytes.Compare(nextNode.Key, lookupKey) == 0 {
|
||||
return true, nil
|
||||
}
|
||||
var node *skiplist.SkipListElement
|
||||
if found {
|
||||
node, err = nl.skipList.LoadElement(nextNode.Prev)
|
||||
} else {
|
||||
node, err = nl.skipList.GetLargestNode()
|
||||
}
|
||||
if err != nil || node == nil {
|
||||
return false, err
|
||||
}
|
||||
return nl.NodeContainsItem(node.Reference(), name)
|
||||
}
|
||||
|
||||
func (nl *ItemList) IsEmpty() bool {
|
||||
return nl.skipList.StartLevels[0] == nil
|
||||
}
|
||||
@@ -371,24 +419,22 @@ func (nl *ItemList) RemoteAllListElement() error {
|
||||
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeContainsItem(node *skiplist.SkipListElementReference, item string) bool {
|
||||
func (nl *ItemList) NodeContainsItem(node *skiplist.SkipListElementReference, item string) (bool, error) {
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
_, err := nl.client.ZScore(context.Background(), key, item).Result()
|
||||
if err == redis.Nil {
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeSize(node *skiplist.SkipListElementReference) int {
|
||||
func (nl *ItemList) NodeSize(node *skiplist.SkipListElementReference) (int, error) {
|
||||
if node == nil {
|
||||
return 0
|
||||
return 0, nil
|
||||
}
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
return int(nl.client.ZLexCount(context.Background(), key, "-", "+").Val())
|
||||
n, err := nl.client.ZLexCount(context.Background(), key, "-", "+").Result()
|
||||
return int(n), err
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeAddMember(node *skiplist.SkipListElementReference, names ...string) error {
|
||||
@@ -412,24 +458,25 @@ func (nl *ItemList) NodeDelete(node *skiplist.SkipListElementReference) error {
|
||||
return nl.client.Del(context.Background(), key).Err()
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeInnerPosition(node *skiplist.SkipListElementReference, name string) int {
|
||||
func (nl *ItemList) NodeInnerPosition(node *skiplist.SkipListElementReference, name string) (int, error) {
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
return int(nl.client.ZLexCount(context.Background(), key, "-", "("+name).Val())
|
||||
n, err := nl.client.ZLexCount(context.Background(), key, "-", "("+name).Result()
|
||||
return int(n), err
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeMin(node *skiplist.SkipListElementReference) string {
|
||||
// NodeMin returns the node's smallest name after the given one, or "" if there is none.
|
||||
func (nl *ItemList) NodeMin(node *skiplist.SkipListElementReference, after string) (string, error) {
|
||||
key := fmt.Sprintf("%s%dm", nl.prefix, node.ElementPointer)
|
||||
slice := nl.client.ZRangeByLex(context.Background(), key, &redis.ZRangeBy{
|
||||
Min: "-",
|
||||
slice, err := nl.client.ZRangeByLex(context.Background(), key, &redis.ZRangeBy{
|
||||
Min: "(" + after,
|
||||
Max: "+",
|
||||
Offset: 0,
|
||||
Count: 1,
|
||||
}).Val()
|
||||
if len(slice) > 0 {
|
||||
s := slice[0]
|
||||
return s
|
||||
}).Result()
|
||||
if err != nil || len(slice) == 0 {
|
||||
return "", err
|
||||
}
|
||||
return ""
|
||||
return slice[0], nil
|
||||
}
|
||||
|
||||
func (nl *ItemList) NodeScanInclusiveAfter(node *skiplist.SkipListElementReference, startFrom string, visitNamesFn func(name string) bool) bool {
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package redis3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// itemListOp runs fn on the directory list of dir with a small batch size, so
|
||||
// a few names already split it into several nodes, and saves what fn changed.
|
||||
func itemListOp(t *testing.T, store *UniversalRedis3Store, key string, fn func(nl *ItemList) error) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
data, err := store.Client.Get(ctx, key).Result()
|
||||
if err != nil && err != redis.Nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if err := fn(nl); err != nil {
|
||||
t.Fatalf("item list %s: %v", key, err)
|
||||
}
|
||||
if nl.HasChanges() {
|
||||
if err := store.Client.Set(ctx, key, nl.ToBytes(), 0).Err(); err != nil {
|
||||
t.Fatalf("set %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func itemListNames(t *testing.T, store *UniversalRedis3Store, key string, startFrom string) string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
itemListOp(t, store, key, func(nl *ItemList) error {
|
||||
return nl.ListNames(startFrom, func(name string) bool {
|
||||
names = append(names, name)
|
||||
return true
|
||||
})
|
||||
})
|
||||
return fmt.Sprint(names)
|
||||
}
|
||||
|
||||
// A full node [a c] splits on b into [a b] and [c]. The upper node has to be
|
||||
// keyed by c: keyed by b, deleting b found it there and left b listed.
|
||||
func TestItemListSplitKeysTheUpperNodeByItsSmallestName(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "c", "b"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.DeleteName("b") })
|
||||
if got := itemListNames(t, store, key, ""); got != "[a c]" {
|
||||
t.Fatalf("after deleting b: %s, want [a c]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// With nodes [a b] and [c], a listing from b starts inside the first node. A
|
||||
// paged listing resumes from the last name it returned, so it skipped what
|
||||
// that node held after it.
|
||||
func TestItemListListsFromInsideAnEarlierNode(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "b", "c"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
if got := itemListNames(t, store, key, "b"); got != "[b c]" {
|
||||
t.Fatalf("list from b: %s, want [b c]", got)
|
||||
}
|
||||
if got := itemListNames(t, store, key, "a0"); got != "[b c]" {
|
||||
t.Fatalf("list from a0: %s, want [b c]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestItemListContainsName(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
// nodes [b d] and [f]
|
||||
for _, name := range []string{"b", "d", "f"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
for name, want := range map[string]bool{"a": false, "b": true, "c": false, "d": true, "e": false, "f": true, "g": false} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error {
|
||||
got, err := nl.ContainsName(name)
|
||||
if err == nil && got != want {
|
||||
t.Errorf("ContainsName(%q) = %v, want %v", name, got, want)
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A failed read of the node that would hold a name is an error, not a missing name.
|
||||
func TestItemListContainsNameFailingARead(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"b", "d"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: "zscore"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if got, err := nl.ContainsName("d"); err == nil {
|
||||
t.Fatalf("ContainsName = %v, nil although reading the node failed", got)
|
||||
}
|
||||
failing.left.Store(1)
|
||||
if err := nl.DeleteName("d"); err == nil {
|
||||
t.Fatalf("DeleteName succeeded although reading the node failed")
|
||||
}
|
||||
}
|
||||
|
||||
// failingCommands lets the next skip commands of one name through, then fails
|
||||
// the next left of them before they reach redis.
|
||||
type failingCommands struct {
|
||||
name string
|
||||
skip atomic.Int32
|
||||
left atomic.Int32
|
||||
}
|
||||
|
||||
func (h *failingCommands) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h *failingCommands) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
|
||||
func (h *failingCommands) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
if cmd.Name() == h.name && h.skip.Add(-1) < 0 && h.left.Add(-1) >= 0 {
|
||||
err := errors.New("connection reset by peer")
|
||||
cmd.SetErr(err)
|
||||
return err
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
// afterCommand runs fn once, right after the first command of one name on key
|
||||
// has reached redis.
|
||||
type afterCommand struct {
|
||||
name string
|
||||
key string
|
||||
fn func()
|
||||
ran atomic.Bool
|
||||
}
|
||||
|
||||
func (h *afterCommand) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h *afterCommand) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
|
||||
func (h *afterCommand) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
err := next(ctx, cmd)
|
||||
if args := cmd.Args(); cmd.Name() == h.name && len(args) > 1 && args[1] == h.key && h.ran.CompareAndSwap(false, true) {
|
||||
h.fn()
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Deleting the name a node is keyed by reads the node's next smallest name to
|
||||
// key it by. A failed read must not pass for an emptied node, which is dropped
|
||||
// with the names it still holds.
|
||||
func TestItemListDeleteKeepsANodeItFailedToRead(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "b"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: "zrangebylex"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
node := nl.skipList.GetLargestNodeReference()
|
||||
if err := nl.DeleteName("a"); err == nil {
|
||||
t.Fatalf("DeleteName succeeded although reading the node failed")
|
||||
}
|
||||
if n, err := store.Client.ZCard(context.Background(), fmt.Sprintf("%s%dm", key, node.ElementPointer)).Result(); err != nil || n != 1 {
|
||||
t.Fatalf("node holds %d names (err %v), want b kept", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A split that fails to read the node it splits returns before it changes the
|
||||
// list, so the saved list still reaches every name.
|
||||
func TestItemListSplitFailingAReadKeepsEveryName(t *testing.T) {
|
||||
for _, command := range []string{"zrangebylex", "zlexcount"} {
|
||||
t.Run(command, func(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "c"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: command}
|
||||
store.Client.AddHook(failing)
|
||||
for skip := int32(0); ; skip++ {
|
||||
failing.skip.Store(skip)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if err := nl.WriteName("b"); err == nil {
|
||||
if err := store.Client.Set(context.Background(), key, nl.ToBytes(), 0).Err(); err != nil {
|
||||
t.Fatalf("set %s: %v", key, err)
|
||||
}
|
||||
break
|
||||
}
|
||||
if got := itemListNames(t, store, key, ""); got != "[a c]" {
|
||||
t.Fatalf("after failing read %d of the split, listed %s, want [a c]", skip+1, got)
|
||||
}
|
||||
}
|
||||
failing.left.Store(0)
|
||||
if got := itemListNames(t, store, key, ""); got != "[a b c]" {
|
||||
t.Fatalf("listed %s, want [a b c]", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Deleting a name counts the names left in its node. A failed count must not
|
||||
// pass for an emptied node, which is dropped with the names it still holds.
|
||||
func TestItemListDeleteKeepsANodeItFailedToCount(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
for _, name := range []string{"a", "b"} {
|
||||
itemListOp(t, store, key, func(nl *ItemList) error { return nl.WriteName(name) })
|
||||
}
|
||||
|
||||
failing := &failingCommands{name: "zlexcount"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.left.Store(1)
|
||||
data, err := store.Client.Get(context.Background(), key).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("get %s: %v", key, err)
|
||||
}
|
||||
nl := LoadItemList([]byte(data), key, store.Client, newSkipListElementStore(key, store.Client), 2)
|
||||
if err := nl.DeleteName("b"); err == nil {
|
||||
if err := store.Client.Set(context.Background(), key, nl.ToBytes(), 0).Err(); err != nil {
|
||||
t.Fatalf("set %s: %v", key, err)
|
||||
}
|
||||
t.Errorf("DeleteName succeeded although counting the node failed")
|
||||
}
|
||||
if got := itemListNames(t, store, key, ""); got != "[a]" {
|
||||
t.Fatalf("listed %s, want [a]", got)
|
||||
}
|
||||
}
|
||||
@@ -4,24 +4,34 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
redsync "github.com/go-redsync/redsync/v4"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const maxNameBatchSizeLimit = 1000000
|
||||
|
||||
func insertChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string) error {
|
||||
// insertChild adds name to the list at key. A non-nil write runs under the
|
||||
// list's lock once the name is listed, so no removeChild of the name runs
|
||||
// between the two.
|
||||
func insertChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string, write func() error) (err error) {
|
||||
|
||||
// lock and unlock
|
||||
mutex := redisStore.redsync.NewMutex(key + "lock")
|
||||
if err := mutex.Lock(); err != nil {
|
||||
return fmt.Errorf("lock %s: %v", key, err)
|
||||
}
|
||||
relist := false
|
||||
defer func() {
|
||||
mutex.Unlock()
|
||||
if !relist {
|
||||
mutex.Unlock()
|
||||
} else if relistErr := unlockOrRelist(ctx, redisStore, mutex, key, name); err == nil {
|
||||
err = relistErr
|
||||
}
|
||||
}()
|
||||
|
||||
client := redisStore.Client
|
||||
client := redisStore.onMaster()
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
@@ -31,32 +41,65 @@ func insertChild(ctx context.Context, redisStore *UniversalRedis3Store, key stri
|
||||
store := newSkipListElementStore(key, client)
|
||||
nameList := LoadItemList([]byte(data), key, client, store, maxNameBatchSizeLimit)
|
||||
|
||||
relist = true
|
||||
if err := nameList.WriteName(name); err != nil {
|
||||
glog.ErrorfCtx(ctx, "add %s %s: %v", key, name, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if !nameList.HasChanges() {
|
||||
return nil
|
||||
if nameList.HasChanges() {
|
||||
if err := client.Set(ctx, key, nameList.ToBytes(), 0).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := client.Set(ctx, key, nameList.ToBytes(), 0).Err(); err != nil {
|
||||
return err
|
||||
if write != nil {
|
||||
return write()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string) error {
|
||||
// unlockOrRelist releases mutex after a change to name's listing or value, or a
|
||||
// check of its value, made under it. If the lock's lease ran out first, another
|
||||
// filer may have changed the list in between and dropped name, so name is
|
||||
// listed again: the next listing removes a name without a value, but nothing
|
||||
// lists a value whose name is missing.
|
||||
func unlockOrRelist(ctx context.Context, redisStore *UniversalRedis3Store, mutex *redsync.Mutex, key string, name string) error {
|
||||
if held, err := mutex.Unlock(); held && err == nil {
|
||||
return nil
|
||||
}
|
||||
return util.Retry("relist "+key+" "+name, func() error {
|
||||
return insertChild(ctx, redisStore, key, name, nil)
|
||||
})
|
||||
}
|
||||
|
||||
// removeChild removes name from the list at key. A non-nil keep runs under the
|
||||
// list's lock, so no insertChild of the name runs during it, and a true from it
|
||||
// leaves the name in place.
|
||||
func removeChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string, keep func() (bool, error)) (err error) {
|
||||
|
||||
// lock and unlock
|
||||
mutex := redisStore.redsync.NewMutex(key + "lock")
|
||||
if err := mutex.Lock(); err != nil {
|
||||
return fmt.Errorf("lock %s: %v", key, err)
|
||||
}
|
||||
defer mutex.Unlock()
|
||||
relist := false
|
||||
defer func() {
|
||||
if !relist {
|
||||
mutex.Unlock()
|
||||
} else if relistErr := unlockOrRelist(ctx, redisStore, mutex, key, name); err == nil {
|
||||
err = relistErr
|
||||
}
|
||||
}()
|
||||
|
||||
client := redisStore.Client
|
||||
if keep != nil {
|
||||
if kept, err := keep(); err != nil || kept {
|
||||
return err
|
||||
}
|
||||
relist = true
|
||||
}
|
||||
|
||||
client := redisStore.onMaster()
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
@@ -101,7 +144,7 @@ func removeChildren(ctx context.Context, redisStore *UniversalRedis3Store, key s
|
||||
}
|
||||
defer mutex.Unlock()
|
||||
|
||||
client := redisStore.Client
|
||||
client := redisStore.onMaster()
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
@@ -129,6 +172,19 @@ func removeChildren(ctx context.Context, redisStore *UniversalRedis3Store, key s
|
||||
|
||||
}
|
||||
|
||||
func hasChild(ctx context.Context, redisStore *UniversalRedis3Store, key string, name string) (bool, error) {
|
||||
client := redisStore.Client
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
if err != redis.Nil {
|
||||
return false, fmt.Errorf("read %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
store := newSkipListElementStore(key, client)
|
||||
nameList := LoadItemList([]byte(data), key, client, store, maxNameBatchSizeLimit)
|
||||
return nameList.ContainsName(name)
|
||||
}
|
||||
|
||||
func listChildren(ctx context.Context, redisStore *UniversalRedis3Store, key string, startFileName string, eachFn func(name string) bool) error {
|
||||
client := redisStore.Client
|
||||
data, err := client.Get(ctx, key).Result()
|
||||
|
||||
@@ -59,6 +59,11 @@ func (store *RedisCluster3Store) initialize(addresses []string, username string,
|
||||
TLSConfig: tlsConfig,
|
||||
}
|
||||
settings.ApplyToCluster(options)
|
||||
if readOnly || routeByLatency {
|
||||
masterOptions := *options
|
||||
masterOptions.ReadOnly, masterOptions.RouteByLatency = false, false
|
||||
store.masterClient = redis.NewClusterClient(&masterOptions)
|
||||
}
|
||||
store.Client = redis.NewClusterClient(options)
|
||||
store.redsync = redsync.New(goredis.NewPool(store.Client))
|
||||
store.keyPrefix = keyPrefix
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package redis3
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer/redis_conf"
|
||||
)
|
||||
|
||||
func TestClusterStoreChangesListsOnMasters(t *testing.T) {
|
||||
for _, routing := range []struct{ readOnly, routeByLatency bool }{{true, false}, {false, true}} {
|
||||
store := &RedisCluster3Store{}
|
||||
if err := store.initialize([]string{"127.0.0.1:1"}, "", "", "", routing.readOnly, routing.routeByLatency, nil, redis_conf.Settings{}); err != nil {
|
||||
t.Fatalf("initialize %+v: %v", routing, err)
|
||||
}
|
||||
if !store.Client.(*redis.ClusterClient).Options().ReadOnly {
|
||||
t.Errorf("%+v: Client does not read from replicas", routing)
|
||||
}
|
||||
if options := store.onMaster().(*redis.ClusterClient).Options(); options.ReadOnly || options.RouteByLatency || options.RouteRandomly {
|
||||
t.Errorf("%+v: list changes read from replicas", routing)
|
||||
}
|
||||
store.Shutdown()
|
||||
}
|
||||
|
||||
store := &RedisCluster3Store{}
|
||||
if err := store.initialize([]string{"127.0.0.1:1"}, "", "", "", false, false, nil, redis_conf.Settings{}); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
if store.onMaster() != store.Client {
|
||||
t.Errorf("a second client without replica reads")
|
||||
}
|
||||
store.Shutdown()
|
||||
}
|
||||
@@ -19,9 +19,20 @@ const (
|
||||
)
|
||||
|
||||
type UniversalRedis3Store struct {
|
||||
Client redis.UniversalClient
|
||||
redsync *redsync.Redsync
|
||||
keyPrefix string
|
||||
Client redis.UniversalClient
|
||||
// set when Client reads from replicas
|
||||
masterClient redis.UniversalClient
|
||||
redsync *redsync.Redsync
|
||||
keyPrefix string
|
||||
}
|
||||
|
||||
// onMaster returns a client that reads every key from its master. A list change
|
||||
// decided on a lagging replica's read can drop names the master holds.
|
||||
func (store *UniversalRedis3Store) onMaster() redis.UniversalClient {
|
||||
if store.masterClient != nil {
|
||||
return store.masterClient
|
||||
}
|
||||
return store.Client
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) getKey(key string) string {
|
||||
@@ -49,6 +60,7 @@ func (store *UniversalRedis3Store) OverwritesAtOnce() bool {
|
||||
}
|
||||
|
||||
var _ filer.OverwritingStore = (*UniversalRedis3Store)(nil)
|
||||
var _ filer.ExpiredLeftoverStore = (*UniversalRedis3Store)(nil)
|
||||
|
||||
func (store *UniversalRedis3Store) BeginTransaction(ctx context.Context) (context.Context, error) {
|
||||
return ctx, nil
|
||||
@@ -69,7 +81,7 @@ func (store *UniversalRedis3Store) InsertEntry(ctx context.Context, entry *filer
|
||||
dir, name := entry.FullPath.DirAndName()
|
||||
|
||||
if name != "" {
|
||||
if err = insertChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name); err != nil {
|
||||
if err = insertChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name, nil); err != nil {
|
||||
return fmt.Errorf("persisting %s in parent dir: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
@@ -77,15 +89,23 @@ func (store *UniversalRedis3Store) InsertEntry(ctx context.Context, entry *filer
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) doInsertEntry(ctx context.Context, entry *filer.Entry) error {
|
||||
func encodeEntry(entry *filer.Entry) ([]byte, error) {
|
||||
value, err := entry.EncodeAttributesAndChunks()
|
||||
if err != nil {
|
||||
return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
|
||||
return nil, fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
|
||||
}
|
||||
|
||||
if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
|
||||
value = util.MaybeGzipData(value)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) doInsertEntry(ctx context.Context, entry *filer.Entry) error {
|
||||
value, err := encodeEntry(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = store.Client.Set(ctx, store.getKey(string(entry.FullPath)), value, time.Duration(entry.TtlSec)*time.Second).Err(); err != nil {
|
||||
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
||||
@@ -95,7 +115,29 @@ func (store *UniversalRedis3Store) doInsertEntry(ctx context.Context, entry *fil
|
||||
|
||||
func (store *UniversalRedis3Store) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
|
||||
|
||||
return store.doInsertEntry(ctx, entry)
|
||||
value, err := encodeEntry(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
updated, err := store.Client.SetXX(ctx, store.getKey(string(entry.FullPath)), value, time.Duration(entry.TtlSec)*time.Second).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
||||
}
|
||||
if updated {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The value expired since the caller read it, and a lookup or listing may
|
||||
// have taken its name out of the directory since. The name is listed before
|
||||
// the value is written back, under the lock such a removal takes, so a failure
|
||||
// leaves the value missing and a retry lists the name again.
|
||||
dir, name := entry.FullPath.DirAndName()
|
||||
if name == "" {
|
||||
return store.doInsertEntry(ctx, entry)
|
||||
}
|
||||
return insertChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name, func() error {
|
||||
return store.doInsertEntry(ctx, entry)
|
||||
})
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
|
||||
@@ -134,7 +176,7 @@ func (store *UniversalRedis3Store) DeleteEntry(ctx context.Context, fullpath uti
|
||||
dir, name := fullpath.DirAndName()
|
||||
|
||||
if name != "" {
|
||||
if err = removeChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name); err != nil {
|
||||
if err = removeChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name, nil); err != nil {
|
||||
return fmt.Errorf("DeleteEntry %s in parent dir: %v", fullpath, err)
|
||||
}
|
||||
}
|
||||
@@ -175,6 +217,14 @@ func (store *UniversalRedis3Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
dirListKey := store.getKey(genDirectoryListKey(string(dirPath)))
|
||||
counter := int64(0)
|
||||
|
||||
// removing a name restructures the list being walked, so wait for the walk to end
|
||||
var orphans []string
|
||||
defer func() {
|
||||
for _, fileName := range orphans {
|
||||
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
|
||||
}
|
||||
}()
|
||||
|
||||
var callbackErr error
|
||||
err = listChildren(ctx, store, dirListKey, startFileName, func(fileName string) bool {
|
||||
if startFileName != "" {
|
||||
@@ -189,15 +239,15 @@ func (store *UniversalRedis3Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
if err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "list %s : %v", path, err)
|
||||
if err == filer_pb.ErrNotFound {
|
||||
orphans = append(orphans, fileName)
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
if entry.TtlSec > 0 {
|
||||
if entry.Attr.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
|
||||
store.Client.Del(ctx, store.getKey(string(path))).Result()
|
||||
store.Client.ZRem(ctx, dirListKey, fileName).Result()
|
||||
return true
|
||||
if isLogicallyExpired(entry) {
|
||||
if store.deleteExpiredEntry(ctx, path) {
|
||||
orphans = append(orphans, fileName)
|
||||
}
|
||||
return true
|
||||
}
|
||||
counter++
|
||||
|
||||
@@ -229,10 +279,98 @@ func (store *UniversalRedis3Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
// RemoveExpiredLeftover removes the directory list member of an entry whose
|
||||
// value redis expired; a lookup of that entry has nothing else to find it by.
|
||||
func (store *UniversalRedis3Store) RemoveExpiredLeftover(ctx context.Context, fullpath util.FullPath) (removed bool, err error) {
|
||||
dir, name := fullpath.DirAndName()
|
||||
if name == "" {
|
||||
return false, nil
|
||||
}
|
||||
// Most misses are of a name that was never written: no member, nothing to do.
|
||||
if listed, err := hasChild(ctx, store, store.getKey(genDirectoryListKey(dir)), name); err != nil || !listed {
|
||||
return false, err
|
||||
}
|
||||
return store.removeOrphanedDirectoryListMember(ctx, util.FullPath(dir), name)
|
||||
}
|
||||
|
||||
// removeOrphanedDirectoryListMember reports whether it removed the member.
|
||||
func (store *UniversalRedis3Store) removeOrphanedDirectoryListMember(ctx context.Context, dirPath util.FullPath, fileName string) (removed bool, err error) {
|
||||
// survive the listing request being canceled mid-repair
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
path := util.NewFullPath(string(dirPath), fileName)
|
||||
|
||||
// InsertEntry writes the value before it takes the list's lock to add the
|
||||
// name, so a value absent under the lock belongs to no insert in progress.
|
||||
err = removeChild(ctx, store, store.getKey(genDirectoryListKey(string(dirPath))), fileName, func() (bool, error) {
|
||||
exists, err := store.existsOnMaster(ctx, store.getKey(string(path)))
|
||||
if err != nil || exists != 0 {
|
||||
return true, err
|
||||
}
|
||||
// an expired directory may still list children a recursive delete needs to reach
|
||||
children, err := store.existsOnMaster(ctx, store.getKey(genDirectoryListKey(string(path))))
|
||||
removed = err == nil && children == 0
|
||||
return !removed, err
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "remove orphaned %s in %s: %v", fileName, dirPath, err)
|
||||
return false, err
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
// existsOnMaster checks the key's master: a lagging replica can misread a live
|
||||
// value as absent.
|
||||
func (store *UniversalRedis3Store) existsOnMaster(ctx context.Context, key string) (int64, error) {
|
||||
return store.onMaster().Exists(ctx, key).Result()
|
||||
}
|
||||
|
||||
func isLogicallyExpired(entry *filer.Entry) bool {
|
||||
expiresAt, ok := entry.ExpiresAt()
|
||||
return ok && expiresAt.Before(time.Now())
|
||||
}
|
||||
|
||||
// deletes the value only when it still holds exactly the bytes the expiry decision was made on;
|
||||
// -1: already gone, 0: changed under us, 1: deleted
|
||||
const deleteIfUnchangedScript = `
|
||||
local v = redis.call('GET', KEYS[1])
|
||||
if v == false then
|
||||
return -1
|
||||
end
|
||||
if v == ARGV[1] then
|
||||
return redis.call('DEL', KEYS[1])
|
||||
end
|
||||
return 0`
|
||||
|
||||
// deleteExpiredEntry deletes the value of a logically expired entry unless a
|
||||
// concurrent insert recreated it, and reports whether the value is gone.
|
||||
func (store *UniversalRedis3Store) deleteExpiredEntry(ctx context.Context, path util.FullPath) (gone bool) {
|
||||
// survive the listing request being canceled mid-delete
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
valueKey := store.getKey(string(path))
|
||||
|
||||
// re-read so the delete can be conditioned on exactly the bytes checked
|
||||
data, err := store.Client.Get(ctx, valueKey).Bytes()
|
||||
if err == redis.Nil {
|
||||
return true
|
||||
}
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
entry := &filer.Entry{FullPath: path}
|
||||
if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil || !isLogicallyExpired(entry) {
|
||||
return false
|
||||
}
|
||||
deleted, err := store.Client.Eval(ctx, deleteIfUnchangedScript, []string{valueKey}, data).Int()
|
||||
return err == nil && deleted != 0
|
||||
}
|
||||
|
||||
func genDirectoryListKey(dir string) (dirList string) {
|
||||
return dir + DIR_LIST_MARKER
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) Shutdown() {
|
||||
store.Client.Close()
|
||||
if store.masterClient != nil {
|
||||
store.masterClient.Close()
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -231,3 +233,350 @@ func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) {
|
||||
t.Fatalf("listed %v, want [replaced]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A listing removes the entries it finds expired, so it has to judge them as
|
||||
// the filer does. An overwrite keeps an S3 object's Crtime and moves its mtime,
|
||||
// which its TTL counts from, and a directory never expires.
|
||||
func TestListDirectoryEntriesExpiresAnEntryAsTheFilerDoes(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
old, recent := time.Now().Add(-2*time.Hour), time.Now().Add(-time.Minute)
|
||||
s3Object := map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
|
||||
for _, entry := range []*filer.Entry{
|
||||
{FullPath: dir.Child("expired-file"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}},
|
||||
{FullPath: dir.Child("expired-object"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("overwritten-object"), Attr: filer.Attr{Crtime: old, Mtime: recent, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("subdir"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: os.ModeDir | 0755, TtlSec: 3600}},
|
||||
} {
|
||||
if err := store.InsertEntry(ctx, entry); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
names := listNames(t, store, dir)
|
||||
if len(names) != 2 || names[0] != "overwritten-object" || names[1] != "subdir" {
|
||||
t.Fatalf("listed %v, want [overwritten-object subdir]", names)
|
||||
}
|
||||
for name, kept := range map[string]bool{"expired-file": false, "expired-object": false, "overwritten-object": true, "subdir": true} {
|
||||
_, err := store.FindEntry(ctx, dir.Child(name))
|
||||
if kept && err != nil {
|
||||
t.Fatalf("%s is gone after the listing: %v", name, err)
|
||||
}
|
||||
if !kept && err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("%s after the listing: %v, want it removed", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func insertTestEntry(t *testing.T, store *UniversalRedis3Store, path util.FullPath, crtime time.Time, ttlSec int32) {
|
||||
t.Helper()
|
||||
if err := store.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: crtime, Mtime: crtime, Mode: 0644, TtlSec: ttlSec},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func listingKeyExists(t *testing.T, store *UniversalRedis3Store, dir util.FullPath) bool {
|
||||
t.Helper()
|
||||
n, err := store.Client.Exists(context.Background(), store.getKey(genDirectoryListKey(string(dir)))).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("exists %s: %v", dir, err)
|
||||
}
|
||||
return n != 0
|
||||
}
|
||||
|
||||
// A listing that meets the name of an entry redis expired, or of one past its
|
||||
// TTL, takes the name out of the directory's list.
|
||||
func TestListingRemovesExpiredNames(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
|
||||
insertTestEntry(t, store, dir.Child("evicted"), now, 3600)
|
||||
insertTestEntry(t, store, dir.Child("expired"), now.Add(-2*time.Hour), 3600)
|
||||
insertTestEntry(t, store, dir.Child("live"), now, 0)
|
||||
// what redis does once the TTL passes
|
||||
if err := store.Client.Del(ctx, store.getKey(string(dir.Child("evicted")))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "live" {
|
||||
t.Fatalf("listed %v, want [live]", names)
|
||||
}
|
||||
if n, err := store.Client.Exists(ctx, store.getKey(string(dir.Child("expired")))).Result(); err != nil || n != 0 {
|
||||
t.Fatalf("expired value still stored: n=%d err=%v", n, err)
|
||||
}
|
||||
|
||||
if err := store.DeleteEntry(ctx, dir.Child("live")); err != nil {
|
||||
t.Fatalf("DeleteEntry: %v", err)
|
||||
}
|
||||
if listingKeyExists(t, store, dir) {
|
||||
t.Fatalf("listing key left behind by the expired names")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveExpiredLeftover(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("never")); err != nil || removed {
|
||||
t.Fatalf("never written: removed=%v err=%v", removed, err)
|
||||
}
|
||||
|
||||
insertTestEntry(t, store, dir.Child("live"), now, 0)
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("live")); err != nil || removed {
|
||||
t.Fatalf("live: removed=%v err=%v", removed, err)
|
||||
}
|
||||
|
||||
// an expired directory whose children are still listed keeps its name
|
||||
insertTestEntry(t, store, dir.Child("subdir"), now, 3600)
|
||||
insertTestEntry(t, store, dir.Child("subdir").Child("child"), now, 0)
|
||||
insertTestEntry(t, store, dir.Child("evicted"), now, 3600)
|
||||
for _, p := range []util.FullPath{dir.Child("subdir"), dir.Child("evicted")} {
|
||||
if err := store.Client.Del(ctx, store.getKey(string(p))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("subdir")); err != nil || removed {
|
||||
t.Fatalf("subdir with children: removed=%v err=%v", removed, err)
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, dir.Child("evicted")); err != nil || !removed {
|
||||
t.Fatalf("evicted: removed=%v err=%v", removed, err)
|
||||
}
|
||||
|
||||
var names []string
|
||||
if err := listChildren(ctx, store, store.getKey(genDirectoryListKey(string(dir))), "", func(name string) bool {
|
||||
names = append(names, name)
|
||||
return true
|
||||
}); err != nil {
|
||||
t.Fatalf("listChildren: %v", err)
|
||||
}
|
||||
if fmt.Sprint(names) != "[live subdir]" {
|
||||
t.Fatalf("directory list holds %v, want [live subdir]", names)
|
||||
}
|
||||
|
||||
if err := store.DeleteFolderChildren(ctx, dir.Child("subdir")); err != nil {
|
||||
t.Fatalf("DeleteFolderChildren: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// An update that finds the value expired writes it again, and has to list the
|
||||
// name again too: the cleanup of the expired value may have taken it out.
|
||||
func TestUpdateEntryOfAnExpiredValueListsItAgain(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
path := dir.Child("updated")
|
||||
insertTestEntry(t, store, path, now, 3600)
|
||||
if err := store.Client.Del(ctx, store.getKey(string(path))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, path); err != nil || !removed {
|
||||
t.Fatalf("RemoveExpiredLeftover = %v, %v", removed, err)
|
||||
}
|
||||
|
||||
if err := store.UpdateEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644, TtlSec: 7200},
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateEntry: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
if ttl, err := store.Client.TTL(ctx, store.getKey(string(path))).Result(); err != nil || ttl <= time.Hour || ttl > 2*time.Hour {
|
||||
t.Fatalf("TTL = %v, %v; want the update's 2h", ttl, err)
|
||||
}
|
||||
}
|
||||
|
||||
// An update that finds the value expired lists the name before it writes the
|
||||
// value back. Failing to list it leaves the value missing, so a retry lists it.
|
||||
func TestUpdateEntryFailingToListTheNameRetries(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
path := dir.Child("updated")
|
||||
insertTestEntry(t, store, path, now, 3600)
|
||||
if err := store.Client.Del(ctx, store.getKey(string(path))).Err(); err != nil {
|
||||
t.Fatalf("del: %v", err)
|
||||
}
|
||||
if removed, err := store.RemoveExpiredLeftover(ctx, path); err != nil || !removed {
|
||||
t.Fatalf("RemoveExpiredLeftover = %v, %v", removed, err)
|
||||
}
|
||||
|
||||
update := &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644, TtlSec: 7200},
|
||||
}
|
||||
// let the update's SET XX through, then fail the SET NX that takes the list lock
|
||||
failing := &failingCommands{name: "set"}
|
||||
store.Client.AddHook(failing)
|
||||
failing.skip.Store(1)
|
||||
failing.left.Store(1 << 20)
|
||||
if err := store.UpdateEntry(ctx, update); err == nil {
|
||||
t.Fatalf("UpdateEntry succeeded although the list lock failed")
|
||||
}
|
||||
failing.left.Store(0)
|
||||
if n, err := store.Client.Exists(ctx, store.getKey(string(path))).Result(); err != nil || n != 0 {
|
||||
t.Fatalf("value exists = %d, %v; want it left missing", n, err)
|
||||
}
|
||||
|
||||
if err := store.UpdateEntry(ctx, update); err != nil {
|
||||
t.Fatalf("UpdateEntry retry: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A write under the list lock can outlast the lock's lease, so another filer's
|
||||
// cleanup can remove the name before the value lands. The lost lease shows at
|
||||
// unlock, and the name is listed again.
|
||||
func TestInsertChildListsTheNameAgainAfterTheLeaseRanOut(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
path := dir.Child("updated")
|
||||
|
||||
if err := insertChild(ctx, store, key, "updated", func() error {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if removed, err := store.removeOrphanedDirectoryListMember(ctx, dir, "updated"); err != nil || !removed {
|
||||
return fmt.Errorf("cleanup removed = %v, %v", removed, err)
|
||||
}
|
||||
return store.doInsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A cleanup that found no value can outlast the list lock's lease, so another
|
||||
// filer can list the name and write its value before the cleanup removes the
|
||||
// name. The lost lease shows at unlock, and the name is listed again.
|
||||
func TestCleanupListsTheNameAgainAfterTheLeaseRanOut(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
path := dir.Child("updated")
|
||||
if err := insertChild(ctx, store, key, "updated", nil); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
|
||||
if err := removeChild(ctx, store, key, "updated", func() (bool, error) {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
return false, store.UpdateEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatalf("removeChild: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A cleanup can lose its lease and then fail partway through removing the
|
||||
// name, after the name is already gone. The name is listed again all the same.
|
||||
func TestCleanupFailingAfterTheLeaseRanOutListsTheNameAgain(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
insertTestEntry(t, store, dir.Child("a"), now, 0)
|
||||
if err := insertChild(ctx, store, key, "b", nil); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
|
||||
// fail the node size read that follows the removal of b from its node
|
||||
failing := &failingCommands{name: "zlexcount"}
|
||||
store.Client.AddHook(failing)
|
||||
if err := removeChild(ctx, store, key, "b", func() (bool, error) {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
if err := store.UpdateEntry(ctx, &filer.Entry{
|
||||
FullPath: dir.Child("b"),
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
}); err != nil {
|
||||
return true, err
|
||||
}
|
||||
failing.left.Store(1)
|
||||
return false, nil
|
||||
}); err == nil {
|
||||
t.Fatalf("removeChild succeeded although reading the node failed")
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 2 || names[0] != "a" || names[1] != "b" {
|
||||
t.Fatalf("listed %v, want [a b]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// Listing the name again after a lost lease is the only thing that lists a
|
||||
// value written in between, so a failed attempt is retried.
|
||||
func TestRelistingAfterTheLeaseRanOutRetries(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
path := dir.Child("updated")
|
||||
|
||||
// fail the list read of the first attempt to list the name again
|
||||
failing := &failingCommands{name: "get"}
|
||||
store.Client.AddHook(failing)
|
||||
if err := insertChild(ctx, store, key, "updated", func() error {
|
||||
if err := store.Client.Del(ctx, key+"lock").Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if removed, err := store.removeOrphanedDirectoryListMember(ctx, dir, "updated"); err != nil || !removed {
|
||||
return fmt.Errorf("cleanup removed = %v, %v", removed, err)
|
||||
}
|
||||
if err := store.doInsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
failing.left.Store(1)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("insertChild: %v", err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "updated" {
|
||||
t.Fatalf("listed %v, want [updated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
// A list change can outlast the list lock's lease, and another filer's change
|
||||
// based on an earlier read of the list can then drop the name. The lost lease
|
||||
// shows at unlock, and the name is listed again.
|
||||
func TestInsertEntryListsTheNameAgainAfterItsListChangeWasLost(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
key := store.getKey(genDirectoryListKey(string(dir)))
|
||||
|
||||
// after the list write, the lock is gone and another filer, which read the
|
||||
// list before that write, removes the list's last name and with it the list
|
||||
store.Client.AddHook(&afterCommand{name: "set", key: key, fn: func() {
|
||||
if err := store.Client.Del(ctx, key+"lock", key).Err(); err != nil {
|
||||
t.Errorf("del: %v", err)
|
||||
}
|
||||
}})
|
||||
insertTestEntry(t, store, dir.Child("a"), time.Now(), 0)
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "a" {
|
||||
t.Fatalf("listed %v, want [a]", names)
|
||||
}
|
||||
}
|
||||
@@ -27,8 +27,7 @@ func (t *TTLFilter) Filter(level int, key, val []byte) (remove bool, newVal []by
|
||||
if !t.skipLevel0 || level > 0 {
|
||||
entry := filer.Entry{}
|
||||
if err := entry.DecodeAttributesAndChunks(val); err == nil {
|
||||
if entry.TtlSec > 0 &&
|
||||
entry.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now()) {
|
||||
if expiresAt, ok := entry.ExpiresAt(); ok && expiresAt.Before(time.Now()) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,8 +181,10 @@ func (store *TikvStore) deleteExpiredEntry(ctx context.Context, path util.FullPa
|
||||
})
|
||||
}
|
||||
|
||||
// isLogicallyExpired applies the filer's own rule, since a listing removes what it finds expired.
|
||||
func isLogicallyExpired(entry *filer.Entry) bool {
|
||||
return entry.TtlSec > 0 && entry.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now())
|
||||
expiresAt, ok := entry.ExpiresAt()
|
||||
return ok && expiresAt.Before(time.Now())
|
||||
}
|
||||
|
||||
// ~ Entry APIs
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//go:build tikv
|
||||
|
||||
package tikv
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// A listing removes the entries it finds expired, so it has to judge them as
|
||||
// the filer does. An overwrite keeps an S3 object's Crtime and moves its mtime,
|
||||
// which its TTL counts from, and a directory never expires.
|
||||
func TestListingExpiresAnEntryAsTheFilerDoes(t *testing.T) {
|
||||
store, _ := newStoreWithUnreachableReads(t)
|
||||
dir := util.FullPath("/buckets/cam/day1")
|
||||
ctx := context.Background()
|
||||
old, recent := time.Now().Add(-2*time.Hour), time.Now().Add(-time.Minute)
|
||||
s3Object := map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
|
||||
for _, entry := range []*filer.Entry{
|
||||
{FullPath: dir.Child("expired-file"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}},
|
||||
{FullPath: dir.Child("expired-object"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("overwritten-object"), Attr: filer.Attr{Crtime: old, Mtime: recent, Mode: 0644, TtlSec: 3600}, Extended: s3Object},
|
||||
{FullPath: dir.Child("subdir"), Attr: filer.Attr{Crtime: old, Mtime: old, Mode: os.ModeDir | 0755, TtlSec: 3600}},
|
||||
} {
|
||||
if err := store.InsertEntry(ctx, entry); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", entry.FullPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
var names []string
|
||||
if _, err := store.ListDirectoryEntries(ctx, dir, "", true, 100, func(entry *filer.Entry) (bool, error) {
|
||||
names = append(names, entry.Name())
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
t.Fatalf("ListDirectoryEntries: %v", err)
|
||||
}
|
||||
if len(names) != 2 || names[0] != "overwritten-object" || names[1] != "subdir" {
|
||||
t.Fatalf("listed %v, want [overwritten-object subdir]", names)
|
||||
}
|
||||
for name, kept := range map[string]bool{"expired-file": false, "expired-object": false, "overwritten-object": true, "subdir": true} {
|
||||
_, err := store.FindEntry(ctx, dir.Child(name))
|
||||
if kept && err != nil {
|
||||
t.Fatalf("%s is gone after the listing: %v", name, err)
|
||||
}
|
||||
if !kept && err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("%s after the listing: %v, want it removed", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1981,21 +1981,35 @@ func (iam *IdentityAccessManagement) AuthenticateRequest(r *http.Request) (*Iden
|
||||
return ident, err
|
||||
}
|
||||
|
||||
// internalHeaders are canonicalized once: several are not in canonical form,
|
||||
// and Header.Del would canonicalize them again on every request.
|
||||
var internalHeaders = func() []string {
|
||||
keys := []string{
|
||||
s3_constants.SeaweedFSPrincipalHeader,
|
||||
s3_constants.SeaweedFSSessionTokenHeader,
|
||||
s3_constants.ExtObjectLockModeKey,
|
||||
s3_constants.ExtRetentionUntilDateKey,
|
||||
s3_constants.ExtLegalHoldKey,
|
||||
s3_constants.ExtVersionIdKey,
|
||||
s3_constants.SeaweedFSSSEKMSBaseIVHeader,
|
||||
s3_constants.SeaweedFSSSES3BaseIVHeader,
|
||||
s3_constants.SeaweedFSSSES3KeyDataHeader,
|
||||
}
|
||||
for i, key := range keys {
|
||||
keys[i] = http.CanonicalHeaderKey(key)
|
||||
}
|
||||
return keys
|
||||
}()
|
||||
|
||||
// scrubInternalHeaders drops internal headers only the server may set, so
|
||||
// client-supplied values cannot spoof identity claims or reach the handlers'
|
||||
// internal consumers (putToFiler persists the object-lock and version-id ones
|
||||
// into authoritative metadata; the SSE ones carry key material between handler
|
||||
// stages of a request). The server sets them itself after this point.
|
||||
func scrubInternalHeaders(r *http.Request) {
|
||||
r.Header.Del(s3_constants.SeaweedFSPrincipalHeader)
|
||||
r.Header.Del(s3_constants.SeaweedFSSessionTokenHeader)
|
||||
r.Header.Del(s3_constants.ExtObjectLockModeKey)
|
||||
r.Header.Del(s3_constants.ExtRetentionUntilDateKey)
|
||||
r.Header.Del(s3_constants.ExtLegalHoldKey)
|
||||
r.Header.Del(s3_constants.ExtVersionIdKey)
|
||||
r.Header.Del(s3_constants.SeaweedFSSSEKMSBaseIVHeader)
|
||||
r.Header.Del(s3_constants.SeaweedFSSSES3BaseIVHeader)
|
||||
r.Header.Del(s3_constants.SeaweedFSSSES3KeyDataHeader)
|
||||
for _, key := range internalHeaders {
|
||||
delete(r.Header, key)
|
||||
}
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) authenticateRequestInternal(r *http.Request) (*Identity, s3err.ErrorCode, authType) {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
func TestScrubInternalHeadersDropsClientValues(t *testing.T) {
|
||||
keys := []string{
|
||||
s3_constants.SeaweedFSPrincipalHeader,
|
||||
s3_constants.SeaweedFSSessionTokenHeader,
|
||||
s3_constants.ExtObjectLockModeKey,
|
||||
s3_constants.ExtRetentionUntilDateKey,
|
||||
s3_constants.ExtLegalHoldKey,
|
||||
s3_constants.ExtVersionIdKey,
|
||||
s3_constants.SeaweedFSSSEKMSBaseIVHeader,
|
||||
s3_constants.SeaweedFSSSES3BaseIVHeader,
|
||||
s3_constants.SeaweedFSSSES3KeyDataHeader,
|
||||
}
|
||||
r, _ := http.NewRequest(http.MethodPut, "http://localhost/b/k", nil)
|
||||
for _, key := range keys {
|
||||
r.Header.Set(key, "client")
|
||||
}
|
||||
r.Header.Set("X-Amz-Date", "20261205T000000Z")
|
||||
scrubInternalHeaders(r)
|
||||
for _, key := range keys {
|
||||
if got := r.Header.Get(key); got != "" {
|
||||
t.Errorf("%s kept %q", key, got)
|
||||
}
|
||||
}
|
||||
if r.Header.Get("X-Amz-Date") == "" {
|
||||
t.Error("scrub dropped a client header")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkScrubInternalHeaders(b *testing.B) {
|
||||
r, _ := http.NewRequest(http.MethodPut, "http://localhost/b/k", nil)
|
||||
r.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=x")
|
||||
r.Header.Set("X-Amz-Date", "20261205T000000Z")
|
||||
r.Header.Set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD")
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
scrubInternalHeaders(r)
|
||||
}
|
||||
}
|
||||
@@ -417,24 +417,20 @@ func snapshotExtended(extended map[string][]byte, keys ...string) map[string][]b
|
||||
|
||||
// getExtendedAttribute gets an extended attribute from an entry
|
||||
func (h *S3TablesHandler) getExtendedAttribute(ctx context.Context, client filer_pb.SeaweedFilerClient, path, key string) ([]byte, error) {
|
||||
dir, name := splitPath(path)
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir,
|
||||
Name: name,
|
||||
})
|
||||
entry, err := h.lookupEntry(ctx, client, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return extendedAttr(entry, key)
|
||||
}
|
||||
|
||||
if resp.Entry.Extended == nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrAttributeNotFound, key)
|
||||
}
|
||||
|
||||
data, ok := resp.Entry.Extended[key]
|
||||
// extendedAttr is getExtendedAttribute on an entry already looked up, so a
|
||||
// caller needing several attributes of one entry reads it once.
|
||||
func extendedAttr(entry *filer_pb.Entry, key string) ([]byte, error) {
|
||||
data, ok := entry.Extended[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: %s", ErrAttributeNotFound, key)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -631,13 +631,19 @@ func (h *S3TablesHandler) authorizeAbsentTarget(r *http.Request, filerClient Fil
|
||||
}
|
||||
|
||||
func (h *S3TablesHandler) readTags(ctx context.Context, client filer_pb.SeaweedFilerClient, path string) (map[string]string, error) {
|
||||
data, err := h.getExtendedAttribute(ctx, client, path, ExtendedKeyTags)
|
||||
entry, err := h.lookupEntry(ctx, client, path)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrAttributeNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return tagsFromEntry(entry)
|
||||
}
|
||||
|
||||
// tagsFromEntry is readTags on an entry already looked up.
|
||||
func tagsFromEntry(entry *filer_pb.Entry) (map[string]string, error) {
|
||||
data, err := extendedAttr(entry, ExtendedKeyTags)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
tags := make(map[string]string)
|
||||
if err := json.Unmarshal(data, &tags); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal tags: %w", err)
|
||||
|
||||
@@ -35,13 +35,31 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re
|
||||
return err
|
||||
}
|
||||
|
||||
resp, _, err := h.getTableBucket(w, r, filerClient, bucketName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.writeJSON(w, http.StatusOK, resp)
|
||||
return nil
|
||||
}
|
||||
|
||||
// getTableBucket reads a table bucket's record and checks the caller may get
|
||||
// it, answering a failure on w as GetTableBucket does. It looks the bucket up
|
||||
// once and returns that entry too, for a caller that needs more of its
|
||||
// attributes than the record holds.
|
||||
func (h *S3TablesHandler) getTableBucket(w http.ResponseWriter, r *http.Request, filerClient FilerClient, bucketName string) (*GetTableBucketResponse, *filer_pb.Entry, error) {
|
||||
bucketPath := GetTableBucketPath(bucketName)
|
||||
|
||||
var entry *filer_pb.Entry
|
||||
var metadata tableBucketMetadata
|
||||
var bucketPolicy string
|
||||
var bucketTags map[string]string
|
||||
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
data, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata)
|
||||
err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var err error
|
||||
if entry, err = h.lookupEntry(r.Context(), client, bucketPath); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := extendedAttr(entry, ExtendedKeyMetadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -50,14 +68,14 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re
|
||||
}
|
||||
|
||||
// Fetch bucket policy if it exists
|
||||
policyData, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyPolicy)
|
||||
policyData, err := extendedAttr(entry, ExtendedKeyPolicy)
|
||||
if err == nil {
|
||||
bucketPolicy = string(policyData)
|
||||
} else if !errors.Is(err, ErrAttributeNotFound) {
|
||||
return fmt.Errorf("failed to fetch bucket policy: %v", err)
|
||||
}
|
||||
if bucketPolicy != "" {
|
||||
if bucketTags, err = h.readTags(r.Context(), client, bucketPath); err != nil {
|
||||
if bucketTags, err = tagsFromEntry(entry); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -71,7 +89,7 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re
|
||||
} else {
|
||||
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, fmt.Sprintf("failed to get table bucket: %v", err))
|
||||
}
|
||||
return err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
bucketARN := h.generateTableBucketARN(metadata.OwnerAccountID, bucketName)
|
||||
@@ -88,20 +106,17 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
|
||||
return ErrAccessDenied
|
||||
return nil, nil, ErrAccessDenied
|
||||
}
|
||||
|
||||
resp := &GetTableBucketResponse{
|
||||
return &GetTableBucketResponse{
|
||||
ARN: h.generateTableBucketARN(metadata.OwnerAccountID, bucketName),
|
||||
Name: metadata.Name,
|
||||
OwnerAccountID: metadata.OwnerAccountID,
|
||||
CreatedAt: metadata.CreatedAt,
|
||||
Format: metadata.Format,
|
||||
EncryptionConfiguration: metadata.EncryptionConfiguration,
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusOK, resp)
|
||||
return nil
|
||||
}, entry, nil
|
||||
}
|
||||
|
||||
// handleListTableBuckets lists all table buckets
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// GetTableBucket decides on the bucket entry's metadata, policy and tags, all
|
||||
// returned by one lookup of the entry, yet fetched each attribute with a
|
||||
// lookup of its own: two lookups, three under a policy.
|
||||
func TestGetTableBucketLooksUpTheBucketOnce(t *testing.T) {
|
||||
for _, withPolicy := range []bool{false, true} {
|
||||
name := "no policy"
|
||||
if withPolicy {
|
||||
name = "policy"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fs, m := startEmptyBucket(t)
|
||||
if withPolicy {
|
||||
requireOK(t, m, fs, "PutTableBucketPolicy", &PutTableBucketPolicyRequest{TableBucketARN: mustBucketARN(t),
|
||||
ResourcePolicy: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3tables:*","Resource":"*"}]}`})
|
||||
}
|
||||
lookups := 0
|
||||
fs.OnLookup = func(dir, name string) {
|
||||
if dir == TablesPath && name == renameTestBucket {
|
||||
lookups++
|
||||
}
|
||||
}
|
||||
defer func() { fs.OnLookup = nil }()
|
||||
if code, resp := runHandler(t, m, fs.Client, "GetTableBucket", &GetTableBucketRequest{TableBucketARN: mustBucketARN(t)}); code != http.StatusOK {
|
||||
t.Fatalf("GetTableBucket = %d %+v", code, resp)
|
||||
}
|
||||
if lookups != 1 {
|
||||
t.Errorf("GetTableBucket looked up the bucket %d times, want 1", lookups)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,36 @@ func (m *Manager) AuthorizeUpdateView(ctx context.Context, filerClient FilerClie
|
||||
return authErr
|
||||
}
|
||||
|
||||
// GetTableBucketEntry runs GetTableBucket and also returns the attributes of
|
||||
// the bucket entry it read, so a caller needing more of them than the record
|
||||
// holds does not look the bucket up again. The record and its attributes come
|
||||
// from the same read, and the answers are GetTableBucket's.
|
||||
func (m *Manager) GetTableBucketEntry(ctx context.Context, filerClient FilerClient, req *GetTableBucketRequest, identity string) (*GetTableBucketResponse, map[string][]byte, error) {
|
||||
httpReq, err := newManagerRequest(ctx, "GetTableBucket", nil, identity)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
if req.TableBucketARN == "" {
|
||||
m.handler.writeError(recorder, http.StatusBadRequest, ErrCodeInvalidRequest, "tableBucketARN is required")
|
||||
return nil, nil, decodeS3TablesHTTPResponse(recorder, nil)
|
||||
}
|
||||
bucketName, err := parseBucketNameFromARN(req.TableBucketARN)
|
||||
if err != nil {
|
||||
m.handler.writeError(recorder, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
|
||||
return nil, nil, decodeS3TablesHTTPResponse(recorder, nil)
|
||||
}
|
||||
resp, entry, getErr := m.handler.getTableBucket(recorder, httpReq, filerClient, bucketName)
|
||||
if getErr == nil {
|
||||
return resp, entry.Extended, nil
|
||||
}
|
||||
logRequestError("GetTableBucket", recorder.Code, getErr)
|
||||
if decoded := decodeS3TablesHTTPResponse(recorder, nil); decoded != nil {
|
||||
return nil, nil, decoded
|
||||
}
|
||||
return nil, nil, getErr
|
||||
}
|
||||
|
||||
func newManagerRequest(ctx context.Context, operation string, body []byte, identity string) (*http.Request, error) {
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, "/", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package s3vectors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
|
||||
)
|
||||
|
||||
// BenchmarkVectorBucketReads times the requests that read only the bucket
|
||||
// entry against the in-memory filer. The rtt cases add a fixed delay to every
|
||||
// filer lookup to stand in for a filer on another host; they model no measured
|
||||
// deployment. lookups/op is an exact count and does not depend on the machine.
|
||||
func BenchmarkVectorBucketReads(b *testing.B) {
|
||||
fs := s3tablestest.Start(b)
|
||||
s := NewServer(s3tables.NewManagerClient(fs.Client), allowAllAuth{}, newFakeVectors(0))
|
||||
if w := postJSONAs(b, "", s.handleCreateVectorBucket, &CreateVectorBucketRequest{VectorBucketName: "vec-bucket"}); w.Code != http.StatusOK {
|
||||
b.Fatalf("create bucket: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
const policy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3vectors:*","Resource":"*"}]}`
|
||||
if w := postJSONAs(b, "", s.handlePutVectorBucketPolicy, &PutVectorBucketPolicyRequest{VectorBucketName: "vec-bucket", Policy: policy}); w.Code != http.StatusOK {
|
||||
b.Fatalf("put policy: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
var lookups, delay atomic.Int64
|
||||
fs.OnLookup = func(string, string) {
|
||||
lookups.Add(1)
|
||||
if d := time.Duration(delay.Load()); d > 0 {
|
||||
// spin: time.Sleep overshoots a delay this short several times over
|
||||
for start := time.Now(); time.Since(start) < d; {
|
||||
}
|
||||
}
|
||||
}
|
||||
b.Cleanup(func() { fs.OnLookup = nil })
|
||||
|
||||
requests := []struct {
|
||||
name string
|
||||
handler http.HandlerFunc
|
||||
input interface{}
|
||||
}{
|
||||
{"GetVectorBucket", s.handleGetVectorBucket, &GetVectorBucketRequest{VectorBucketName: "vec-bucket"}},
|
||||
{"GetVectorBucketPolicy", s.handleGetVectorBucketPolicy, &GetVectorBucketPolicyRequest{VectorBucketName: "vec-bucket"}},
|
||||
}
|
||||
for _, req := range requests {
|
||||
for _, rtt := range []time.Duration{0, 200 * time.Microsecond} {
|
||||
b.Run(fmt.Sprintf("%s/rtt=%s", req.name, rtt), func(b *testing.B) {
|
||||
delay.Store(int64(rtt))
|
||||
defer delay.Store(0)
|
||||
lookups.Store(0)
|
||||
ops := 0
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
if w := postJSONAs(b, "", req.handler, req.input); w.Code != http.StatusOK {
|
||||
b.Fatalf("%s = %d %s", req.name, w.Code, w.Body.String())
|
||||
}
|
||||
ops++
|
||||
}
|
||||
b.ReportMetric(float64(lookups.Load())/float64(ops), "lookups/op")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package s3vectors
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
|
||||
)
|
||||
|
||||
// Authorizing a vector request needs the bucket's record, its s3vectors policy
|
||||
// and its tags, all attributes of the one bucket entry. The check reads the
|
||||
// record through the catalog's GetTableBucket and then the entry again for the
|
||||
// policy and tags, three lookups of the same entry, and GetVectorBucketPolicy
|
||||
// reads it a fourth time for the policy it returns. One lookup is enough.
|
||||
func TestVectorAuthorizationLooksUpTheBucketOnce(t *testing.T) {
|
||||
fs := s3tablestest.Start(t)
|
||||
s := NewServer(s3tables.NewManagerClient(fs.Client), allowAllAuth{}, newFakeVectors(0))
|
||||
if w := postJSONAs(t, "", s.handleCreateVectorBucket, &CreateVectorBucketRequest{VectorBucketName: "vec-bucket"}); w.Code != http.StatusOK {
|
||||
t.Fatalf("create bucket: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
const policy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3vectors:*","Resource":"*"}]}`
|
||||
if w := postJSONAs(t, "", s.handlePutVectorBucketPolicy, &PutVectorBucketPolicyRequest{VectorBucketName: "vec-bucket", Policy: policy}); w.Code != http.StatusOK {
|
||||
t.Fatalf("put policy: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
dir, name := splitEntryPath(s3tables.GetTableBucketPath("vec-bucket"))
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
call func() int
|
||||
}{
|
||||
{"authorizeVector", func() int {
|
||||
r := httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
r = r.WithContext(contextWithIdentity(r.Context(), ""))
|
||||
if _, err := s.authorizeVector(r.Context(), r, "s3vectors:GetVectorBucket", "vec-bucket", ""); err != nil {
|
||||
t.Fatalf("authorize: %v", err)
|
||||
}
|
||||
return http.StatusOK
|
||||
}},
|
||||
{"GetVectorBucket", func() int {
|
||||
return postJSONAs(t, "", s.handleGetVectorBucket, &GetVectorBucketRequest{VectorBucketName: "vec-bucket"}).Code
|
||||
}},
|
||||
{"GetVectorBucketPolicy", func() int {
|
||||
return postJSONAs(t, "", s.handleGetVectorBucketPolicy, &GetVectorBucketPolicyRequest{VectorBucketName: "vec-bucket"}).Code
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
lookups := 0
|
||||
fs.OnLookup = func(d, n string) {
|
||||
if d == dir && n == name {
|
||||
lookups++
|
||||
}
|
||||
}
|
||||
defer func() { fs.OnLookup = nil }()
|
||||
if code := tc.call(); code != http.StatusOK {
|
||||
t.Fatalf("%s = %d", tc.name, code)
|
||||
}
|
||||
if lookups != 1 {
|
||||
t.Errorf("%s looked up the bucket %d times, want 1", tc.name, lookups)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -719,33 +719,15 @@ func stripVectorActions(raw string) (string, bool) {
|
||||
// identity for the authorization lookup; nothing reaches the caller until
|
||||
// the permission check below it passes.
|
||||
func (s *Server) vectorBucket(ctx context.Context, bucket string) (*s3tables.GetTableBucketResponse, error) {
|
||||
var resp s3tables.GetTableBucketResponse
|
||||
if err := s.internalCatalog(ctx, "GetTableBucket",
|
||||
&s3tables.GetTableBucketRequest{TableBucketARN: s.s3tablesArn(bucket)}, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
record, _, err := s.vectorBucketEntry(ctx, bucket)
|
||||
return record, err
|
||||
}
|
||||
|
||||
// vectorPolicy reads the bucket's stored s3vectors policy and its tags. A
|
||||
// bucket written before the dedicated key carried the raw document in the
|
||||
// shared policy slot; one that still names vector actions keeps working until
|
||||
// the next vector policy write migrates it out.
|
||||
func (s *Server) vectorPolicy(ctx context.Context, bucket string) (policy string, tags map[string]string, err error) {
|
||||
dir, name := splitEntryPath(s3tables.GetTableBucketPath(bucket))
|
||||
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
policy = vectorPolicyFromExt(resp.Entry.Extended)
|
||||
tags, err = tagsFromExt(resp.Entry.Extended)
|
||||
return err
|
||||
})
|
||||
return policy, tags, err
|
||||
// vectorBucketEntry is vectorBucket plus the attributes of the bucket entry
|
||||
// the record was read from: its policy and tags, with no second lookup.
|
||||
func (s *Server) vectorBucketEntry(ctx context.Context, bucket string) (*s3tables.GetTableBucketResponse, map[string][]byte, error) {
|
||||
return s.internal.GetTableBucketEntry(ctx, s.filerClient,
|
||||
&s3tables.GetTableBucketRequest{TableBucketARN: s.s3tablesArn(bucket)}, "")
|
||||
}
|
||||
|
||||
// indexTags reads an index's tags; one not created yet has none.
|
||||
@@ -949,35 +931,44 @@ func (s *Server) authorizeVector(ctx context.Context, r *http.Request, action, b
|
||||
// authorizeVectorTags is authorizeVector for a request that sets or removes
|
||||
// tags.
|
||||
func (s *Server) authorizeVectorTags(ctx context.Context, r *http.Request, action, bucket, index string, req tagRequest) (*s3tables.GetTableBucketResponse, error) {
|
||||
record, _, err := s.authorizeVectorPolicy(ctx, r, action, bucket, index, req)
|
||||
return record, err
|
||||
}
|
||||
|
||||
// authorizeVectorPolicy is authorizeVectorTags that also returns the
|
||||
// s3vectors policy the request was granted under. The record, the policy and
|
||||
// the tags all come from one read of the bucket entry.
|
||||
func (s *Server) authorizeVectorPolicy(ctx context.Context, r *http.Request, action, bucket, index string, req tagRequest) (*s3tables.GetTableBucketResponse, string, error) {
|
||||
setRequestTarget(r, bucket, index)
|
||||
record, err := s.vectorBucket(ctx, bucket)
|
||||
record, ext, err := s.vectorBucketEntry(ctx, bucket)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
policy, bucketTags, err := s.vectorPolicy(ctx, bucket)
|
||||
policy := vectorPolicyFromExt(ext)
|
||||
bucketTags, err := tagsFromExt(ext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
resourceARN, resourceTags := s.vectorBucketArn(bucket), bucketTags
|
||||
if index != "" {
|
||||
resourceARN, resourceTags = s.indexArn(bucket, index), nil
|
||||
if _, usesIAM := s.authenticator.(IAMAuthorizer); readsResourceTags(policy) || usesIAM {
|
||||
if resourceTags, err = s.indexTags(ctx, bucket, index); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
}
|
||||
principal := s.tables.PrincipalFor(r)
|
||||
if !s.checkPermission(r, action, principal, record.OwnerAccountID, policy, resourceARN,
|
||||
s.policyContext(r, bucket, bucketTags, resourceTags, req)) {
|
||||
return nil, &s3tables.S3TablesError{Type: s3tables.ErrCodeAccessDenied, Message: "access denied"}
|
||||
return nil, "", &s3tables.S3TablesError{Type: s3tables.ErrCodeAccessDenied, Message: "access denied"}
|
||||
}
|
||||
if !isVectorBucket(record) {
|
||||
return nil, &s3tables.S3TablesError{Type: s3tables.ErrCodeNoSuchBucket,
|
||||
return nil, "", &s3tables.S3TablesError{Type: s3tables.ErrCodeNoSuchBucket,
|
||||
Message: fmt.Sprintf("vector bucket %s not found", bucket)}
|
||||
}
|
||||
authorizeRequest(r, bucket, index)
|
||||
return record, nil
|
||||
return record, policy, nil
|
||||
}
|
||||
|
||||
func (s *Server) handlePutVectorBucketPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -1039,11 +1030,8 @@ func (s *Server) handleGetVectorBucketPolicy(w http.ResponseWriter, r *http.Requ
|
||||
writeError(w, http.StatusBadRequest, "ValidationException", err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := s.authorizeVector(r.Context(), r, "s3vectors:GetVectorBucketPolicy", arns.bucket, ""); err != nil {
|
||||
catalogErr(w, err)
|
||||
return
|
||||
}
|
||||
policy, _, err := s.vectorPolicy(r.Context(), arns.bucket)
|
||||
// The policy returned is the one the request was granted under.
|
||||
_, policy, err := s.authorizeVectorPolicy(r.Context(), r, "s3vectors:GetVectorBucketPolicy", arns.bucket, "", tagRequest{})
|
||||
if err != nil {
|
||||
catalogErr(w, err)
|
||||
return
|
||||
|
||||
@@ -833,7 +833,7 @@ func TestValidateVectorPolicy(t *testing.T) {
|
||||
|
||||
// postJSONAs runs the handler under a named identity: empty resolves to the
|
||||
// account the catalog would charge, a name is a non-owner principal.
|
||||
func postJSONAs(t *testing.T, identity string, handler http.HandlerFunc, payload interface{}) *httptest.ResponseRecorder {
|
||||
func postJSONAs(t testing.TB, identity string, handler http.HandlerFunc, payload interface{}) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package s3vectors
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
|
||||
)
|
||||
|
||||
// These tests pin how a vector request reads its bucket: the answers a
|
||||
// missing, damaged or foreign bucket entry gives, and the catalog's own
|
||||
// rules the read still honours.
|
||||
|
||||
// startReadBucket creates vec-bucket and returns its filer entry location.
|
||||
func startReadBucket(t *testing.T) (*s3tablestest.MemFiler, *Server, string, string) {
|
||||
t.Helper()
|
||||
fs := s3tablestest.Start(t)
|
||||
s := NewServer(s3tables.NewManagerClient(fs.Client), allowAllAuth{}, newFakeVectors(0))
|
||||
if w := postJSONAs(t, "", s.handleCreateVectorBucket, &CreateVectorBucketRequest{VectorBucketName: "vec-bucket"}); w.Code != http.StatusOK {
|
||||
t.Fatalf("create bucket: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
dir, name := splitEntryPath(s3tables.GetTableBucketPath("vec-bucket"))
|
||||
return fs, s, dir, name
|
||||
}
|
||||
|
||||
// editBucket rewrites the bucket entry's attributes.
|
||||
func editBucket(fs *s3tablestest.MemFiler, dir, name string, edit func(ext map[string][]byte)) {
|
||||
ext := fs.Get(dir, name).Extended
|
||||
edit(ext)
|
||||
fs.Put(dir, name, ext)
|
||||
}
|
||||
|
||||
func setBucketMetadata(t *testing.T, key string, value interface{}) func(ext map[string][]byte) {
|
||||
return func(ext map[string][]byte) {
|
||||
var meta map[string]interface{}
|
||||
if err := json.Unmarshal(ext[s3tables.ExtendedKeyMetadata], &meta); err != nil {
|
||||
t.Fatalf("decode bucket metadata: %v", err)
|
||||
}
|
||||
meta[key] = value
|
||||
data, err := json.Marshal(meta)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ext[s3tables.ExtendedKeyMetadata] = data
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
catalogDenyGetBucket = `{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*","Action":"s3tables:GetTableBucket","Resource":"*"}]}`
|
||||
catalogAllowGetBucket = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3tables:GetTableBucket","Resource":"*"}]}`
|
||||
)
|
||||
|
||||
func TestVectorBucketReadAnswers(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
bucket string
|
||||
edit func(t *testing.T) func(ext map[string][]byte)
|
||||
identity string
|
||||
want int
|
||||
wantType string
|
||||
}{
|
||||
{name: "intact", want: http.StatusOK},
|
||||
{name: "absent", bucket: "nope", want: http.StatusNotFound, wantType: "NotFoundException"},
|
||||
{name: "no metadata", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return func(ext map[string][]byte) { delete(ext, s3tables.ExtendedKeyMetadata) }
|
||||
}, want: http.StatusNotFound, wantType: "NotFoundException"},
|
||||
{name: "damaged metadata", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return func(ext map[string][]byte) { ext[s3tables.ExtendedKeyMetadata] = []byte("{bad") }
|
||||
}, want: http.StatusInternalServerError, wantType: "InternalFailure"},
|
||||
// The catalog's record check reads no bucket marker.
|
||||
{name: "no bucket marker", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return func(ext map[string][]byte) { delete(ext, s3tables.ExtendedKeyTableBucket) }
|
||||
}, want: http.StatusOK},
|
||||
{name: "damaged tags", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return func(ext map[string][]byte) { ext[s3tables.ExtendedKeyTags] = []byte("{bad") }
|
||||
}, want: http.StatusInternalServerError, wantType: "InternalFailure"},
|
||||
{name: "damaged tags under a catalog policy", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return func(ext map[string][]byte) {
|
||||
ext[s3tables.ExtendedKeyTags] = []byte("{bad")
|
||||
ext[s3tables.ExtendedKeyPolicy] = []byte(catalogAllowGetBucket)
|
||||
}
|
||||
}, want: http.StatusInternalServerError, wantType: "InternalFailure"},
|
||||
// The record is read through the catalog's GetTableBucket, so a deny
|
||||
// of that action in the shared policy slot hides the bucket.
|
||||
{name: "catalog deny of GetTableBucket", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return func(ext map[string][]byte) { ext[s3tables.ExtendedKeyPolicy] = []byte(catalogDenyGetBucket) }
|
||||
}, want: http.StatusNotFound, wantType: "NotFoundException"},
|
||||
// The permission check comes before the format check, so a caller
|
||||
// that may not read the bucket does not learn it is no vector bucket.
|
||||
{name: "iceberg bucket", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return setBucketMetadata(t, "format", s3tables.FormatIceberg)
|
||||
}, want: http.StatusNotFound, wantType: "NotFoundException"},
|
||||
{name: "iceberg bucket, foreign caller", edit: func(t *testing.T) func(map[string][]byte) {
|
||||
return setBucketMetadata(t, "format", s3tables.FormatIceberg)
|
||||
}, identity: "stranger", want: http.StatusForbidden, wantType: "AccessDeniedException"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fs, s, dir, name := startReadBucket(t)
|
||||
if tc.edit != nil {
|
||||
editBucket(fs, dir, name, tc.edit(t))
|
||||
}
|
||||
bucket := tc.bucket
|
||||
if bucket == "" {
|
||||
bucket = "vec-bucket"
|
||||
}
|
||||
w := postJSONAs(t, tc.identity, s.handleGetVectorBucket, &GetVectorBucketRequest{VectorBucketName: bucket})
|
||||
if w.Code != tc.want {
|
||||
t.Fatalf("GetVectorBucket = %d %s, want %d", w.Code, w.Body.String(), tc.want)
|
||||
}
|
||||
if tc.wantType != "" {
|
||||
var body struct {
|
||||
Type string `json:"__type"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Type != tc.wantType {
|
||||
t.Fatalf("GetVectorBucket error = %s, want %s", w.Body.String(), tc.wantType)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The policy GetVectorBucketPolicy returns is the bucket's s3vectors policy:
|
||||
// the dedicated key, else a shared-slot document naming vector actions, and
|
||||
// none for a bucket without either.
|
||||
func TestGetVectorBucketPolicyAnswers(t *testing.T) {
|
||||
const vectorPolicy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3vectors:GetVectorBucketPolicy","Resource":"*"}]}`
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
edit func(ext map[string][]byte)
|
||||
want int
|
||||
body string
|
||||
}{
|
||||
{"none", func(map[string][]byte) {}, http.StatusNotFound, ""},
|
||||
{"dedicated key", func(ext map[string][]byte) { ext[vectorPolicyKey] = []byte(vectorPolicy) }, http.StatusOK, vectorPolicy},
|
||||
{"legacy shared slot", func(ext map[string][]byte) { ext[s3tables.ExtendedKeyPolicy] = []byte(vectorPolicy) }, http.StatusOK, vectorPolicy},
|
||||
{"catalog-only shared slot", func(ext map[string][]byte) { ext[s3tables.ExtendedKeyPolicy] = []byte(catalogAllowGetBucket) }, http.StatusNotFound, ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fs, s, dir, name := startReadBucket(t)
|
||||
editBucket(fs, dir, name, tc.edit)
|
||||
w := postJSONAs(t, "", s.handleGetVectorBucketPolicy, &GetVectorBucketPolicyRequest{VectorBucketName: "vec-bucket"})
|
||||
if w.Code != tc.want {
|
||||
t.Fatalf("GetVectorBucketPolicy = %d %s, want %d", w.Code, w.Body.String(), tc.want)
|
||||
}
|
||||
if tc.body == "" {
|
||||
return
|
||||
}
|
||||
var resp GetVectorBucketPolicyResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil || resp.Policy != tc.body {
|
||||
t.Fatalf("GetVectorBucketPolicy = %s, want policy %s", w.Body.String(), tc.body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v5"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
func benchmarkFilerAuthConnRequestContext(b *testing.B, source FilerTokenSource, wantToken bool) {
|
||||
c := &filerAuthConn{source: source}
|
||||
ctx, err := c.requestContext(context.Background(), "/filer_pb.SeaweedFiler/CreateEntry")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if got := metadata.ValueFromOutgoingContext(ctx, "authorization") != nil; got != wantToken {
|
||||
b.Fatalf("authorization set %v, want %v", got, wantToken)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
if _, err := c.requestContext(context.Background(), "/filer_pb.SeaweedFiler/CreateEntry"); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkFilerAuthConnRequestContext(b *testing.B) {
|
||||
key := SigningKey("0123456789abcdef0123456789abcdef")
|
||||
benchmarkFilerAuthConnRequestContext(b, func(context.Context) (EncodedJwt, error) {
|
||||
return GenJwtForFilerAdmin(key, 10), nil
|
||||
}, true)
|
||||
}
|
||||
|
||||
func BenchmarkFilerAuthConnRequestContextTokenless(b *testing.B) {
|
||||
benchmarkFilerAuthConnRequestContext(b, func(context.Context) (EncodedJwt, error) {
|
||||
return GenJwtForFilerAdmin(nil, 10), nil
|
||||
}, false)
|
||||
}
|
||||
|
||||
// withinOneSecond runs f until a run starts and ends in the same second.
|
||||
func withinOneSecond(f func(start int64)) {
|
||||
for {
|
||||
start := time.Now().Unix()
|
||||
f(start)
|
||||
if time.Now().Unix() == start {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenJwtForFilerAdminReusesSameSecondToken(t *testing.T) {
|
||||
key := SigningKey("0123456789abcdef0123456789abcdef")
|
||||
var first, second EncodedJwt
|
||||
var cachedBefore, cachedAfter *filerAdminJwt
|
||||
withinOneSecond(func(int64) {
|
||||
first = GenJwtForFilerAdmin(key, 10)
|
||||
cachedBefore = lastFilerAdminJwt.Load()
|
||||
second = GenJwtForFilerAdmin(key, 10)
|
||||
cachedAfter = lastFilerAdminJwt.Load()
|
||||
})
|
||||
if first == "" || first != second {
|
||||
t.Fatalf("tokens signed in one second differ: %q %q", first, second)
|
||||
}
|
||||
if cachedBefore != cachedAfter {
|
||||
t.Fatal("the second token was signed again instead of reused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenJwtForFilerAdminKeepsKeysApart(t *testing.T) {
|
||||
keyA := SigningKey("0123456789abcdef0123456789abcdef")
|
||||
keyB := SigningKey("fedcba9876543210fedcba9876543210")
|
||||
var a1, b1, a2 EncodedJwt
|
||||
var start int64
|
||||
withinOneSecond(func(s int64) {
|
||||
start = s
|
||||
a1 = GenJwtForFilerAdmin(keyA, 10)
|
||||
b1 = GenJwtForFilerAdmin(keyB, 10)
|
||||
a2 = GenJwtForFilerAdmin(keyA, 10)
|
||||
})
|
||||
if a1 != a2 || a1 == b1 {
|
||||
t.Fatalf("tokens per key: a1=%q b=%q a2=%q", a1, b1, a2)
|
||||
}
|
||||
for key, token := range map[string]EncodedJwt{string(keyA): a2, string(keyB): b1} {
|
||||
claims := &SeaweedFilerAdminClaims{}
|
||||
parsed, err := jwt.ParseWithClaims(string(token), claims, func(*jwt.Token) (interface{}, error) { return []byte(key), nil })
|
||||
if err != nil || !parsed.Valid {
|
||||
t.Fatalf("token does not verify with its key: %v", err)
|
||||
}
|
||||
if got := claims.ExpiresAt.Unix(); got < start+9 || got > start+11 {
|
||||
t.Fatalf("expiry %d, want about %d", got, start+10)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -189,8 +189,7 @@ func WithFilerSubscriptionToken(ctx context.Context, source FilerTokenSource) (c
|
||||
// bearer with admin authority. It preserves deadlines, cancellation and all
|
||||
// unrelated metadata, without modifying the original context's metadata.
|
||||
func WithFilerToken(ctx context.Context, source FilerTokenSource) (context.Context, error) {
|
||||
md, _ := metadata.FromOutgoingContext(ctx)
|
||||
if _, supplied := md["authorization"]; supplied || source == nil {
|
||||
if source == nil || metadata.ValueFromOutgoingContext(ctx, "authorization") != nil {
|
||||
return ctx, nil
|
||||
}
|
||||
token, err := source(ctx)
|
||||
@@ -200,9 +199,7 @@ func WithFilerToken(ctx context.Context, source FilerTokenSource) (context.Conte
|
||||
if token == "" {
|
||||
return ctx, nil
|
||||
}
|
||||
md = md.Copy()
|
||||
md.Set("authorization", BearerPrefix+string(token))
|
||||
return metadata.NewOutgoingContext(ctx, md), nil
|
||||
return metadata.AppendToOutgoingContext(ctx, "authorization", BearerPrefix+string(token)), nil
|
||||
}
|
||||
|
||||
// WithFilerClientAuth wraps a connection interface for one logical client,
|
||||
|
||||
+23
-1
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v5"
|
||||
@@ -96,6 +97,17 @@ type SeaweedFilerAdminClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// filerAdminJwt is the last admin token signed. Its claims hold only an
|
||||
// expiry, which jwt truncates to the second, so a token signed in the same
|
||||
// second with the same key is the same token.
|
||||
type filerAdminJwt struct {
|
||||
signingKey string
|
||||
expiresAt int64
|
||||
token EncodedJwt
|
||||
}
|
||||
|
||||
var lastFilerAdminJwt atomic.Pointer[filerAdminJwt]
|
||||
|
||||
// GenJwtForFilerAdmin mints a Bearer token for the filer IAM gRPC service.
|
||||
// Returns an empty string if the signing key is not configured.
|
||||
func GenJwtForFilerAdmin(signingKey SigningKey, expiresAfterSec int) EncodedJwt {
|
||||
@@ -103,11 +115,20 @@ func GenJwtForFilerAdmin(signingKey SigningKey, expiresAfterSec int) EncodedJwt
|
||||
return ""
|
||||
}
|
||||
|
||||
var expires time.Time
|
||||
var expiresAt int64
|
||||
if expiresAfterSec > 0 {
|
||||
expires = time.Now().Add(time.Second * time.Duration(expiresAfterSec)).Truncate(jwt.TimePrecision)
|
||||
expiresAt = expires.UnixNano()
|
||||
}
|
||||
if last := lastFilerAdminJwt.Load(); last != nil && last.expiresAt == expiresAt && last.signingKey == string(signingKey) {
|
||||
return last.token
|
||||
}
|
||||
claims := SeaweedFilerAdminClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{},
|
||||
}
|
||||
if expiresAfterSec > 0 {
|
||||
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(expiresAfterSec)))
|
||||
claims.ExpiresAt = jwt.NewNumericDate(expires)
|
||||
}
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
encoded, e := t.SignedString([]byte(signingKey))
|
||||
@@ -115,6 +136,7 @@ func GenJwtForFilerAdmin(signingKey SigningKey, expiresAfterSec int) EncodedJwt
|
||||
glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
|
||||
return ""
|
||||
}
|
||||
lastFilerAdminJwt.Store(&filerAdminJwt{signingKey: string(signingKey), expiresAt: expiresAt, token: EncodedJwt(encoded)})
|
||||
return EncodedJwt(encoded)
|
||||
}
|
||||
|
||||
|
||||
@@ -108,3 +108,26 @@ func TestSendHeartbeatRejectsAddresslessFirstHeartbeat(t *testing.T) {
|
||||
assert.Zero(t, uint32(ms.Topo.GetMaxVolumeId()))
|
||||
assert.Empty(t, stream.sent)
|
||||
}
|
||||
|
||||
// The expected-reporter release a single-master weed server or weed mini
|
||||
// uses gates only which report lifts the allocation hold: volume servers
|
||||
// started beside the embedded one are still admitted and applied.
|
||||
func TestSendHeartbeatAdmitsOutsideReporterBesideExpected(t *testing.T) {
|
||||
ms := newLeaderMaster()
|
||||
ms.Topo.RaftServer = admitTestRaftServer{}
|
||||
ms.Topo.ReleaseAllocationOnReport("10.0.0.1:8080")
|
||||
|
||||
stream := &fakeHeartbeatStream{heartbeats: []*master_pb.Heartbeat{{
|
||||
Ip: "10.0.0.2",
|
||||
Port: 8080,
|
||||
MaxVolumeIdSeen: 7,
|
||||
HasNoVolumes: true,
|
||||
}}}
|
||||
|
||||
err := ms.SendHeartbeat(stream)
|
||||
if err != nil {
|
||||
assert.NotContains(t, err.Error(), "rejected")
|
||||
}
|
||||
assert.EqualValues(t, 7, ms.Topo.GetMaxVolumeId())
|
||||
assert.NotEmpty(t, stream.sent)
|
||||
}
|
||||
@@ -72,14 +72,15 @@ type MasterOption struct {
|
||||
VolumeGrowthDisabled bool
|
||||
// ReleaseAllocOnFirstReport lifts the post-mint allocation hold as soon as
|
||||
// one full volume-server inventory has been applied, for setups whose
|
||||
// embedded volume server is the only possible reporter (weed mini).
|
||||
// embedded volume server is the only possible reporter.
|
||||
// SingleVolumeReporter pins that reporter's ip:port; any other volume
|
||||
// server trying to register is rejected.
|
||||
ReleaseAllocOnFirstReport bool
|
||||
SingleVolumeReporter string
|
||||
// ExpectedReporterAddr names the one volume server whose first clean full
|
||||
// inventory lifts the post-mint allocation hold (a single-master weed
|
||||
// server's embedded volume server). Other reporters are still admitted.
|
||||
// inventory lifts the post-mint allocation hold (the embedded volume
|
||||
// server of a single-master weed server or weed mini). Other reporters
|
||||
// are still admitted.
|
||||
ExpectedReporterAddr string
|
||||
}
|
||||
|
||||
|
||||
@@ -2045,8 +2045,8 @@ func (t *Topology) SetTopologyInitPending(pending bool) {
|
||||
// ReleaseAllocationOnFirstReport opts the topology into lifting the post-mint
|
||||
// allocation hold once one full volume-server inventory has been applied, and
|
||||
// pins the admitted volume-server reporter: the early release is only sound
|
||||
// when a single embedded server (weed mini) can carry prior cluster state, so
|
||||
// every other reporter must be refused rather than silently trusted.
|
||||
// when a single embedded server can carry prior cluster state, so every other
|
||||
// reporter must be refused rather than silently trusted.
|
||||
func (t *Topology) ReleaseAllocationOnFirstReport(onlyReporter ...string) {
|
||||
if len(onlyReporter) > 0 {
|
||||
t.singleReporter.Store(onlyReporter[0])
|
||||
|
||||
@@ -321,7 +321,14 @@ func (mc *MasterClient) resetVidMap() {
|
||||
}
|
||||
|
||||
func (mc *MasterClient) tryAllMasters(ctx context.Context) {
|
||||
var nextHintedLeader pb.ServerAddress
|
||||
var nextHintedLeader, redirectedFrom pb.ServerAddress
|
||||
// A canceled client keeps an address for unary queries (see below), so
|
||||
// give back the redirecting master if the hinted leader never answered.
|
||||
defer func() {
|
||||
if ctx.Err() != nil && redirectedFrom != "" && mc.getCurrentMaster() == "" {
|
||||
mc.setCurrentMaster(redirectedFrom)
|
||||
}
|
||||
}()
|
||||
failedMasters := make(map[pb.ServerAddress]struct{})
|
||||
mc.refreshMasters()
|
||||
masterAddrs := mc.masterInstances()
|
||||
@@ -340,6 +347,11 @@ func (mc *MasterClient) tryAllMasters(ctx context.Context) {
|
||||
return
|
||||
default:
|
||||
target := nextHintedLeader
|
||||
// the redirecting master cannot serve leader-only calls
|
||||
if current := mc.getCurrentMaster(); current != "" {
|
||||
redirectedFrom = current
|
||||
}
|
||||
mc.setCurrentMaster("")
|
||||
nextHintedLeader = mc.tryConnectToMaster(ctx, target)
|
||||
if nextHintedLeader == "" {
|
||||
// connection to target failed; remember it so we skip
|
||||
@@ -353,6 +365,7 @@ func (mc *MasterClient) tryAllMasters(ctx context.Context) {
|
||||
// only clear the serving address on an unintended disconnect.
|
||||
if ctx.Err() == nil {
|
||||
mc.setCurrentMaster("")
|
||||
redirectedFrom = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -373,16 +386,22 @@ func (mc *MasterClient) tryConnectToMaster(ctx context.Context, master pb.Server
|
||||
}
|
||||
glog.V(1).Infof("%s.%s masterClient gRPC stream established to %s in %v", mc.FilerGroup, mc.clientType, master, time.Since(connectStartTime))
|
||||
|
||||
// The stream is usable for queries before registration, so callers
|
||||
// blocked in GetMaster (e.g. loading a chunked filer.conf during
|
||||
// startup) proceed while the announce gate still holds.
|
||||
mc.setCurrentMaster(master)
|
||||
|
||||
if mc.announceCh != nil {
|
||||
select {
|
||||
case <-mc.announceCh:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
// The stream is usable for queries before registration, so
|
||||
// callers blocked in GetMaster (e.g. loading a chunked
|
||||
// filer.conf during startup) proceed while the announce gate
|
||||
// still holds. Otherwise wait for the first answer: a follower
|
||||
// only names the leader, and queries sent to it fail with
|
||||
// "Not current leader".
|
||||
mc.setCurrentMaster(master)
|
||||
select {
|
||||
case <-mc.announceCh:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package wdclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -62,3 +63,176 @@ func TestAnnounceGateDelaysRegistration(t *testing.T) {
|
||||
t.Fatalf("registration ClientAddress = %q, want filer1:18888", req.ClientAddress)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeFollowerServer answers once release is closed. With no leader set it
|
||||
// answers as the leader and keeps the stream open.
|
||||
type fakeFollowerServer struct {
|
||||
master_pb.UnimplementedSeaweedServer
|
||||
leader pb.ServerAddress
|
||||
registered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (s *fakeFollowerServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {
|
||||
if _, err := stream.Recv(); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case s.registered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-s.release:
|
||||
case <-stream.Context().Done():
|
||||
return stream.Context().Err()
|
||||
}
|
||||
if err := stream.Send(&master_pb.KeepConnectedResponse{VolumeLocation: &master_pb.VolumeLocation{Leader: string(s.leader)}}); err != nil || s.leader != "" {
|
||||
return err
|
||||
}
|
||||
<-stream.Context().Done()
|
||||
return nil
|
||||
}
|
||||
|
||||
// A client without an announce gate, or one that already announced (e.g.
|
||||
// reconnecting after a failover), must not hand out a follower it is still
|
||||
// waiting on: leader-only calls sent there fail with "Not current leader".
|
||||
func TestGetMasterWaitsForLeaderAnswer(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
clientType string
|
||||
announced bool
|
||||
}{
|
||||
{"no announce gate", "shell", false},
|
||||
{"announce gate open", "filer", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// distinct http ports, since masters compare by their http address
|
||||
leader := pb.ServerAddress(strings.Replace(string(startFakeMasterServer(t, &fakeKeepConnectedServer{requests: make(chan *master_pb.KeepConnectedRequest, 4)})), ":0.", ":1.", 1))
|
||||
follower := &fakeFollowerServer{leader: leader, registered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
followerAddr := pb.ServerAddress(strings.Replace(string(startFakeMasterServer(t, follower)), ":0.", ":2.", 1))
|
||||
mc := NewMasterClient(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
"", tc.clientType, "", "", "",
|
||||
*pb.NewServiceDiscoveryFromMap(map[string]pb.ServerAddress{"m": followerAddr}),
|
||||
)
|
||||
if tc.announced {
|
||||
gate := make(chan struct{})
|
||||
close(gate)
|
||||
mc.SetAnnounceCh(gate)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go mc.KeepConnectedToMaster(ctx)
|
||||
|
||||
select {
|
||||
case <-follower.registered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("follower received no KeepConnected registration")
|
||||
}
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer waitCancel()
|
||||
if m := mc.GetMaster(waitCtx); m != "" {
|
||||
t.Fatalf("GetMaster = %q before any master answered", m)
|
||||
}
|
||||
|
||||
close(follower.release)
|
||||
waitCtx, waitCancel = context.WithTimeout(ctx, 5*time.Second)
|
||||
defer waitCancel()
|
||||
if m := mc.GetMaster(waitCtx); m != leader {
|
||||
t.Fatalf("GetMaster = %q, want leader %q", m, leader)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A filer that reached a follower behind its announce gate must stop handing
|
||||
// it out once the follower redirects, until the leader answers.
|
||||
func TestGetMasterDropsRedirectingFollower(t *testing.T) {
|
||||
leaderSrv := &fakeFollowerServer{registered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
leader := pb.ServerAddress(strings.Replace(string(startFakeMasterServer(t, leaderSrv)), ":0.", ":1.", 1))
|
||||
follower := &fakeFollowerServer{leader: leader, registered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
close(follower.release)
|
||||
followerAddr := pb.ServerAddress(strings.Replace(string(startFakeMasterServer(t, follower)), ":0.", ":2.", 1))
|
||||
mc := NewMasterClient(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
"", "filer", "filer1:18888", "", "",
|
||||
*pb.NewServiceDiscoveryFromMap(map[string]pb.ServerAddress{"m": followerAddr}),
|
||||
)
|
||||
gate := make(chan struct{})
|
||||
mc.SetAnnounceCh(gate)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go mc.KeepConnectedToMaster(ctx)
|
||||
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer waitCancel()
|
||||
if m := mc.GetMaster(waitCtx); m != followerAddr {
|
||||
t.Fatalf("GetMaster behind the gate = %q, want %q", m, followerAddr)
|
||||
}
|
||||
|
||||
close(gate)
|
||||
select {
|
||||
case <-leaderSrv.registered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("leader received no KeepConnected registration")
|
||||
}
|
||||
waitCtx, waitCancel = context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer waitCancel()
|
||||
if m := mc.GetMaster(waitCtx); m != "" {
|
||||
t.Fatalf("GetMaster = %q after the follower redirected, before the leader answered", m)
|
||||
}
|
||||
|
||||
close(leaderSrv.release)
|
||||
waitCtx, waitCancel = context.WithTimeout(ctx, 5*time.Second)
|
||||
defer waitCancel()
|
||||
if m := mc.GetMaster(waitCtx); m != leader {
|
||||
t.Fatalf("GetMaster = %q, want leader %q", m, leader)
|
||||
}
|
||||
}
|
||||
|
||||
// Canceling the client while it waits on the hinted leader keeps an address,
|
||||
// so unary queries after the cancel do not block forever.
|
||||
func TestGetMasterAfterCancelDuringRedirect(t *testing.T) {
|
||||
leaderSrv := &fakeFollowerServer{registered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
leader := pb.ServerAddress(strings.Replace(string(startFakeMasterServer(t, leaderSrv)), ":0.", ":1.", 1))
|
||||
follower := &fakeFollowerServer{leader: leader, registered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
close(follower.release)
|
||||
followerAddr := pb.ServerAddress(strings.Replace(string(startFakeMasterServer(t, follower)), ":0.", ":2.", 1))
|
||||
mc := NewMasterClient(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
"", "filer", "filer1:18888", "", "",
|
||||
*pb.NewServiceDiscoveryFromMap(map[string]pb.ServerAddress{"m": followerAddr}),
|
||||
)
|
||||
gate := make(chan struct{})
|
||||
mc.SetAnnounceCh(gate)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
mc.KeepConnectedToMaster(ctx)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer waitCancel()
|
||||
if m := mc.GetMaster(waitCtx); m != followerAddr {
|
||||
t.Fatalf("GetMaster behind the gate = %q, want %q", m, followerAddr)
|
||||
}
|
||||
close(gate)
|
||||
select {
|
||||
case <-leaderSrv.registered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("leader received no KeepConnected registration")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("KeepConnectedToMaster did not stop after cancel")
|
||||
}
|
||||
waitCtx, waitCancel = context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer waitCancel()
|
||||
if m := mc.GetMaster(waitCtx); m != followerAddr {
|
||||
t.Fatalf("GetMaster after cancel = %q, want %q", m, followerAddr)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user