Compare commits

..
Author SHA1 Message Date
pingqiu 6edc30b6ec Merge current master for answer policy review 2026-12-05 17:07:21 -08:00
pingqiu 255b6532ce fix(block): preserve response precedence and refusal origin 2026-12-05 17:06:21 -08:00
Ping Qiu b5e4406f84 Merge branch 'master' into block/unified-answer-policy 2026-12-05 16:04:50 -08:00
pingqiu e6dde9f215 fix(block): preserve admitted outcomes and caller completion 2026-12-05 15:31:54 -08:00
pingqiu f09fe52cb1 Merge PR #13479 into the shared answer policy 2026-12-05 15:16:50 -08:00
pingqiu e71b319170 fix: preserve answer provenance through observation and recovery 2026-12-05 14:58:53 -08:00
pingqiu ceeeca9e84 test: pin answer precedence and certificate-chain boundaries 2026-12-05 14:46:54 -08:00
pingqiu 1e9983fc01 Cover CA rotation in the Kubernetes status writer 2026-12-05 14:18:19 -08:00
Chris LuandClaude Opus 5.5 35f64da0a4 seaweed-block: master-crash test expects the shared refusal presentation
Competing clean moves after the master restart are still definite
refusals (exit 1). The workspace client now keeps the gRPC status in the
error chain and appends the registry cure, so the stderr line carries the
status prefix and "resolve the server's stated precondition before
retrying".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:15:12 -08:00
Chris LuandClaude Opus 5.5 2e0a98d990 seaweed-block: workspace caller deadline before send is not a master refusal
A workspace RPC whose caller deadline passed (or was canceled) before it
was sent projects to exit 1, and the exit-1 branch turned it into
OutcomeRefused. force-move then printed "refused by the master (nothing
moved)" and read an admission preview, though the master never answered.
Report these as unsent; the policy exit stays 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 14:13:39 -08:00
pingqiu eaac405ece Allow unused CA alternatives during certificate rotation 2026-12-05 14:11:57 -08:00
pingqiu 0c0f241ce1 Test CA rotation with unused expired and future roots 2026-12-05 14:05:47 -08:00
Chris LuandClaude Opus 5.5 dd198e27c3 seaweed-block: document the failover caller-deadline exit
The failover help, the v1.1.x legacy table and the classification design
note name the caller deadline before send next to the unsent remote
failure as the two failover cases that keep exit 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:44:33 -08:00
Chris LuandClaude Opus 5.5 20e7f5fa9a seaweed-block: failover keeps exit 3 for a caller deadline before send
A failover whose caller deadline passed before the request was sent
(e.g. a master that never completes the handshake) is Recover under the
failover contract, so the command prints result=unknown and asks the
operator to read the current line. The canonical projection gave it
exit 1, which the help text reserves for a definite answer, while
v1.1.x returned 3. Add the failover legacy row next to the unsent
remote-failure one so the exit matches the printed outcome.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 13:44:09 -08:00
pingqiu 46f2f80e80 seaweed-block: unify operator answer policy with admission evidence 2026-12-05 12:53:30 -08:00
117 changed files with 5771 additions and 878 deletions

No files matched your search

@@ -40,7 +40,7 @@ func TestProcedureMasterKilledAfterMoveBeforeTargetStarts(t *testing.T) {
{"s2", "different-request"}, {"s3", "different-target"},
} {
out, stderr, code := env.h.run(t, env.moveClean(e, conflict.target, conflict.request)...)
if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: workspace move: missing or changed authority/lease" {
if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: rpc error: code = FailedPrecondition desc = workspace move: missing or changed authority/lease; resolve the server's stated precondition before retrying" {
t.Fatalf("competing move to %s: exit=%d stdout=%q stderr=%q; want the definite-refusal exit and changed-authority answer", conflict.target, code, out, stderr)
}
}
@@ -0,0 +1,29 @@
package main
import (
"bytes"
"path/filepath"
"testing"
)
func TestCanonicalCredentialExitAtCommandEntries(t *testing.T) {
dir := t.TempDir()
t.Setenv("SW_BLOCK_TLS_CERT", filepath.Join(dir, "missing-cert"))
t.Setenv("SW_BLOCK_TLS_KEY", filepath.Join(dir, "missing-key"))
t.Setenv("SW_BLOCK_TLS_CA", filepath.Join(dir, "missing-ca"))
for _, args := range [][]string{
{"ops", "workspace", "show", "--master", "m:1", "--volume", "v"},
{"ops", "volume", "resolve", "--master", "m:1", "v"},
createAndPlaceArgs("m:1"),
{"cluster", "finalize-format", "--master", "m:1"},
{"cluster", "retire-host", "--master", "m:1", "--server", "h", "--confirm", "h"},
failoverArgs(),
} {
t.Run(args[0]+"/"+args[1]+"/"+args[2], func(t *testing.T) {
var out, diag bytes.Buffer
if exit := run(args, &out, &diag); exit != 78 {
t.Fatalf("args=%v exit=%d out=%s diag=%s", args, exit, &out, &diag)
}
})
}
}
@@ -0,0 +1,87 @@
package main
import (
"bytes"
"context"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type lostRestoreAnswer struct {
control.UnimplementedLifecycleServiceServer
calls atomic.Int64
id atomic.Value
}
func TestChunkHTTPPostLostAnswerIsUnknown(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
_ = conn.Close()
}))
defer server.Close()
var out, diag bytes.Buffer
exit := chunkPost("snapshot", server.URL, "/chunk/snapshot", time.Second, map[string]any{"requestID": "same-snapshot"}, &out, &diag)
got := chunkErrorOut(t, out.String())
if calls.Load() != 1 || exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "replay key") {
t.Fatalf("calls=%d exit=%d answer=%+v", calls.Load(), exit, got)
}
}
func TestChunkHTTPRejectsAnUnlistedServerErrorCode(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`{"code":"unlisted_server_code","message":"retry this new error","retryable":true}`))
}))
defer server.Close()
var out, diag bytes.Buffer
exit := chunkPost("snapshot", server.URL, "/chunk/snapshot", time.Second, map[string]any{"requestID": "same-snapshot"}, &out, &diag)
got := chunkErrorOut(t, out.String())
if calls.Load() != 1 || exit != 3 || got.Code != "unsupported_error_code" || got.Retryable || !strings.Contains(got.Message, "unlisted") {
t.Fatalf("calls=%d exit=%d answer=%+v", calls.Load(), exit, got)
}
}
func (server *lostRestoreAnswer) CreateVolume(_ context.Context, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
server.calls.Add(1)
server.id.Store(req.GetCreateRequestId())
return nil, status.Error(codes.Unavailable, "reply unavailable after request was received")
}
func TestRestoreUnavailableAfterSendIsUnknown(t *testing.T) {
for _, env := range []string{link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA} {
t.Setenv(env, "")
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
service := &lostRestoreAnswer{}
server := link.NewServer(link.ServerConfig{})
control.RegisterLifecycleServiceServer(server, service)
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
var out, diag bytes.Buffer
exit := runOpsChunk([]string{"restore", "--source", "source", "--target", "target", "--snapshot", "daily", "--request-id", "same-restore", "--master", listener.Addr().String(), "--timeout", "5s"}, &out, &diag)
got := chunkErrorOut(t, out.String())
if service.calls.Load() != 1 || service.id.Load() != "same-restore" || exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || !strings.Contains(got.Message, "replay key") {
t.Fatalf("calls=%d id=%v exit=%d answer=%+v", service.calls.Load(), service.id.Load(), exit, got)
}
}
@@ -11,6 +11,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -18,7 +19,7 @@ import (
type unavailableCatalogRead struct{ *memChunkStore }
func (s unavailableCatalogRead) LookupEntry(context.Context, string, string) (*filerpb.Entry, error) {
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", status.Error(codes.Unavailable, "connection refused"))
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")))
}
func TestOpsChunkCatalogUnavailableIsTyped(t *testing.T) {
@@ -97,14 +98,14 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
code string
retry bool
}{
{"wrapped", fmt.Errorf("lookup: %w", unavailable), "remote_unavailable", true},
{"deadline", errors.Join(context.DeadlineExceeded, unavailable), "deadline_exceeded", true},
{"caller cancellation", errors.Join(context.Canceled, unavailable), "canceled", false},
{"wrapped", fmt.Errorf("lookup: %w", unavailable), "outcome_unknown", true},
{"deadline", errors.Join(context.DeadlineExceeded, unavailable), "outcome_unknown", true},
{"caller cancellation", errors.Join(context.Canceled, unavailable), "outcome_unknown", true},
{"identity", errors.Join(layout.ErrIdentity, unavailable), "identity_mismatch", false},
{"catalog", &chunkstore.CatalogError{Code: "outcome_unknown", Retryable: true, Err: unavailable}, "outcome_unknown", true},
{"permission", status.Error(codes.PermissionDenied, "refused"), "internal", false},
{"permission", status.Error(codes.PermissionDenied, "refused"), "not_authorized", false},
{"unknown", errors.New("unexpected implementation error"), "internal", false},
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "internal", false},
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "bad_request", false},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
@@ -114,6 +115,15 @@ func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
if tc.code == codeUnavailableCLI {
wantExit = 75
}
if tc.code == "outcome_unknown" {
wantExit = 3
}
if tc.code == "bad_request" {
wantExit = 78
}
if tc.code == "not_authorized" {
wantExit = 5
}
if exit != wantExit || e.Code != tc.code || e.Retryable != tc.retry {
t.Fatalf("exit=%d answer=%+v", exit, e)
}
@@ -67,7 +67,7 @@ func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCata
if errors.Is(err, layout.ErrHasDependents) {
return nil, &chunkstore.CatalogError{Code: "snapshot_has_dependents", Message: "remove dependent volumes or release their dependency before resuming the same --request-id", Err: err}
}
if chunkTransportFailure(err) || chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) {
if knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if err != nil {
+35 -28
View File
@@ -25,6 +25,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
const (
@@ -67,6 +68,15 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat
func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int {
ctx, cancel := context.WithTimeoutCause(parent, timeout, chunkstore.ErrSingleFilerWindowExpired)
defer cancel()
if cause := context.Cause(ctx); cause != nil {
// No census call was started. Preserve the caller's own completion.
// The pass's silence sentinel and the historical explicit deadline
// signal keep their owned mappings; opaque caller causes need Err too.
if !errors.Is(cause, errVerifyStalled) && !errors.Is(cause, context.DeadlineExceeded) {
cause = answer.RecordContext(ctx, answer.Unsent, errors.Join(ctx.Err(), cause))
}
return chunkResult(name, nil, cause, stdout, stderr)
}
err := checkSingleFiler(ctx, f)
if err != nil && !errors.Is(err, chunkstore.ErrSingleFilerWindowExpired) && parent.Err() != nil {
if c := context.Cause(parent); c != nil && !errors.Is(err, c) {
@@ -76,7 +86,7 @@ func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunks
switch {
case err == nil:
return -1
case chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) || chunkTransportFailure(err):
case knownChunkFailure(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled):
return chunkResult(name, nil, err, stdout, stderr)
case errors.Is(err, chunkstore.ErrNotSingleFiler):
return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
@@ -177,14 +187,14 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
if len(admission) == 1 && admission[0] != nil {
req.Header.Set("Prefer", "respond-async")
}
resp, err := chunkHTTPClient.Do(req)
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.Unsent)
if err != nil {
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
return chunkResult(name, nil, err, stdout, stderr)
}
defer resp.Body.Close()
out, err := io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit+1))
if err != nil {
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "read the response: "+err.Error(), true)
return chunkResult(name, nil, err, stdout, stderr)
}
if int64(len(out)) > chunkResponseLimit {
// Refuse rather than relay a truncated body; the operation may have
@@ -219,12 +229,17 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))), false)
}
// The route's error body is already the CLI's error body: relay it.
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, chunkErrorAdvice(e.Code, e.Retryable, e.Message))
policy, check := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Domain(e.Code, e.Retryable, e.Message)))
if check != nil {
policy, _ = answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Guard("unsupported_error_code")))
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, check.Error()+"; "+policy.Cure, false)
}
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, policy.Cure)
if err := writeAll(stdout, out); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the error: %v\n", name, err)
return chunkExitFailed
}
return chunkErrorExit(chunkExitFailed, e.Code, e.Retryable)
return policy.Exit
}
func chunkCut(args []string, stdout, stderr io.Writer) int {
@@ -367,27 +382,12 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
// chunkResult prints v as JSON, or err as "<code>: <message>".
func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
if err != nil {
var ce *chunkstore.CatalogError
switch {
case errors.As(err, &ce):
exit := chunkExitFailed
if name == "volume-delete" && ce.Code == "not_admitted" && ce.Retryable {
exit = 75 // temporary admission refusal; retry the same request ID
}
return chunkFail(name, stdout, stderr, exit, ce.Code, ce.Detail(), ce.Retryable)
case chunkCanceled(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeCanceledCLI, "operation interrupted by its caller", false)
case errors.Is(err, context.DeadlineExceeded):
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
case chunkTransportFailure(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
case errors.Is(err, errVerifyStalled):
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
case layoutCode(err) != "":
return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition) || errors.Is(err, layout.ErrBusy))
default:
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
contract := answer.Chunk
if name == "verify" {
contract = answer.ChunkVerify
}
policy, detail := chunkAnswerFor(err, contract)
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, detail, policy.Retryable)
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(v); err != nil {
@@ -422,6 +422,11 @@ type chunkErrBody struct {
func chunkFail(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int {
exit = chunkErrorExit(exit, code, retryable)
message = chunkErrorAdvice(code, retryable, message)
return chunkWriteFailure(name, stdout, stderr, exit, code, message, retryable)
}
// chunkWriteFailure only renders an already-decided policy or server answer.
func chunkWriteFailure(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int {
prefix := "sw-block ops chunk"
if name != "" {
prefix += " " + name
@@ -449,13 +454,15 @@ func writeAll(w io.Writer, p []byte) error {
// CLI temporary remote failures use EX_TEMPFAIL consistently across commands.
func chunkErrorExit(exit int, code string, retryable bool) int {
if code == codeUnavailableCLI && retryable {
return 75
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, "")))
return policy.Exit
}
return exit
}
func chunkErrorAdvice(code string, retryable bool, message string) string {
if code == codeUnavailableCLI && retryable {
return message + "; retry the same operation when the remote is reachable"
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, answer.Domain(code, retryable, message)))
return policy.Cure
}
return message
}
@@ -0,0 +1,74 @@
package main
import (
"context"
"errors"
"net"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/status"
)
// Translate domain facts and transport evidence; the registry owns the
// output code, retry decision and exit. Partial verify uses the same path.
func chunkAnswer(err error) (answer.Policy, string) {
return chunkAnswerFor(err, answer.Chunk)
}
func chunkAnswerFor(err error, contract answer.Contract) (answer.Policy, string) {
var domain *chunkstore.CatalogError
hasDomain := errors.As(err, &domain)
guard := layoutCode(err)
_, recordedPolicy := answer.PolicyOf(err, contract)
if !hasDomain && guard == "" && recordedPolicy != nil && errors.Is(err, errVerifyStalled) {
policy, _ := answer.Lookup(answer.Unsent, answer.ForContract(contract, answer.Guard("deadline_exceeded")))
return policy, err.Error() + "; " + policy.Cure
}
if (!hasDomain || domain.Code == chunkstore.CodeRemoteUnavailable) && (guard == "" || errors.Is(err, layout.ErrHolderActive)) {
observed := err
if kind, listed := answer.ErrorKind(err); listed && kind == answer.Configuration {
observed = answer.EnsureEvidence(answer.Unsent, err)
}
if _, remote := status.FromError(err); remote {
observed = answer.EnsureEvidence(answer.PossiblyAdmitted, err)
}
var network *net.OpError
if errors.As(err, &network) {
observed = answer.EnsureEvidence(answer.PossiblyAdmitted, observed)
}
if policy, check := answer.PolicyOf(observed, contract); check == nil {
if policy.Code == codeCanceledCLI {
return policy, policy.Cure
}
detail := err.Error()
if hasDomain {
detail = domain.Detail()
}
return policy, detail + "; " + policy.Cure
}
}
kind, detail := answer.Guard("internal"), err.Error()
switch {
case hasDomain:
kind = answer.Domain(domain.Code, domain.Retryable, domain.Detail())
case guard != "":
kind = answer.Guard(guard)
case errors.Is(err, context.Canceled):
kind = answer.Canceled
case errors.Is(err, context.DeadlineExceeded):
kind = answer.CallerDeadline
case errors.Is(err, errVerifyStalled):
kind = answer.Guard("deadline_exceeded")
}
policy, check := answer.Lookup(answer.Unsent, answer.ForContract(contract, kind))
if check != nil {
policy, _ = answer.Lookup(answer.Unsent, answer.ForContract(contract, answer.Guard("unsupported_error_code")))
return policy, detail + "; " + check.Error()
}
if hasDomain || policy.Code == codeCanceledCLI {
detail = policy.Cure
}
return policy, detail
}
+6 -16
View File
@@ -17,6 +17,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
@@ -45,7 +46,7 @@ func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdo
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
return nil, nil, chunkResult(name, nil, err, stdout, stderr)
}
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
@@ -151,7 +152,7 @@ func (c *bCommand) run(args []string, writes bool, refs func() error, do func(co
return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if err := refs(); err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
if knownChunkFailure(err) && status.Code(err) != codes.NotFound {
return chunkResult(name, nil, err, c.stdout, c.stderr)
}
if status.Code(err) == codes.NotFound { // the master does not know the volume
@@ -393,21 +394,10 @@ func chunkRestore(args []string, stdout, stderr io.Writer) int {
VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID,
})
if err != nil {
switch status.Code(err) {
case codes.NotFound:
return chunkFail("restore", stdout, stderr, chunkExitFailed, "snapshot_not_found", err.Error(), false)
case codes.AlreadyExists:
return chunkFail("restore", stdout, stderr, chunkExitFailed, "target_exists", err.Error(), false)
case codes.InvalidArgument:
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
case codes.FailedPrecondition:
if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
return chunkFail("restore", stdout, stderr, chunkExitFailed, layoutCode(layout.ErrForeignSource), err.Error(), false)
}
return chunkFail("restore", stdout, stderr, chunkExitFailed, "not_admitted", err.Error(), false)
default:
return chunkResult("restore", nil, err, stdout, stderr)
if policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.Restore); check == nil {
return chunkWriteFailure("restore", stdout, stderr, policy.Exit, policy.Code, err.Error()+"; "+policy.Cure, policy.Retryable)
}
return chunkResult("restore", nil, err, stdout, stderr)
}
if resp.GetVolumeId() != target || !resp.GetStoreReady() {
return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, "master did not confirm the restored target is store-ready", true)
@@ -4,7 +4,10 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net"
@@ -12,13 +15,47 @@ import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health/grpc_health_v1"
)
func TestChunkCensusPreflightPreservesOpaqueContextCause(t *testing.T) {
previous := checkSingleFiler
t.Cleanup(func() { checkSingleFiler = previous })
calls := 0
checkSingleFiler = func(context.Context, chunkstore.Filer) error { calls++; return nil }
for _, deadline := range []bool{false, true} {
t.Run(fmt.Sprint("deadline=", deadline), func(t *testing.T) {
cause := errors.New("opaque caller reason")
var ctx context.Context
if deadline {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), cause)
defer cancel()
} else {
var cancel context.CancelCauseFunc
ctx, cancel = context.WithCancelCause(context.Background())
cancel(cause)
}
var out, diag bytes.Buffer
exit := refuseUnlessSingleFilerWithin(ctx, "verify", nil, time.Second, &out, &diag)
got := chunkErrorOut(t, out.String())
code := "canceled"
if deadline {
code = "deadline_exceeded"
}
if exit != 1 || got.Code != code || got.Retryable != deadline {
t.Fatalf("exit=%d answer=%+v", exit, got)
}
if calls != 0 {
t.Fatalf("census calls=%d want zero", calls)
}
})
}
}
// A real gRPC call canceled by its caller keeps a cancellation answer.
func TestChunkCallerCancelIsNotTransport(t *testing.T) {
conn, err := grpc.NewClient("127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := link.Dial("127.0.0.1:1")
if err != nil {
t.Fatal(err)
}
@@ -1,7 +1,6 @@
package main
import (
"context"
"io"
"net"
"net/http"
@@ -13,28 +12,30 @@ import (
"testing/synctest"
)
// Keep the refused-dial fixture independent of port reuse and host forwarding:
// net/http still builds and sends the request through its real Transport,
// whose dial boundary supplies the kernel's typed refusal.
func installRefusedHolderDial(t *testing.T) *atomic.Int32 {
// Exercise the owned native dial path, not a caller-supplied transport whose
// partial tracing cannot establish whether the request was sent.
func installRefusedHolderDial(t *testing.T) string {
t.Helper()
calls := new(atomic.Int32)
transport := &http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
calls.Add(1)
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
}}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
old := chunkHTTPClient
chunkHTTPClient = &http.Client{Transport: transport}
t.Cleanup(func() { transport.CloseIdleConnections(); chunkHTTPClient = old })
return calls
chunkHTTPClient = &http.Client{}
t.Cleanup(func() { chunkHTTPClient = old })
return "http://" + addr
}
func TestPlainDetachRefusedDialIsRemoteUnavailable(t *testing.T) {
calls := installRefusedHolderDial(t)
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder")
addr := installRefusedHolderDial(t)
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", addr)
e := chunkErrorOut(t, out)
if code != 75 || e.Code != codeUnavailableCLI || !e.Retryable || strings.Contains(errOut, "outcome_unknown") || calls.Load() != 1 {
t.Fatalf("refused dial: exit=%d dials=%d stdout=%s stderr=%s", code, calls.Load(), out, errOut)
if code != 75 || e.Code != codeUnavailableCLI || !e.Retryable || strings.Contains(errOut, "outcome_unknown") {
t.Fatalf("refused dial: exit=%d stdout=%s stderr=%s", code, out, errOut)
}
}
@@ -15,6 +15,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -32,7 +33,7 @@ func TestChunkErrorFamilyAnswerTable(t *testing.T) {
advice string
only string
}{
{"remote", status.Error(codes.Unavailable, "connection refused"), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
{"remote", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused")), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
{"caller timeout", context.DeadlineExceeded, "deadline_exceeded", 1, true, context.DeadlineExceeded.Error(), ""},
{"caller cancel", context.Canceled, "canceled", 1, false, "operation interrupted by its caller", ""},
{"dependents", layout.ErrHasDependents, "snapshot_has_dependents", 1, false, layout.ErrHasDependents.Error(), ""},
@@ -156,7 +157,7 @@ func TestSnapshotDeleteWorkTransportUsesSharedClassifier(t *testing.T) {
return status.Error(codes.Unavailable, "filer stopped after admission")
}, false, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
if exit != 3 || answer.Code != "outcome_unknown" || !answer.Retryable {
t.Fatalf("exit=%d answer=%+v", exit, answer)
}
retained, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
@@ -176,8 +177,20 @@ func TestVerifyIncompleteTransportPreservesPartialProgress(t *testing.T) {
if err := json.Unmarshal(out.Bytes(), &answer); err != nil {
t.Fatal(err)
}
const message = "rpc error: code = Unavailable desc = filer stopped; retry the same operation when the remote is reachable"
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: remote_unavailable: "+message+" (incomplete)\n" {
const message = "rpc error: code = Unavailable desc = filer stopped; verification is read-only; after resolving the failure, run verification again; do not treat the incomplete scan as a clean result"
if exit != 1 || answer.Code != "outcome_unknown" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: outcome_unknown: "+message+" (incomplete)\n" {
t.Fatalf("exit=%d answer=%+v stderr=%q", exit, answer, diag.String())
}
}
func TestVerifyStartCheckLostAnswerNeverLooksLikeFindings(t *testing.T) {
useMemChunkStore(t, newMemChunkStore())
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
return answer.Record(answer.PossiblyAdmitted, status.Error(codes.Unavailable, "census answer lost"))
}
exit, out, diag := runChunk("verify", "--volume", "verify-00112233", "--chunk-filer", "fake:18888")
body := chunkErrorOut(t, out)
if exit != 1 || body.Code != "outcome_unknown" {
t.Fatalf("exit=%d body=%+v diag=%s", exit, body, diag)
}
}
+2 -1
View File
@@ -13,6 +13,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// chunkTimeoutHelp is the --timeout text of the commands that use chunkPostLoop.
@@ -184,7 +185,7 @@ func chunkStats(statusAddr, volumeID string, deadline time.Time) (chunkStagedSta
if err != nil {
return chunkStagedStats{}, false
}
resp, err := chunkHTTPClient.Do(req)
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
if err != nil {
return chunkStagedStats{}, false
}
@@ -107,7 +107,7 @@ func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) {
return nil, status.Error(codes.Unavailable, "filer unreachable")
}
var out, errs bytes.Buffer
if code := run(args, &out, &errs); code != 75 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
if code := run(args, &out, &errs); code != 3 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), "outcome_unknown") {
t.Fatalf("uncertain restore must be retryable: code=%d out=%q err=%q", code, out.String(), errs.String())
}
}
+2 -2
View File
@@ -135,8 +135,8 @@ func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) {
t.Fatalf("unknown flag: exit %d %q", code, out)
}
t.Run("refused holder dial", func(t *testing.T) {
installRefusedHolderDial(t)
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://holder"); code != 75 {
addr := installRefusedHolderDial(t)
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", addr); code != 75 {
t.Fatalf("unreachable blockvolume: exit %d %q", code, out)
} else if e := chunkErrorOut(t, out); e.Code != codeUnavailableCLI || !e.Retryable {
t.Fatalf("unreachable blockvolume: %+v, want remote_unavailable and retryable", e)
+11 -12
View File
@@ -5,7 +5,7 @@ import (
"errors"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"net"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -29,17 +29,9 @@ func chunkTransportFailure(err error) bool {
if layoutCode(err) != "" && !errors.Is(err, layout.ErrHolderActive) {
return false
}
switch status.Code(err) {
case codes.Unavailable, codes.DeadlineExceeded:
return true
}
var address *net.AddrError
var syntax *net.ParseError
if errors.As(err, &address) || errors.As(err, &syntax) {
return false
}
var network net.Error
return errors.As(err, &network)
kind, listed := answer.ErrorKind(err)
return listed && (kind == answer.Connection || kind == answer.PlaintextConnection || kind == answer.DNS || kind == answer.Timeout)
}
// gRPC cancellation does not wrap context.Canceled. Keep it distinct from an
@@ -54,3 +46,10 @@ func chunkCanceled(err error) bool {
}
return errors.Is(err, context.Canceled) || status.Code(err) == codes.Canceled
}
// Routing only: known error facts go to the shared policy; unknown local
// argument errors remain with the command's validation path.
func knownChunkFailure(err error) bool {
_, listed := answer.ErrorKind(err)
return listed
}
@@ -14,6 +14,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -56,6 +57,7 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
continue
}
t.Run(failure.name+"/"+phase+"/"+command, func(t *testing.T) {
fixtureErr := answer.Record(answer.Unsent, failure.err)
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "transport-source", "daily")
@@ -84,18 +86,18 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
case "resolve":
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) {
calls.Add(1)
return layout.VolumeID{}, failure.err
return layout.VolumeID{}, fixtureErr
}
case "dial":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, failure.err }
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, fixtureErr }
case "census":
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
calls.Add(1)
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, failure.err)
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, fixtureErr)
}
case "read":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
return transportLookupStore{mem, failure.err, &calls}, func() error { return nil }, nil
return transportLookupStore{mem, fixtureErr, &calls}, func() error { return nil }, nil
}
case "restore":
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
@@ -110,6 +112,11 @@ func TestOpsChunkTransportFailureMatrix(t *testing.T) {
if failure.name == "rpc-canceled" {
wantCode, wantRetry, wantExit = "canceled", false, 1
}
if phase == "reserve" || phase == "no-lease" || phase == "restore" {
// These are real server RPCs: the server received the
// request before returning its ambiguous transport status.
wantCode, wantRetry, wantExit = "outcome_unknown", true, 3
}
if calls.Load() == 0 || exit != wantExit || e.Code != wantCode || e.Retryable != wantRetry || (wantCode == codeUnavailableCLI && !strings.Contains(e.Message, "retry")) {
t.Errorf("calls=%d exit=%d answer=%+v", calls.Load(), exit, e)
}
@@ -25,8 +25,8 @@ func jsonCode(t *testing.T, out []byte) string {
// The JSON codes a runner decides by, never the message text: a restore the
// master refused for a foreign source is restore_source_not_own (from its
// typed reason; an untyped FailedPrecondition stays not_admitted), and a
// volume the master does not know is volume_not_found (any other resolve
// transport failure is retryable remote_unavailable).
// volume the master does not know is volume_not_found. A resolve failure
// without admission evidence requires recovery of the same operation.
func TestOpsChunkTypedRefusalCodes(t *testing.T) {
prevRestore, prevResolve := restoreCreateRPC, resolveVolumeID
t.Cleanup(func() { restoreCreateRPC, resolveVolumeID = prevRestore, prevResolve })
@@ -55,7 +55,7 @@ func TestOpsChunkTypedRefusalCodes(t *testing.T) {
code string
}{
{"unknown volume", status.Error(codes.NotFound, "volume not found"), chunkExitFailed, "volume_not_found"},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 75, codeUnavailableCLI},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 3, "outcome_unknown"},
} {
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{}, c.err }
var out, errs bytes.Buffer
+8 -14
View File
@@ -14,6 +14,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// chunkVerify: sw-block ops chunk verify --master master:9180 --volume v --chunk-filer host:port
@@ -21,8 +22,9 @@ import (
// (the current image and every snapshot), their segments and chunks
// (chunkstore.VerifyLayout). --orphans also reports the volume's own names
// that no reachable root names (it never deletes them). Exit 0: clean; 3:
// the pass completed with findings; 1: it could not complete (the partial
// result is printed with the reason); 2: usage.
// the pass completed with findings. Incomplete failures retain their typed
// class and partial result: unknown/operational 1, arguments 2, integrity 4,
// auth 5, unsent/retryable remote 75, local configuration 78; never findings 3.
func chunkVerify(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("verify", stderr)
var (
@@ -114,7 +116,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
if knownChunkFailure(err) {
return verifyIncomplete(layout.VerifyResult{}, err, stdout, stderr)
}
return usage(err.Error())
@@ -290,17 +292,9 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ
chunkErrBody
Verify layout.VerifyResult `json:"verify"`
}{Verify: res}
body.Code, body.Message = codeInternalCLI, err.Error()
if chunkCanceled(err) {
body.Code, body.Message = codeCanceledCLI, "operation interrupted by its caller"
} else if chunkTransportFailure(err) {
body.Code, body.Retryable = codeUnavailableCLI, true
}
if errors.Is(err, context.DeadlineExceeded) || (errors.Is(err, errVerifyStalled) && !chunkTransportFailure(err)) {
body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true
}
body.Message = chunkErrorAdvice(body.Code, body.Retryable, body.Message)
policy, detail := chunkAnswerFor(err, answer.ChunkVerify)
body.Code, body.Message, body.Retryable = policy.Code, detail, policy.Retryable
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
chunkResult("verify", body, nil, stdout, stderr)
return chunkErrorExit(chunkExitFailed, body.Code, body.Retryable)
return policy.Exit
}
@@ -14,6 +14,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
@@ -95,15 +96,7 @@ func (m *masterAuthority) NoLiveLease(ctx context.Context) error {
// Anything else (unavailable, deadline, a lost response) leaves
// the outcome unknown and a rerun decides.
func authorityErr(err error) error {
// A serving holder can renew its horizon indefinitely. A clean stop is
// distinguished by the master's typed detail, never by a dated message.
result := finalLeaseBarrierErr(err)
var refusal *chunkstore.CatalogError
if errors.As(result, &refusal) && refusal.Code == "not_admitted" && refusal.Retryable && !deleteLeaseBarrierDetail(err) {
refusal.Retryable = false
refusal.Message = "stop the volume first"
}
return result
return leaseRefusal(err, false)
}
func deleteLeaseBarrierDetail(err error) bool {
@@ -118,6 +111,12 @@ func deleteLeaseBarrierDetail(err error) bool {
// finalLeaseBarrierErr projects the dated deletion barrier. Reserve callers
// additionally require the clean-stop detail before allowing timed retry.
func finalLeaseBarrierErr(err error) error {
return leaseRefusal(err, true)
}
// Translate the master's dated refusal and the admission step into facts.
// Retry policy and cure text belong to the shared registry.
func leaseRefusal(err error, committed bool) error {
switch status.Code(err) {
case codes.OK:
return nil
@@ -127,7 +126,15 @@ func finalLeaseBarrierErr(err error) error {
if _, rest, ok := strings.Cut(status.Convert(err).Message(), "workspace delete: live until "); ok {
if stamp, reason, ok := strings.Cut(rest, ": "); ok && reason != "" {
if until, parseErr := time.Parse(time.RFC3339Nano, stamp); parseErr == nil {
return &chunkstore.CatalogError{Code: "not_admitted", Message: "retry the same --request-id after " + until.UTC().Format(time.RFC3339Nano), Retryable: true, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
kind := answer.LeaseBarrier(until.UTC().Format(time.RFC3339Nano))
if !committed && !deleteLeaseBarrierDetail(err) {
kind = answer.Guard("delete_live_holder")
}
policy, check := answer.Lookup(answer.Unsent, answer.ForContract(answer.Chunk, kind))
if check != nil {
return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, check)
}
return &chunkstore.CatalogError{Code: policy.Code, Message: policy.Cure, Retryable: policy.Retryable, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
}
}
}
@@ -227,7 +234,10 @@ func deleteVolumeWithProgress(ctx context.Context, cat *chunkstore.BCatalog, ref
}
return all, nil
}
transient := errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Unavailable
policy, _ := chunkAnswer(err)
// This is reconciliation of the same full volume ID under the same
// deletion reservation, never admission of a second operation.
transient := policy.Retryable && (chunkTransportFailure(err) || errors.Is(err, context.DeadlineExceeded))
if !transient {
return nil, err
}
@@ -10,6 +10,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -40,7 +41,11 @@ func (f *transientDeleteFiler) DeleteEntry(ctx context.Context, dir, name string
return err
}
}
return status.Error(f.code, "object deadline")
phase := answer.Unsent // this fixture refuses before applying any delete
if f.lost {
phase = answer.PossiblyAdmitted
}
return answer.Record(phase, status.Error(f.code, "object deadline"))
}
return f.memChunkStore.DeleteEntry(ctx, dir, name, expected)
}
@@ -119,7 +124,7 @@ func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string,
return err
}
if f.stall {
return status.Error(codes.Unavailable, "stalled after first removal")
return answer.Record(answer.Unsent, status.Error(codes.Unavailable, "stalled after first removal"))
}
if !f.waited {
f.waited = true
@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
@@ -40,7 +41,8 @@ func TestVolumeDeleteAdmissionRetryAnswer(t *testing.T) {
{"HEAD boundary horizon", fmt.Errorf("%w: %w", layout.ErrHolderActive, lease), 75, "not_admitted", true},
{"invalid admission", authorityErr(status.Error(codes.InvalidArgument, "invalid token")), 1, "not_admitted", false},
{"dependents", layout.ErrHasDependents, 1, "snapshot_has_dependents", false},
{"remote unknown", authorityErr(status.Error(codes.Unavailable, "connection refused")), 75, "remote_unavailable", true},
{"remote unknown without phase proof", authorityErr(status.Error(codes.Unavailable, "connection refused")), 3, "outcome_unknown", true},
{"remote proven unsent", authorityErr(answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection refused"))), 75, "remote_unavailable", true},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
+35 -16
View File
@@ -11,11 +11,11 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
policy "github.com/seaweedfs/seaweed-block/core/rpc/answer"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@@ -152,7 +152,8 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
@@ -164,15 +165,15 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
if reason == "" {
reason = status.Code(err).String()
}
switch status.Code(err) {
case codes.FailedPrecondition:
p, check := policy.PolicyOf(policy.EnsureEvidence(policy.PossiblyAdmitted, err), policy.Cluster)
if check != nil {
return fail("failed", reason, check.Error(), finalizeExitFailed)
}
if p.Code == "not_admitted" {
answer.Hosts = metadataHosts(md, lifecycleclient.HostMetadataPrefix)
answer.Listed = metadataHosts(md, lifecycleclient.UnconfirmedMetadataPrefix)
return fail("refused", reason, msg, finalizeExitRefused)
case codes.Unavailable, codes.DeadlineExceeded:
return fail("unavailable", reason, msg, finalizeExitTempFail)
}
return fail("failed", reason, msg, finalizeExitFailed)
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
}
answer.FormatLevel = resp.GetFormatLevel()
for _, u := range resp.GetUnconfirmed() {
@@ -289,7 +290,8 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
answer.Server = *server
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
@@ -300,14 +302,14 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
if reason == "" {
reason = status.Code(err).String()
}
switch status.Code(err) {
case codes.FailedPrecondition:
answer.Volumes = retireVolumes(md)
return fail("refused", reason, msg, finalizeExitRefused)
case codes.Unavailable, codes.DeadlineExceeded:
return fail("unavailable", reason, msg, finalizeExitTempFail)
p, check := policy.PolicyOf(policy.EnsureEvidence(policy.PossiblyAdmitted, err), policy.Cluster)
if check != nil {
return fail("failed", reason, check.Error(), finalizeExitFailed)
}
return fail("failed", reason, msg, finalizeExitFailed)
if p.Code == "not_admitted" {
answer.Volumes = retireVolumes(md)
}
return fail(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
}
answer.Result, answer.Message = "retired", "host retired from the node inventory"
if !jsonMode {
@@ -316,6 +318,23 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
return finalizeExitOK
}
// Serialize the shared class in the cluster command's existing result field.
func clusterPolicyResult(p policy.Policy) string {
switch p.Code {
case "not_admitted":
return "refused"
case "remote_unavailable":
return "unavailable"
case "outcome_unknown":
if p.Exit == finalizeExitFailed {
return "failed"
}
return "unknown"
default:
return "failed"
}
}
// retireVolumes reads the held volumes from the refusal's typed metadata,
// sorted.
func retireVolumes(md map[string]string) []string {
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"reflect"
"sort"
"testing"
@@ -50,12 +51,12 @@ func TestClusterFinalizeFormatTypedAnswer(t *testing.T) {
listed: []finalizeHost{{"node-d", "no report"}}},
{name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"},
{name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 1, result: "failed", reason: "Internal"},
{name: "dial", dialErr: answer.LocalConfiguration(errors.New("bad address")), exit: 78, result: "failed", reason: "bad_request"},
{name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 3, result: "unknown", reason: "Internal"},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
return tc.resp, tc.err
return tc.resp, answer.Record(answer.Unsent, tc.err)
}}
withClusterMaster(t, f)
if tc.dialErr != nil {
@@ -179,8 +180,8 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
{name: "not-registered", err: status.Error(codes.FailedPrecondition, "retire refused: host is not registered"), exit: 2, result: "refused", reason: "FailedPrecondition"},
{name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"},
{name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"},
{name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 1, result: "failed", reason: "Internal"},
{name: "dial", dialErr: answer.LocalConfiguration(errors.New("bad address")), exit: 78, result: "failed", reason: "bad_request"},
{name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 3, result: "unknown", reason: "Internal"},
{name: "usage", args: []string{"cluster", "retire-host", "--json", "--bogus", "--master", "m:1"}, exit: 1, result: "failed", reason: "usage"},
} {
t.Run(tc.name, func(t *testing.T) {
@@ -188,7 +189,7 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) {
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
calls++
if tc.err != nil {
return nil, tc.err
return nil, answer.Record(answer.Unsent, tc.err)
}
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
}}
@@ -4,16 +4,15 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
const cutObservationSlack = 5 * time.Second
@@ -84,15 +83,16 @@ func chunkObserveHandle(name, route, addr string, window time.Duration, deadline
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
phase := answer.Unsent
if id != "" {
phase = answer.PossiblyAdmitted
}
resp, err := answer.DoHTTP(&client, req, phase)
var raw []byte
if err != nil && id == "" {
cancel()
// A failed dial sent no admission request. Other transport
// failures may have lost an applied request's answer.
var network *net.OpError
if errors.As(err, &network) && network.Op == "dial" && chunkTransportFailure(err) {
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
if policy, check := answer.PolicyOf(err, answer.Chunk); check == nil {
return chunkWriteFailure(name, stdout, stderr, policy.Exit, policy.Code, err.Error()+"; "+policy.Cure, policy.Retryable)
}
return unknown(name + " admission answer was not received (" + err.Error() + "); no second one was started")
}
+17 -32
View File
@@ -2,7 +2,6 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
@@ -11,9 +10,8 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const opsFailoverName = "sw-block ops failover"
@@ -51,10 +49,12 @@ volumes); a line that moved since is refused.
Needs an admin client certificate: SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and
SW_BLOCK_TLS_CA, all three; without them the command refuses before dialing.
Exit: 0 moved; 1 refused by blockmaster, or the line did not move; 2 bad
arguments or identity (no call made); 3 outcome unknown (the connection or the
deadline failed: the line may have moved; read it with sw-block ops volumes
before retrying).
Exit: 0 moved; 1 definite precondition refusal, caller cancellation before
sending, or the line did not move; 2 bad arguments or a server argument
refusal; 3 outcome unknown (or an unsent connection failure or caller
deadline): read the current line with sw-block ops volumes before another
move; 4 unproven integrity readout; 5 authentication rejection; 78 local
credential/configuration error.
`
func runOpsFailover(args []string, stdout, stderr io.Writer) int {
@@ -93,11 +93,13 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
}
// An admin command never falls back to a plaintext link.
if tls, err := link.MasterTLSFromEnv(); err != nil {
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, err)
return 2
p, detail := operatorAnswer(err, answer.Failover)
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, detail)
return p.Exit
} else if tls == nil {
fmt.Fprintf(stderr, "%s: needs an admin client certificate: set %s, %s and %s\n", opsFailoverName, link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)
return 2
p, _ := operatorAnswer(answer.LocalCredential(fmt.Errorf("admin client certificate is required")), answer.Failover)
return p.Exit
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
@@ -119,14 +121,15 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int {
EvidenceRefs: []string{"sw-block ops failover", "operator_confirmed_old_node_off=" + volume},
})
if err != nil {
if failoverOutcomeUnknown(err) {
policy, detail := operatorAnswer(err, answer.Failover)
if policy.Retry == answer.Recover {
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=unknown\n", volume, target, curReplica, curEpoch)
fmt.Fprintf(stderr, "%s: outcome unknown (%v): the line may have moved; read it with sw-block ops volumes before retrying\n", opsFailoverName, err)
return 3
return policy.Exit
}
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch)
fmt.Fprintf(stderr, "%s: refused: %v (no line published; a refused fencing round may have fenced the survivors)\n", opsFailoverName, err)
return 1
fmt.Fprintf(stderr, "%s: %v (a refused fencing round may have fenced the survivors)\n", opsFailoverName, detail)
return policy.Exit
}
moved := res.FailbackStarted && res.AuthorityEpochAdvanced && res.SinglePrimaryAfterFailback
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=%s epoch_advanced=%t single_primary=%t publish_target_swapped=%t\n",
@@ -150,21 +153,3 @@ func parseReplicaAtEpoch(s string) (string, uint64, bool) {
}
return s[:i], e, true
}
// failoverOutcomeUnknown: the call did not get blockmaster's decision back
// (connection, deadline, cancellation or an internal failure), so the line
// may or may not have moved. A decided refusal is any other status.
func failoverOutcomeUnknown(err error) bool {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return true
}
s, ok := status.FromError(err)
if !ok {
return true
}
switch s.Code() {
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss, codes.ResourceExhausted:
return true
}
return false
}
+64 -2
View File
@@ -11,6 +11,7 @@ import (
"encoding/pem"
"errors"
"math/big"
"net"
"os"
"os/exec"
"path/filepath"
@@ -19,6 +20,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -169,6 +171,42 @@ func TestOpsFailoverReportsAnUnknownOutcome(t *testing.T) {
}
}
// A master that never answers the handshake leaves the call unsent when the
// caller's deadline passes; the operator must still read the line first.
func TestOpsFailoverUnsentCallerDeadlineIsUnknown(t *testing.T) {
cert, key, ca := writeClientIdentity(t, t.TempDir())
t.Setenv(link.EnvTLSCert, cert)
t.Setenv(link.EnvTLSKey, key)
t.Setenv(link.EnvTLSCA, ca)
silent, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
held := make(chan net.Conn, 16)
go func() {
for {
conn, err := silent.Accept()
if err != nil {
close(held)
return
}
held <- conn
}
}()
t.Cleanup(func() {
silent.Close()
for conn := range held {
conn.Close()
}
})
args := failoverArgs("--timeout", "300ms")
args[3] = silent.Addr().String()
var out, errb bytes.Buffer
if rc := run(args, &out, &errb); rc != 3 || !strings.Contains(out.String(), "result=unknown") {
t.Fatalf("rc=%d stdout=%q stderr=%q; want 3 and result=unknown", rc, out.String(), errb.String())
}
}
// The admin command never dials without a complete, valid client identity:
// unset, partial or unreadable TLS settings are refused locally (exit 2, no
// call); a valid identity makes the call.
@@ -202,8 +240,8 @@ func TestOpsFailoverRequiresAClientIdentity(t *testing.T) {
if len(f.calls) != c.calls {
t.Fatalf("calls=%d; want %d (rc=%d stderr %q)", len(f.calls), c.calls, rc, errb.String())
}
if c.calls == 0 && rc != 2 {
t.Fatalf("rc=%d; want 2", rc)
if c.calls == 0 && rc != 78 {
t.Fatalf("rc=%d; want 78", rc)
}
if c.calls == 1 && rc != 0 {
t.Fatalf("rc=%d stderr %q; want 0", rc, errb.String())
@@ -288,3 +326,27 @@ func TestAlphaFailbackExecutorRendersTheSelectedImage(t *testing.T) {
t.Fatalf("rendered executor does not run the selected image: %s", r)
}
}
func TestOpsFailoverUsesSharedDefiniteExitProjection(t *testing.T) {
for _, row := range []struct {
name string
err error
exit int
}{
{"certificate", status.Error(codes.Unauthenticated, "certificate rejected"), 5},
{"role", status.Error(codes.PermissionDenied, "admin required"), 5},
{"integrity", status.Error(codes.DataLoss, "line readout unproven"), 4},
{"arguments", status.Error(codes.InvalidArgument, "invalid target"), 2},
{"precondition", status.Error(codes.FailedPrecondition, "target not ready"), 1},
{"unknown", status.Error(codes.Unavailable, "answer lost"), 3},
{"unsent", answer.Record(answer.Unsent, status.Error(codes.Unavailable, "connection unavailable")), 3},
} {
t.Run(row.name, func(t *testing.T) {
withFailoverRuntime(t, &fakeFailoverRuntime{err: row.err})
var out, diag bytes.Buffer
if exit := run(failoverArgs(), &out, &diag); exit != row.exit {
t.Fatalf("exit=%d want=%d out=%s diag=%s", exit, row.exit, out.String(), diag.String())
}
})
}
}
+1 -1
View File
@@ -2340,7 +2340,7 @@ func usage(w io.Writer) {
fmt.Fprintln(w, " sw-block ops chunk snapshots|snapshot-delete --volume <id> [--name <name>] --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
fmt.Fprintln(w, " sw-block ops chunk show --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
fmt.Fprintln(w, " sw-block ops chunk verify --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks] [--depth meta|bindings|data] [--orphans] [--timeout <d>]")
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)")
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 completed findings; incomplete: 1 operational/unknown, 2 usage/server arguments, 4 unproven readout, 5 auth, 75 unsent/retryable remote, 78 local config; --depth data needs --timeout)")
fmt.Fprintln(w, " sw-block ops volume resolve --master <addr> [--timeout 10s] <name> (prints the master layout id)")
fmt.Fprintln(w, " sw-block ops volume-unheld --path <volume-file> (exit 0: no process on this host holds it; local filesystems only)")
fmt.Fprintln(w, " sw-block ops failover --master <addr> --volume <id> --target <replica> --target-data <addr> --target-ctrl <addr> --expect-current <replica>@<epoch> --confirm-old-node-off <volume>")
+5 -2
View File
@@ -18,6 +18,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// sw-block mini starts the single-host configuration in one command, after
@@ -292,6 +293,7 @@ func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) {
// ready waits until every port listens, while c is alive, bounded.
func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
deadline := time.Now().Add(miniStartWait)
var lastErr error
for {
if d := r.dead(); d != nil {
return fmt.Errorf("%s exited during startup: %v (see %s.log)", d.name, d.err, d.name)
@@ -300,6 +302,7 @@ func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
for _, p := range ports {
conn, err := net.DialTimeout("tcp", loopback(p), 200*time.Millisecond)
if err != nil {
lastErr = answer.Record(answer.Unsent, err) // TCP probe writes no application request
up = false
break
}
@@ -309,11 +312,11 @@ func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log)", c.name, miniStartWait, ports, c.name)
return fmt.Errorf("%s not ready within %s (ports %v; see %s.log): %w", c.name, miniStartWait, ports, c.name, answer.Present(lastErr, answer.Ops))
}
select {
case <-ctx.Done():
return ctx.Err()
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
case <-time.After(250 * time.Millisecond):
}
}
+4 -2
View File
@@ -13,6 +13,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
type inspectionShell struct {
@@ -207,8 +208,9 @@ func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int {
defer cancel()
cluster, err := readMasterClusterEvidence(ctx, s.master)
if err != nil {
fmt.Fprintf(stderr, "%s: %v\n", name, err)
return 1
policy, detail := operatorAnswer(err, answer.Shell)
fmt.Fprintf(stderr, "%s: %v\n", name, detail)
return policy.Exit
}
var value any = cluster
text := ops.RenderClusterEvidenceText(cluster)
+7 -1
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
@@ -191,6 +192,11 @@ func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObse
}
o.filerErr = err
}
o.masterErr, o.lifecycleErr, o.filerErr = inspectionError(o.masterErr), inspectionError(o.lifecycleErr), inspectionError(o.filerErr)
for i := range o.volumes {
v := &o.volumes[i]
v.leaseErr, v.holderErr, v.durableErr = inspectionError(v.leaseErr), inspectionError(v.holderErr), inspectionError(v.durableErr)
}
rows := make([]inspectionResult, 0, len(inspectionChecks))
code := 0
for _, c := range inspectionChecks {
@@ -297,7 +303,7 @@ func (s inspectionShell) readHolderAt(ctx context.Context, addr, path, volume st
return err
}
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("status redirects are refused") }}
resp, err := client.Do(req)
resp, err := answer.DoHTTP(client, req, answer.Unsent)
if err != nil {
return err
}
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"net/url"
@@ -69,6 +70,12 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
if handle.Scheme != origin.Scheme || handle.Host != origin.Host || handle.User != nil {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation handle changed origin", false)
}
// A failed handle read says nothing definite about the admitted POST.
// Keep its identity and recovery contract even for a definite GET refusal.
unobserved := func(err error) int {
err = fmt.Errorf("snapshot operation %s status at %s: %w", a.Answer.ID, handle.String(), err)
return chunkResult("snapshot", nil, answer.Rekind(answer.Record(answer.PossiblyAdmitted, err), answer.Connection), stdout, stderr)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
for {
@@ -78,13 +85,13 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
cancel()
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
}
resp, err := chunkHTTPClient.Do(req)
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
var current snapshotCLIAnswer
if err == nil {
err = json.NewDecoder(io.LimitReader(resp.Body, chunkResponseLimit+1)).Decode(&current)
_ = resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("operation status HTTP %d", resp.StatusCode)
err = answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("operation status HTTP %d", resp.StatusCode))
}
}
cancel()
@@ -93,10 +100,10 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
return chunkExitFailed
}
if err != nil {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
return unobserved(err)
}
if current.ID != a.Answer.ID {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation status changed identity", false)
return unobserved(fmt.Errorf("operation status changed identity"))
}
switch current.State {
case "succeeded":
@@ -117,7 +124,7 @@ func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]an
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, "no_progress", "snapshot stalled; repeat with --request-id "+a.Answer.ID, true)
case "accepted", "running":
default:
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "unknown operation state", false)
return unobserved(fmt.Errorf("unknown operation state"))
}
timer := time.NewTimer(100 * time.Millisecond)
select {
@@ -0,0 +1,197 @@
package main
import (
"bytes"
"context"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
type snapshotPollFailure struct {
base http.RoundTripper
mode string
polls *atomic.Int32
invalid *atomic.Bool
}
func snapshotPollRequestError(r *http.Request) error {
if r.Method == http.MethodPost {
if r.URL.Path != "/chunk/snapshot" {
return fmt.Errorf("wrong POST path: %s", r.URL.Path)
}
var body struct {
ID string `json:"requestID"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
return err
}
if body.ID != "original" {
return fmt.Errorf("changed replay ID: %s", body.ID)
}
return nil
}
if r.Method != http.MethodGet || r.URL.RequestURI() != "/operations/original" {
return fmt.Errorf("wrong handle: %s %s", r.Method, r.URL.RequestURI())
}
return nil
}
func (p snapshotPollFailure) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Method != http.MethodGet {
return p.base.RoundTrip(r)
}
p.polls.Add(1)
if snapshotPollRequestError(r) != nil {
p.invalid.Store(true)
}
if p.mode == "tls" {
return nil, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
}
if p.mode == "body-tls" {
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: pollCertificateBody{}, Request: r}, nil
}
return p.base.RoundTrip(r)
}
type pollCertificateBody struct{}
func (pollCertificateBody) Read([]byte) (int, error) {
return 0, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
}
func (pollCertificateBody) Close() error { return nil }
// Each observer runs in an owned child: a polling regression cannot prevent
// the parent from joining it, nor restore a client while it is still in use.
func TestSnapshotAdmittedPollFailureKeepsOriginalOperation(t *testing.T) {
for _, mode := range []string{"401", "403", "404", "409", "412", "428", "503", "tls", "body-tls", "success", "refused", "wrong-id"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotAdmittedPollChild$", "-test.count=1")
cmd.Env = append(os.Environ(), "SWBLOCK_POLL_CONTROL="+mode)
cmd.WaitDelay = time.Second
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bounded observer: %v (context %v): %s", err, ctx.Err(), output)
}
})
}
}
func TestSnapshotAdmittedPollChild(t *testing.T) {
mode := os.Getenv("SWBLOCK_POLL_CONTROL")
if mode == "" {
t.Skip("owned child only")
}
var posts, polls atomic.Int32
var invalid atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := snapshotPollRequestError(r); err != nil {
invalid.Store(true)
http.Error(w, err.Error(), 400)
return
}
if r.Method == http.MethodPost {
posts.Add(1)
w.Header().Set("Location", "/operations/original")
w.WriteHeader(202)
_ = json.NewEncoder(w).Encode(map[string]string{"operation_id": "original", "state": "running"})
return
}
if mode == "success" || mode == "refused" || mode == "wrong-id" || mode == "loop" {
id, state := "original", "succeeded"
if mode == "wrong-id" {
id = "changed"
}
if mode == "loop" {
state = "running"
fmt.Fprintln(os.Stderr, "poll-loop-entered")
}
if mode == "refused" {
state = "refused"
}
_ = json.NewEncoder(w).Encode(map[string]any{"operation_id": id, "state": state, "result": map[string]bool{"ok": true}, "code": "not_admitted", "message": "definite operation refusal"})
return
}
code, err := strconv.Atoi(mode)
if err != nil {
http.Error(w, "unexpected mode", 500)
return
}
http.Error(w, "status read refused", code)
}))
defer server.Close()
previous := chunkHTTPClient
defer func() { chunkHTTPClient = previous }()
chunkHTTPClient = &http.Client{Transport: snapshotPollFailure{base: http.DefaultTransport, mode: mode, polls: &polls, invalid: &invalid}}
var out, diag bytes.Buffer
exit := chunkObserveSnapshot(server.URL, time.Second, map[string]any{"requestID": "original"}, false, &out, &diag)
if posts.Load() != 1 || polls.Load() != 1 || invalid.Load() {
t.Fatalf("wire proof: posts=%d polls=%d invalid=%v", posts.Load(), polls.Load(), invalid.Load())
}
if mode == "success" {
if exit != 0 || !strings.Contains(out.String(), `"ok":true`) {
t.Fatalf("terminal success: exit=%d out=%s", exit, out.String())
}
return
}
body := chunkErrorOut(t, out.String())
if mode == "refused" {
if exit != 1 || body.Code != "not_admitted" || body.Retryable {
t.Fatalf("terminal refusal: exit=%d answer=%+v", exit, body)
}
return
}
if exit != 3 || body.Code != "outcome_unknown" || !body.Retryable || !strings.Contains(body.Message, "replay key") || !strings.Contains(body.Message, "original") || posts.Load() != 1 || polls.Load() != 1 || invalid.Load() {
t.Fatalf("exit=%d answer=%+v posts=%d polls=%d invalid=%v", exit, body, posts.Load(), polls.Load(), invalid.Load())
}
}
func TestSnapshotPollWireControlRejectsChangedIdentityAndRoute(t *testing.T) {
for _, row := range []struct{ method, path, body string }{
{"POST", "/wrong", `{"requestID":"original"}`},
{"POST", "/chunk/snapshot", `{"requestID":"changed"}`},
{"GET", "/operations/changed", ""},
} {
req, _ := http.NewRequest(row.method, "http://example"+row.path, strings.NewReader(row.body))
if err := snapshotPollRequestError(req); err == nil {
t.Fatalf("wire control accepted %+v", row)
}
}
for _, row := range []struct{ method, path, body string }{
{"POST", "/chunk/snapshot", `{"requestID":"original"}`},
{"GET", "/operations/original", ""},
} {
req, _ := http.NewRequest(row.method, "http://example"+row.path, strings.NewReader(row.body))
if err := snapshotPollRequestError(req); err != nil {
t.Fatal(err)
}
}
}
var _ io.ReadCloser = pollCertificateBody{}
// Negative control: an observer that never reaches a terminal state is killed
// and joined before any parent-side fixtures can be reclaimed.
func TestSnapshotPollWatchdogJoinsAnUnfinishedObserver(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotAdmittedPollChild$", "-test.count=1")
cmd.Env = append(os.Environ(), "SWBLOCK_POLL_CONTROL=loop")
cmd.WaitDelay = time.Second
output, err := cmd.CombinedOutput()
if ctx.Err() != context.DeadlineExceeded || err == nil || cmd.ProcessState == nil || !strings.Contains(string(output), "poll-loop-entered") {
t.Fatalf("watchdog did not terminate and join: ctx=%v err=%v state=%v output=%s", ctx.Err(), err, cmd.ProcessState, output)
}
}
@@ -0,0 +1,52 @@
package main
import (
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// A whole-job command has stable derived operation identities. Preserve its
// existing wire exit while obtaining its failure class and cure centrally.
func operatorAnswer(err error, contract answer.Contract) (answer.Policy, error) {
var presented *operatorFailure
if errors.As(err, &presented) && presented.contract == contract {
return presented.policy, err
}
observed := answer.EnsureEvidence(answer.PossiblyAdmitted, err)
if _, listed := answer.ErrorKind(observed); !listed {
// These callers have already checked a reply's identity/completeness
// or lost their workflow's observation; this is not a transport guess.
observed = answer.Rekind(observed, answer.Guard("outcome_unknown"))
}
policy, check := answer.PolicyOf(observed, contract)
if check != nil {
policy, _ = answer.Lookup(answer.Unsent, answer.Guard("internal"))
return policy, fmt.Errorf("%w; %v", err, check)
}
if policy.Code == "outcome_unknown" {
return policy, &operatorFailure{policy, contract, fmt.Errorf("the outcome is unknown (%w); %s", err, policy.Cure)}
}
return policy, &operatorFailure{policy, contract, fmt.Errorf("%s: %w; %s", policy.Code, err, policy.Cure)}
}
type operatorFailure struct {
policy answer.Policy
contract answer.Contract
err error
}
func (e *operatorFailure) Error() string { return e.err.Error() }
func (e *operatorFailure) Unwrap() error { return e.err }
func inspectionError(err error) error {
if err == nil {
return nil
}
if _, listed := answer.ErrorKind(err); !listed {
return err
} // explicit business finding, not a transport failure
_, detail := operatorAnswer(err, answer.Shell)
return detail
}
+27 -38
View File
@@ -19,8 +19,8 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -130,8 +130,9 @@ func volumeBackup(ctx context.Context, env verbEnv, o backupOpts, stdout, stderr
return refuse("snapshot", fmt.Sprintf("%s; a cut that timed out keeps what it uploaded; after correcting the refusal, run the same command (it resumes the same request and reuses completed uploads): %s", text, again))
}
if err != nil {
fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", err, again)
return 1
policy, detail := operatorAnswer(err, answer.VolumeJob)
fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", detail, again)
return policy.Exit
}
fmt.Fprintf(stdout, "sw-block volume backup: snapshot %s of %s: head generation %d, cut LSN %d, at %s\n",
shQuote(a.Name), o.Volume, *a.HeadGen, *a.CutLSN, time.Unix(0, *a.CreatedNs).UTC().Format(time.RFC3339))
@@ -163,8 +164,13 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
client := *env.HTTP
client.Timeout = timeout + 5*time.Second
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
unknown := func(why string) (snapshotAnswer, *snapshotRefusal, error) {
return snapshotAnswer{}, nil, fmt.Errorf("the snapshot's outcome is unknown (%s)", why)
unknown := func(why string, causes ...error) (snapshotAnswer, *snapshotRefusal, error) {
cause := error(errors.New(why))
if len(causes) == 1 {
cause = fmt.Errorf("%s: %w", why, causes[0])
}
_, detail := operatorAnswer(cause, answer.VolumeJob)
return snapshotAnswer{}, nil, detail
}
rctx, cancel := context.WithTimeout(ctx, timeout)
req, err := http.NewRequestWithContext(rctx, http.MethodPost, "http://"+status+"/chunk/snapshot", bytes.NewReader(body))
@@ -174,16 +180,16 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Prefer", "respond-async")
resp, err := client.Do(req)
resp, err := answer.DoHTTP(&client, req, answer.Unsent)
if err != nil {
cancel()
return unknown(err.Error())
return unknown("snapshot admission answer not received", err)
}
b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
resp.Body.Close()
cancel()
if err != nil {
return unknown("answer unreadable: " + err.Error())
return unknown("snapshot answer unreadable", err)
}
if resp.StatusCode == http.StatusAccepted {
var adm snapshotOperationIdentity
@@ -191,7 +197,7 @@ func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requ
return unknown("the admission answer does not identify this backup's operation")
}
if b, err = observeSnapshotOperation(ctx, env, client, status, adm, timeout); err != nil {
return unknown(err.Error())
return unknown("snapshot observation failed", err)
}
var op struct {
State string `json:"state"`
@@ -272,7 +278,7 @@ func observeSnapshotOperation(ctx context.Context, env verbEnv, client http.Clie
cancel()
return nil, err
}
resp, err := client.Do(req)
resp, err := answer.DoHTTP(&client, req, answer.PossiblyAdmitted)
var b []byte
if err == nil {
b, err = io.ReadAll(io.LimitReader(resp.Body, 64<<10))
@@ -402,8 +408,9 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
return ops.VolumeStatusExitInvalid
}
unknown := func(step string, err error) int {
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, err, ways)
return 1
policy, detail := operatorAnswer(err, answer.VolumeJob)
fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, detail, ways)
return policy.Exit
}
src, err := readEnvFile(filepath.Join(env.EtcDir, o.Source+".env"))
if err != nil {
@@ -425,10 +432,11 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
resp, err := restoreCreateRPC(rctx, master, &control.CreateVolumeRequest{VolumeId: v.VolumeID, SourceVolume: o.Source, SourceSnapshot: o.Snapshot, CreateRequestId: id})
cancel()
if err != nil {
if code := restoreRefusal(err); code != "" {
return refuse("restore", code+": "+err.Error())
if policy, detail := operatorAnswer(err, answer.VolumeJob); !policy.Retryable {
fmt.Fprintf(stderr, "sw-block volume restore: restore: %v\n", detail)
return policy.Exit
}
return unknown("restore", fmt.Errorf("the outcome is unknown (%v)", err))
return unknown("restore", err)
}
if resp.GetVolumeId() != v.VolumeID || !resp.GetStoreReady() {
return unknown("restore", errors.New("the master did not confirm the new volume store-ready"))
@@ -476,10 +484,10 @@ func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []strin
break
}
}
switch status.Code(err) {
case codes.FailedPrecondition, codes.InvalidArgument, codes.AlreadyExists, codes.PermissionDenied:
fmt.Fprintf(stderr, "sw-block volume restore: %s: refused: %v; the new volume exists but is not placed; to undo it: %s\n", step, err, abort)
return ops.VolumeStatusExitInvalid
policy, detail := operatorAnswer(err, answer.VolumePlacement)
if policy.Retry == answer.Never && !policy.Retryable {
fmt.Fprintf(stderr, "sw-block volume restore: %s: refused: %v; the new volume exists but is not placed; to undo it: %s\n", step, detail, abort)
return policy.Exit
}
return unknown(step, err)
}
@@ -631,25 +639,6 @@ var (
runOpsRelease = chunkRelease
)
// restoreRefusal maps a refused restore create to its JSON code (the codes
// ops chunk restore reports); "" for an outcome a re-run may change.
func restoreRefusal(err error) string {
if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
return "restore_source_not_own"
}
switch status.Code(err) {
case codes.NotFound:
return "snapshot_not_found"
case codes.AlreadyExists:
return "target_exists"
case codes.InvalidArgument:
return codeBadRequestCLI
case codes.FailedPrecondition:
return "not_admitted"
}
return ""
}
// restorePlaced reads the volume's published authority line at the master
// (QueryVolumeStatus: the publisher's line itself, which exists before any
// lease is granted on it) and its bindings (QueryWorkspace): placed when
@@ -590,6 +590,9 @@ func TestVolumeBackupInterruptedResumesWithTheSameCommand(t *testing.T) {
}
code, _, errs := runBackup(env, "vol-a", "--name", "nightly")
wantCode := 1
if c == "lost" || c == "unknown" {
wantCode = 3
}
if c == "refuse" {
wantCode = 2
}
@@ -617,7 +620,7 @@ func TestVolumeBackupIncompleteAnswerIsUnknown(t *testing.T) {
sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), true)
sh.setMode("missing-" + f)
code, out, errs := runBackup(env, "vol-a", "--name", "n1")
if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
if code != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") {
t.Fatalf("missing %s: %d %s %s", f, code, out, errs)
}
sh.setMode("")
@@ -720,7 +723,11 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
}
m.failNext = r.fail
code, _, errs := runRestore(env, restoreArgs(h)...)
if code != 1 || !strings.Contains(errs, "to finish, run the same command: sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r") ||
wantExit := 1
if r.step == "restore" || r.step == "place" || r.fail != "" {
wantExit = 3
}
if code != wantExit || !strings.Contains(errs, "to finish, run the same command: sudo /usr/local/bin/sw-block volume restore vol-a --snapshot s1 --as vol-r") ||
!strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("interrupted restore: %d\n%s", code, errs)
}
@@ -786,7 +793,7 @@ func TestVolumeRestoreCrashTableBothWays(t *testing.T) {
// After an abort the name is never created again: the master
// refuses the deleting target, and the catalog's tombstone
// refuses a target that never had HEAD (FailedPrecondition).
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") {
t.Fatalf("restore after abort: %d %s", code, errs)
}
})
@@ -822,7 +829,11 @@ func TestVolumeRestoreRefusals(t *testing.T) {
{"no snapshot flag", []string{"vol-a", "--as", "vol-r"}, "--snapshot is required"},
{"unknown source", append([]string{"vol-z"}, restoreArgs(h)[1:]...), "was vol-z started"},
} {
if code, _, errs := runRestore(env, c.args...); code != 2 || !strings.Contains(errs, c.want) {
wantExit := 2
if c.name == "missing snapshot" {
wantExit = 1
}
if code, _, errs := runRestore(env, c.args...); code != wantExit || !strings.Contains(errs, c.want) {
t.Errorf("%s: %d %s", c.name, code, errs)
}
}
@@ -831,11 +842,11 @@ func TestVolumeRestoreRefusals(t *testing.T) {
if raw, err := os.ReadFile(filepath.Join(env.EtcDir, "vol-a.env")); err != nil || os.WriteFile(sourceT, raw, 0o640) != nil {
t.Fatal(err)
}
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 2 || !strings.Contains(errs, "restore_source_not_own") {
if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 1 || !strings.Contains(errs, "restore_source_not_own") {
t.Errorf("restore target as source: %d %s", code, errs)
}
m.vols["vol-r"] = &restoreRec{source: "vol-a", snap: "s1", req: "another", ready: true}
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "target_exists") {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "target_exists") {
t.Errorf("target of another request: %d %s", code, errs)
}
delete(m.vols, "vol-r")
@@ -853,7 +864,7 @@ func TestVolumeRestoreRefusals(t *testing.T) {
func TestVolumeRestoreRefusedPlacementNamesTheAbort(t *testing.T) {
h, env, m, _ := restoreSetup(t)
m.failNext = "bind-refuse"
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "to undo it: "+abortCmd) {
if code, _, errs := runRestore(env, restoreArgs(h)...); code != 1 || !strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("refused placement: %d %s", code, errs)
}
if h.called("enable") != 0 {
@@ -994,7 +1005,7 @@ func TestVolumeRestorePublicationDuringThePlacement(t *testing.T) {
h3, env3, m3, _ := restoreSetup(t)
m3.failNext = "publish-race-reread-fails"
code, _, errs = runRestore(env3, restoreArgs(h3)...)
if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
if code != 3 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") {
t.Fatalf("failed re-read: %d %s", code, errs)
}
if code, _, errs := runRestore(env3, restoreArgs(h3)...); code != 0 {
@@ -1066,7 +1077,7 @@ func TestVolumeRestoreRefusesAMalformedLayoutAnswer(t *testing.T) {
h, env, m, _ := restoreSetup(t)
m.failNext = "create-badlayout"
code, _, errs := runRestore(env, restoreArgs(h)...)
if code != 1 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
if code != 3 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) {
t.Fatalf("malformed layout answer: %d %s", code, errs)
}
if m.binds != 0 || h.called("enable") != 0 {
+14 -8
View File
@@ -11,6 +11,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
@@ -53,20 +54,25 @@ func runOpsVolumeCreate(args []string, stdout, stderr io.Writer) int {
}
conn, err := link.DialMasterFromEnv(*master)
if err != nil {
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", err)
return 2
policy, detail := operatorAnswer(err, answer.VolumeCreate)
fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", detail)
return policy.Exit
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
fail := func(step string, err error) int {
code, outcome := 78, "refused"
switch status.Code(err) {
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss:
code, outcome = 75, "unknown"
policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.VolumeCreate)
if check != nil {
fmt.Fprintf(stderr, "sw-block ops volume create: %s: %v\n", step, check)
return 75
}
fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; earlier steps may remain recorded; retry the identical name, geometry and placement\n", step, outcome, err)
return code
outcome := "refused"
if policy.Retryable {
outcome = "unknown"
}
fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; %s\n", step, outcome, err, policy.Cure)
return policy.Exit
}
q := &control.CreateVolumeRequest{VolumeId: binding.VolumeId, SizeBytes: *size, ReplicationFactor: 1, Protocol: *protocol, FrontendTransport: *transport, BlockSize: geometry.BlockSize, ChunkBytes: geometry.ChunkBytes}
v, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, q)
+5 -10
View File
@@ -8,8 +8,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// runOpsVolume exposes the same master name binding used by ops chunk.
@@ -38,15 +37,11 @@ func runOpsVolume(args []string, stdout, stderr io.Writer) int {
defer cancel()
id, err := resolveVolumeID(ctx, *master, fs.Arg(0))
if err != nil {
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v\n", err)
// Match blockvolume: an unavailable or unknown master answer is retryable;
// a definite refusal or invalid local configuration needs correction.
if s, ok := status.FromError(err); ok {
switch s.Code() {
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal:
return 75
}
if policy, check := answer.PolicyOf(answer.EnsureEvidence(answer.PossiblyAdmitted, err), answer.VolumeResolve); check == nil {
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v; %s\n", err, policy.Cure)
return policy.Exit
}
fmt.Fprintf(stderr, "sw-block ops volume resolve: %v\n", err)
return 78
}
fmt.Fprintln(stdout, id.String())
@@ -6,7 +6,6 @@ import (
"io"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
const unknownStartOwnerCost = "The master could not prove the current authority holder. START refuses rather than guessing from issued moves, ACKs or prepared bindings. An operator who independently knows the correct host can use the force-move operation's --target-host option; START cannot choose or print that target."
@@ -73,13 +72,13 @@ func prepareVolumeStart(ctx context.Context, v volumeSpec, stdout, stderr io.Wri
client, err := workspaceDial(v.Master)
if err != nil {
fmt.Fprintf(stderr, "sw-block volume start: volume_start_move_not_sent: %v\n", err)
return 1
return workspaceErrorExit(err)
}
defer client.Close()
grant, err := client.CleanMove(setup, q)
if err != nil {
fmt.Fprintf(stderr, "sw-block volume start: volume_start_move: %v; rerun the same volume start (request %s)\n", err, q.RequestId)
return workspaceExit(wsclient.OutcomeOf(err))
return workspaceErrorExit(err)
}
if grant.GetNewEpoch() != epoch+1 || grant.GetOldHost() != v.ServerID {
fmt.Fprintln(stderr, "sw-block volume start: volume_start_move_outcome_unknown: grant is not epoch+1; the unit was not started")
+19 -6
View File
@@ -21,6 +21,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// The whole-job volume commands: each runs on the volume's host, prints
@@ -386,7 +387,7 @@ func getJSON(ctx context.Context, env verbEnv, url string, into any) error {
if err != nil {
return err
}
resp, err := env.HTTP.Do(req)
resp, err := answer.DoHTTP(env.HTTP, req, answer.Unsent)
if err != nil {
return err
}
@@ -633,8 +634,16 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
payload["deadlineNs"] = deadline.UnixNano()
}
body, _ := json.Marshal(payload)
unknown := func(why string) (cutAnswer, error) {
return cutAnswer{}, fmt.Errorf("the cut's outcome is unknown (%s): it may have published", why)
unknown := func(why string, causes ...error) (cutAnswer, error) {
cause := error(errors.New(why))
if len(causes) == 1 {
cause = fmt.Errorf("%s: %w", why, causes[0])
}
policy, detail := operatorAnswer(cause, answer.VolumeStop)
if policy.Retry == answer.Recover {
detail = fmt.Errorf("%w: it may have published", detail)
}
return cutAnswer{}, detail
}
client := *env.HTTP
client.Timeout = timeout + slack
@@ -662,11 +671,15 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
phase := answer.Unsent
if id != "" {
phase = answer.PossiblyAdmitted
}
resp, err := answer.DoHTTP(&client, req, phase)
if err != nil {
cancel()
if id == "" {
return unknown(err.Error())
return unknown("cut admission answer not received", err)
}
time.Sleep(min(env.Poll, time.Until(until)))
continue
@@ -675,7 +688,7 @@ func volumeCut(ctx context.Context, env verbEnv, status, volume string, timeout
resp.Body.Close()
cancel()
if err != nil {
return unknown("answer unreadable: " + err.Error())
return unknown("cut answer unreadable", err)
}
// Every answer speaks this CLI's integer cut API version (this
// CLI's or the one before). Only the first answer may lack it, as a
+23 -23
View File
@@ -9,6 +9,7 @@ import (
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
@@ -67,12 +68,12 @@ lost-range prints the stored lost ranges of the volume's issued forced moves, in
issue order (all of them, or the one of --request-id). It never prints "no loss"
for a forced move whose record is missing or fails its checks.
exit: 0 done; 1 refused by the master (nothing moved); 2 refused locally (usage
or confirmation; nothing sent); 3 outcome unknown: rerun with the SAME
--request-id; 4 the move is issued but its lost range is not proven (or a
stored range is unreadable); 5 not authorized by blockmaster (no client
certificate where it requires mutual TLS, or a certificate or role its role
file does not admit; set SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY, SW_BLOCK_TLS_CA).
exit: 0 done; 1 definite refusal or caller cancellation/deadline before send;
2 local usage/confirmation or server argument refusal; 3 outcome unknown:
rerun with the SAME --request-id; 4 unproven lost-range readout; 5 certificate
or role rejection; 75 proven unsent remote failure; 78 local credential or
configuration error. Set SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and SW_BLOCK_TLS_CA
for a master that requires mutual TLS.
`
// workspaceDial is swapped by tests.
@@ -105,20 +106,16 @@ func runOpsWorkspace(args []string, stdout, stderr io.Writer) int {
}
}
func workspaceExit(o wsclient.Outcome) int {
switch o {
case wsclient.OutcomeOK:
// Render the shared projection without a second outcome-to-exit table.
func workspaceErrorExit(err error) int {
if err == nil {
return wsExitOK
case wsclient.OutcomeRefusedLocally:
return wsExitRefusedLocally
case wsclient.OutcomeRefused:
return wsExitRefused
case wsclient.OutcomeReadoutUnproven:
return wsExitReadoutUnproven
case wsclient.OutcomeNotAuthorized:
return wsExitNotAuthorized
}
return wsExitUnknown
if code, ok := wsclient.ExitOf(err); ok {
return code
}
policy, _ := operatorAnswer(err, answer.Workspace)
return policy.Exit
}
// workspaceForceMoveAnswer is output only; admission and exit policy stay in
@@ -199,7 +196,7 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "%s: refused locally, nothing sent: master address: %v\n", workspaceForceMoveName, err)
return wsExitRefusedLocally
return workspaceErrorExit(err)
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -240,13 +237,16 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stderr, "%s: admissible at %s, master clock (the lease horizon plus clock skew); wait, there is no bypass\n", workspaceForceMoveName, wsclient.FormatTime(at.UnixNano()))
}
return wsExitRefused
case wsclient.OutcomeUnsent:
fmt.Fprintf(stderr, "%s: nothing sent: %v\n", workspaceForceMoveName, err)
return workspaceErrorExit(err)
case wsclient.OutcomeUnknown:
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
fmt.Fprintf(stderr, "%s: outcome unknown: rerun with the SAME --request-id %s\n", workspaceForceMoveName, m.RequestID)
return wsExitUnknown
default:
fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err)
return workspaceExit(o)
return workspaceErrorExit(err)
}
}
@@ -287,7 +287,7 @@ func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.Forced
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintf(stderr, "%s --dry-run: the preview failed; nothing was written\n", workspaceForceMoveName)
}
return workspaceExit(wsclient.OutcomeOf(err))
return workspaceErrorExit(err)
}
if answer != nil {
answer.Admitted, answer.Code = p.GetAdmitted(), p.GetCode()
@@ -350,7 +350,7 @@ func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "%s: master address: %v\n", workspaceLostRangeName, err)
return wsExitRefusedLocally
return workspaceErrorExit(err)
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -361,7 +361,7 @@ func runWorkspaceLostRange(args []string, stdout, stderr io.Writer) int {
if wsclient.OutcomeOf(err) == wsclient.OutcomeReadoutUnproven {
fmt.Fprintf(stderr, "%s: a forced move's lost range is missing or unreadable: the readout is NOT proven; do not assume no loss\n", workspaceLostRangeName)
}
return workspaceExit(wsclient.OutcomeOf(err))
return workspaceErrorExit(err)
}
if len(ranges) == 0 {
fmt.Fprintf(stdout, "volume %s has no issued forced move\n", volume)
@@ -54,7 +54,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace move: refused locally, nothing sent: %v\n", err)
return wsExitRefusedLocally
return workspaceErrorExit(err)
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -66,7 +66,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int {
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintf(stderr, "workspace move: outcome unknown; rerun with the SAME --request-id %s\n", q.RequestId)
}
return workspaceExit(wsclient.OutcomeOf(err))
return workspaceErrorExit(err)
}
answer.Issued, answer.MoveID, answer.NewHost, answer.NewReplica = true, g.GetRequestId(), g.GetNewHost(), g.GetNewReplicaId()
epoch := g.GetNewEpoch()
@@ -44,7 +44,7 @@ func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace revoke: refused locally, nothing sent: %v\n", err)
return wsExitRefusedLocally
return workspaceErrorExit(err)
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -55,7 +55,7 @@ func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int {
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintln(stderr, "workspace revoke: outcome unknown; inspect workspace show before proceeding")
}
return workspaceExit(wsclient.OutcomeOf(err))
return workspaceErrorExit(err)
}
fmt.Fprintf(stdout, "revocation requested: volume %s holder %s@%d expiry_ns %d\n", id.VolumeId, id.ReplicaId, id.Epoch, lease.GetExpiresAtNs())
if withoutSeal {
+2 -3
View File
@@ -8,7 +8,6 @@ import (
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
// Read-only M2 Granted -> Revoking -> Acked -> Moved (clean) facts,
@@ -31,7 +30,7 @@ func runWorkspaceShow(args []string, stdout, stderr io.Writer) int {
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace show: refused locally, nothing sent: %v\n", err)
return wsExitRefusedLocally
return workspaceErrorExit(err)
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
@@ -39,7 +38,7 @@ func runWorkspaceShow(args []string, stdout, stderr io.Writer) int {
view, err := c.Show(ctx, volume)
if err != nil {
fmt.Fprintf(stderr, "workspace show: %v\n", err)
return workspaceExit(wsclient.OutcomeOf(err))
return workspaceErrorExit(err)
}
printWorkspaceView(stdout, volume, view)
return wsExitOK
@@ -453,3 +453,33 @@ func TestWorkspaceHelpText(t *testing.T) {
}
}
}
// A master that never answers leaves the call unsent when the caller's
// deadline passes: nothing was refused, and no admission preview is read.
func TestWorkspaceForceMoveUnsentCallerDeadlineIsNotARefusal(t *testing.T) {
silent, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
held := make(chan net.Conn, 16)
go func() {
for {
conn, err := silent.Accept()
if err != nil {
close(held)
return
}
held <- conn
}
}()
t.Cleanup(func() {
silent.Close()
for conn := range held {
conn.Close()
}
})
code, out, errOut := runCLI(forceMoveArgs(silent.Addr().String(), "--confirm-forced", "vol@3", "--timeout", "300ms"))
if code != wsExitRefused || out != "" || strings.Contains(errOut, "refused by the master") || !strings.Contains(errOut, "nothing sent") {
t.Fatalf("exit %d stdout %q stderr %s", code, out, errOut)
}
}
+20 -45
View File
@@ -327,28 +327,12 @@ func (c *TopologyController) processSupportedVolumeLocked(
c.outcome[vol.VolumeID] = "no ask: " + reason
return
}
// Same-ask dedupe: while the identical ask is pending (queued, or
// taken by the publisher and still being applied), do not
// re-enqueue. Without this guard, repeated identical supported
// feeds would mint a new Reassign epoch each iteration —
// authority churn. An identical ask that is no longer pending
// ended without a publication (lost): enqueue it again, keeping
// its DesiredAt so a repeatedly lost ask still reports Stuck.
// Same-ask dedupe: if the identical ask is already the current
// desired, do not re-enqueue. Without this guard, repeated
// identical supported feeds would mint a new Reassign epoch
// each iteration — authority churn.
if prev, ok := c.desired[vol.VolumeID]; ok && sameAsk(prev.Ask, ask) {
since := prev.DesiredAt.UTC().Format(time.RFC3339Nano)
if c.queue.pending(vol.VolumeID) {
c.outcome[vol.VolumeID] = fmt.Sprintf("already desired since %s: %s %s (%s)", since, ask.Intent, ask.ReplicaID, prev.Reason)
return
}
// Not pending also after the publisher published it since the line
// was read: lost only while the line is still the one decided against.
if line, ok := c.reader.VolumeAuthorityLine(vol.VolumeID); ok != hasLine || line != currentLine {
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: the line moved to %s@%d while deciding against %s@%d", line.ReplicaID, line.Epoch, currentLine.ReplicaID, currentLine.Epoch)
return
}
c.queue.enqueue(ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued again %s %s (%s): desired since %s, its last ask ended without a publication", ask.Intent, ask.ReplicaID, prev.Reason, since)
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("already desired since %s: %s %s (%s)", prev.DesiredAt.UTC().Format(time.RFC3339Nano), ask.Intent, ask.ReplicaID, prev.Reason)
return
}
@@ -566,14 +550,13 @@ func (c *TopologyController) decideVolume(
return AssignmentAsk{}, "the current primary is acceptable; rebalance target " + target.ReplicaID + " has no planned-move evidence", false
}
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: target.ReplicaID,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: IntentReassign,
Evidence: plannedEvidence(target.PromotionEvidence),
Incarnation: target.Incarnation,
ExpectCurrent: expectedLineOf(currentLine),
VolumeID: vol.VolumeID,
ReplicaID: target.ReplicaID,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: IntentReassign,
Evidence: plannedEvidence(target.PromotionEvidence),
Incarnation: target.Incarnation,
}, "rebalance", true
}
return AssignmentAsk{}, "the current primary is acceptable", false
@@ -600,14 +583,13 @@ func (c *TopologyController) decideVolume(
// its target (one decider): no evidence, no promotion.
if best.PromotionEvidence.Kind == adapter.PrimaryKindPromotion {
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: best.ReplicaID,
DataAddr: best.DataAddr,
CtrlAddr: best.CtrlAddr,
Intent: IntentReassign,
Evidence: best.PromotionEvidence,
Incarnation: best.Incarnation,
ExpectCurrent: expectedLineOf(currentLine),
VolumeID: vol.VolumeID,
ReplicaID: best.ReplicaID,
DataAddr: best.DataAddr,
CtrlAddr: best.CtrlAddr,
Intent: IntentReassign,
Evidence: best.PromotionEvidence,
Incarnation: best.Incarnation,
}, "failover", true
}
why = "failover target " + best.ReplicaID + " has no promotion evidence"
@@ -641,17 +623,10 @@ func refreshAsk(volumeID string, current ReplicaCandidate, line AuthorityBasis)
CtrlAddr: current.CtrlAddr,
Intent: IntentRefreshEndpoint,
Incarnation: current.Incarnation,
ExpectCurrent: expectedLineOf(line),
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr},
}
}
// expectedLineOf conditions an ask on the line it was decided against: a
// publication that lands while the ask waits in the queue (an operator's
// failback) refuses it instead of being overwritten.
func expectedLineOf(line AuthorityBasis) *ExpectedLine {
return &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}
}
func volumeIncludesReplica(vol VolumeTopologySnapshot, replicaID string) bool {
for _, slot := range vol.Slots {
if slot.ReplicaID == replicaID {
@@ -1,252 +0,0 @@
package authority
import (
"context"
"errors"
"strings"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
)
// The same-ask dedupe holds a desired Reassign only while that ask is
// pending: queued, or taken by the publisher and still being applied. An
// ask the publisher took and ended without publishing (its apply refused
// it) is lost, and the next intake of the same state enqueues it again.
// Holding the lost ask as "already desired" would keep the volume on its
// old primary for good.
func TestALostReassignIsEnqueuedAgainOnTheNextIntake(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
ctrl := NewTopologyController(TopologyControllerConfig{}, reader)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
submit := func() {
t.Helper()
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
}
submit()
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("first intake: %+v, want Reassign r2", ask)
}
// The publisher holds the ask (applying it): the same state again is
// deduplicated, nothing is queued twice.
submit()
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "already desired since ") {
t.Fatalf("while the ask is being applied: outcome %q, want already desired", out)
}
// The apply ended without a publication (the line is still r1@1) and
// the publisher waits for its next ask: the ask is lost.
next := make(chan AssignmentAsk, 1)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
go func() {
if ask, err := ctrl.Next(ctx); err == nil {
next <- ask
}
}()
synctest.Wait() // the publisher is back in Next, holding nothing
submit()
select {
case ask := <-next:
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("after the loss: %+v, want Reassign r2 again", ask)
}
case <-ctx.Done():
t.Fatalf("a lost Reassign was never enqueued again; the controller's outcome: %q", ctrl.LastOutcome("v1"))
}
})
}
// A Reassign lost again and again keeps its first DesiredAt across every
// re-enqueue, so it still becomes Stuck once the retry window passes from
// that first desire: a retry that re-anchored DesiredAt would never report
// the volume stuck however long its asks keep failing.
func TestARepeatedlyLostReassignKeepsItsDesiredAtAndBecomesStuck(t *testing.T) {
const window = 10 * time.Second
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
ctrl := NewTopologyController(TopologyControllerConfig{RetryWindow: window}, reader)
clk := newFakeClock(time.Date(2026, 12, 5, 9, 0, 0, 0, time.UTC))
ctrl.SetNowForTest(clk.Now)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
first := clk.Now()
ended, cancel := context.WithCancel(context.Background())
cancel() // the publisher's next call after an apply that published nothing
for cycle := 0; cycle < 4; cycle++ {
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if cycle > 0 && !strings.HasPrefix(ctrl.LastOutcome("v1"), "enqueued again Reassign r2") {
t.Fatalf("cycle %d: outcome %q, want the lost ask enqueued again", cycle, ctrl.LastOutcome("v1"))
}
if d, ok := ctrl.DesiredFor("v1"); !ok || !d.DesiredAt.Equal(first) {
t.Fatalf("cycle %d at +%v: desired %+v (ok=%v), want DesiredAt kept at the first desire %v", cycle, clk.Now().Sub(first), d, ok, first)
}
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("cycle %d: took %+v, want Reassign r2", cycle, ask)
}
_, _ = ctrl.Next(ended) // the apply ended without a publication: the ask is lost
clk.Advance(4 * time.Second)
}
// +16 s since the first desire, past the 10 s window: the latest intake
// (+12 s) found the desire unconfirmed past the window.
ev, stuck := ctrl.LastConvergenceStuck("v1")
if !stuck {
t.Fatalf("a Reassign lost on every apply for %v is not reported stuck (window %v)", clk.Now().Sub(first), window)
}
if !ev.DesiredAt.Equal(first) || ev.Ask.ReplicaID != "r2" {
t.Fatalf("stuck evidence %+v, want the first desire (%v) of Reassign r2", ev, first)
}
}
// publishOnRead runs publish once, right after the controller's skip+1-th
// line read: the publisher applies its ask between the read an intake decides
// against and that intake's dedupe.
type publishOnRead struct {
*fakeBasisReader
skip int
publish func()
}
func (r *publishOnRead) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) {
line, ok := r.fakeBasisReader.VolumeAuthorityLine(volumeID)
if r.publish != nil {
if r.skip > 0 {
r.skip--
} else {
p := r.publish
r.publish = nil
p()
}
}
return line, ok
}
// An ask the publisher publishes, and then asks past, while an intake is
// deciding against the line read before that publication is not lost: the
// intake must not enqueue it again, or a planned move would be minted twice.
func TestAnAskPublishedDuringTheIntakeIsNotEnqueuedAgain(t *testing.T) {
reader := newFakeBasisReader()
line := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}
reader.Set("v1", "r1", line)
publishing := &publishOnRead{fakeBasisReader: reader}
ctrl := NewTopologyController(TopologyControllerConfig{}, publishing)
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if ask := nextAskOrFail(t, ctrl); ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("first intake: %+v, want Reassign r2", ask)
}
ended, cancel := context.WithCancel(context.Background())
cancel()
publishing.skip = 1 // the intake's load count reads the line first
publishing.publish = func() {
reader.Set("v1", "r2", AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"})
_, _ = ctrl.Next(ended) // published: the publisher is back for its next ask
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if out := ctrl.LastOutcome("v1"); strings.HasPrefix(out, "enqueued again") {
t.Fatalf("an ask published during the intake was enqueued again: %q", out)
}
expectNoNext(t, ctrl)
}
// A controller Reassign waits in the queue until the publisher takes it. A
// publication that lands meanwhile outside the queue (an operator's failback)
// is not overwritten by the ask decided against the older line, whether the
// ask is a first one or a lost one enqueued again.
func TestAQueuedReassignDoesNotOverwriteALaterPublication(t *testing.T) {
for _, lost := range []bool{false, true} {
holder := &basisReaderHolder{}
ctrl := NewTopologyController(TopologyControllerConfig{}, holder)
pub := NewPublisher(ctrl)
holder.set(pub)
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
line, _ := pub.VolumeAuthorityLine("v1")
r1 := candidate("r1", "s1", "d1", "c1", 10)
r1.Reachable = false
snap := ClusterSnapshot{
CollectedRevision: 2,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{clusterVolume("v1", line, r1, candidate("r2", "s2", "d2", "c2", 20), candidate("r3", "s3", "d3", "c3", 10))},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if lost {
nextAskOrFail(t, ctrl)
ended, cancel := context.WithCancel(context.Background())
cancel()
_, _ = ctrl.Next(ended) // the apply ended without a publication
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
if out := ctrl.LastOutcome("v1"); !strings.HasPrefix(out, "enqueued again Reassign r2") {
t.Fatalf("outcome %q, want the lost ask enqueued again", out)
}
}
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r3", DataAddr: "d3", CtrlAddr: "c3", Intent: IntentReassign,
Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 10, Basis: adapter.BasisPlanned},
ExpectCurrent: &ExpectedLine{ReplicaID: line.ReplicaID, Epoch: line.Epoch}}); err != nil {
t.Fatalf("failback: %v", err)
}
ask := nextAskOrFail(t, ctrl)
if ask.Intent != IntentReassign || ask.ReplicaID != "r2" {
t.Fatalf("lost=%v: took %+v, want Reassign r2", lost, ask)
}
if err := pub.apply(ask); !errors.Is(err, ErrExpectedLineMoved) {
t.Fatalf("lost=%v: the queued Reassign decided against %s@%d: err=%v, want ErrExpectedLineMoved", lost, line.ReplicaID, line.Epoch, err)
}
if after, _ := pub.VolumeAuthorityLine("v1"); after.ReplicaID != "r3" || after.Epoch != line.Epoch+1 {
t.Fatalf("lost=%v: line %+v, want the failback's r3@%d", lost, after, line.Epoch+1)
}
}
}
-17
View File
@@ -14,10 +14,6 @@ type assignmentQueue struct {
items map[string]AssignmentAsk
order []string
wake chan struct{}
// taken is the volume of the ask the publisher took last and is still
// applying: it is cleared when the publisher asks for its next one (the
// publisher applies one ask at a time, between two calls of next).
taken string
}
func newAssignmentQueue() *assignmentQueue {
@@ -46,19 +42,7 @@ func (q *assignmentQueue) discard(volumeID string) {
delete(q.items, volumeID)
}
// pending reports whether volumeID's ask is queued or still being applied.
// A desired ask that is neither ended without a publication (lost).
func (q *assignmentQueue) pending(volumeID string) bool {
q.mu.Lock()
defer q.mu.Unlock()
_, queued := q.items[volumeID]
return queued || q.taken == volumeID
}
func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
q.mu.Lock()
q.taken = "" // the publisher is done with the ask it took last
q.mu.Unlock()
for {
q.mu.Lock()
if len(q.order) > 0 {
@@ -70,7 +54,6 @@ func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) {
continue
}
delete(q.items, vid)
q.taken = vid
q.mu.Unlock()
return ask, nil
}
@@ -7,6 +7,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net"
"net/http"
@@ -97,7 +98,7 @@ func (r *InClusterPVCMetadataResolver) ResolvePVCUID(ctx context.Context, name,
return "", err
}
req.Header.Set("Authorization", "Bearer "+r.token)
resp, err := r.client.Do(req)
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
if err != nil {
return "", err
}
@@ -150,7 +151,7 @@ func (r *InClusterSwBlockVolumeRegistrar) EnsureVolumeObject(ctx context.Context
return err
}
r.setJSONHeaders(req)
resp, err := r.client.Do(req)
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
if err != nil {
return err
}
@@ -177,7 +178,7 @@ func (r *InClusterSwBlockVolumeRegistrar) patchVolumeSpec(ctx context.Context, n
}
r.setJSONHeaders(req)
req.Header.Set("Content-Type", "application/merge-patch+json")
resp, err := r.client.Do(req)
resp, err := answer.DoHTTP(r.client, req, answer.Unsent)
if err != nil {
return err
}
@@ -16,6 +16,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
@@ -293,13 +294,20 @@ func grpcAddress(a string) (string, error) {
// Inspect one owned context's completion before its immutable winning cause.
// Do not mix the parent's pre-expiry cause with the child's later Err.
func singleFilerContextError(ctx context.Context, err error) error {
if answer.DefiniteAnswer(err) {
return err
}
done := ctx.Err()
if done == nil {
return err
}
cause := context.Cause(ctx)
if errors.Is(cause, ErrSingleFilerWindowExpired) {
return fmt.Errorf("%w: %w: %v", status.Error(codes.Unavailable, "filer transport unavailable"), cause, err)
return answer.Rekind(fmt.Errorf("%w: %w: %w", status.Error(codes.Unavailable, "filer transport unavailable"), cause, err), answer.Connection)
}
return fmt.Errorf("%w: %w: %v", done, cause, err)
kind := answer.Canceled
if done == context.DeadlineExceeded {
kind = answer.CallerDeadline
}
return answer.Rekind(fmt.Errorf("%w: %w: %w", done, cause, err), kind)
}
@@ -20,6 +20,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
type configFiler struct {
@@ -820,3 +821,21 @@ func TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus(t *testing.T) {
t.Fatalf("invalid configured master must refuse before census: %v", err)
}
}
func TestSingleFilerReviewPreservesDefiniteAndCallerWinner(t *testing.T) {
ctx, cancel := context.WithCancelCause(context.Background())
cancel(ErrSingleFilerWindowExpired)
got := singleFilerContextError(ctx, answer.Record(answer.PossiblyAdmitted, status.Error(codes.Unimplemented, "wrong service")))
p, check := answer.PolicyOf(got)
if check != nil || p.Code != "unsupported" || p.Retryable {
t.Errorf("definite refusal lost: %+v %v", p, check)
}
ctx, cancel = context.WithCancelCause(context.Background())
custom := errors.New("caller canceled census")
cancel(custom)
got = singleFilerContextError(ctx, answer.Record(answer.Unsent, status.Error(codes.Unavailable, "earlier network error")))
p, check = answer.PolicyOf(got)
if check != nil || p.Code != "canceled" || !errors.Is(got, custom) {
t.Errorf("caller winner lost: %+v %v %v", p, check, got)
}
}
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -87,9 +88,7 @@ const blobIdleConnsPerHost = 64
// in flight to one volume server opened a new TCP connection and left a
// TIME_WAIT behind, enough to exhaust ephemeral ports at a high rate.
func newBlobHTTPClient(timeout time.Duration) *http.Client {
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.MaxIdleConnsPerHost = blobIdleConnsPerHost
tr.MaxIdleConns = 4 * blobIdleConnsPerHost
tr := answer.NewHTTPTransport(answer.HTTPPool{MaxIdleConnsPerHost: blobIdleConnsPerHost, MaxIdleConns: 4 * blobIdleConnsPerHost})
return &http.Client{Timeout: timeout, Transport: tr}
}
@@ -370,7 +369,7 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) {
if err != nil {
return nil, err
}
resp, err := c.http.Do(req)
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
if err != nil {
return nil, err
}
@@ -379,7 +378,7 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) {
// Drain before close so the connection is reused: a 404 is an
// ordinary answer while a restore target hydrates.
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
return nil, &blobStatusError{code: resp.StatusCode, host: host}
return nil, answer.HTTPStatusFailure(resp.StatusCode, &blobStatusError{code: resp.StatusCode, host: host})
}
return io.ReadAll(resp.Body)
}
@@ -439,7 +438,7 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error {
if err != nil {
return err
}
resp, err := c.http.Do(req)
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
if err != nil {
return err
}
@@ -447,10 +446,10 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
resp.Body.Close()
if resp.StatusCode == http.StatusBadRequest {
return fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode)
return answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("%w: delete %s: http %d", ErrBlobDeleteRejected, fid, resp.StatusCode))
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode)
return answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("chunkstore: delete %s: http %d", fid, resp.StatusCode))
}
}
return nil
@@ -0,0 +1,48 @@
package chunkstore
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestBlobHTTPAnswerSurvivesLayoutFetch(t *testing.T) {
for _, row := range []struct {
status int
code string
exit int
}{
{400, "bad_request", 2}, {401, "not_authorized", 5}, {500, "outcome_unknown", 3}, {503, "outcome_unknown", 3},
} {
t.Run(fmt.Sprint(row.status), func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(row.status) }))
defer server.Close()
host := strings.TrimPrefix(server.URL, "http://")
filer := &fakeFilerGRPC{
lookupResp: &filerpb.LookupDirectoryEntryResponse{Entry: &filerpb.Entry{Name: "root", Chunks: []*filerpb.FileChunk{{FileId: "7,01abcdef", Size: 1}}}},
lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: host}}}}},
}
client := startFakeFiler(t, filer)
catalog, err := NewBCatalog(client, client, "/blocks")
if err != nil {
t.Fatal(err)
}
store, err := catalog.Store(VolumeRef{Name: "v", ID: layout.VolumeID{1}})
if err != nil {
t.Fatal(err)
}
_, found, err := store.Fetch(context.Background(), "/blocks/v-01000000/root")
policy, check := answer.PolicyOf(err, answer.Chunk)
if err == nil || found || check != nil || policy.Code != row.code || policy.Exit != row.exit {
t.Fatalf("found=%t err=%v policy=%+v check=%v", found, err, policy, check)
}
})
}
}
@@ -14,6 +14,7 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"math"
"net"
@@ -207,7 +208,7 @@ func (c *SWFS) probe(ctx context.Context, r blobRange, i int) ([]byte, error) {
if err != nil {
return nil, err
}
resp, err := c.http.Do(req)
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
if err != nil {
return nil, fmt.Errorf("chunkstore: probe %s: %w", fid, err)
}
@@ -218,7 +219,7 @@ func (c *SWFS) probe(ctx context.Context, r blobRange, i int) ([]byte, error) {
case http.StatusNotFound:
return nil, fmt.Errorf("%w %s", errBlobAbsent, fid)
}
return nil, fmt.Errorf("chunkstore: probe %s: http %d", fid, resp.StatusCode)
return nil, answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("chunkstore: probe %s: http %d", fid, resp.StatusCode))
}
// upload POSTs data raw to fid on the volume server at host.
@@ -235,14 +236,14 @@ func (c *SWFS) upload(ctx context.Context, host, fid, auth string, fsync bool, d
if auth != "" {
req.Header.Set("Authorization", "BEARER "+auth)
}
resp, err := c.http.Do(req)
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
if err != nil {
return fmt.Errorf("chunkstore: upload %s: %w", fid, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
err := fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body)))
err := answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body))))
switch {
case resp.StatusCode == http.StatusUnauthorized:
return errors.Join(errRangeAuth, err)
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"net/http"
"strings"
)
@@ -55,14 +56,14 @@ func (c *SWFS) headFromAll(ctx context.Context, urls []string, fid string) (uint
if err != nil {
return 0, false, err
}
resp, err := c.http.Do(req)
resp, err := answer.DoHTTP(c.http, req, answer.Unsent)
if err == nil {
closeErr := resp.Body.Close()
switch {
case closeErr != nil:
err = closeErr
case resp.StatusCode != http.StatusOK:
err = &blobStatusError{code: resp.StatusCode, host: host}
err = answer.HTTPStatusFailure(resp.StatusCode, &blobStatusError{code: resp.StatusCode, host: host})
case resp.ContentLength < 0:
err = errors.New("chunkstore: needle HEAD has no size")
default:
@@ -1,60 +0,0 @@
package master
import (
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
)
// A fenced replace decided by the gate reaches the controller as a failover
// whatever the gate's reason. Here the gate replaces a primary only it reads
// as unacceptable: its node reads format level 0 on a level-1 cluster (not
// placement-eligible), while the primary's own slot flags still read
// reachable and ready, and it still reports (no loss is recorded). The
// controller judges acceptability by those flags alone, so unless the gate
// marks the replaced primary unacceptable in what it submits, the controller
// answers "the current primary is acceptable" on every tick and the fenced
// decision never publishes.
func TestAFencedReplaceOfAPrimaryOnlyTheGateRejectsReachesAReassign(t *testing.T) {
ctrl, pub, _ := lossCluster(t, authority.TopologyControllerConfig{})
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
h.ctrl = ctrl
h.boot = &bootstrap.DurableAuthorityBootstrap{Publisher: pub}
h.reads = newReadsLevels(time.Hour)
h.reads.note("s1", "vol-rf3", "p-r1", 0) // the primary's node reads the old level
h.reads.note("s2", "vol-rf3", "p-r2", 1)
h.reads.note("s3", "vol-rf3", "p-r3", 1)
h.format.v.Store(1)
t0 := time.Date(2026, 12, 5, 8, 0, 0, 0, time.UTC)
for tick := range 3 {
now := t0.Add(time.Duration(tick) * time.Second)
snap := silentPrimary() // r1's flags read reachable and ready
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
if snap.Volumes[0].Authority.Epoch != 1 {
break // published
}
heard := map[string]time.Time{"r1": now, "r2": now, "r3": now} // r1 still reports: no loss
h.notePrimaryLosses(rx(heard, now), &snap)
h.takeGateReplaces()
h.applyPromotionEvidenceGate(&snap)
if l := gateLine(t, buf.String(), "vol-rf3"); !regexp.MustCompile(`primary_lost=false decision=replace\(fenced_at=2\)$`).MatchString(l) {
t.Fatalf("tick %d: gate line %q; want a fenced replace with no loss recorded", tick, l)
}
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
h.reportReplaces("", nil, outcomes)
}
if strings.Contains(buf.String(), "controller: no ask: the current primary is acceptable") {
t.Fatalf("the controller kept a primary the gate replaced:\n%s", buf.String())
}
if !regexp.MustCompile(`decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`).MatchString(buf.String()) {
t.Fatalf("the fenced replace was not enqueued as a failover:\n%s", buf.String())
}
waitLossLine(t, pub, "vol-rf3", func(l authority.AuthorityBasis) bool { return l.Epoch == 2 && l.ReplicaID != "r1" })
}
@@ -500,15 +500,12 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
slot.PlannedMoveAllowed = false
}
}
// A fenced replacement reaches the controller as a failover,
// whatever the gate's reason (a recorded loss, or a primary only
// the gate reads as unacceptable, such as one on a node below the
// cluster's format level): its slot no longer reads acceptable, so
// the controller publishes the fenced target with its fenced
// evidence (the line is minted only at the fenced epoch), never
// keeping the old line by its own acceptability predicate nor
// A fenced replacement of a lost primary reaches the controller as
// a failover: its slot no longer reads acceptable, so the controller
// publishes the fenced target with its fenced evidence (the line is
// minted only at the fenced epoch), never keeping the old line nor
// routing the target as a planned rebalance without that epoch.
if fencedReplace {
if lost && fencedReplace {
current := &vol.Slots[currentIdx]
current.Reachable, current.ReadyForPrimary = false, false
}
+2 -1
View File
@@ -7,6 +7,7 @@ import (
"crypto/x509"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"net/url"
@@ -206,7 +207,7 @@ func (c *KubernetesDeploymentClient) send(req *http.Request) (*http.Response, er
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.httpClient.Do(req)
resp, err := answer.DoHTTP(c.httpClient, req, answer.Unsent)
if err != nil {
return nil, fmt.Errorf("launcher: Kubernetes %s %s: %w", req.Method, req.URL.Path, err)
}
@@ -0,0 +1,47 @@
package ops
import (
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestKubernetesCredentialsFailTypedBeforeClientConstruction(t *testing.T) {
dir := t.TempDir()
token := filepath.Join(dir, "token")
if err := os.WriteFile(token, []byte("fixture-token"), 0600); err != nil {
t.Fatal(err)
}
ca := authtest.NewCA(t, "client-config")
valid := ca.WriteCA(t, dir)
expired := ca.Issue(t, "expired", time.Now().Add(-time.Minute))
expiredPath := filepath.Join(dir, "expired.pem")
if err := os.WriteFile(expiredPath, expired.CertPEM, 0600); err != nil {
t.Fatal(err)
}
malformed := filepath.Join(dir, "bad.pem")
if err := os.WriteFile(malformed, []byte("not a certificate"), 0600); err != nil {
t.Fatal(err)
}
for _, row := range []struct{ name, token, ca string }{
{"missing-token", filepath.Join(dir, "missing-token"), valid},
{"missing-ca", token, filepath.Join(dir, "missing-ca")},
{"malformed-ca", token, malformed}, {"expired-ca", token, expiredPath},
} {
t.Run(row.name, func(t *testing.T) {
client, err := newKubernetesStatusClient("127.0.0.1", "1", row.token, row.ca)
if client != nil || !errors.Is(err, answer.ErrLocalCredential) {
t.Fatalf("constructed=%t typed=%t error=%v", client != nil, errors.Is(err, answer.ErrLocalCredential), err)
}
p, check := answer.PolicyOf(err, answer.Ops)
if check != nil || p.Code != "bad_request" || p.Retryable || p.Exit != 78 {
t.Fatalf("policy=%+v check=%v", p, check)
}
})
}
}
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -44,14 +45,14 @@ func (r *HTTPAuthorityRebuildRuntime) ExecuteRebuild(ctx context.Context, req Au
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
resp, err := client.Do(httpReq)
resp, err := answer.DoForContract(client, httpReq, answer.Unsent, answer.Ops)
if err != nil {
return AuthorityRebuildRuntimeResult{}, fmt.Errorf("post rebuild runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
payload, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return AuthorityRebuildRuntimeResult{}, fmt.Errorf("rebuild runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
return AuthorityRebuildRuntimeResult{}, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("rebuild runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))), answer.Ops)
}
var result AuthorityRebuildRuntimeResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
@@ -32,7 +33,7 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
conn, err = link.DialMasterFromEnv(r.Addr)
}
if err != nil {
return FailbackRuntimeResult{}, err
return FailbackRuntimeResult{}, answer.Present(err, answer.Ops)
}
defer conn.Close()
@@ -50,7 +51,7 @@ func (r *GRPCFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
EvidenceRefs: append([]string(nil), req.EvidenceRefs...),
})
if err != nil {
return FailbackRuntimeResult{}, err
return FailbackRuntimeResult{}, answer.Present(err, answer.Ops)
}
return FailbackRuntimeResult{
FailbackStarted: resp.GetFailbackStarted(),
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -44,14 +45,14 @@ func (r *HTTPFailbackRuntime) ExecuteFailback(ctx context.Context, req FailbackR
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
resp, err := client.Do(httpReq)
resp, err := answer.DoForContract(client, httpReq, answer.Unsent, answer.Ops)
if err != nil {
return FailbackRuntimeResult{}, fmt.Errorf("post failback runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
payload, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return FailbackRuntimeResult{}, fmt.Errorf("failback runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
return FailbackRuntimeResult{}, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("failback runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))), answer.Ops)
}
var result FailbackRuntimeResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"strings"
@@ -44,14 +45,14 @@ func (r *HTTPFrontendPublicationRuntime) ExecuteFrontendPublication(ctx context.
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "application/json")
resp, err := client.Do(httpReq)
resp, err := answer.DoForContract(client, httpReq, answer.Unsent, answer.Ops)
if err != nil {
return FrontendPublicationRuntimeResult{}, fmt.Errorf("post frontend publication runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
payload, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return FrontendPublicationRuntimeResult{}, fmt.Errorf("frontend publication runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))
return FrontendPublicationRuntimeResult{}, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("frontend publication runtime returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(payload)))), answer.Ops)
}
var result FrontendPublicationRuntimeResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+4 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"net"
"net/url"
"os"
@@ -473,7 +474,7 @@ func waitInventoryTCPReady(ctx context.Context, host string, port int, done <-ch
}
return err
case <-ctx.Done():
return ctx.Err()
return answer.Present(answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Ops)
default:
}
conn, err := net.DialTimeout("tcp", addr, 500*time.Millisecond)
@@ -481,11 +482,11 @@ func waitInventoryTCPReady(ctx context.Context, host string, port int, done <-ch
_ = conn.Close()
return nil
}
lastErr = err
lastErr = answer.Record(answer.Unsent, err) // handshake-only probe sends no application bytes
time.Sleep(250 * time.Millisecond)
}
if lastErr != nil {
return lastErr
return answer.Present(lastErr, answer.Ops)
}
return fmt.Errorf("timed out")
}
@@ -0,0 +1,75 @@
package ops
import (
"context"
"crypto/tls"
"encoding/pem"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
)
// CertificatePool also gates this HTTP writer, not only RPC constructors.
func TestKubernetesStatusCARotationUsesTheVerifiedChain(t *testing.T) {
var goodCalls, badCalls atomic.Int64
good := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PATCH" || r.Header.Get("Authorization") != "Bearer fixture-token" {
t.Errorf("unexpected writer request %s %q", r.Method, r.Header.Get("Authorization"))
}
goodCalls.Add(1)
w.WriteHeader(http.StatusOK)
}))
defer good.Close()
dir := t.TempDir()
ca := authtest.NewCA(t, "unused-rotation")
expired := ca.Issue(t, "expired-alternative", time.Now().Add(-time.Hour))
bundle := append(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: good.Certificate().Raw}), expired.CertPEM...)
caPath, tokenPath := filepath.Join(dir, "ca.pem"), filepath.Join(dir, "token")
if err := os.WriteFile(caPath, bundle, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(tokenPath, []byte("fixture-token"), 0o600); err != nil {
t.Fatal(err)
}
clientFor := func(address string) *KubernetesStatusClient {
host, port, err := net.SplitHostPort(strings.TrimPrefix(address, "https://"))
if err != nil {
t.Fatal(err)
}
client, err := newKubernetesStatusClient(host, port, tokenPath, caPath)
if err != nil {
t.Fatalf("unused expired entry blocks HTTP writer construction: %v", err)
}
t.Cleanup(client.HTTPClient.CloseIdleConnections)
return client
}
write := func(client *KubernetesStatusClient) error {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return client.WriteClusterStatus(ctx, OperatorObjectRef{Namespace: "default", Name: "demo"}, SwBlockClusterCRDStatus{})
}
if err := write(clientFor(good.URL)); err != nil {
t.Fatalf("valid HTTP chain beside unused expired entry: %v", err)
}
if goodCalls.Load() != 1 {
t.Fatalf("status PATCH was not witnessed: calls=%d", goodCalls.Load())
}
bad := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { badCalls.Add(1); w.WriteHeader(http.StatusOK) }))
bad.TLS = &tls.Config{Certificates: []tls.Certificate{expired.TLS}, MinVersion: tls.VersionTLS12}
bad.StartTLS()
defer bad.Close()
if err := write(clientFor(bad.URL)); err == nil {
t.Fatal("selected expired HTTP certificate accepted")
}
if badCalls.Load() != 0 {
t.Fatalf("invalid selected chain reached status writer: calls=%d", badCalls.Load())
}
}
@@ -3,7 +3,9 @@ package ops
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"sort"
@@ -116,7 +118,7 @@ func (c *KubernetesStatusClient) getJSON(ctx context.Context, path string, out a
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -125,7 +127,7 @@ func (c *KubernetesStatusClient) getJSON(ctx context.Context, path string, out a
return json.NewDecoder(resp.Body).Decode(out)
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return kubernetesAPIError{StatusCode: resp.StatusCode, Body: string(raw)}
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, kubernetesAPIError{StatusCode: resp.StatusCode, Body: string(raw)}), answer.Ops)
}
func (c *KubernetesStatusClient) apiURL(path string) string {
@@ -229,8 +231,8 @@ func mergeNodeCSIEvidence(conditions []ObservationCondition, namespace, nodeName
}
func isKubernetesNotFound(err error) bool {
apiErr, ok := err.(kubernetesAPIError)
return ok && apiErr.StatusCode == http.StatusNotFound
var apiErr kubernetesAPIError
return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound
}
type kubernetesAPIError struct {
@@ -4,9 +4,9 @@ import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"io"
"net/http"
"net/url"
@@ -37,20 +37,24 @@ type KubernetesStatusClient struct {
func NewInClusterKubernetesStatusClient() (*KubernetesStatusClient, error) {
host := os.Getenv("KUBERNETES_SERVICE_HOST")
port := os.Getenv("KUBERNETES_SERVICE_PORT")
return newKubernetesStatusClient(host, port, serviceAccountTokenPath, serviceAccountCAPath)
}
func newKubernetesStatusClient(host, port, tokenPath, caPath string) (*KubernetesStatusClient, error) {
if host == "" || port == "" {
return nil, fmt.Errorf("KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are required for non-dry-run operator status")
return nil, answer.Present(answer.LocalConfiguration(fmt.Errorf("KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are required for non-dry-run operator status")), answer.Ops)
}
token, err := os.ReadFile(serviceAccountTokenPath)
token, err := os.ReadFile(tokenPath)
if err != nil {
return nil, fmt.Errorf("read service account token: %w", err)
return nil, answer.Present(answer.LocalCredential(fmt.Errorf("read service account token: %w", err)), answer.Ops)
}
ca, err := os.ReadFile(serviceAccountCAPath)
ca, err := os.ReadFile(caPath)
if err != nil {
return nil, fmt.Errorf("read service account CA: %w", err)
return nil, answer.Present(answer.LocalCredential(fmt.Errorf("read service account CA: %w", err)), answer.Ops)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(ca) {
return nil, fmt.Errorf("service account CA bundle is empty or invalid")
pool, err := answer.CertificatePool(ca, time.Now())
if err != nil {
return nil, answer.Present(fmt.Errorf("service account CA bundle is empty or invalid: %w", err), answer.Ops)
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{RootCAs: pool}
@@ -105,14 +109,14 @@ func (c *KubernetesStatusClient) ListSwBlockVolumes(ctx context.Context, namespa
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockVolumePlural, resp.StatusCode, strings.TrimSpace(string(raw)))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockVolumePlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
var list kubernetesSwBlockVolumeList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -156,14 +160,14 @@ func (c *KubernetesStatusClient) ListSwBlockReplicaEligibilities(ctx context.Con
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaEligibilityPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaEligibilityPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
var list kubernetesSwBlockReplicaEligibilityList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -205,14 +209,14 @@ func (c *KubernetesStatusClient) ListSwBlockReplicaRebuilds(ctx context.Context,
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaRebuildPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaRebuildPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
var list kubernetesSwBlockReplicaRebuildList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -254,14 +258,14 @@ func (c *KubernetesStatusClient) ListSwBlockFrontendPublications(ctx context.Con
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockFrontendPublicationPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockFrontendPublicationPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
var list kubernetesSwBlockFrontendPublicationList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -303,14 +307,14 @@ func (c *KubernetesStatusClient) ListSwBlockReplicaFailbacks(ctx context.Context
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaFailbackPlural, resp.StatusCode, strings.TrimSpace(string(raw)))
return nil, answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("list %s failed: http %d %s", SwBlockReplicaFailbackPlural, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
var list kubernetesSwBlockReplicaFailbackList
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
@@ -365,7 +369,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaRebuild(ctx context.Context
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -374,7 +378,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaRebuild(ctx context.Context
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaRebuildPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaRebuildPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
func (c *KubernetesStatusClient) CreateSwBlockFrontendPublication(ctx context.Context, namespace string, obj SwBlockFrontendPublicationObject) error {
@@ -406,7 +410,7 @@ func (c *KubernetesStatusClient) CreateSwBlockFrontendPublication(ctx context.Co
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -415,7 +419,7 @@ func (c *KubernetesStatusClient) CreateSwBlockFrontendPublication(ctx context.Co
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("create %s/%s failed: http %d %s", SwBlockFrontendPublicationPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create %s/%s failed: http %d %s", SwBlockFrontendPublicationPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
func (c *KubernetesStatusClient) CreateSwBlockReplicaFailback(ctx context.Context, namespace string, obj SwBlockReplicaFailbackObject) error {
@@ -447,7 +451,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaFailback(ctx context.Contex
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -456,7 +460,7 @@ func (c *KubernetesStatusClient) CreateSwBlockReplicaFailback(ctx context.Contex
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaFailbackPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create %s/%s failed: http %d %s", SwBlockReplicaFailbackPlural, obj.Ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Context, ref OperatorObjectRef, finalizers []string) error {
@@ -480,7 +484,7 @@ func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Contex
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -489,7 +493,7 @@ func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Contex
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("patch %s/%s finalizers failed: http %d %s", SwBlockVolumePlural, ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("patch %s/%s finalizers failed: http %d %s", SwBlockVolumePlural, ref.Name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, resource, name string, status any) error {
@@ -513,7 +517,7 @@ func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, res
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -522,7 +526,7 @@ func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, res
return nil
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("patch %s/%s status failed: http %d %s", resource, name, resp.StatusCode, strings.TrimSpace(string(raw)))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("patch %s/%s status failed: http %d %s", resource, name, resp.StatusCode, strings.TrimSpace(string(raw)))), answer.Ops)
}
func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKubernetesEvent) error {
@@ -564,7 +568,7 @@ func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKu
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -576,7 +580,7 @@ func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKu
return nil
}
rawResp, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("create event %s failed: http %d %s", event.Reason, resp.StatusCode, strings.TrimSpace(string(rawResp)))
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("create event %s failed: http %d %s", event.Reason, resp.StatusCode, strings.TrimSpace(string(rawResp)))), answer.Ops)
}
func (c *KubernetesStatusClient) statusURL(namespace, resource, name string) string {
+6 -4
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"net/http"
"net/url"
"os/exec"
@@ -96,10 +97,11 @@ func NewLiveVolumeStatusReportCollector(cfg LiveVolumeStatusConfig) VolumeStatus
func queryLiveMasterStatus(ctx context.Context, masterAddr, volumeID string) (*control.StatusResponse, error) {
conn, err := link.DialMasterFromEnv(masterAddr)
if err != nil {
return nil, fmt.Errorf("dial master: %w", err)
return nil, answer.Present(fmt.Errorf("dial master: %w", err), answer.Ops)
}
defer conn.Close()
return control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: volumeID})
reply, err := control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: volumeID})
return reply, answer.Present(err, answer.Ops)
}
func getStatusJSON(ctx context.Context, client *http.Client, base, path, volumeID string, out any, allowNotFound bool) error {
@@ -111,7 +113,7 @@ func getStatusJSON(ctx context.Context, client *http.Client, base, path, volumeI
if err != nil {
return err
}
resp, err := client.Do(req)
resp, err := answer.DoForContract(client, req, answer.Unsent, answer.Ops)
if err != nil {
return err
}
@@ -120,7 +122,7 @@ func getStatusJSON(ctx context.Context, client *http.Client, base, path, volumeI
return nil
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("GET %s: %s", endpoint, resp.Status)
return answer.Present(answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("GET %s: %s", endpoint, resp.Status)), answer.Ops)
}
return json.NewDecoder(resp.Body).Decode(out)
}
@@ -0,0 +1,72 @@
package answer_test
import (
"net"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// The same produced failures traverse every command-family wire contract.
// Exit compatibility is explicit here, independently of the registry builder.
func TestCommandFamilyTransportGrid(t *testing.T) {
for _, row := range []struct {
name string
produce func(*testing.T) error
}{
{"dial-refused", refusedDial},
{"reset-after-write", resetConnection},
{"dns", failedDNS},
{"read-timeout", readTimeout},
} {
err := row.produce(t)
kind, listed := answer.ErrorKind(err)
if err == nil || !listed {
t.Fatalf("%s did not produce a listed failure: %v", row.name, err)
}
for _, family := range []struct {
contract answer.Contract
unsent, possible int
}{
{answer.Chunk, 75, 3}, {answer.ChunkVerify, 75, 1}, {answer.Workspace, 75, 3},
{answer.VolumeCreate, 75, 75}, {answer.VolumeResolve, 75, 75},
{answer.Cluster, 75, 3}, {answer.Restore, 75, 3}, {answer.Failover, 3, 3},
{answer.VolumeJob, 75, 3}, {answer.VolumeStop, 75, 3}, {answer.VolumePlacement, 75, 3}, {answer.Shell, 75, 3}, {answer.Ops, 75, 3},
} {
t.Run(string(family.contract)+"/"+row.name, func(t *testing.T) {
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
got, check := answer.Lookup(phase, answer.ForContract(family.contract, kind))
code, rule, exit := "remote_unavailable", answer.Resend, family.unsent
if phase == answer.PossiblyAdmitted {
code, rule, exit = "outcome_unknown", answer.Recover, family.possible
if family.contract == answer.ChunkVerify {
rule = answer.Resend
}
}
if check != nil || got.Code != code || !got.Retryable || (got.Retry != rule && family.contract != answer.Failover) || got.Exit != exit || got.Cure == "" {
t.Fatalf("phase=%s policy=%+v check=%v", phase, got, check)
}
}
if _, check := answer.Lookup(answer.Unsent, answer.ForContract(family.contract, answer.Kind{Name: "unlisted"})); check == nil {
t.Fatal("an unlisted family row passed the table check")
}
})
}
}
}
// The platform fixture reserves a destination that cannot gain a listener
// between setup and dialing; assert the native refusal rather than its text.
func refusedDial(t *testing.T) error {
t.Helper()
conn, err := net.DialTimeout("tcp", refusedTCPAddress(t), 5*time.Second)
if conn != nil {
conn.Close()
}
if !isRefusedDial(err) {
t.Fatalf("fixture did not produce a refused TCP dial: %v", err)
}
return err
}
@@ -0,0 +1,60 @@
package answer
import (
"crypto/x509"
"encoding/pem"
"fmt"
"time"
)
// CertificatePool validates locally supplied authentication material before
// any dial. The same provenance is used by RPC and HTTP client constructors.
func CertificatePool(raw []byte, now time.Time) (*x509.CertPool, error) {
count := 0
current := 0
var dateErr error
for rest := raw; len(rest) > 0; {
block, remaining := pem.Decode(rest)
if block == nil {
break
}
rest = remaining
if block.Type != "CERTIFICATE" {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, LocalCredential(err)
}
if err := ValidateCertificate(cert, now); err != nil {
if dateErr == nil {
dateErr = err
}
} else {
current++
}
count++
}
pool := x509.NewCertPool()
if count == 0 || !pool.AppendCertsFromPEM(raw) {
return nil, LocalCredential(fmt.Errorf("CA bundle holds no valid PEM certificate"))
}
// Roots are alternatives during rotation, not one certificate chain.
// An unused stale root does not invalidate a current one. TLS still
// verifies the dates of the chain it actually selects. Preserve the
// local configuration refusal when the bundle has no current entry.
if current == 0 {
return nil, dateErr
}
return pool, nil
}
func ValidateCertificate(cert *x509.Certificate, now time.Time) error {
if now.Before(cert.NotBefore) {
return LocalCredential(fmt.Errorf("certificate is not yet valid (valid from %s)", cert.NotBefore.Format(time.RFC3339)))
}
if now.After(cert.NotAfter) {
return LocalCredential(fmt.Errorf("certificate has expired (valid until %s)", cert.NotAfter.Format(time.RFC3339)))
}
return nil
}
+103
View File
@@ -0,0 +1,103 @@
package answer
import "strings"
// LeaseBarrier is a definite dated admission refusal, not a transport guess.
func LeaseBarrier(stamp string) Kind { return Kind{Name: "delete_lease_barrier", ServerMessage: stamp} }
// Domain preserves an authoritative typed answer, rather than inferring
// admission or retry safety from a transport diagnostic.
func Domain(code string, retryable bool, message string) Kind {
return Kind{Name: "server_domain", ServerCode: code, ServerRetryable: retryable, ServerMessage: message}
}
// Guard names an existing definite local/kernel refusal.
func Guard(code string) Kind { return Kind{Name: "guard/" + code} }
func isDomainKind(kind Kind) bool {
return kind.Name == "server_domain" || strings.HasPrefix(kind.Name, "guard/")
}
func addDomainCells(registry map[key]Policy) {
for _, phase := range []Phase{Unsent, PossiblyAdmitted} {
for _, code := range strings.Fields(`awaiting_assignment bad_request base_installing canceled capture_refused closing
cut_aborted cut_busy cut_stalled deadline_exceeded detach_aborted epoch_stale fenced forbidden
format_level_below_head_version frozen_detach_unsupported frozen_tail_too_large geometry_mismatch
head_conflict host_slot_busy in_progress internal invalid_class invalid_freeze_budget invalid_label
invalid_name invalid_policy layout_busy layout_refused lsn_behind method_not_allowed no_progress
not_chunk_volume not_found not_primary operation_capacity operation_conflict operation_handle_mismatch
operation_incomplete operation_intent_conflict operation_not_found operation_retired outcome_unknown
plain_detach_busy plain_detach_unsupported precopy_not_converged precopy_unknown queue_full reconciling
remote_full remote_unavailable schedule_not_running snapshot_delete_requires_operation snapshot_deleting
snapshot_exists snapshot_generation_mismatch snapshot_generation_unavailable snapshot_has_dependents
snapshot_limit snapshot_name_taken snapshot_not_found snapshot_operations_unsupported target_exists
unknown_cut_id volume_not_served volume_not_found restore_source_not_own not_admitted target_live
identity_mismatch volume_deleting conflict unsupported_api_version unsupported_error_code`) {
registry[key{phase, Kind{Name: "server_domain", ServerCode: code}}] = Policy{Retry: Never}
}
registry[key{phase, LeaseBarrier("")}] = Policy{"not_admitted", true, Recover, "", 0}
}
for _, row := range []struct {
code string
retry bool
cure string
}{
{"bad_request", false, "correct the request before sending it again"},
{"deadline_exceeded", true, "retry the same operation with a sufficient no-progress window"},
{"internal", false, "inspect the reported error before retrying the operation"},
{"readout_unproven", false, "inspect the stored range and its integrity evidence; never infer no loss from an unproven readout"},
{"outcome_unknown", true, "recover the same operation by its replay key or poll its existing handle; do not start another operation"},
{"unsupported_error_code", false, "upgrade the client, then recover the original operation by its replay key or poll; do not start another operation"},
{"queue_full", true, "let pending work drain before retrying the same operation"},
{"layout_busy", true, "retry the same operation after the current layout activity releases"},
{"snapshot_not_found", false, "check the snapshot identity; do not target a replacement as a retry"},
{"snapshot_delete_requires_operation", false, "delete through the snapshot operation interface with a stable request id"},
{"snapshot_has_dependents", false, "remove dependent volumes or release their dependency before resuming the same request id"},
{"restore_source_not_own", false, "use a source that owns its snapshot's chunks"},
{"volume_not_found", false, "check the recorded volume identity"},
{"target_exists", false, "read the existing target and reconcile the original operation"},
{"volume_deleting", false, "resume the existing deletion instead of creating a new operation"},
{"not_admitted", false, "resolve the stated admission refusal before retrying"},
{"delete_live_holder", false, "stop the volume first"},
{"target_live", false, "stop and release the target before retrying"},
{"identity_mismatch", false, "use the recorded full volume identity"},
{"geometry_mismatch", false, "use the recorded geometry"},
{"conflict", true, "read the current state and retry the same operation"},
{"invalid_policy", false, "correct the retention policy before retrying"},
} {
rule := Never
if row.retry {
rule = Resend
}
if row.code == "outcome_unknown" || row.code == "unsupported_error_code" {
rule = Recover
}
for _, phase := range []Phase{Unsent, PossiblyAdmitted} {
code := row.code
if code == "delete_live_holder" {
code = "not_admitted"
}
registry[key{phase, Guard(row.code)}] = Policy{code, row.retry, rule, row.cure, 0}
}
}
}
func projectDomain(policy Policy, kind Kind) Policy {
policy.Code, policy.Retryable, policy.Cure = kind.ServerCode, kind.ServerRetryable, kind.ServerMessage
if kind.ServerRetryable {
policy.Retry = Resend
}
if kind.ServerCode == "outcome_unknown" || kind.ServerCode == "in_progress" || kind.ServerCode == "no_progress" {
policy.Retry = Recover
}
if kind.ServerCode == "remote_unavailable" && kind.ServerRetryable {
remote := registry[key{Unsent, ForContract(kind.Contract, Connection)}]
if !strings.HasSuffix(policy.Cure, remote.Cure) {
policy.Cure += "; " + remote.Cure
}
}
if kind.ServerCode == "not_admitted" && kind.ServerRetryable && kind.Contract == Chunk {
policy.Retry = Recover
}
return policy
}
@@ -0,0 +1,146 @@
package answer_test
import (
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// Runtime Lookup rejects dynamic unknown codes. This inventory also catches
// a new locally declared/emitted code before a peer can send it to the CLI.
func TestDeclaredDomainCodesHaveRegistryRows(t *testing.T) {
root := filepath.Join("..", "..", "..")
fset := token.NewFileSet()
var files []*ast.File
constants := map[string]ast.Expr{}
for _, dir := range []string{"core/frontend/chunkstore", "core/host/volume", "cmd/sw-block"} {
paths, err := filepath.Glob(filepath.Join(root, filepath.FromSlash(dir), "*.go"))
if err != nil {
t.Fatal(err)
}
for _, path := range paths {
if strings.HasSuffix(path, "_test.go") {
continue
}
file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
if err != nil {
t.Fatal(err)
}
files = append(files, file)
for _, decl := range file.Decls {
group, ok := decl.(*ast.GenDecl)
if !ok || group.Tok != token.CONST {
continue
}
for _, spec := range group.Specs {
value := spec.(*ast.ValueSpec)
for i, name := range value.Names {
if i < len(value.Values) {
constants[file.Name.Name+"."+name.Name] = value.Values[i]
}
}
}
}
}
}
var literal func(string, ast.Expr, int) (string, bool)
literal = func(pkg string, expr ast.Expr, depth int) (string, bool) {
if depth > 20 {
return "", false
}
switch x := expr.(type) {
case *ast.BasicLit:
if x.Kind == token.STRING {
s, err := strconv.Unquote(x.Value)
return s, err == nil
}
case *ast.Ident:
if next := constants[pkg+"."+x.Name]; next != nil {
return literal(pkg, next, depth+1)
}
case *ast.SelectorExpr:
if owner, ok := x.X.(*ast.Ident); ok {
if next := constants[owner.Name+"."+x.Sel.Name]; next != nil {
return literal(owner.Name, next, depth+1)
}
}
}
return "", false
}
seen := map[string]bool{}
check := func(pkg string, expr ast.Expr) {
code, ok := literal(pkg, expr, 0)
if !ok || code == "" || code[0] < 'a' || code[0] > 'z' {
return
}
seen[code] = true
if _, err := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Domain(code, false, "declared domain answer"))); err != nil {
t.Errorf("%s: domain code %q has no registry row: %v", fset.Position(expr.Pos()), code, err)
}
}
for _, file := range files {
pkg := file.Name.Name
ast.Inspect(file, func(node ast.Node) bool {
switch x := node.(type) {
case *ast.ValueSpec:
for i, name := range x.Names {
if i < len(x.Values) && (strings.HasPrefix(name.Name, "Code") || strings.HasPrefix(name.Name, "code")) {
check(pkg, x.Values[i])
}
}
case *ast.CallExpr:
if name, ok := x.Fun.(*ast.Ident); ok {
index := -1
switch name.Name {
case "catErr":
index = 0
case "writeChunkErr":
index = 2
case "chunkFail":
index = 4
}
if index >= 0 && index < len(x.Args) {
check(pkg, x.Args[index])
}
}
case *ast.CompositeLit:
name := ""
switch typ := x.Type.(type) {
case *ast.Ident:
name = typ.Name
case *ast.SelectorExpr:
name = typ.Sel.Name
}
if name == "CatalogError" || name == "chunkErrorBody" || name == "snapshotRefusal" {
for _, field := range x.Elts {
if item, ok := field.(*ast.KeyValueExpr); ok {
if key, ok := item.Key.(*ast.Ident); ok && key.Name == "Code" {
check(pkg, item.Value)
}
}
}
}
}
return true
})
for _, decl := range file.Decls {
if function, ok := decl.(*ast.FuncDecl); ok && function.Name.Name == "chunkErrorCode" {
ast.Inspect(function.Body, func(node ast.Node) bool {
if ret, ok := node.(*ast.ReturnStmt); ok && len(ret.Results) == 3 {
check(pkg, ret.Results[1])
}
return true
})
}
}
}
if len(seen) < 50 {
t.Fatalf("domain census did not reach the expected emitters: %d codes", len(seen))
}
}
+123
View File
@@ -0,0 +1,123 @@
package answer
import (
"context"
"crypto/x509"
"errors"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"io"
"net"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ErrorKind translates a concrete transport error to a registry key. It
// deliberately has no output code, retry flag, cure or exit decision.
func ErrorKind(err error) (Kind, bool) {
var recorded *failure
if errors.As(err, &recorded) {
return recorded.kind, recorded.kind.Name != ""
}
if errors.Is(err, ErrLocalCredential) {
return Credential, true
}
if errors.Is(err, ErrLocalConfiguration) {
return Configuration, true
}
var httpFailure *httpStatusFailure
if errors.As(err, &httpFailure) {
return httpStatusKind(httpFailure.status), true
}
if remote, ok := status.FromError(err); ok {
if remote.Code() == codes.FailedPrecondition && lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn {
return Guard("restore_source_not_own"), true
}
switch remote.Code() {
case codes.InvalidArgument, codes.FailedPrecondition, codes.NotFound, codes.AlreadyExists, codes.PermissionDenied, codes.Unauthenticated, codes.Unimplemented, codes.DataLoss:
return rpcKindKey(remote.Code()), true
}
}
var authority x509.UnknownAuthorityError
if errors.As(err, &authority) {
return Trust, true
}
var hostname x509.HostnameError
if errors.As(err, &hostname) {
return Name, true
}
var invalid x509.CertificateInvalidError
if errors.As(err, &invalid) {
return Certificate, true
}
if errors.Is(err, context.Canceled) {
return Canceled, true
}
if errors.Is(err, context.DeadlineExceeded) {
return Timeout, true
}
var address *net.AddrError
var syntax *net.ParseError
if errors.As(err, &address) || errors.As(err, &syntax) {
return Configuration, true
}
var dns *net.DNSError
if errors.As(err, &dns) {
return DNS, true
}
var timed net.Error
if errors.As(err, &timed) && timed.Timeout() {
return Timeout, true
}
var network *net.OpError
if errors.As(err, &network) {
// crypto/tls reports TCP alerts as net.OpError with an unexported
// tls.alert (tls.AlertError is exported for QUIC). Translate only
// this structured remote-alert boundary and its exact finite names,
// never arbitrary gRPC/HTTP diagnostic text. In TLS 1.3 this alert
// may arrive on the first read after the client wrote its request.
if network.Op == "remote error" && network.Err != nil {
switch network.Err.Error() {
case "tls: bad certificate", "tls: unsupported certificate", "tls: revoked certificate",
"tls: expired certificate", "tls: unknown certificate", "tls: unknown certificate authority",
"tls: certificate unobtainable", "tls: bad certificate status response",
"tls: bad certificate hash value", "tls: certificate required":
return Certificate, true
}
}
return Connection, true
}
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return Connection, true
}
if remote, ok := status.FromError(err); ok && remote.Code() > codes.OK && remote.Code() <= codes.Unauthenticated {
return rpcKindKey(remote.Code()), true
}
return Kind{}, false
}
// DefiniteAnswer reports a typed server refusal, never a transport guess.
func DefiniteAnswer(err error) bool {
kind, _ := ErrorKind(err)
if isDomainKind(kind) {
return true
}
switch kind.Name {
case "rpc/InvalidArgument", "rpc/FailedPrecondition", "rpc/NotFound", "rpc/AlreadyExists", "rpc/PermissionDenied", "rpc/Unauthenticated", "rpc/Unimplemented", "rpc/DataLoss",
"http/400", "http/401", "http/403", "http/404", "http/405", "http/406", "http/409", "http/410", "http/412", "http/413", "http/415", "http/422", "http/428", "http/501":
return true
}
return false
}
func rpcKindKey(code codes.Code) Kind {
switch code {
case codes.Unavailable:
return Connection
case codes.DeadlineExceeded:
return Timeout
case codes.Canceled:
return Canceled
}
return Kind{Name: "rpc/" + code.String()}
}
@@ -0,0 +1,81 @@
package answer
import "google.golang.org/grpc/codes"
// One projection owns exits. Classification and recovery are decided before
// this projection; a legacy exit never makes an ambiguous operation safe.
var canonicalExits = map[string]int{
"remote_unavailable": 75, "outcome_unknown": 3, "not_authorized": 5,
"local_configuration": 78, "canceled": 1, "deadline_exceeded": 1,
"readout_unproven": 4, "bad_request": 2, "domain_refusal": 1,
"domain_precondition": 1,
"lease_barrier": 75,
}
// LegacyExit is a documented v1.1.x wire exception, removed in v1.2.
// Command is the registry contract for that command, never an adapter table.
type LegacyExit struct {
Command Contract
Class string
Exit int
Source, Reason, RemovedIn string
}
var legacyExits = []LegacyExit{
{Failover, "remote_unavailable", 3, "docs/standalone-deployment.md", "Failover requires reading the current authority line before another move even when its RPC was unsent.", "v1.2"},
{Failover, "deadline_exceeded", 3, "docs/standalone-deployment.md", "A caller deadline before sending also requires reading the current authority line before another move.", "v1.2"},
{ChunkVerify, "outcome_unknown", 1, "docs/standalone-deployment.md", "Incomplete verification must not share exit 3 with a completed scan containing findings; JSON retains the failure class.", "v1.2"},
{VolumeCreate, "bad_request", 78, "docs/standalone-deployment.md", "Create documents server refusal as 78; local argument parsing remains 2.", "v1.2"},
{VolumeResolve, "bad_request", 78, "docs/standalone-deployment.md", "Resolve documents definite server refusal as 78; local argument parsing remains 2.", "v1.2"},
{VolumeCreate, "outcome_unknown", 75, "docs/standalone-deployment.md", "Identical create reuses the recorded layout identity and compatible spec; binding/placement do not overwrite another assignment. Preserve all original settings.", "v1.2"},
{VolumeCreate, "domain_refusal", 78, "docs/standalone-deployment.md", "Documented definite create refusal; no new placement is attempted after refusal.", "v1.2"},
{VolumeCreate, "domain_precondition", 78, "docs/standalone-deployment.md", "Documented definite create refusal, including format admission.", "v1.2"},
{VolumeCreate, "not_authorized", 78, "docs/standalone-deployment.md", "Create documents definite refusal as 78.", "v1.2"},
{VolumeResolve, "outcome_unknown", 75, "docs/standalone-deployment.md", "The documented unknown answer is a read-only query; retry cannot create an operation.", "v1.2"},
{VolumeResolve, "domain_refusal", 78, "docs/standalone-deployment.md", "Resolve documents definite refusal, not-found and invalid identity as 78.", "v1.2"},
{VolumeResolve, "domain_precondition", 78, "docs/standalone-deployment.md", "Resolve documents definite refusal as 78.", "v1.2"},
{VolumeResolve, "not_authorized", 78, "docs/standalone-deployment.md", "Resolve documents definite refusal as 78.", "v1.2"},
{Cluster, "domain_precondition", 2, "docs/operations-manual.md", "Finalize and retire-host document typed precondition refusal as 2.", "v1.2"},
}
// LegacyExits returns the compatibility grid, including its removal boundary.
func LegacyExits() []LegacyExit { return append([]LegacyExit(nil), legacyExits...) }
func exitClass(kind Kind, policy Policy) string {
if kind.Name == "server_domain" && kind.ServerCode == "forbidden" {
return "not_authorized"
}
if kind.Name == "server_domain" && policy.Code == "remote_unavailable" && !policy.Retryable {
return "domain_refusal"
}
if kind.Name == "delete_lease_barrier" || kind.Name == "server_domain" && kind.ServerCode == "not_admitted" && kind.ServerRetryable && kind.Contract == Chunk {
return "lease_barrier"
}
if kind.Name == Credential.Name || kind.Name == Configuration.Name {
return "local_configuration"
}
if kind.Name == rpcKindKey(codes.FailedPrecondition).Name || kind.Name == "http/409" || kind.Name == "http/412" || kind.Name == "http/428" {
return "domain_precondition"
}
if _, listed := canonicalExits[policy.Code]; listed {
return policy.Code
}
if kind.Name == Guard("unsupported_error_code").Name {
return "outcome_unknown"
}
return "domain_refusal"
}
func projectExit(kind Kind, policy Policy) int {
class := exitClass(kind, policy)
exit := canonicalExits[class]
for _, legacy := range legacyExits {
if legacy.Command == kind.Contract && legacy.Class == class {
if legacy.Exit == 75 && kind.Name == "server_domain" && !policy.Retryable {
continue
}
return legacy.Exit
}
}
return exit
}
@@ -0,0 +1,141 @@
package answer_test
import (
"context"
"crypto/x509"
"errors"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestCanonicalExitProjectionGrid(t *testing.T) {
cert := serverCertificate(t, time.Now().Add(-time.Hour), time.Now().Add(time.Hour))
leaf, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
t.Fatal(err)
}
_, trust := leaf.Verify(x509.VerifyOptions{Roots: x509.NewCertPool()})
_, missing := os.ReadFile(filepath.Join(t.TempDir(), "absent-key"))
_, badAddress := net.DialTimeout("tcp", "127.0.0.1", time.Second)
ctx, cancel := context.WithTimeout(context.Background(), -time.Second)
defer cancel()
for _, row := range []struct {
name string
err error
phase answer.Phase
exit int
}{
{"unsent", refusedDial(t), answer.Unsent, 75},
{"unknown", resetConnection(t), answer.PossiblyAdmitted, 3},
{"trust", trust, answer.Unsent, 5},
{"local-credential", answer.LocalCredential(missing), answer.Unsent, 78},
{"local-configuration", answer.LocalConfiguration(badAddress), answer.Unsent, 78},
{"canceled", canceledCall(t), answer.Unsent, 1},
{"caller-deadline", answer.RecordContext(ctx, answer.Unsent, ctx.Err()), answer.Unsent, 1},
{"readout-unproven", status.Error(codes.DataLoss, "unproven"), answer.PossiblyAdmitted, 4},
} {
for _, contract := range []answer.Contract{"", answer.Chunk, answer.ChunkVerify, answer.Workspace, answer.VolumeCreate, answer.VolumeResolve, answer.Cluster, answer.Restore, answer.Failover, answer.VolumeJob, answer.VolumeStop, answer.VolumePlacement, answer.Shell, answer.Ops} {
t.Run(string(contract)+"/"+row.name, func(t *testing.T) {
got, check := answer.PolicyOf(answer.Record(row.phase, row.err), contract)
want := row.exit
if contract == answer.ChunkVerify && row.name == "unknown" {
want = 1
}
if contract == answer.Failover && (row.name == "unsent" || row.name == "caller-deadline") {
want = 3
}
if (contract == answer.VolumeCreate || contract == answer.VolumeResolve) && row.name == "unknown" {
want = 75
}
if (contract == answer.VolumeCreate || contract == answer.VolumeResolve) && row.name == "trust" {
want = 78
}
if check != nil || got.Exit != want {
t.Fatalf("policy=%+v wantExit=%d check=%v", got, want, check)
}
if row.name == "unknown" && contract != answer.ChunkVerify && got.Retry != answer.Recover {
t.Fatalf("legacy exit weakened recovery: %+v", got)
}
})
}
}
}
func TestEveryLegacyExitHasADocumentedGridRow(t *testing.T) {
expired, cancel := context.WithTimeout(context.Background(), -time.Second)
defer cancel()
expected := []struct {
contract answer.Contract
err error
phase answer.Phase
exit int
}{
{answer.Failover, answer.Record(answer.Unsent, refusedDial(t)), answer.Unsent, 3},
{answer.Failover, answer.RecordContext(expired, answer.Unsent, expired.Err()), answer.Unsent, 3},
{answer.ChunkVerify, resetConnection(t), answer.PossiblyAdmitted, 1},
{answer.VolumeCreate, status.Error(codes.InvalidArgument, "server refused"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, status.Error(codes.InvalidArgument, "server refused"), answer.PossiblyAdmitted, 78},
{answer.VolumeCreate, resetConnection(t), answer.PossiblyAdmitted, 75},
{answer.VolumeCreate, status.Error(codes.AlreadyExists, "same target"), answer.PossiblyAdmitted, 78},
{answer.VolumeCreate, status.Error(codes.FailedPrecondition, "format"), answer.PossiblyAdmitted, 78},
{answer.VolumeCreate, status.Error(codes.PermissionDenied, "role"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, resetConnection(t), answer.PossiblyAdmitted, 75},
{answer.VolumeResolve, status.Error(codes.NotFound, "missing volume"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, status.Error(codes.FailedPrecondition, "identity"), answer.PossiblyAdmitted, 78},
{answer.VolumeResolve, status.Error(codes.PermissionDenied, "role"), answer.PossiblyAdmitted, 78},
{answer.Cluster, status.Error(codes.FailedPrecondition, "HOST_HOLDS_WORK"), answer.PossiblyAdmitted, 2},
}
legacy := answer.LegacyExits()
if len(legacy) != len(expected) {
t.Fatalf("new legacy row needs an independent control: %d != %d", len(legacy), len(expected))
}
for i, row := range legacy {
want := expected[i]
if row.Command != want.contract || row.Reason == "" || row.RemovedIn != "v1.2" {
t.Fatalf("row%d lacks compatibility contract: %+v", i, row)
}
if _, err := os.Stat(filepath.Join("..", "..", "..", filepath.FromSlash(row.Source))); err != nil {
t.Fatalf("legacy source: %v", err)
}
got, check := answer.PolicyOf(answer.Record(want.phase, want.err), want.contract)
if check != nil || got.Exit != want.exit || got.Exit != row.Exit {
t.Fatalf("row%d %+v check=%v", i, got, check)
}
}
if _, err := answer.PolicyOf(answer.Record(answer.Unsent, errors.New("unlisted")), answer.Ops); err == nil {
t.Fatal("projection invented an unlisted policy")
}
}
func TestTypedRemoteUnavailableRespectsRetryable(t *testing.T) {
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
for _, retryable := range []bool{false, true} {
p, err := answer.Lookup(phase, answer.ForContract(answer.Chunk, answer.Domain("remote_unavailable", retryable, "definite server answer")))
want := 1
if retryable {
want = 75
}
if err != nil || p.Exit != want || p.Retryable != retryable {
t.Fatalf("phase=%s retryable=%t policy=%+v error=%v", phase, retryable, p, err)
}
}
}
}
func TestNonRetryableServerAnswerNeverInvitesTemporaryRetry(t *testing.T) {
for _, contract := range []answer.Contract{answer.Chunk, answer.ChunkVerify, answer.Workspace, answer.VolumeCreate, answer.VolumeResolve, answer.Cluster, answer.Restore, answer.Failover, answer.VolumeJob, answer.VolumeStop, answer.VolumePlacement, answer.Shell, answer.Ops} {
for _, code := range []string{"remote_unavailable", "outcome_unknown", "not_admitted"} {
p, err := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(contract, answer.Domain(code, false, "server refuses retry")))
if err != nil || p.Retryable || p.Exit == 75 {
t.Errorf("contract=%s code=%s policy=%+v error=%v", contract, code, p, err)
}
}
}
}
+121
View File
@@ -0,0 +1,121 @@
package answer
import (
"context"
"errors"
"fmt"
"google.golang.org/grpc/status"
)
// ErrLocalCredential identifies credential validation before a dial. It is
// independent of diagnostic text, including an underlying file-load error.
var ErrLocalCredential = errors.New("local credentials")
var ErrLocalConfiguration = errors.New("local configuration")
func LocalCredential(err error) error {
if err == nil {
return nil
}
if errors.Is(err, ErrLocalCredential) {
return err
}
return Record(Unsent, fmt.Errorf("%w: %w", ErrLocalCredential, err))
}
func LocalConfiguration(err error) error {
if err == nil {
return nil
}
if errors.Is(err, ErrLocalConfiguration) {
return err
}
return Record(Unsent, fmt.Errorf("%w: %w", ErrLocalConfiguration, err))
}
type failure struct {
phase Phase
kind Kind
cause error
}
func (f *failure) Error() string { return f.cause.Error() }
func (f *failure) Unwrap() error { return f.cause }
func (f *failure) GRPCStatus() *status.Status {
server, ok := status.FromError(f.cause)
if !ok {
return nil
} // transport evidence never manufactures a server answer
return server
}
// Record attaches the evidence of one transport attempt without deciding
// its outcome. An unlisted kind remains unlisted at PolicyOf.
func Record(phase Phase, err error) error {
if err == nil {
return nil
}
kind, _ := ErrorKind(err)
return &failure{phase: phase, kind: kind, cause: err}
}
// EnsureEvidence preserves recorded facts. An opaque RPC error without
// transport evidence can only receive the caller's conservative phase.
func EnsureEvidence(phase Phase, err error) error {
if err == nil {
return nil
}
var existing *failure
if errors.As(err, &existing) {
return err
}
return Record(phase, err)
}
// Rekind translates an owned boundary's error provenance without replacing
// the request's admission evidence. Missing evidence remains conservative.
func Rekind(err error, kind Kind) error {
if err == nil {
return nil
}
phase := PossiblyAdmitted
var recorded *failure
if errors.As(err, &recorded) {
phase = recorded.phase
}
return &failure{phase: phase, kind: kind, cause: err}
}
// PolicyOf reads evidence preserved by a transport adapter. Unannotated
// errors are not evidence that an operation was never admitted.
func PolicyOf(err error, contracts ...Contract) (Policy, error) {
var f *failure
if errors.As(err, &f) {
kind := f.kind
if len(contracts) == 1 {
kind = ForContract(contracts[0], kind)
}
if len(contracts) > 1 {
return Policy{}, fmt.Errorf("answer: multiple wire contracts")
}
return Lookup(f.phase, kind)
}
return Policy{}, fmt.Errorf("answer: failure has no admission evidence: %v", err)
}
// Snapshot one owned context once. A non-nil winning cause is immutable;
// only then read Err to distinguish a custom deadline cause from cancellation.
func RecordContext(ctx context.Context, phase Phase, err error) error {
if err == nil {
return nil
}
kind, _ := ErrorKind(err)
if cause := context.Cause(ctx); cause != nil && (kind == Connection || kind == PlaintextConnection || kind == Timeout || kind == Canceled) {
kind = Canceled
if ctx.Err() == context.DeadlineExceeded {
kind = CallerDeadline
}
return &failure{phase: phase, kind: kind, cause: errors.Join(err, ctx.Err(), cause)}
}
return Record(phase, err)
}
+110
View File
@@ -0,0 +1,110 @@
package answer
import (
"context"
"errors"
"io"
"sync/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/stats"
)
type rpcEvidenceKey struct{}
type rpcEvidence struct {
started uint64
peerGeneration atomic.Uint64
peerPool atomic.Pointer[peerPool]
dial atomic.Pointer[dialObservation]
writeStarted atomic.Bool
tls atomic.Pointer[connectionTLSInfo]
}
// ClientOptions preserve per-call admission facts on every link. OutHeader
// is emitted by gRPC's NewStream before it returns after queuing headers.
// Its absence when Invoke returns proves that no request stream was sent;
// its presence is deliberately conservative across transparent retries.
func ClientOptions() []grpc.DialOption {
return []grpc.DialOption{grpc.WithDefaultServiceConfig(`{"loadBalancingConfig":[{"answer_pick_first":{}}]}`), grpc.WithStatsHandler(rpcStats{}), grpc.WithChainUnaryInterceptor(recordUnary), grpc.WithChainStreamInterceptor(recordStream)}
}
func recordStream(ctx context.Context, desc *grpc.StreamDesc, conn *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
evidence := &rpcEvidence{started: attemptSequence.Load()}
ctx = context.WithValue(ctx, rpcEvidenceKey{}, evidence)
stream, err := streamer(ctx, desc, conn, method, opts...)
if err != nil {
return nil, evidence.record(ctx, err)
}
return &observedStream{ClientStream: stream, record: func(err error) error { return evidence.record(ctx, err) }}, nil
}
func (e *rpcEvidence) record(ctx context.Context, err error) error {
if err == nil {
return nil
}
phase := Unsent
if e.writeStarted.Load() {
phase = PossiblyAdmitted
}
// Picker causes explain fail-fast Unavailable, not a WaitForReady call
// ended by its caller or a definite server answer.
kind, _ := ErrorKind(err)
if phase == Unsent && ctx.Err() == nil && kind == Connection {
if observation := e.dial.Load(); observation != nil {
err = &failure{phase: Unsent, kind: observation.kind, cause: errors.Join(err, observation.cause)}
}
}
return RecordContext(ctx, phase, err)
}
type observedStream struct {
grpc.ClientStream
record func(error) error
}
func (s *observedStream) Header() (metadata.MD, error) {
header, err := s.ClientStream.Header()
return header, s.record(err)
}
func (s *observedStream) SendMsg(msg any) error {
err := s.ClientStream.SendMsg(msg)
if err == io.EOF {
return err
} // callers obtain the final status via RecvMsg
return s.record(err)
}
func (s *observedStream) RecvMsg(msg any) error {
err := s.ClientStream.RecvMsg(msg)
if err == io.EOF {
return err
} // successful stream completion, not a transport EOF
return s.record(err)
}
func (s *observedStream) CloseSend() error { return s.record(s.ClientStream.CloseSend()) }
func recordUnary(ctx context.Context, method string, req, reply any, conn *grpc.ClientConn, invoke grpc.UnaryInvoker, opts ...grpc.CallOption) error {
evidence := &rpcEvidence{started: attemptSequence.Load()}
ctx = context.WithValue(ctx, rpcEvidenceKey{}, evidence)
err := invoke(ctx, method, req, reply, conn, opts...)
return evidence.record(ctx, err)
}
type rpcStats struct{}
func (rpcStats) TagRPC(ctx context.Context, _ *stats.RPCTagInfo) context.Context { return ctx }
func (rpcStats) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context { return ctx }
func (rpcStats) HandleConn(context.Context, stats.ConnStats) {}
func (rpcStats) HandleRPC(ctx context.Context, event stats.RPCStats) {
if _, ok := event.(*stats.OutHeader); ok {
if evidence, ok := ctx.Value(rpcEvidenceKey{}).(*rpcEvidence); ok {
evidence.writeStarted.Store(true)
if p, ok := peer.FromContext(ctx); ok {
if info, ok := p.AuthInfo.(*connectionTLSInfo); ok {
evidence.tls.Store(info)
}
}
}
}
}
+66
View File
@@ -0,0 +1,66 @@
package answer
import (
"context"
"io"
"net/http"
"net/http/httptrace"
"sync/atomic"
)
// DoHTTP records transport evidence for one HTTP call. An already admitted
// operation must pass PossiblyAdmitted even when this call only polls it.
func DoHTTP(client *http.Client, req *http.Request, phase Phase) (*http.Response, error) {
if err := req.Context().Err(); err != nil {
// Do not invoke even a custom transport after a preflight cancellation.
// An earlier admission still belongs to the operation, including polls.
return nil, RecordContext(req.Context(), phase, err)
}
// A concrete http.Transport may delegate through RegisterProtocol. Only
// our privately owned native path can supply positive trace provenance.
if client.Transport == nil {
copy := *client
copy.Transport = defaultHTTPTransport
client = &copy
}
_, trustedTrace := client.Transport.(*nativeHTTPTransport)
// Lack of trace support is not proof of an unsent request. GotConn is
// conservative: from that point a request write may have started, even
// if a WroteHeaders callback never arrives after a partial write.
var traced, connected atomic.Bool
trace := &httptrace.ClientTrace{
GetConn: func(string) { traced.Store(true) },
GotConn: func(httptrace.GotConnInfo) { connected.Store(true) },
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
resp, err := client.Do(req)
observed := PossiblyAdmitted
if phase == Unsent && trustedTrace && traced.Load() && !connected.Load() {
observed = Unsent
}
if err != nil {
recorded := RecordContext(req.Context(), observed, err)
kind, _ := ErrorKind(recorded)
if phase == PossiblyAdmitted && (certificateKind(kind) || kind == Credential || kind == Configuration) {
return resp, Rekind(recorded, Connection)
}
return resp, recorded
}
if resp.Body != nil {
resp.Body = &responseBody{ReadCloser: resp.Body, ctx: req.Context()}
}
return resp, nil
}
type responseBody struct {
io.ReadCloser
ctx context.Context
}
func (body *responseBody) Read(p []byte) (int, error) {
n, err := body.ReadCloser.Read(p)
if err != nil && err != io.EOF {
err = RecordContext(body.ctx, PossiblyAdmitted, err)
}
return n, err
}
@@ -0,0 +1,61 @@
package answer
import (
"fmt"
"google.golang.org/grpc/codes"
"net/http"
"strconv"
)
// HTTPStatusFailure records a response the caller has decided is a failure.
// It does not decide whether a 404/409 is protocol state or an error.
func HTTPStatusFailure(status int, cause error) error {
if cause == nil {
cause = fmt.Errorf("HTTP %d", status)
}
// The response status belongs to this attempt; a nested body-read
// failure cannot replace it. Keep outer operation records authoritative.
return &failure{phase: PossiblyAdmitted, kind: httpStatusKind(status), cause: &httpStatusFailure{status: status, cause: cause}}
}
type httpStatusFailure struct {
status int
cause error
}
func (f *httpStatusFailure) Error() string { return f.cause.Error() }
func (f *httpStatusFailure) Unwrap() error { return f.cause }
func httpStatusKind(status int) Kind { return Kind{Name: "http/" + strconv.Itoa(status)} }
// HTTP adapters supply status facts. These cells derive their policy from
// the same canonical rows as RPC; no adapter owns a parallel decision table.
func addHTTPStatusCells(registry map[key]Policy) {
for status, rpc := range map[int]codes.Code{
http.StatusBadRequest: codes.InvalidArgument, http.StatusUnauthorized: codes.Unauthenticated,
http.StatusForbidden: codes.PermissionDenied, http.StatusNotFound: codes.NotFound,
http.StatusMethodNotAllowed: codes.Unimplemented, http.StatusNotAcceptable: codes.InvalidArgument,
http.StatusConflict: codes.FailedPrecondition, http.StatusGone: codes.NotFound,
http.StatusPreconditionFailed: codes.FailedPrecondition, http.StatusRequestEntityTooLarge: codes.InvalidArgument,
http.StatusUnsupportedMediaType: codes.InvalidArgument, http.StatusUnprocessableEntity: codes.InvalidArgument,
http.StatusPreconditionRequired: codes.FailedPrecondition, http.StatusTooManyRequests: codes.ResourceExhausted,
http.StatusInternalServerError: codes.Internal, http.StatusNotImplemented: codes.Unimplemented,
http.StatusBadGateway: codes.Unavailable, http.StatusServiceUnavailable: codes.Unavailable,
http.StatusGatewayTimeout: codes.DeadlineExceeded, http.StatusInsufficientStorage: codes.ResourceExhausted,
http.StatusLoopDetected: codes.Internal,
} {
canonical := rpcKindKey(rpc)
for cell, policy := range registry {
if cell.kind != ForContract(cell.kind.Contract, canonical) {
continue
}
if status == http.StatusUnauthorized {
policy.Cure = "fix authentication credentials for the HTTP peer before retrying"
}
if status == http.StatusForbidden {
policy.Cure = "fix the HTTP peer's access policy or the caller's credentials before retrying"
}
registry[key{cell.phase, ForContract(cell.kind.Contract, httpStatusKind(status))}] = policy
}
}
}
@@ -0,0 +1,43 @@
package answer_test
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestProducedHTTPStatusPolicyRows(t *testing.T) {
for _, row := range []struct {
status int
code string
retry bool
exit int
}{
{400, "bad_request", false, 2}, {401, "not_authorized", false, 5}, {403, "not_authorized", false, 5},
{404, "not_found", false, 1}, {405, "unsupported", false, 1}, {406, "bad_request", false, 2},
{409, "not_admitted", false, 1}, {410, "not_found", false, 1}, {412, "not_admitted", false, 1},
{413, "bad_request", false, 2}, {415, "bad_request", false, 2}, {422, "bad_request", false, 2},
{428, "not_admitted", false, 1}, {429, "outcome_unknown", true, 3}, {500, "outcome_unknown", true, 3},
{501, "unsupported", false, 1}, {502, "outcome_unknown", true, 3}, {503, "outcome_unknown", true, 3},
{504, "outcome_unknown", true, 3}, {507, "outcome_unknown", true, 3}, {508, "outcome_unknown", true, 3},
} {
t.Run(fmt.Sprint(row.status), func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(row.status) }))
defer server.Close()
req, _ := http.NewRequest(http.MethodPost, server.URL, nil)
resp, err := answer.DoHTTP(server.Client(), req, answer.Unsent)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
err = answer.HTTPStatusFailure(resp.StatusCode, fmt.Errorf("server answered %s", resp.Status))
got, check := answer.PolicyOf(err)
if check != nil || got.Code != row.code || got.Retryable != row.retry || got.Exit != row.exit || got.Cure == "" {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
}
}
+192
View File
@@ -0,0 +1,192 @@
package answer_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/status"
)
type countedTransport struct{ calls atomic.Int64 }
func (tr *countedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
tr.calls.Add(1)
return nil, req.Context().Err()
}
func TestHTTPCancellationBeforeDispatchKeepsOperationPhase(t *testing.T) {
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
for _, deadline := range []bool{false, true} {
ctx, cancel := context.WithCancel(context.Background())
cause := error(context.Canceled)
if deadline {
cancel()
cause = errors.New("custom caller deadline")
ctx, cancel = context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), cause)
} else {
cancel()
}
tr := &countedTransport{}
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "http://unused.invalid", nil)
_, err := answer.DoHTTP(&http.Client{Transport: tr}, req, phase)
cancel()
got, check := answer.PolicyOf(err, answer.Chunk)
code, exit := "canceled", 1
if deadline {
code = "deadline_exceeded"
}
if phase == answer.PossiblyAdmitted {
code, exit = "outcome_unknown", 3
}
if tr.calls.Load() != 0 || check != nil || got.Code != code || got.Exit != exit || !errors.Is(err, cause) {
t.Fatalf("phase=%s deadline=%t dispatched=%d policy=%+v check=%v error=%v", phase, deadline, tr.calls.Load(), got, check, err)
}
}
}
}
func TestHTTPAdapterKeepsAdmissionEvidence(t *testing.T) {
t.Run("nothing sent", func(t *testing.T) {
req, err := http.NewRequest(http.MethodPost, "http://"+refusedTCPAddress(t), strings.NewReader("request"))
if err != nil {
t.Fatal(err)
}
// A destination port of zero cannot be a listening endpoint. Keeping
// the target unavailable avoids the close/reallocate race of a
// listener's former ephemeral port on a busy test host.
_, err = answer.DoHTTP(&http.Client{Timeout: 5 * time.Second}, req, answer.Unsent)
if !isRefusedDial(err) {
t.Fatalf("fixture did not produce a refused TCP dial: %v", err)
}
if _, ok := status.FromError(err); ok {
t.Fatal("an HTTP dial failure became a typed gRPC server answer", err)
}
got, check := answer.PolicyOf(err)
if check != nil || got.Code != "remote_unavailable" || got.Exit != 75 || got.Retry != answer.Resend {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
t.Run("poll dial cannot erase earlier admission", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://"+refusedTCPAddress(t), nil)
_, err := answer.DoHTTP(&http.Client{Timeout: 5 * time.Second}, req, answer.PossiblyAdmitted)
got, check := answer.PolicyOf(err)
if check != nil || got.Code != "outcome_unknown" || got.Retry != answer.Recover {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
t.Run("request received but answer lost", func(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
io.Copy(io.Discard, r.Body)
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
conn.Close()
}))
defer server.Close()
req, err := http.NewRequest(http.MethodPost, server.URL, strings.NewReader("request"))
if err != nil {
t.Fatal(err)
}
_, err = answer.DoHTTP(&http.Client{Timeout: 5 * time.Second}, req, answer.Unsent)
got, check := answer.PolicyOf(err)
if calls.Load() != 1 || check != nil || got.Code != "outcome_unknown" || got.Exit != 3 || got.Retry != answer.Recover {
t.Fatalf("calls=%d policy=%+v check=%v error=%v", calls.Load(), got, check, err)
}
})
}
type getConnOnlyLostAnswerTransport struct{ inner http.RoundTripper }
func (tr getConnOnlyLostAnswerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// A custom transport supports one trace event but omits GotConn. Its real
// request uses another context so native tracing cannot fill the gap.
if trace := httptrace.ContextClientTrace(req.Context()); trace != nil && trace.GetConn != nil {
trace.GetConn(req.URL.Host)
}
resp, err := tr.inner.RoundTrip(req.WithContext(context.Background()))
if err != nil {
return nil, err
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
return nil, io.EOF // server answered; custom transport lost the answer
}
func TestHTTPPartialCustomTraceCannotProveUnsentAfterReceivedPOST(t *testing.T) {
assertPartialHTTPTraceIsUnknown(t, false)
}
func TestHTTPRegisteredProtocolCannotProveUnsentAfterReceivedPOST(t *testing.T) {
assertPartialHTTPTraceIsUnknown(t, true)
}
func TestHTTPOwnedTransportDoesNotInheritRegisteredDefault(t *testing.T) {
var received atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
received.Add(1)
_, _ = io.Copy(io.Discard, r.Body)
_, _ = io.WriteString(w, "received")
}))
defer server.Close()
native := http.DefaultTransport.(*http.Transport).Clone()
defer native.CloseIdleConnections()
poisoned := &http.Transport{}
poisoned.RegisterProtocol("http", getConnOnlyLostAnswerTransport{inner: native})
previous := http.DefaultTransport
http.DefaultTransport = poisoned
t.Cleanup(func() { http.DefaultTransport = previous; poisoned.CloseIdleConnections() })
client := &http.Client{Transport: answer.NewHTTPTransport(answer.HTTPPool{}), Timeout: 5 * time.Second}
defer client.CloseIdleConnections()
req, _ := http.NewRequest(http.MethodPost, server.URL, strings.NewReader("one operation"))
resp, err := answer.DoHTTP(client, req, answer.Unsent)
if err != nil {
t.Fatal("owned transport inherited the registered protocol:", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil || string(body) != "received" || received.Load() != 1 {
t.Fatalf("body=%q received=%d err=%v", body, received.Load(), err)
}
}
func assertPartialHTTPTraceIsUnknown(t *testing.T, registered bool) {
t.Helper()
var received atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(r.Body)
if err != nil || r.Method != http.MethodPost || string(raw) != "admit-once" {
t.Errorf("receipt: method=%s body=%q error=%v", r.Method, raw, err)
}
received.Add(1)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
native := http.DefaultTransport.(*http.Transport).Clone()
defer native.CloseIdleConnections()
var transport http.RoundTripper = getConnOnlyLostAnswerTransport{inner: native}
if registered {
outer := &http.Transport{}
outer.RegisterProtocol("http", transport)
defer outer.CloseIdleConnections()
transport = outer
}
req, _ := http.NewRequest(http.MethodPost, server.URL, strings.NewReader("admit-once"))
_, err := answer.DoHTTP(&http.Client{Transport: transport, Timeout: 5 * time.Second}, req, answer.Unsent)
policy, check := answer.PolicyOf(err, answer.Chunk)
if received.Load() != 1 || check != nil || policy.Code != "outcome_unknown" || policy.Exit != 3 || policy.Retry != answer.Recover {
t.Fatalf("received=%d policy=%+v check=%v error=%v", received.Load(), policy, check, err)
}
}
@@ -0,0 +1,42 @@
package answer
import (
"net"
"net/http"
"time"
)
// HTTPPool sets idle connection retention, not request concurrency. Zero values
// use the standard transport defaults. No dial or protocol callback is exposed.
type HTTPPool struct {
MaxIdleConns, MaxIdleConnsPerHost int
}
// NewHTTPTransport owns a native transport whose request path cannot be replaced
// with RegisterProtocol. Caller-supplied RoundTrippers have no such provenance.
func NewHTTPTransport(pool HTTPPool) http.RoundTripper {
maxIdle := pool.MaxIdleConns
if maxIdle == 0 {
maxIdle = 100
}
return &nativeHTTPTransport{transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: maxIdle,
MaxIdleConnsPerHost: pool.MaxIdleConnsPerHost,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: time.Second,
}}
}
type nativeHTTPTransport struct{ transport *http.Transport }
func (tr *nativeHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return tr.transport.RoundTrip(req)
}
func (tr *nativeHTTPTransport) CloseIdleConnections() { tr.transport.CloseIdleConnections() }
var defaultHTTPTransport = NewHTTPTransport(HTTPPool{})
+266
View File
@@ -0,0 +1,266 @@
package answer
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"google.golang.org/grpc/balancer"
_ "google.golang.org/grpc/balancer/pickfirst"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/serviceconfig"
)
const observedPickFirst = "answer_pick_first"
const maxPeerDiagnostics = 8
var attemptSequence atomic.Uint64
type peerAttempt struct {
peer string
attempt, completed, nonCertificate uint64
state connectivity.State
kind Kind
cause error
singleAddress bool
}
type peerPool struct {
mu sync.Mutex
generation uint64
ambiguous bool
plaintext bool
peers map[string]*peerAttempt
}
type dialObservation struct {
kind Kind
cause error
}
type evidenceBuilder struct{ inner balancer.Builder }
func init() { balancer.Register(evidenceBuilder{inner: balancer.Get("pick_first")}) }
func (b evidenceBuilder) Name() string { return observedPickFirst }
func (b evidenceBuilder) ParseConfig(raw json.RawMessage) (serviceconfig.LoadBalancingConfig, error) {
if parser, ok := b.inner.(balancer.ConfigParser); ok {
return parser.ParseConfig(raw)
}
return nil, nil
}
func (b evidenceBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer {
creds := opts.DialCreds
if creds == nil && opts.CredsBundle != nil {
creds = opts.CredsBundle.TransportCredentials()
}
pool := &peerPool{peers: map[string]*peerAttempt{}, plaintext: creds != nil && creds.Info().SecurityProtocol == "insecure"}
delegate := b.inner.Build(&evidenceClientConn{ClientConn: cc, pool: pool}, opts)
return &evidenceBalancer{Balancer: delegate, pool: pool}
}
type evidenceBalancer struct {
balancer.Balancer
pool *peerPool
}
func peerKey(addr resolver.Address) string {
if addr.ServerName != "" {
return addr.Addr + " (TLS name " + addr.ServerName + ")"
}
return addr.Addr
}
func (b *evidenceBalancer) UpdateClientConnState(state balancer.ClientConnState) error {
peers := map[string]bool{}
ambiguous := false
add := func(addr resolver.Address) {
key := peerKey(addr)
if peers[key] {
ambiguous = true
}
peers[key] = true
}
if len(state.ResolverState.Endpoints) > 0 {
for _, endpoint := range state.ResolverState.Endpoints {
for _, addr := range endpoint.Addresses {
add(addr)
}
}
} else {
for _, addr := range state.ResolverState.Addresses {
add(addr)
}
}
b.pool.mu.Lock()
b.pool.generation++
b.pool.ambiguous = ambiguous
for peer := range b.pool.peers {
if !peers[peer] {
delete(b.pool.peers, peer)
}
}
for peer := range peers {
if b.pool.peers[peer] == nil {
b.pool.peers[peer] = &peerAttempt{peer: peer}
}
}
b.pool.mu.Unlock()
return b.Balancer.UpdateClientConnState(state)
}
type evidenceClientConn struct {
balancer.ClientConn
pool *peerPool
}
func (cc *evidenceClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
listener := opts.StateListener
peer := ""
if len(addrs) == 1 {
peer = peerKey(addrs[0])
}
cc.pool.mu.Lock()
item := &peerAttempt{peer: peer, singleAddress: len(addrs) == 1}
if previous := cc.pool.peers[peer]; previous != nil {
item.nonCertificate = previous.nonCertificate
cc.pool.peers[peer] = item
}
cc.pool.mu.Unlock()
// A multi-address SubConn hides which address failed. It can never
// support an all-peers certificate proof; preserve the delegate unchanged.
opts.StateListener = func(state balancer.SubConnState) {
cc.pool.mu.Lock()
if cc.pool.peers[peer] == item {
item.singleAddress = len(addrs) == 1
if state.ConnectivityState == connectivity.Connecting {
item.attempt = 0 // notification delivery is not attempt-start evidence
item.completed = 0
item.cause = nil
item.kind = Kind{}
}
if state.ConnectivityState == connectivity.TransientFailure {
item.completed = attemptSequence.Add(1)
item.cause = connectionOrigin(state.ConnectionError)
item.kind, _ = ErrorKind(item.cause)
var actual *attemptFailure
if errors.As(item.cause, &actual) && actual.started > 0 && actual.completed >= actual.started {
item.attempt, item.completed = actual.started, actual.completed
}
if !certificateKind(item.kind) {
item.nonCertificate = item.completed
}
}
if state.ConnectivityState != connectivity.Shutdown {
item.state = state.ConnectivityState
}
}
cc.pool.mu.Unlock()
if listener != nil {
listener(state)
}
}
return cc.ClientConn.NewSubConn(addrs, opts)
}
func (cc *evidenceClientConn) UpdateState(state balancer.State) {
cc.pool.mu.Lock()
generation := cc.pool.generation
cc.pool.mu.Unlock()
state.Picker = &evidencePicker{Picker: state.Picker, pool: cc.pool, generation: generation}
cc.ClientConn.UpdateState(state)
}
type evidencePicker struct {
balancer.Picker
pool *peerPool
generation uint64 // immutable generation that produced this delegate picker
}
func (p *evidencePicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
rpc, _ := info.Ctx.Value(rpcEvidenceKey{}).(*rpcEvidence)
if rpc != nil {
generation := p.generation
if rpc.peerPool.CompareAndSwap(nil, p.pool) {
rpc.peerGeneration.Store(generation)
}
}
result, err := p.Picker.Pick(info)
if rpc != nil && err != nil && !errors.Is(err, balancer.ErrNoSubConnAvailable) {
generation := rpc.peerGeneration.Load()
if rpc.peerPool.Load() != p.pool {
generation = 0
}
rpc.dial.Store(p.pool.observe(rpc.started, generation))
}
return result, err
}
func certificateKind(kind Kind) bool { return kind == Certificate || kind == Trust || kind == Name }
func connectionOrigin(err error) error {
// gRPC's transport ConnectionError exposes its typed Origin publicly
// through this method, although its concrete package is internal.
if source, ok := err.(interface{ Origin() error }); ok {
if cause := source.Origin(); cause != nil {
return cause
}
}
return err
}
func (pool *peerPool) observe(started, generation uint64) *dialObservation {
pool.mu.Lock()
defer pool.mu.Unlock()
all := len(pool.peers) > 0 && pool.generation == generation && !pool.ambiguous
kind := Certificate
hasTrust, hasName := false, false
var localKind Kind
names := make([]string, 0, maxPeerDiagnostics)
for peer, item := range pool.peers {
if len(names) < maxPeerDiagnostics {
names = append(names, peer)
sort.Strings(names)
} else if peer < names[len(names)-1] {
names[len(names)-1] = peer
sort.Strings(names)
}
if !item.singleAddress || item.attempt <= started || item.completed <= started || item.nonCertificate > started || item.state != connectivity.TransientFailure || !certificateKind(item.kind) {
all = false
}
hasTrust = hasTrust || item.kind == Trust
hasName = hasName || item.kind == Name
if pool.generation == generation && item.attempt > started && item.completed > started && (item.kind == Credential || item.kind == Configuration) {
localKind = item.kind
}
}
sort.Strings(names)
descriptions := make([]string, 0, maxPeerDiagnostics)
for _, peer := range names {
if len(descriptions) == maxPeerDiagnostics {
break
}
item := pool.peers[peer]
cause := "attempt not yet proven complete"
if item.cause != nil {
cause = item.cause.Error()
}
descriptions = append(descriptions, fmt.Sprintf("peer %s attempt %d: %s", peer, item.attempt, cause))
}
if len(pool.peers) > len(descriptions) {
descriptions = append(descriptions, fmt.Sprintf("%d more peer causes omitted", len(pool.peers)-len(descriptions)))
}
if hasTrust {
kind = Trust
} else if hasName {
kind = Name
}
if !all {
kind = Connection
}
if localKind.Name != "" {
kind = localKind
}
if kind == Connection && pool.plaintext {
kind = PlaintextConnection
}
return &dialObservation{kind: kind, cause: errors.New(strings.Join(descriptions, "; "))}
}
+108
View File
@@ -0,0 +1,108 @@
package answer
import (
"context"
"crypto/x509"
"errors"
"fmt"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/resolver"
"net"
"strings"
"testing"
"google.golang.org/grpc/connectivity"
)
func TestPeerCertificateProofRequiresEveryFreshCompletedAttempt(t *testing.T) {
for _, row := range []struct {
name string
completed, nonCertificate uint64
state connectivity.State
generation uint64
want Kind
}{
{"fresh-cert", 4, 0, connectivity.TransientFailure, 1, Trust},
{"cached-cert", 2, 0, connectivity.TransientFailure, 1, Connection},
{"network-then-cert-in-same-call", 4, 3, connectivity.TransientFailure, 1, Connection},
{"network-before-call-then-fresh-cert", 4, 1, connectivity.TransientFailure, 1, Trust},
{"attempt-in-flight", 4, 0, connectivity.Connecting, 1, Connection},
{"resolver-changed", 4, 0, connectivity.TransientFailure, 2, Connection},
} {
t.Run(row.name, func(t *testing.T) {
pool := &peerPool{generation: row.generation, peers: map[string]*peerAttempt{"peer-a": {peer: "peer-a", attempt: 3, completed: row.completed, nonCertificate: row.nonCertificate, state: row.state, kind: Trust, cause: errors.New("certificate rejected"), singleAddress: true}}}
got := pool.observe(2, 1)
if got.kind != row.want {
t.Fatalf("proof authorized wrong class: got=%v want=%v cause=%v", got.kind, row.want, got.cause)
}
})
}
}
func TestPeerDiagnosticTruncationNeverAuthorizesTerminalClassification(t *testing.T) {
pool := &peerPool{generation: 1, peers: map[string]*peerAttempt{}}
for i := 0; i < maxPeerDiagnostics; i++ {
name := fmt.Sprintf("a-%02d", i)
pool.peers[name] = &peerAttempt{peer: name, attempt: 3, completed: 4, state: connectivity.TransientFailure, kind: Trust, cause: errors.New("certificate rejected"), singleAddress: true}
}
pool.peers["z-network"] = &peerAttempt{peer: "z-network", attempt: 3, completed: 4, nonCertificate: 4, state: connectivity.TransientFailure, kind: Connection, cause: errors.New("dial refused"), singleAddress: true}
got := pool.observe(2, 1)
if got.kind != Connection || !strings.Contains(got.cause.Error(), "1 more peer causes omitted") {
t.Fatalf("diagnostic cap weakened proof: %v %v", got.kind, got.cause)
}
}
type heldNotificationClientConn struct {
balancer.ClientConn
deliver func(balancer.SubConnState)
}
func (cc *heldNotificationClientConn) NewSubConn(_ []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
cc.deliver = opts.StateListener
return nil, nil
}
type rejectingCredentials struct {
credentials.TransportCredentials
cause error
}
func (c *rejectingCredentials) ClientHandshake(context.Context, string, net.Conn) (net.Conn, credentials.AuthInfo, error) {
return nil, nil, c.cause
}
func TestDelayedPeerNotificationCannotRefreshAnOldTLSFailure(t *testing.T) {
for _, name := range []string{"failure-before-call", "failure-during-call", "unobserved-failure"} {
t.Run(name, func(t *testing.T) {
pool := &peerPool{generation: 1, peers: map[string]*peerAttempt{"peer-a": {peer: "peer-a"}}}
cc := &heldNotificationClientConn{}
observer := &evidenceClientConn{ClientConn: cc, pool: pool}
if _, err := observer.NewSubConn([]resolver.Address{{Addr: "peer-a"}}, balancer.NewSubConnOptions{}); err != nil {
t.Fatal(err)
}
// The TLS boundary fails first; its two balancer notifications remain
// queued until after the next RPC starts, exactly as async delivery may.
cause := error(x509.UnknownAuthorityError{Cert: &x509.Certificate{}})
wrapped, _ := ObserveCredentials(&rejectingCredentials{cause: cause})
started := attemptSequence.Load()
_, _, failure := wrapped.ClientHandshake(context.Background(), "peer-a", nil)
if name == "failure-before-call" {
started = attemptSequence.Load()
}
if name == "unobserved-failure" {
failure = cause
}
cc.deliver(balancer.SubConnState{ConnectivityState: connectivity.Connecting})
cc.deliver(balancer.SubConnState{ConnectivityState: connectivity.TransientFailure, ConnectionError: failure})
got := pool.observe(started, 1)
want := Connection
if name == "failure-during-call" {
want = Trust
}
if got.kind != want {
t.Fatalf("notification relabeled failure: got=%v want=%v cause=%v", got.kind, want, got.cause)
}
})
}
}
+210
View File
@@ -0,0 +1,210 @@
// Package answer owns the operator failure policy shared by CLI and RPC
// adapters. Transport adapters supply facts; they do not decide retry safety.
package answer
import (
"fmt"
"google.golang.org/grpc/codes"
"time"
)
// Phase is admission evidence, not a guess based on an error message.
type Phase string
const (
Unsent Phase = "unsent"
PossiblyAdmitted Phase = "possibly_admitted"
)
// Contract is the existing output protocol, not a retry decision. It is
// part of the error kind so the same pure registry preserves wire exits.
type Contract string
const (
Chunk Contract = "chunk"
ChunkVerify Contract = "chunk_verify"
Workspace Contract = "workspace"
VolumeCreate Contract = "volume_create"
VolumeResolve Contract = "volume_resolve"
Cluster Contract = "cluster"
Restore Contract = "restore"
Failover Contract = "failover"
VolumeJob Contract = "volume_job"
VolumeStop Contract = "volume_stop"
VolumePlacement Contract = "volume_placement"
Shell Contract = "shell"
Ops Contract = "ops"
)
type Kind struct {
Name string
Contract Contract
ServerCode string
ServerRetryable bool
ServerMessage string
}
func (kind Kind) String() string {
name := string(kind.Contract) + "/" + kind.Name
if kind.ServerCode != "" && len(kind.ServerCode) <= 64 {
name += "/" + kind.ServerCode
}
return name
}
func ForContract(contract Contract, kind Kind) Kind { kind.Contract = contract; return kind }
var (
Connection = Kind{Name: "connection"}
PlaintextConnection = Kind{Name: "plaintext_connection"}
Certificate = Kind{Name: "certificate"}
Trust = Kind{Name: "trust"}
Name = Kind{Name: "name"}
DNS = Kind{Name: "dns"}
Timeout = Kind{Name: "timeout"}
Canceled = Kind{Name: "canceled"}
Credential = Kind{Name: "local_credential"}
Configuration = Kind{Name: "local_configuration"}
CallerDeadline = Kind{Name: "caller_deadline"}
)
// RetryRule describes recovery of this operation, never a new operation.
type RetryRule string
const (
Resend RetryRule = "resend_same_operation"
Recover RetryRule = "replay_key_or_poll"
Never RetryRule = "fix_before_retry"
)
type Policy struct {
Code string
Retryable bool
Retry RetryRule
Cure string
Exit int
}
type key struct {
phase Phase
kind Kind
}
// The registry is the sole owner of classification, cure and exit policy.
var registry = buildRegistry()
func buildRegistry() map[key]Policy {
base := map[key]Policy{
{Unsent, Credential}: {"bad_request", false, Never, "fix the local credential files (certificate, key, CA or token) before dialing again", 0},
{Unsent, Configuration}: {"bad_request", false, Never, "correct the local address or transport configuration before dialing again", 0},
{PossiblyAdmitted, Configuration}: {"bad_request", false, Never, "correct the local address or transport configuration, then recover the same operation", 0},
{Unsent, CallerDeadline}: {"deadline_exceeded", true, Resend, "the caller's deadline passed before sending; retry the same operation with a sufficient caller window", 0},
{PossiblyAdmitted, CallerDeadline}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{PossiblyAdmitted, Credential}: {"bad_request", false, Never, "fix the local credential files (certificate, key, CA or token), then recover the same operation", 0},
{Unsent, Connection}: {"remote_unavailable", true, Resend, "retry the same operation when the remote is reachable", 0},
{PossiblyAdmitted, Connection}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{Unsent, DNS}: {"remote_unavailable", true, Resend, "check name resolution, then retry the same operation", 0},
{PossiblyAdmitted, DNS}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{Unsent, Certificate}: {"not_authorized", false, Never, "fix the client certificate, its key and the peer's certificate policy before retrying", 0},
{PossiblyAdmitted, Certificate}: {"not_authorized", false, Never, "fix the client certificate, its key and the peer's certificate policy before retrying", 0},
{Unsent, Trust}: {"not_authorized", false, Never, "fix the trusted CA before retrying", 0},
{PossiblyAdmitted, Trust}: {"not_authorized", false, Never, "fix the trusted CA before retrying", 0},
{Unsent, Name}: {"not_authorized", false, Never, "fix the peer address or its certificate names before retrying", 0},
{PossiblyAdmitted, Name}: {"not_authorized", false, Never, "fix the peer address or its certificate names before retrying", 0},
{Unsent, Timeout}: {"remote_unavailable", true, Resend, "retry the same operation when the remote is reachable", 0},
{PossiblyAdmitted, Timeout}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
{Unsent, Canceled}: {"canceled", false, Never, "operation interrupted by its caller", 0},
{PossiblyAdmitted, Canceled}: {"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0},
}
base[key{Unsent, PlaintextConnection}] = base[key{Unsent, Connection}]
base[key{PossiblyAdmitted, PlaintextConnection}] = base[key{PossiblyAdmitted, Connection}]
for _, row := range []struct {
code codes.Code
policy Policy
}{
{codes.InvalidArgument, Policy{"bad_request", false, Never, "correct the server's stated argument error before retrying", 0}},
{codes.FailedPrecondition, Policy{"not_admitted", false, Never, "resolve the server's stated precondition before retrying", 0}},
{codes.NotFound, Policy{"not_found", false, Never, "check the requested identity; do not create a replacement as a retry", 0}},
{codes.AlreadyExists, Policy{"target_exists", false, Never, "read the existing target and reconcile the original operation", 0}},
{codes.PermissionDenied, Policy{"not_authorized", false, Never, "check the certificate's role in the server's role file before retrying", 0}},
{codes.Unauthenticated, Policy{"not_authorized", false, Never, "check the certificate and the server's trusted CA and role file before retrying", 0}},
{codes.Unimplemented, Policy{"unsupported", false, Never, "use a server that supports this operation", 0}},
{codes.DataLoss, Policy{"readout_unproven", false, Never, "inspect the stored operation and its loss or integrity evidence before proceeding", 0}},
{codes.Internal, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.Unknown, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.Aborted, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.OutOfRange, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
{codes.ResourceExhausted, Policy{"outcome_unknown", true, Recover, "recover the same operation by its replay key or poll its existing handle; do not start another operation", 0}},
} {
for _, phase := range []Phase{Unsent, PossiblyAdmitted} {
base[key{phase, rpcKindKey(row.code)}] = row.policy
}
}
addDomainCells(base)
for _, contract := range []Contract{Chunk, ChunkVerify, Workspace, VolumeCreate, VolumeResolve, Cluster, Restore, Failover, VolumeJob, VolumeStop, VolumePlacement, Shell, Ops} {
for cell, policy := range base {
if cell.kind.Contract != "" {
continue
}
if cell.kind == rpcKindKey(codes.NotFound) && (contract == Restore || contract == VolumeJob) {
policy.Code = "snapshot_not_found"
}
if contract == Failover && policy.Retryable {
policy.Retry = Recover
policy.Cure = "read the current authority line before another move; do not blindly repeat an uncertain move"
}
if contract == VolumeCreate && policy.Retryable {
policy.Cure = "earlier steps may remain recorded; retry identical name, geometry and placement"
}
if contract == Workspace && (cell.kind == rpcKindKey(codes.PermissionDenied) || cell.kind == rpcKindKey(codes.Unauthenticated)) {
policy.Cure = "not authorized by blockmaster: " + policy.Cure
}
base[key{cell.phase, ForContract(contract, cell.kind)}] = policy
}
}
addHTTPStatusCells(base)
return base
}
// Lookup refuses unlisted combinations. Callers must not invent a retry
// policy when an adapter supplies a new error kind or lacks phase evidence.
func Lookup(phase Phase, kind Kind) (Policy, error) {
lookup := kind
if kind.Name == "server_domain" {
if kind.ServerCode == "" || len(kind.ServerCode) > 64 {
return Policy{}, fmt.Errorf("answer: server domain code must have 1..64 bytes")
}
lookup.ServerMessage, lookup.ServerRetryable = "", false
}
if kind.Name == "delete_lease_barrier" {
if len(kind.ServerMessage) > 64 {
return Policy{}, fmt.Errorf("answer: invalid lease barrier stamp")
}
if _, err := time.Parse(time.RFC3339Nano, kind.ServerMessage); err != nil {
return Policy{}, fmt.Errorf("answer: invalid lease barrier stamp: %w", err)
}
lookup.ServerMessage = ""
}
policy, ok := registry[key{phase, lookup}]
if !ok {
return Policy{}, fmt.Errorf("answer: unlisted phase %q, error kind %q", phase, kind)
}
if kind.Name == "server_domain" {
policy = projectDomain(policy, kind)
}
if kind.Name == "delete_lease_barrier" {
policy.Cure = "retry the same --request-id after " + kind.ServerMessage
}
if kind.Contract == Shell && kind.Name != "server_domain" && kind.Name != "delete_lease_barrier" && kind.Name != CallerDeadline.Name && policy.Retryable {
policy.Cure = "recover this read-only inspection by polling the same record; this inspection does not mutate the volume"
}
if kind.Contract == ChunkVerify && policy.Code == "outcome_unknown" && policy.Retryable {
policy.Retry = Resend
policy.Cure = "verification is read-only; after resolving the failure, run verification again; do not treat the incomplete scan as a clean result"
}
if kind.Name == PlaintextConnection.Name && phase == Unsent {
policy.Cure += "; this client is configured for plaintext: check whether the endpoint requires a TLS-capable client (for blockmaster, configure SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and SW_BLOCK_TLS_CA); a closed preface alone does not prove a TLS requirement"
}
policy.Exit = projectExit(kind, policy)
return policy, nil
}
@@ -0,0 +1,353 @@
package answer_test
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"io"
"math/big"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestProducedFailurePolicyTable(t *testing.T) {
for _, row := range []struct {
name string
produce func(*testing.T) error
kind answer.Kind
unsentCode string
unsentRetry bool
unsentExit int
possibleCode string
possibleRetry bool
possibleExit int
}{
{"read-timeout", readTimeout, answer.Timeout, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
{"dns", failedDNS, answer.DNS, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
{"reset-after-request", resetConnection, answer.Connection, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
{"canceled", canceledCall, answer.Canceled, "canceled", false, 1, "outcome_unknown", true, 3},
{"eof", func(*testing.T) error { _, err := io.ReadFull(bytes.NewReader(nil), make([]byte, 1)); return err }, answer.Connection, "remote_unavailable", true, 75, "outcome_unknown", true, 3},
} {
t.Run(row.name, func(t *testing.T) {
err := row.produce(t)
if err == nil {
t.Fatal("fixture did not produce a failure")
}
kind, ok := answer.ErrorKind(err)
if !ok || kind != row.kind {
t.Fatalf("error kind %q, listed=%t: %T: %v", kind, ok, err, err)
}
for _, want := range []struct {
phase answer.Phase
code string
retry bool
exit int
}{
{answer.Unsent, row.unsentCode, row.unsentRetry, row.unsentExit},
{answer.PossiblyAdmitted, row.possibleCode, row.possibleRetry, row.possibleExit},
} {
got, err := answer.Lookup(want.phase, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != want.code || got.Retryable != want.retry || got.Exit != want.exit || got.Cure == "" {
t.Fatalf("%s: %+v", want.phase, got)
}
if want.phase == answer.PossiblyAdmitted && got.Retry != answer.Recover {
t.Fatalf("possibly admitted must recover: %+v", got)
}
}
})
}
}
func failedDNS(t *testing.T) error {
t.Helper()
server, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
defer close(done)
buf := make([]byte, 512)
for {
n, addr, err := server.ReadFrom(buf)
if err != nil {
return
}
if n < 12 {
continue
}
buf[2], buf[3] = 0x81, 0x83 // response, recursion available, NXDOMAIN
for i := 6; i < 12; i++ {
buf[i] = 0
}
_, _ = server.WriteTo(buf[:n], addr)
}
}()
defer func() { server.Close(); <-done }()
resolver := &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "udp", server.LocalAddr().String())
}}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = resolver.LookupHost(ctx, "missing.test.")
return err
}
func resetConnection(t *testing.T) error {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
done := make(chan error, 1)
go func() {
conn, err := listener.Accept()
if err != nil {
done <- err
return
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
_, err = io.ReadFull(conn, make([]byte, 1))
if err == nil {
err = conn.(*net.TCPConn).SetLinger(0)
}
done <- err
}()
conn, err := net.DialTimeout("tcp", listener.Addr().String(), 5*time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
if _, err := conn.Write([]byte{1}); err != nil {
t.Fatal(err)
}
_, err = conn.Read(make([]byte, 1))
if serverErr := <-done; serverErr != nil {
t.Fatal(serverErr)
}
return err
}
func canceledCall(t *testing.T) error {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
cancel()
<-ctx.Done()
return ctx.Err()
}
func readTimeout(t *testing.T) error {
t.Helper()
a, b := net.Pipe()
defer a.Close()
defer b.Close()
a.SetReadDeadline(time.Now().Add(-time.Second))
_, err := a.Read(make([]byte, 1))
return err
}
func TestUnlistedFailureFailsTheTableCheck(t *testing.T) {
if kind, listed := answer.ErrorKind(errors.New("new failure without a policy")); listed {
t.Fatalf("unknown error silently became %q", kind)
}
if _, err := answer.Lookup(answer.Unsent, answer.Kind{Name: "future-kind"}); err == nil {
t.Fatal("unlisted kind accepted")
}
if _, err := answer.Lookup(answer.Phase("unknown-phase"), answer.Connection); err == nil {
t.Fatal("unlisted phase accepted")
}
}
func TestTLS13CertificateRejectionAfterWriteIsTerminal(t *testing.T) {
cert := serverCertificate(t, time.Now().Add(-time.Hour), time.Now().Add(time.Hour))
listener, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{
MinVersion: tls.VersionTLS13, MaxVersion: tls.VersionTLS13,
Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert,
})
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
release := make(chan struct{})
stopped := make(chan struct{})
t.Cleanup(func() { close(release); listener.Close(); <-stopped })
go func() {
defer close(stopped)
conn, err := listener.Accept()
if err != nil {
done <- err
return
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
done <- conn.(*tls.Conn).Handshake()
// Keep TCP open until the client consumes the TLS alert. Closing
// immediately can replace the alert with an unrelated TCP reset.
<-release
}()
pool := x509.NewCertPool()
pool.AddCert(cert.Leaf)
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", listener.Addr().String(), &tls.Config{
MinVersion: tls.VersionTLS13, MaxVersion: tls.VersionTLS13, RootCAs: pool,
})
if err != nil {
t.Fatalf("client handshake must finish before the late alert: %v", err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
if n, err := conn.Write([]byte("request")); err != nil || n != 7 {
t.Fatalf("write: %d %v", n, err)
}
_, err = conn.Read(make([]byte, 1))
if err == nil {
t.Fatal("server accepted missing client certificate")
}
if serverErr := <-done; serverErr == nil {
t.Fatal("server handshake accepted missing client certificate")
}
kind, ok := answer.ErrorKind(err)
if !ok {
t.Fatalf("unlisted post-write certificate alert: %T: %v", err, err)
}
got, err := answer.Lookup(answer.PossiblyAdmitted, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != "not_authorized" || got.Retryable || got.Retry != answer.Never || got.Exit != 5 {
t.Fatalf("certificate rejection after write: %+v", got)
}
}
func serverCertificate(t *testing.T, from, until time.Time) tls.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "local test server"},
NotBefore: from, NotAfter: until, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
leaf, err := x509.ParseCertificate(der)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}
}
func TestProducedTLSValidationPolicies(t *testing.T) {
now := time.Now()
for _, row := range []struct {
name string
from, until time.Time
trust bool
serverName string
kind answer.Kind
cure string
}{
{"unknown-authority", now.Add(-time.Hour), now.Add(time.Hour), false, "", answer.Trust, "fix the trusted CA before retrying"},
{"name-mismatch", now.Add(-time.Hour), now.Add(time.Hour), true, "wrong.invalid", answer.Name, "fix the peer address or its certificate names before retrying"},
{"expired", now.Add(-2 * time.Hour), now.Add(-time.Hour), true, "", answer.Certificate, "fix the client certificate, its key and the peer's certificate policy before retrying"},
{"not-yet-valid", now.Add(time.Hour), now.Add(2 * time.Hour), true, "", answer.Certificate, "fix the client certificate, its key and the peer's certificate policy before retrying"},
} {
t.Run(row.name, func(t *testing.T) {
cert := serverCertificate(t, row.from, row.until)
listener, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12})
if err != nil {
t.Fatal(err)
}
defer listener.Close()
done := make(chan struct{})
go func() {
defer close(done)
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(5 * time.Second))
_ = conn.(*tls.Conn).Handshake()
}()
pool := x509.NewCertPool()
if row.trust {
pool.AddCert(cert.Leaf)
}
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", listener.Addr().String(), &tls.Config{RootCAs: pool, ServerName: row.serverName, MinVersion: tls.VersionTLS12})
if conn != nil {
conn.Close()
}
if err == nil {
t.Fatal("invalid server certificate accepted")
}
<-done
kind, listed := answer.ErrorKind(err)
if !listed || kind != row.kind {
t.Fatalf("kind=%q listed=%t: %T: %v", kind, listed, err, err)
}
for _, phase := range []answer.Phase{answer.Unsent, answer.PossiblyAdmitted} {
got, err := answer.Lookup(phase, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != "not_authorized" || got.Retryable || got.Exit != 5 || got.Retry != answer.Never || got.Cure != row.cure {
t.Fatalf("%s: %+v", phase, got)
}
}
})
}
}
func TestRefusedConnectionHasOneUnsentPolicy(t *testing.T) {
err := refusedDial(t)
kind, ok := answer.ErrorKind(err)
if !ok {
t.Fatalf("unlisted dial error: %T: %v", err, err)
}
got, err := answer.Lookup(answer.Unsent, kind)
if err != nil {
t.Fatal(err)
}
if got.Code != "remote_unavailable" || !got.Retryable || got.Exit != 75 || got.Retry != answer.Resend {
t.Fatalf("refused dial: %+v", got)
}
}
func TestMalformedAddressIsConfigurationBeforeDial(t *testing.T) {
conn, err := net.DialTimeout("tcp", "127.0.0.1", 5*time.Second)
if conn != nil {
conn.Close()
}
if err == nil {
t.Fatal("malformed address was accepted")
}
got, check := answer.PolicyOf(answer.Record(answer.Unsent, err), answer.Chunk)
if check != nil || got.Code != "bad_request" || got.Retryable || got.Exit != 78 {
t.Fatalf("policy=%+v check=%v error=%T: %v", got, check, err, err)
}
}
func TestUnlistedServerDomainCodeFailsTheRegistryCheck(t *testing.T) {
_, err := answer.Lookup(answer.PossiblyAdmitted, answer.ForContract(answer.Chunk, answer.Domain("unlisted_server_code", true, "retry this new server error")))
if err == nil {
t.Fatal("an unlisted server code acquired a safe-resend policy")
}
}
@@ -0,0 +1,76 @@
package answer
import (
"errors"
"fmt"
"io"
"net/http"
"google.golang.org/grpc/status"
)
// Present formats a recorded failure for an operator. It preserves the
// original typed status/details and error chain for protocol decisions.
func Present(err error, contract Contract) error {
if err == nil {
return nil
}
var prior *presentation
if errors.As(err, &prior) && prior.contract == contract {
return err
}
observed := EnsureEvidence(PossiblyAdmitted, err)
policy, check := PolicyOf(observed, contract)
if check != nil {
policy, fallback := Lookup(PossiblyAdmitted, ForContract(contract, Guard("unsupported_error_code")))
if fallback != nil {
policy, _ = Lookup(PossiblyAdmitted, Guard("unsupported_error_code"))
}
return &presentation{contract: contract, cause: fmt.Errorf("%w; %v", observed, check), policy: policy}
}
return &presentation{contract: contract, cause: observed, policy: policy}
}
type presentation struct {
contract Contract
cause error
policy Policy
}
func (p *presentation) Error() string {
return fmt.Sprintf("%s: %v; %s", p.policy.Code, p.cause, p.policy.Cure)
}
func (p *presentation) Unwrap() error { return p.cause }
func (p *presentation) GRPCStatus() *status.Status {
server, ok := status.FromError(p.cause)
if !ok {
return nil
}
return server
}
// DoForContract adds presentation after transport evidence exists. It does
// not turn HTTP statuses into errors: callers still own 404/409 state rules.
func DoForContract(client *http.Client, req *http.Request, phase Phase, contract Contract) (*http.Response, error) {
resp, err := DoHTTP(client, req, phase)
if err != nil {
return resp, Present(err, contract)
}
if resp != nil && resp.Body != nil {
resp.Body = &presentedBody{ReadCloser: resp.Body, contract: contract}
}
return resp, nil
}
type presentedBody struct {
io.ReadCloser
contract Contract
}
func (b *presentedBody) Read(p []byte) (int, error) {
n, err := b.ReadCloser.Read(p)
if err != nil && err != io.EOF {
err = Present(err, b.contract)
}
return n, err
}
@@ -0,0 +1,40 @@
package answer_test
import (
"errors"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestPresentationFailsClosedForUnknownContract(t *testing.T) {
err := answer.Present(errors.New("opaque failure"), answer.Contract("unlisted"))
if !strings.Contains(err.Error(), "unsupported_error_code:") || !strings.Contains(err.Error(), "do not start another operation") {
t.Fatalf("missing conservative policy: %v", err)
}
}
func TestPresentationPreservesProtocolErrorChain(t *testing.T) {
rpc := status.Error(codes.FailedPrecondition, "server precondition")
shown := answer.Present(answer.Record(answer.PossiblyAdmitted, rpc), answer.Ops)
if status.Code(shown) != codes.FailedPrecondition || !strings.Contains(shown.Error(), "server precondition") {
t.Fatalf("lost status: %v", shown)
}
plain := errors.New("HTTP response failure")
shown = answer.Present(answer.HTTPStatusFailure(503, plain), answer.Ops)
if !errors.Is(shown, plain) {
t.Fatalf("lost HTTP cause: %v", shown)
}
if _, ok := status.FromError(shown); ok {
t.Fatalf("manufactured gRPC status: %v", shown)
}
}
func TestUnlistedHTTPStatusFailsPolicyCheck(t *testing.T) {
if _, err := answer.PolicyOf(answer.HTTPStatusFailure(599, errors.New("unlisted HTTP status"))); err == nil {
t.Fatal("unlisted HTTP status passed the registry")
}
}
@@ -0,0 +1,13 @@
//go:build !windows
package answer_test
import (
"errors"
"syscall"
"testing"
)
func isRefusedDial(err error) bool { return errors.Is(err, syscall.ECONNREFUSED) }
func refusedTCPAddress(*testing.T) string { return "127.0.0.1:0" }
@@ -0,0 +1,35 @@
package answer_test
import (
"errors"
"net"
"strconv"
"syscall"
"testing"
)
func isRefusedDial(err error) bool { return errors.Is(err, syscall.Errno(10061)) }
// Hold a bound, non-listening socket: its port cannot be reused by a server.
// Windows rejects destination port zero before attempting a TCP connection.
func refusedTCPAddress(t *testing.T) string {
t.Helper()
var data syscall.WSAData
if err := syscall.WSAStartup(0x202, &data); err != nil {
t.Fatal(err)
}
socket, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
if err != nil {
syscall.WSACleanup()
t.Fatal(err)
}
t.Cleanup(func() { syscall.Closesocket(socket); syscall.WSACleanup() })
if err := syscall.Bind(socket, &syscall.SockaddrInet4{Addr: [4]byte{127, 0, 0, 1}}); err != nil {
t.Fatal(err)
}
addr, err := syscall.Getsockname(socket)
if err != nil {
t.Fatal(err)
}
return net.JoinHostPort("127.0.0.1", strconv.Itoa(addr.(*syscall.SockaddrInet4).Port))
}
@@ -0,0 +1,36 @@
package answer
import (
"errors"
"io"
"net/http"
"testing"
)
func TestReviewHTTPStatusOverridesNestedTransport(t *testing.T) {
body := Record(PossiblyAdmitted, io.ErrUnexpectedEOF)
err := HTTPStatusFailure(http.StatusForbidden, body)
kind, ok := ErrorKind(err)
p, check := PolicyOf(err, Chunk)
if !ok || kind != httpStatusKind(http.StatusForbidden) || check != nil || p.Exit != 5 || p.Retryable || !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("HTTP response lost to body: kind=%+v policy=%+v check=%v err=%v", kind, p, check, err)
}
// A failed status poll still cannot settle its previously admitted operation.
p, check = PolicyOf(Rekind(err, Connection), Chunk)
if check != nil || p.Code != "outcome_unknown" || p.Exit != 3 {
t.Fatalf("explicit outer operation evidence lost: %+v %v", p, check)
}
}
func TestReviewVerifyPreservesServerRetryRefusal(t *testing.T) {
for _, retryable := range []bool{false, true} {
p, err := Lookup(PossiblyAdmitted, ForContract(ChunkVerify, Domain("outcome_unknown", retryable, "inspect the original answer")))
want := Recover
if retryable {
want = Resend
}
if err != nil || p.Retry != want || p.Retryable != retryable || p.Exit != 1 || (!retryable && p.Cure != "inspect the original answer") {
t.Errorf("retryable=%v: %+v %v", retryable, p, err)
}
}
}
@@ -0,0 +1,163 @@
package answer
import (
"context"
"crypto/x509"
"errors"
"google.golang.org/grpc"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/status"
"net/http"
"strings"
"testing"
"time"
)
func TestReviewContextAndDefiniteAnswerPrecedence(t *testing.T) {
for _, code := range []codes.Code{codes.Canceled, codes.DeadlineExceeded} {
t.Run(code.String(), func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
e := &rpcEvidence{}
e.dial.Store(&dialObservation{kind: Trust, cause: errors.New("earlier picker trust failure")})
got := e.record(ctx, status.Error(code, "caller ended the WaitForReady call"))
p, check := PolicyOf(got)
if check != nil || p.Code != "canceled" || !errors.Is(got, context.Canceled) {
t.Fatalf("caller lost to picker: %+v %v %v", p, check, got)
}
})
}
e := &rpcEvidence{}
e.writeStarted.Store(true)
info := &connectionTLSInfo{}
info.late.Store(&observedTLSFailure{kind: Certificate})
e.tls.Store(info)
ctx := context.WithValue(context.Background(), rpcEvidenceKey{}, e)
got := (&HandshakeEvidence{}).record(ctx, status.Error(codes.FailedPrecondition, "definite refusal"))
if status.Code(got) != codes.FailedPrecondition {
t.Fatalf("status changed: %v", got)
}
p, err := PolicyOf(EnsureEvidence(PossiblyAdmitted, got))
if err != nil || p.Code != "not_admitted" {
t.Fatalf("late TLS replaced definite answer: %+v %v", p, err)
}
}
type capturedPickerConn struct {
balancer.ClientConn
state balancer.State
}
func (c *capturedPickerConn) UpdateState(s balancer.State) { c.state = s }
type fixedErrorPicker struct{ err error }
func (p fixedErrorPicker) Pick(balancer.PickInfo) (balancer.PickResult, error) {
return balancer.PickResult{}, p.err
}
func TestReviewOldPickerCannotBorrowNewPeerGeneration(t *testing.T) {
pool := &peerPool{generation: 1, peers: map[string]*peerAttempt{}}
cc := &capturedPickerConn{}
wrapped := &evidenceClientConn{ClientConn: cc, pool: pool}
wrapped.UpdateState(balancer.State{Picker: fixedErrorPicker{status.Error(codes.Unavailable, "old peer network failure")}})
old := cc.state.Picker
pool.generation = 2
pool.peers["new"] = &peerAttempt{peer: "new", attempt: 3, completed: 4, state: connectivity.TransientFailure, kind: Trust, cause: errors.New("new peer trust"), singleAddress: true}
e := &rpcEvidence{started: 2}
ctx := context.WithValue(context.Background(), rpcEvidenceKey{}, e)
_, _ = old.Pick(balancer.PickInfo{Ctx: ctx})
if got := e.dial.Load(); got == nil || got.kind != Connection {
t.Fatalf("old picker borrowed new proof: %+v", got)
}
}
func TestReviewContractProjectionAndReadOnlyRecovery(t *testing.T) {
for _, status := range []int{http.StatusConflict, http.StatusPreconditionFailed, http.StatusPreconditionRequired} {
p, err := PolicyOf(HTTPStatusFailure(status, nil), Cluster)
if err != nil || p.Exit != 2 {
t.Errorf("HTTP %d cluster precondition: %+v %v", status, p, err)
}
}
p, err := Lookup(PossiblyAdmitted, ForContract(Chunk, Domain("forbidden", false, "access refused")))
if err != nil || p.Exit != 5 || p.Code != "forbidden" {
t.Errorf("typed authorization: %+v %v", p, err)
}
p, err = Lookup(PossiblyAdmitted, ForContract(ChunkVerify, Connection))
if err != nil || p.Exit != 1 || p.Retry != Resend || !strings.Contains(p.Cure, "verification") || strings.Contains(p.Cure, "replay key") {
t.Errorf("read-only recovery: %+v %v", p, err)
}
}
type certFailTransport struct{}
func (certFailTransport) RoundTrip(*http.Request) (*http.Response, error) {
return nil, x509.UnknownAuthorityError{Cert: &x509.Certificate{}}
}
func TestReviewAdmittedPollTLSFailureKeepsOperationRecoverable(t *testing.T) {
for _, phase := range []Phase{Unsent, PossiblyAdmitted} {
req, _ := http.NewRequest(http.MethodGet, "https://poll.example/operation", nil)
_, err := DoHTTP(&http.Client{Transport: certFailTransport{}}, req, phase)
p, check := PolicyOf(err, Chunk)
want := "not_authorized"
if phase == PossiblyAdmitted {
want = "outcome_unknown"
}
if check != nil || p.Code != want {
t.Errorf("phase %s: %+v %v", phase, p, check)
}
}
}
func TestReviewPickerCannotReplaceCustomCallerDeadline(t *testing.T) {
custom := errors.New("caller deadline cause")
ctx, cancel := context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), custom)
defer cancel()
e := &rpcEvidence{}
e.dial.Store(&dialObservation{kind: Trust, cause: errors.New("earlier trust rejection")})
err := e.record(ctx, status.Error(codes.DeadlineExceeded, "caller ended pending RPC"))
p, check := PolicyOf(err)
if check != nil || p.Code != "deadline_exceeded" || !errors.Is(err, custom) {
t.Fatalf("caller deadline lost: %+v %v %v", p, check, err)
}
}
// The selected connection can report an alert after the RPC's caller has
// already won. Exercise both interceptors in their production order.
func TestReviewSelectedTLSCannotReplaceCallerCompletion(t *testing.T) {
for _, deadline := range []bool{false, true} {
t.Run(map[bool]string{false: "cancel", true: "custom-deadline"}[deadline], func(t *testing.T) {
custom := errors.New("caller chose this deadline")
ctx, cancel := context.WithCancel(context.Background())
if deadline {
cancel()
ctx, cancel = context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), custom)
} else {
cancel()
}
defer cancel()
e := &rpcEvidence{}
e.writeStarted.Store(true)
info := &connectionTLSInfo{}
info.late.Store(&observedTLSFailure{kind: Certificate})
e.tls.Store(info)
ctx = context.WithValue(ctx, rpcEvidenceKey{}, e)
code := codes.Canceled
wantCause := error(context.Canceled)
if deadline {
code = codes.DeadlineExceeded
wantCause = custom
}
inner := (&HandshakeEvidence{}).UnaryInterceptor(ctx, "/control", nil, nil, nil,
func(context.Context, string, any, any, *grpc.ClientConn, ...grpc.CallOption) error {
return status.Error(code, "caller completed selected RPC")
})
got := e.record(ctx, inner)
p, check := PolicyOf(got)
if check != nil || p.Code != "outcome_unknown" || p.Retry != Recover || !errors.Is(got, wantCause) {
t.Fatalf("selected TLS replaced caller: policy=%+v check=%v error=%v", p, check, got)
}
})
}
}
+143
View File
@@ -0,0 +1,143 @@
package answer
import (
"context"
"fmt"
"net"
"sync/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type observedTLSFailure struct{ kind Kind }
// Source stamps belong to the actual TLS attempt, never to the later
// asynchronous SubConn notification. Missing stamps cannot prove freshness.
type attemptFailure struct {
started, completed uint64
cause error
}
func (f *attemptFailure) Error() string { return f.cause.Error() }
func (f *attemptFailure) Unwrap() error { return f.cause }
// HandshakeEvidence reads the established connection's TLS cause. Initial
// attempts are observed at the SubConn/Picker boundary, including TCP failures
// which never enter a TLS callback. No channel-wide last TLS cause is used.
type HandshakeEvidence struct{}
// ObserveCredentials preserves typed TLS failures before gRPC converts a
// handshake/preface error into an opaque Unavailable status message.
func ObserveCredentials(inner credentials.TransportCredentials) (credentials.TransportCredentials, *HandshakeEvidence) {
return &observedCredentials{TransportCredentials: inner}, &HandshakeEvidence{}
}
type observedCredentials struct {
credentials.TransportCredentials
}
func (c *observedCredentials) Clone() credentials.TransportCredentials {
return &observedCredentials{TransportCredentials: c.TransportCredentials.Clone()}
}
func (c *observedCredentials) ClientHandshake(ctx context.Context, authority string, raw net.Conn) (net.Conn, credentials.AuthInfo, error) {
started := attemptSequence.Add(1)
conn, info, err := c.TransportCredentials.ClientHandshake(ctx, authority, raw)
if err != nil {
kind, _ := ErrorKind(err)
if certificateKind(kind) || kind == Credential || kind == Configuration {
return conn, info, &attemptFailure{started: started, completed: attemptSequence.Add(1), cause: err}
}
return conn, info, err
}
local := &connectionTLSInfo{AuthInfo: info, attempt: started}
return &observedTLSConn{Conn: conn, info: local}, local, nil
}
type connectionTLSInfo struct {
credentials.AuthInfo
attempt uint64
late atomic.Pointer[observedTLSFailure]
}
// Keep the underlying credentials' authority check: observing the connection
// must neither reject a valid per-call override nor authorize a mismatch.
func (info *connectionTLSInfo) ValidateAuthority(authority string) error {
if validator, ok := info.AuthInfo.(credentials.AuthorityValidator); ok {
return validator.ValidateAuthority(authority)
}
return fmt.Errorf("credentials type %q cannot validate authority %q", info.AuthType(), authority)
}
func (info *connectionTLSInfo) GetCommonAuthInfo() credentials.CommonAuthInfo {
if inner, ok := info.AuthInfo.(interface {
GetCommonAuthInfo() credentials.CommonAuthInfo
}); ok {
return inner.GetCommonAuthInfo()
}
return credentials.CommonAuthInfo{}
}
type observedTLSConn struct {
net.Conn
info *connectionTLSInfo
}
func (conn *observedTLSConn) Read(p []byte) (int, error) {
n, err := conn.Conn.Read(p)
if err != nil {
kind, _ := ErrorKind(err)
fact := &observedTLSFailure{kind: kind}
conn.info.late.Store(fact)
if certificateKind(kind) {
err = &attemptFailure{started: conn.info.attempt, completed: attemptSequence.Add(1), cause: err}
}
}
return n, err
}
// UnaryInterceptor only attaches a typed TLS fact. Classification still
// happens solely in Lookup; established calls use their own connection.
func (e *HandshakeEvidence) UnaryInterceptor(ctx context.Context, method string, req, reply any, conn *grpc.ClientConn, invoke grpc.UnaryInvoker, opts ...grpc.CallOption) error {
err := invoke(ctx, method, req, reply, conn, opts...)
return e.record(ctx, err)
}
func (e *HandshakeEvidence) StreamInterceptor(ctx context.Context, desc *grpc.StreamDesc, conn *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
stream, err := streamer(ctx, desc, conn, method, opts...)
if err != nil {
return nil, e.record(ctx, err)
}
return &observedStream{ClientStream: stream, record: func(err error) error { return e.record(ctx, err) }}, nil
}
func (e *HandshakeEvidence) record(ctx context.Context, err error) error {
if err == nil {
return nil
}
if DefiniteAnswer(err) {
return err
}
rpc, ok := ctx.Value(rpcEvidenceKey{}).(*rpcEvidence)
if !ok {
return err
}
phase := Unsent
var fact *observedTLSFailure
if rpc.writeStarted.Load() {
phase = PossiblyAdmitted
fact = nil
if info := rpc.tls.Load(); info != nil {
fact = info.late.Load()
}
}
// A completed caller owns the RPC result before a later reader alert.
// Definite server answers were preserved above.
if context.Cause(ctx) != nil {
return RecordContext(ctx, phase, err)
}
if fact != nil && (fact.kind == Certificate || fact.kind == Trust || fact.kind == Name || fact.kind == Credential) {
return &failure{phase: phase, kind: fact.kind, cause: err}
}
return err
}
@@ -0,0 +1,168 @@
package answer_test
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io/fs"
"path/filepath"
"strconv"
"strings"
"testing"
)
// Pin the owned client construction/evidence boundary. Unknown shortcuts
// fail closed; generated code and typed non-network Once callbacks do not
// become transport adapters merely because their method is named Do.
func TestOwnedClientTransportsKeepAdmissionEvidence(t *testing.T) {
type source struct {
path string
file *ast.File
imports map[string]string
}
root := filepath.Join("..", "..", "..")
fset := token.NewFileSet()
var sources []source
httpOwners := map[string]bool{}
for _, dir := range []string{"core", "cmd"} {
err := filepath.WalkDir(filepath.Join(root, dir), func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") || strings.HasSuffix(path, ".pb.go") {
return nil
}
file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
if err != nil {
return err
}
rel, _ := filepath.Rel(root, path)
s := source{filepath.ToSlash(rel), file, map[string]string{}}
for _, spec := range file.Imports {
pkg, _ := strconv.Unquote(spec.Path.Value)
alias := filepath.Base(pkg)
if spec.Name != nil {
alias = spec.Name.Name
}
s.imports[alias] = pkg
}
ast.Inspect(file, func(node ast.Node) bool {
if selector, ok := node.(*ast.SelectorExpr); ok {
if owner, ok := selector.X.(*ast.Ident); ok && s.imports[owner.Name] == "net/http" && (selector.Sel.Name == "Client" || selector.Sel.Name == "DefaultClient") {
httpOwners[filepath.Dir(s.path)] = true
}
}
return true
})
sources = append(sources, s)
return nil
})
if err != nil {
t.Fatal(err)
}
}
text := func(node ast.Node) string { var b bytes.Buffer; _ = printer.Fprint(&b, fset, node); return b.String() }
nonNetworkDo := map[string]int{
"core/lifecycle/node_inventory.go|once.Do|s.mu.Unlock": 1,
"core/storage/chunk_layer.go|l.touchedSeed.Do|l.seedTouched": 2,
}
grpcConstructors, httpDo, statsHandlers, nativeRoundTrips := 0, 0, 0, 0
for _, s := range sources {
for _, decl := range s.file.Decls {
function, ok := decl.(*ast.FuncDecl)
if !ok || function.Body == nil {
continue
}
ast.Inspect(function.Body, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
selector, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
pkg := ""
if owner, ok := selector.X.(*ast.Ident); ok {
pkg = s.imports[owner.Name]
}
fail := func(why string) { t.Errorf("%s: %s: %s", fset.Position(call.Pos()), why, text(call.Fun)) }
if pkg == "google.golang.org/grpc" {
switch selector.Sel.Name {
case "NewClient", "Dial", "DialContext":
if s.path != "core/rpc/link/link.go" || (function.Name.Name != "Dial" && function.Name.Name != "DialWith") {
fail("unregistered RPC constructor")
} else {
grpcConstructors++
}
case "WithStatsHandler":
if s.path != "core/rpc/answer/grpc.go" || function.Name.Name != "ClientOptions" {
fail("new stats context needs an evidence-preservation control")
} else {
statsHandlers++
}
}
}
if selector.Sel.Name == "Do" {
if len(call.Args) == 1 {
if _, callback := call.Args[0].(*ast.FuncLit); callback {
return true
}
}
key := s.path + "|" + text(call.Fun) + "|"
if len(call.Args) == 1 {
key += text(call.Args[0])
}
if nonNetworkDo[key] > 0 {
nonNetworkDo[key]--
return true
}
if s.path != "core/rpc/answer/http.go" || function.Name.Name != "DoHTTP" {
fail("HTTP calls must retain phase through the shared adapter")
} else {
httpDo++
}
}
if pkg == "net/http" {
switch selector.Sel.Name {
case "Get", "Post", "PostForm", "Head":
fail("default-client shortcut bypasses evidence")
}
}
if httpOwners[filepath.Dir(s.path)] {
switch selector.Sel.Name {
case "RoundTrip":
if s.path == "core/rpc/answer/http_transport.go" && function.Name.Name == "RoundTrip" && text(selector.X) == "tr.transport" {
nativeRoundTrips++
} else {
fail("client shortcut bypasses evidence")
}
case "Post", "PostForm":
fail("client shortcut bypasses evidence")
case "Get", "Head":
if pkg == "google.golang.org/grpc/balancer" && s.path == "core/rpc/answer/peers.go" {
return true
} // registry lookup, not HTTP
if len(call.Args) == 1 {
header, ok := selector.X.(*ast.SelectorExpr)
if !ok || header.Sel.Name != "Header" {
fail("unclassified single-argument getter in an HTTP client package")
}
}
}
}
return true
})
}
}
for site, left := range nonNetworkDo {
if left != 0 {
t.Errorf("stale non-network inventory: %s (%d)", site, left)
}
}
if grpcConstructors != 2 || httpDo != 1 || statsHandlers != 1 || nativeRoundTrips != 1 {
t.Fatalf("boundary inventory: RPC=%d HTTP=%d stats=%d native=%d", grpcConstructors, httpDo, statsHandlers, nativeRoundTrips)
}
}
@@ -0,0 +1,283 @@
package link_test
import (
"context"
"crypto/tls"
"crypto/x509"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
_ "google.golang.org/grpc/balancer/roundrobin"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
"google.golang.org/grpc/status"
)
type heldHealthAnswer struct {
grpc_health_v1.UnimplementedHealthServer
entered chan struct{}
release chan struct{}
}
func (server *heldHealthAnswer) Check(ctx context.Context, _ *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
close(server.entered)
select {
case <-server.release:
return nil, status.Error(codes.Unavailable, "received request, lost answer")
case <-ctx.Done():
return nil, ctx.Err()
}
}
// The signal follows the observed credentials' return, so the failing
// peer's typed fact is installed before the held RPC is released.
type signaledHandshake struct {
credentials.TransportCredentials
failed chan struct{}
once *sync.Once
}
func (c *signaledHandshake) ClientHandshake(ctx context.Context, authority string, raw net.Conn) (net.Conn, credentials.AuthInfo, error) {
conn, info, err := c.TransportCredentials.ClientHandshake(ctx, authority, raw)
if err != nil {
c.once.Do(func() { close(c.failed) })
}
return conn, info, err
}
func (c *signaledHandshake) Clone() credentials.TransportCredentials {
return &signaledHandshake{c.TransportCredentials.Clone(), c.failed, c.once}
}
func TestSentRPCDoesNotBorrowAnotherPeersCertificateFailure(t *testing.T) {
trusted := authtest.NewCA(t, "trusted-peer")
untrusted := authtest.NewCA(t, "untrusted-peer")
service := &heldHealthAnswer{entered: make(chan struct{}), release: make(chan struct{})}
serve := func(ca *authtest.CA) string {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
cert := ca.Issue(t, "localhost", time.Now().Add(time.Hour))
server := link.NewServer(link.ServerConfig{}, grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{cert.TLS}, MinVersion: tls.VersionTLS12})))
grpc_health_v1.RegisterHealthServer(server, service)
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
return listener.Addr().String()
}
good, bad := serve(trusted), serve(untrusted)
pool := x509.NewCertPool()
pool.AddCert(trusted.Cert)
observed, evidence := answer.ObserveCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool, ServerName: "localhost", MinVersion: tls.VersionTLS12}))
failed := make(chan struct{})
creds := &signaledHandshake{observed, failed, &sync.Once{}}
addresses := manual.NewBuilderWithScheme("answer-peer")
addresses.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: good}}})
conn, err := link.DialWith("answer-peer:///service", grpc.WithResolvers(addresses), grpc.WithTransportCredentials(creds), grpc.WithChainUnaryInterceptor(evidence.UnaryInterceptor), grpc.WithDefaultServiceConfig(`{"loadBalancingConfig":[{"round_robin":{}}]}`))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
done := make(chan error, 1)
go func() {
_, err := grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
done <- err
}()
select {
case <-service.entered:
case <-ctx.Done():
t.Fatal("RPC never reached the trusted peer", ctx.Err())
}
addresses.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: good}, {Addr: bad}}})
select {
case <-failed:
case <-ctx.Done():
t.Fatal("untrusted peer did not fail its handshake", ctx.Err())
}
close(service.release)
err = <-done
got, check := answer.PolicyOf(err, answer.Chunk)
if check != nil || got.Code != "outcome_unknown" || got.Retry != answer.Recover || got.Exit != 3 {
t.Fatalf("sent RPC borrowed another peer's TLS failure: policy=%+v check=%v error=%v", got, check, err)
}
}
func TestUnsentRPCWithMixedPeerFailuresIsRetryable(t *testing.T) {
trusted := authtest.NewCA(t, "peer-trust")
untrusted := authtest.NewCA(t, "bad-peer")
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
cert := untrusted.Issue(t, "localhost", time.Now().Add(time.Hour))
server := link.NewServer(link.ServerConfig{}, grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{cert.TLS}})))
grpc_health_v1.RegisterHealthServer(server, &heldHealthAnswer{})
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
closed, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
badNetwork := closed.Addr().String()
closed.Close()
pool := x509.NewCertPool()
pool.AddCert(trusted.Cert)
observed, evidence := answer.ObserveCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool, ServerName: "localhost"}))
certFailed := make(chan struct{})
creds := &signaledHandshake{observed, certFailed, &sync.Once{}}
addresses := manual.NewBuilderWithScheme("answer-mixed-peer")
addresses.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: listener.Addr().String()}, {Addr: badNetwork}}})
var networkAttempts atomic.Int32
conn, err := link.DialWith("answer-mixed-peer:///service", grpc.WithResolvers(addresses), grpc.WithTransportCredentials(creds), grpc.WithChainUnaryInterceptor(evidence.UnaryInterceptor), grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
if addr == badNetwork {
networkAttempts.Add(1)
}
return (&net.Dialer{}).DialContext(ctx, "tcp", addr)
}))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
select {
case <-certFailed:
default:
t.Fatal("certificate peer was not attempted")
}
if networkAttempts.Load() == 0 {
t.Fatal("network peer was not attempted")
}
got, check := answer.PolicyOf(err, answer.Chunk)
if check != nil || got.Code != "remote_unavailable" || !got.Retryable || got.Exit != 75 || got.Retry != answer.Resend {
t.Fatalf("mixed attempts became terminal: %+v check=%v error=%v", got, check, err)
}
if !strings.Contains(err.Error(), listener.Addr().String()) || !strings.Contains(err.Error(), badNetwork) {
t.Fatalf("mixed answer lost peer causes: %v", err)
}
}
type boundedPeerHandshake struct {
credentials.TransportCredentials
peer string
}
func (c *boundedPeerHandshake) Clone() credentials.TransportCredentials {
return &boundedPeerHandshake{c.TransportCredentials.Clone(), c.peer}
}
func (c *boundedPeerHandshake) ClientHandshake(ctx context.Context, authority string, raw net.Conn) (net.Conn, credentials.AuthInfo, error) {
if raw.RemoteAddr().String() == c.peer {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()
}
return c.TransportCredentials.ClientHandshake(ctx, authority, raw)
}
func TestRPCPeerCertificateFailureDoesNotHideHandshakeTimeout(t *testing.T) {
trusted := authtest.NewCA(t, "timeout-trust")
wrong := authtest.NewCA(t, "timeout-bad-peer")
bad, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
cert := wrong.Issue(t, "localhost", time.Now().Add(time.Hour))
server := link.NewServer(link.ServerConfig{}, grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{cert.TLS}})))
go func() { _ = server.Serve(bad) }()
t.Cleanup(server.Stop)
silent, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
stopped := make(chan struct{})
var workers sync.WaitGroup
workers.Add(1)
go func() {
defer workers.Done()
for {
conn, err := silent.Accept()
if err != nil {
return
}
workers.Add(1)
go func() { defer workers.Done(); defer conn.Close(); <-stopped }()
}
}()
t.Cleanup(func() { silent.Close(); close(stopped); workers.Wait() })
pool := x509.NewCertPool()
pool.AddCert(trusted.Cert)
raw := &boundedPeerHandshake{credentials.NewTLS(&tls.Config{RootCAs: pool, ServerName: "localhost"}), silent.Addr().String()}
creds, evidence := answer.ObserveCredentials(raw)
addresses := manual.NewBuilderWithScheme("answer-timeout-peer")
addresses.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: bad.Addr().String()}, {Addr: silent.Addr().String()}}})
conn, err := link.DialWith("answer-timeout-peer:///service", grpc.WithResolvers(addresses), grpc.WithTransportCredentials(creds), grpc.WithChainUnaryInterceptor(evidence.UnaryInterceptor))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
got, check := answer.PolicyOf(err, answer.Chunk)
if check != nil || got.Code != "remote_unavailable" || !got.Retryable || got.Exit != 75 {
t.Fatalf("mixed timeout: %+v check=%v error=%v", got, check, err)
}
if !strings.Contains(err.Error(), bad.Addr().String()) || !strings.Contains(err.Error(), silent.Addr().String()) {
t.Fatalf("missing peer causes: %v", err)
}
}
func TestRPCSucceedsOnGoodPeerAfterBadCertificate(t *testing.T) {
trusted := authtest.NewCA(t, "good-peer")
wrong := authtest.NewCA(t, "bad-peer")
serve := func(ca *authtest.CA) string {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
cert := ca.Issue(t, "localhost", time.Now().Add(time.Hour))
server := link.NewServer(link.ServerConfig{}, grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{cert.TLS}})))
grpc_health_v1.RegisterHealthServer(server, health.NewServer())
go func() { _ = server.Serve(l) }()
t.Cleanup(server.Stop)
return l.Addr().String()
}
bad, good := serve(wrong), serve(trusted)
pool := x509.NewCertPool()
pool.AddCert(trusted.Cert)
observed, evidence := answer.ObserveCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool, ServerName: "localhost"}))
failed := make(chan struct{})
creds := &signaledHandshake{observed, failed, &sync.Once{}}
addresses := manual.NewBuilderWithScheme("answer-good-peer")
addresses.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: bad}, {Addr: good}}})
conn, err := link.DialWith("answer-good-peer:///service", grpc.WithResolvers(addresses), grpc.WithTransportCredentials(creds), grpc.WithChainUnaryInterceptor(evidence.UnaryInterceptor))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
if err != nil || resp.GetStatus() != grpc_health_v1.HealthCheckResponse_SERVING {
t.Fatalf("good peer failed: %v %v", resp, err)
}
select {
case <-failed:
default:
t.Fatal("bad peer was not attempted first")
}
}
@@ -0,0 +1,429 @@
package link_test
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
)
func TestCallerDeadlineBeforeSendKeepsItsCause(t *testing.T) {
conn, err := link.Dial("127.0.0.1:1")
if err != nil {
t.Fatal(err)
}
defer conn.Close()
for _, custom := range []bool{false, true} {
cause := error(context.DeadlineExceeded)
if custom {
cause = errors.New("caller-owned deadline")
}
ctx, cancel := context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), cause)
_, err := grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
cancel()
got, check := answer.PolicyOf(err, answer.Chunk)
if check != nil || got.Code != "deadline_exceeded" || got.Exit != 1 || !errors.Is(err, cause) {
t.Fatalf("custom=%t policy=%+v check=%v error=%v", custom, got, check, err)
}
}
}
func TestObservedTLSForwardsPerCallAuthorityValidation(t *testing.T) {
ca := authtest.NewCA(t, "authority")
leaf := ca.Issue(t, "master", time.Now().Add(time.Hour))
server := grpc.NewServer(grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{leaf.TLS}})))
var received atomic.Int64
grpc_health_v1.RegisterHealthServer(server, &authorityHealth{received: &received})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
dir := t.TempDir()
cert, key := ca.Issue(t, "operator", time.Now().Add(time.Hour)).WriteFiles(t, dir, "operator")
option, err := link.ClientCredentials(link.TLSFiles{Cert: cert, Key: key, CA: ca.WriteCA(t, dir)}, "")
if err != nil {
t.Fatal(err)
}
conn, err := link.DialMaster(listener.Addr().String(), option)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
client := grpc_health_v1.NewHealthClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := client.Check(ctx, &grpc_health_v1.HealthCheckRequest{}); err != nil {
t.Fatal(err)
}
for _, row := range []struct {
authority string
wantOK bool
}{
{"localhost", true}, {"mismatch.invalid", false}, {"127.0.0.1", true},
} {
t.Run(row.authority, func(t *testing.T) {
before := received.Load()
_, err := client.Check(ctx, &grpc_health_v1.HealthCheckRequest{}, grpc.CallAuthority(row.authority))
if (err == nil) != row.wantOK {
t.Fatalf("authority=%s err=%v wantOK=%t", row.authority, err, row.wantOK)
}
want := before
if row.wantOK {
want++
}
if got := received.Load(); got != want {
t.Fatalf("server receipts=%d want=%d", got, want)
}
})
}
}
type authorityHealth struct {
grpc_health_v1.UnimplementedHealthServer
received *atomic.Int64
}
func (s *authorityHealth) Check(context.Context, *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
s.received.Add(1)
return &grpc_health_v1.HealthCheckResponse{}, nil
}
func TestLocalCredentialsFailBeforeDialWithTypedPolicy(t *testing.T) {
ca := authtest.NewCA(t, "local")
dir := t.TempDir()
cert, key := ca.Issue(t, "operator", time.Now().Add(time.Hour)).WriteFiles(t, dir, "valid")
expired := ca.Issue(t, "expired", time.Now().Add(-time.Minute))
expiredCert, expiredKey := expired.WriteFiles(t, dir, "expired")
caPath := ca.WriteCA(t, dir)
badCA := filepath.Join(dir, "bad-ca.pem")
if err := os.WriteFile(badCA, []byte("not PEM"), 0o600); err != nil {
t.Fatal(err)
}
expiredCA := filepath.Join(dir, "expired-ca.pem")
if err := os.WriteFile(expiredCA, expired.CertPEM, 0o600); err != nil {
t.Fatal(err)
}
for _, row := range []struct {
name string
files link.TLSFiles
}{
{"missing", link.TLSFiles{Cert: filepath.Join(dir, "missing"), Key: key, CA: caPath}},
{"parse", link.TLSFiles{Cert: cert, Key: key, CA: badCA}},
{"own-expiry", link.TLSFiles{Cert: expiredCert, Key: expiredKey, CA: caPath}},
{"ca-expiry", link.TLSFiles{Cert: cert, Key: key, CA: expiredCA}},
} {
t.Run(row.name, func(t *testing.T) {
option, err := link.ClientCredentials(row.files, "localhost")
if err == nil || option != nil {
t.Fatalf("invalid local credentials accepted: %v", err)
}
got, check := answer.PolicyOf(err)
if check != nil || got.Code != "bad_request" || got.Retryable || got.Retry != answer.Never || got.Exit != 78 {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
}
}
func TestLinkPreservesUnsentFailureEvidence(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
listener.Close()
conn, err := link.Dial(addr)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
if err == nil {
t.Fatal("closed listener answered")
}
got, check := answer.PolicyOf(err)
if check != nil || got.Code != "remote_unavailable" || got.Exit != 75 || got.Retry != answer.Resend {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
stream, err := grpc_health_v1.NewHealthClient(conn).Watch(ctx, &grpc_health_v1.HealthCheckRequest{})
if err == nil {
_, err = stream.Recv()
}
if err == nil {
t.Fatal("closed listener answered stream")
}
got, check = answer.PolicyOf(err)
if check != nil || got.Code != "remote_unavailable" || got.Retry != answer.Resend {
t.Fatalf("stream policy=%+v check=%v error=%v", got, check, err)
}
}
type lostHealthAnswer struct {
grpc_health_v1.UnimplementedHealthServer
calls atomic.Int64
}
type typedHealthAnswer struct {
grpc_health_v1.UnimplementedHealthServer
code codes.Code
}
func (server *typedHealthAnswer) Check(context.Context, *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
return nil, status.Error(server.code, "typed server answer")
}
func TestGRPCServerAnswerPolicyRows(t *testing.T) {
for _, row := range []struct {
status codes.Code
code string
retry bool
rule answer.RetryRule
exit int
}{
{codes.InvalidArgument, "bad_request", false, answer.Never, 2},
{codes.FailedPrecondition, "not_admitted", false, answer.Never, 1},
{codes.NotFound, "not_found", false, answer.Never, 1},
{codes.AlreadyExists, "target_exists", false, answer.Never, 1},
{codes.PermissionDenied, "not_authorized", false, answer.Never, 5},
{codes.Unauthenticated, "not_authorized", false, answer.Never, 5},
{codes.Unimplemented, "unsupported", false, answer.Never, 1},
{codes.DataLoss, "readout_unproven", false, answer.Never, 4},
{codes.Internal, "outcome_unknown", true, answer.Recover, 3},
{codes.Unknown, "outcome_unknown", true, answer.Recover, 3},
{codes.Aborted, "outcome_unknown", true, answer.Recover, 3},
{codes.OutOfRange, "outcome_unknown", true, answer.Recover, 3},
{codes.ResourceExhausted, "outcome_unknown", true, answer.Recover, 3},
{codes.Unavailable, "outcome_unknown", true, answer.Recover, 3},
{codes.DeadlineExceeded, "outcome_unknown", true, answer.Recover, 3},
{codes.Canceled, "outcome_unknown", true, answer.Recover, 3},
} {
t.Run(row.status.String(), func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := link.NewServer(link.ServerConfig{})
grpc_health_v1.RegisterHealthServer(server, &typedHealthAnswer{code: row.status})
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
conn, err := link.Dial(listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
got, check := answer.PolicyOf(err)
if check != nil || got.Code != row.code || got.Retryable != row.retry || got.Retry != row.rule || got.Exit != row.exit {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
})
}
}
func (server *lostHealthAnswer) Check(context.Context, *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
server.calls.Add(1)
return nil, status.Error(codes.Unavailable, "answer unavailable after applying request")
}
func TestLinkNeverTurnsASentRequestIntoSafeResend(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
service := &lostHealthAnswer{}
server := link.NewServer(link.ServerConfig{})
grpc_health_v1.RegisterHealthServer(server, service)
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
conn, err := link.Dial(listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
got, check := answer.PolicyOf(err)
if service.calls.Load() != 1 || check != nil || got.Code != "outcome_unknown" || got.Retry != answer.Recover || got.Exit != 3 {
t.Fatalf("calls=%d policy=%+v check=%v error=%v", service.calls.Load(), got, check, err)
}
if got := status.Convert(err).Message(); got != "answer unavailable after applying request" {
t.Fatalf("transport annotation changed the server's status message: %q", got)
}
}
func TestLinkKeepsCertificateFailureInsteadOfOpaqueUnavailable(t *testing.T) {
ca := authtest.NewCA(t, "trusted")
wrong := authtest.NewCA(t, "untrusted")
dir := t.TempDir()
serverCert, serverKey := ca.Issue(t, "blockmaster", time.Now().Add(time.Hour)).WriteFiles(t, dir, "server")
clientCert, clientKey := ca.Issue(t, "operator", time.Now().Add(time.Hour)).WriteFiles(t, dir, "client")
serverOption, err := link.ServerCredentials(link.TLSFiles{Cert: serverCert, Key: serverKey, CA: ca.WriteCA(t, dir)})
if err != nil {
t.Fatal(err)
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
// This control needs a definite certificate alert before any HTTP/2
// write. TLS1.3's post-write alert has its own dedicated protocol control.
pair, err := tls.LoadX509KeyPair(serverCert, serverKey)
if err != nil {
t.Fatal(err)
}
clientCAs := x509.NewCertPool()
clientCAs.AddCert(ca.Cert)
server := link.NewServer(link.ServerConfig{}, serverOption, grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{pair}, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientCAs, MaxVersion: tls.VersionTLS12})))
grpc_health_v1.RegisterHealthServer(server, health.NewServer())
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
option, err := link.ClientCredentials(link.TLSFiles{Cert: clientCert, Key: clientKey, CA: wrong.WriteCA(t, t.TempDir())}, "localhost")
if err != nil {
t.Fatal(err)
}
conn, err := link.DialMaster(listener.Addr().String(), option)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
if err == nil {
t.Fatal("untrusted server accepted")
}
got, check := answer.PolicyOf(err)
if check != nil || got.Code != "not_authorized" || got.Retryable || got.Retry != answer.Never || got.Cure != "fix the trusted CA before retrying" {
t.Fatalf("policy=%+v check=%v error=%v", got, check, err)
}
closed, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
closedAddr := closed.Addr().String()
closed.Close()
// Dial options are reusable. A certificate failure on the first channel
// is not evidence of a certificate failure on this refused TCP dial.
refused, err := link.DialMaster(closedAddr, option)
if err != nil {
t.Fatal(err)
}
defer refused.Close()
refusedCtx, refusedCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer refusedCancel()
_, err = grpc_health_v1.NewHealthClient(refused).Check(refusedCtx, &grpc_health_v1.HealthCheckRequest{})
got, check = answer.PolicyOf(err)
if check != nil || got.Code != "remote_unavailable" || !got.Retryable || got.Exit != 75 {
t.Fatalf("stale credential evidence crossed channels: policy=%+v check=%v error=%v", got, check, err)
}
badCert, badKey := wrong.Issue(t, "untrusted-client", time.Now().Add(time.Hour)).WriteFiles(t, dir, "bad-client")
option, err = link.ClientCredentials(link.TLSFiles{Cert: badCert, Key: badKey, CA: ca.WriteCA(t, t.TempDir())}, "localhost")
if err != nil {
t.Fatal(err)
}
badConn, err := link.DialMaster(listener.Addr().String(), option)
if err != nil {
t.Fatal(err)
}
defer badConn.Close()
badCtx, badCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer badCancel()
_, err = grpc_health_v1.NewHealthClient(badConn).Check(badCtx, &grpc_health_v1.HealthCheckRequest{})
if err == nil {
t.Fatal("server accepted untrusted client certificate")
}
got, check = answer.PolicyOf(err)
if check != nil || got.Code != "not_authorized" || got.Retryable || got.Retry != answer.Never || got.Cure != "fix the client certificate, its key and the peer's certificate policy before retrying" {
t.Fatalf("untrusted client policy=%+v check=%v error=%v", got, check, err)
}
server.Stop()
// The channel still remembers its earlier TLS error, but this call
// encounters a stopped TCP listener. No fresh certificate rejection
// belongs to this call; a cached peer diagnostic cannot supply one.
stoppedCtx, stoppedCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer stoppedCancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(stoppedCtx, &grpc_health_v1.HealthCheckRequest{})
got, check = answer.PolicyOf(err)
if check != nil || got.Code != "remote_unavailable" || !got.Retryable {
t.Fatalf("stale TLS evidence crossed attempts: policy=%+v check=%v error=%v", got, check, err)
}
}
// The approved no-probe fallback must not turn a restart/drop into a
// terminal TLS diagnosis. Neither peer accepts an RPC request stream.
func TestPlaintextPrefaceFailureKeepsUnsentRetryAndTLSHint(t *testing.T) {
for _, secure := range []bool{false, true} {
t.Run(fmt.Sprint(secure), func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
if secure {
ca := authtest.NewCA(t, "plaintext-test")
dir := t.TempDir()
cert, key := ca.Issue(t, "master", time.Now().Add(time.Hour)).WriteFiles(t, dir, "server")
option, err := link.ServerCredentials(link.TLSFiles{Cert: cert, Key: key, CA: ca.WriteCA(t, dir)})
if err != nil {
t.Fatal(err)
}
server := link.NewServer(link.ServerConfig{}, option)
grpc_health_v1.RegisterHealthServer(server, health.NewServer())
go server.Serve(listener)
t.Cleanup(server.Stop)
} else {
done := make(chan struct{})
go func() {
defer close(done)
for {
conn, err := listener.Accept()
if err != nil {
return
}
conn.SetDeadline(time.Now().Add(5 * time.Second))
io.ReadFull(conn, make([]byte, 24)) // HTTP/2 connection preface, not an RPC
conn.Close()
}
}()
t.Cleanup(func() { listener.Close(); <-done })
}
conn, err := link.Dial(listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{})
policy, check := answer.PolicyOf(err, answer.Workspace)
if err == nil || check != nil || policy.Code != "remote_unavailable" || policy.Exit != 75 || !policy.Retryable || policy.Retry != answer.Resend || !strings.Contains(policy.Cure, "plaintext") || !strings.Contains(policy.Cure, "TLS") {
t.Fatalf("TLS=%t policy=%+v check=%v error=%v", secure, policy, check, err)
}
})
}
}
@@ -0,0 +1,191 @@
package link_test
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
func TestMasterLinkCARotationRejectsAllInvalidRootsLocally(t *testing.T) {
now := time.Now()
dir := t.TempDir()
good := authtest.NewCA(t, "own-certificate")
cert, key := good.Issue(t, "operator", now.Add(time.Hour)).WriteFiles(t, dir, "own")
expired, _, _ := datedRotationRoot(t, dir, now.Add(-2*time.Hour), now.Add(-time.Hour))
future, _, _ := datedRotationRoot(t, dir, now.Add(time.Hour), now.Add(2*time.Hour))
path := filepath.Join(dir, "all-invalid.pem")
if err := os.WriteFile(path, append(expired, future...), 0o600); err != nil {
t.Fatal(err)
}
files := link.TLSFiles{Cert: cert, Key: key, CA: path}
for _, row := range []struct {
name string
build func() error
}{
{"client", func() error { _, err := link.ClientCredentials(files, ""); return err }},
{"server", func() error { _, err := link.ServerCredentials(files); return err }},
} {
t.Run(row.name, func(t *testing.T) {
err := row.build()
if err == nil {
t.Fatal("all-invalid bundle accepted locally")
}
policy, check := answer.PolicyOf(err)
if check != nil || policy.Exit != 78 || policy.Retryable || policy.Retry != answer.Never {
t.Fatalf("all-invalid bundle policy=%+v check=%v err=%v", policy, check, err)
}
})
}
}
// A CA bundle is a set of alternatives. An unused old/future root must not
// prevent startup or a valid mTLS call; selecting that root must still fail.
func TestMasterLinkCARotationUsesTheVerifiedChain(t *testing.T) {
now := time.Now()
for _, row := range []struct {
name string
from, until time.Time
}{
{"expired", now.Add(-2 * time.Hour), now.Add(-time.Hour)},
{"future", now.Add(time.Hour), now.Add(2 * time.Hour)},
} {
t.Run(row.name, func(t *testing.T) {
dir := t.TempDir()
good := authtest.NewCA(t, "rotation-good")
badPEM, badClient, badKey := datedRotationRoot(t, dir, row.from, row.until)
caPath := filepath.Join(dir, "rotation-ca.pem")
if err := os.WriteFile(caPath, append(append([]byte{}, good.PEM...), badPEM...), 0o600); err != nil {
t.Fatal(err)
}
sc, sk := good.Issue(t, "master", now.Add(time.Hour)).WriteFiles(t, dir, "master")
cc, ck := good.Issue(t, "operator", now.Add(time.Hour)).WriteFiles(t, dir, "operator")
// A transmitted chain may retain an unused alternative too.
// The peer builds its own chain; only our leaf is locally dated.
for _, path := range []string{sc, cc} {
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, append(raw, badPEM...), 0600); err != nil {
t.Fatal(err)
}
}
serverOpt, serverErr := link.ServerCredentials(link.TLSFiles{Cert: sc, Key: sk, CA: caPath})
clientOpt, clientErr := link.ClientCredentials(link.TLSFiles{Cert: cc, Key: ck, CA: caPath}, "")
if serverErr != nil {
t.Errorf("unused %s root blocks server startup: %v", row.name, serverErr)
}
if clientErr != nil {
t.Errorf("unused %s root blocks client construction: %v", row.name, clientErr)
}
if serverErr != nil || clientErr != nil {
return
}
var calls atomic.Int64
server := link.NewServer(link.ServerConfig{Unary: []grpc.UnaryServerInterceptor{
func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) {
calls.Add(1)
return next(ctx, req)
},
}}, serverOpt)
healthpb.RegisterHealthServer(server, health.NewServer())
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() { defer close(done); _ = server.Serve(listener) }()
t.Cleanup(func() {
server.Stop()
select {
case <-done:
case <-time.After(time.Second):
t.Error("rotation server did not join")
}
})
check := func(option grpc.DialOption) error {
conn, err := link.DialMaster(listener.Addr().String(), option)
if err != nil {
return err
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err = healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{})
return err
}
if err := check(clientOpt); err != nil {
t.Fatalf("valid chain beside unused %s root: %v", row.name, err)
}
if got := calls.Load(); got != 1 {
t.Fatalf("valid request path not witnessed: calls=%d", got)
}
badOpt, err := link.ClientCredentials(link.TLSFiles{Cert: badClient, Key: badKey, CA: caPath}, "")
if err != nil {
t.Fatalf("selected-chain control must reach handshake: %v", err)
}
if err := check(badOpt); err == nil {
t.Fatalf("selected %s root accepted", row.name)
}
if got := calls.Load(); got != 1 {
t.Fatalf("invalid selected chain reached handler: calls=%d", got)
}
})
}
}
func datedRotationRoot(t *testing.T, dir string, from, until time.Time) ([]byte, string, string) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
root := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "rotation-alternative"}, NotBefore: from, NotAfter: until, IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature}
der, err := x509.CreateCertificate(rand.Reader, root, root, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
root, err = x509.ParseCertificate(der)
if err != nil {
t.Fatal(err)
}
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
leaf := &x509.Certificate{SerialNumber: big.NewInt(3), Subject: pkix.Name{CommonName: "operator"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}
leafDER, err := x509.CreateCertificate(rand.Reader, leaf, root, &leafKey.PublicKey, key)
if err != nil {
t.Fatal(err)
}
keyDER, err := x509.MarshalECPrivateKey(leafKey)
if err != nil {
t.Fatal(err)
}
certPath, keyPath := filepath.Join(dir, "dated-client.crt"), filepath.Join(dir, "dated-client.key")
if err := os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafDER}), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil {
t.Fatal(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), certPath, keyPath
}
+14 -3
View File
@@ -8,6 +8,8 @@ package link
import (
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials/insecure"
@@ -18,15 +20,24 @@ import (
func Dial(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
all := make([]grpc.DialOption, 0, len(opts)+1)
all = append(all, grpc.WithTransportCredentials(insecure.NewCredentials()))
all = append(all, opts...)
return grpc.NewClient(target, all...)
all = append(all, answer.ClientOptions()...)
all = append(all, observeClientTLS(opts)...)
conn, err := grpc.NewClient(target, all...)
if err != nil {
return nil, answer.LocalConfiguration(err)
}
return conn, nil
}
// DialWith opens a lazy client connection to target with exactly opts: the
// caller supplies the transport credentials (no default is added). It is the
// one place a link with caller-chosen options is built.
func DialWith(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
return grpc.NewClient(target, opts...)
conn, err := grpc.NewClient(target, append(answer.ClientOptions(), observeClientTLS(opts)...)...)
if err != nil {
return nil, answer.LocalConfiguration(err)
}
return conn, nil
}
// ServerConfig is a server's interceptor chain; the zero value has none.
+43 -9
View File
@@ -7,6 +7,8 @@ import (
"os"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
@@ -30,10 +32,10 @@ func (f TLSFiles) Check() error {
return nil
}
if f.Cert == "" || f.Key == "" || f.CA == "" {
return fmt.Errorf("mutual TLS needs a certificate, its key and a CA: got cert=%q key=%q ca=%q", f.Cert, f.Key, f.CA)
return answer.LocalCredential(fmt.Errorf("mutual TLS needs a certificate, its key and a CA: got cert=%q key=%q ca=%q", f.Cert, f.Key, f.CA))
}
if _, err := tls.LoadX509KeyPair(f.Cert, f.Key); err != nil {
return fmt.Errorf("TLS certificate %s / key %s: %w", f.Cert, f.Key, err)
if _, err := f.loadPair(); err != nil {
return err
}
_, err := f.pool()
return err
@@ -42,11 +44,11 @@ func (f TLSFiles) Check() error {
func (f TLSFiles) pool() (*x509.CertPool, error) {
raw, err := os.ReadFile(f.CA)
if err != nil {
return nil, fmt.Errorf("TLS CA: %w", err)
return nil, answer.LocalCredential(fmt.Errorf("TLS CA: %w", err))
}
p := x509.NewCertPool()
if !p.AppendCertsFromPEM(raw) {
return nil, fmt.Errorf("TLS CA %s holds no PEM certificate", f.CA)
p, err := answer.CertificatePool(raw, time.Now())
if err != nil {
return nil, answer.LocalCredential(fmt.Errorf("TLS CA %s: %w", f.CA, err))
}
return p, nil
}
@@ -56,7 +58,18 @@ func (f TLSFiles) pool() (*x509.CertPool, error) {
func (f TLSFiles) loadPair() (*tls.Certificate, error) {
c, err := tls.LoadX509KeyPair(f.Cert, f.Key)
if err != nil {
return nil, fmt.Errorf("TLS certificate %s / key %s: %w", f.Cert, f.Key, err)
return nil, answer.LocalCredential(fmt.Errorf("TLS certificate %s / key %s: %w", f.Cert, f.Key, err))
}
// Only the leaf is our local identity. The peer builds and verifies its
// own chain and may ignore alternative certificates sent after the leaf.
for _, der := range c.Certificate[:1] {
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, answer.LocalCredential(fmt.Errorf("TLS certificate %s: %w", f.Cert, err))
}
if err := answer.ValidateCertificate(cert, time.Now()); err != nil {
return nil, answer.LocalCredential(fmt.Errorf("TLS certificate %s: %w", f.Cert, err))
}
}
return &c, nil
}
@@ -103,7 +116,28 @@ func ClientCredentials(f TLSFiles, serverName string) (grpc.DialOption, error) {
return f.loadPair()
},
}
return grpc.WithTransportCredentials(credentials.NewTLS(cfg)), nil
creds := credentials.NewTLS(cfg)
return clientTLSOption{DialOption: grpc.WithTransportCredentials(creds), credentials: creds}, nil
}
type clientTLSOption struct {
grpc.DialOption
credentials credentials.TransportCredentials
}
// A dial option may be reused for unrelated channels. Transport evidence
// belongs to the new channel, never to the reusable credentials option.
func observeClientTLS(opts []grpc.DialOption) []grpc.DialOption {
result := make([]grpc.DialOption, 0, len(opts)+2)
for _, option := range opts {
if observed, ok := option.(clientTLSOption); ok {
creds, evidence := answer.ObserveCredentials(observed.credentials.Clone())
result = append(result, grpc.WithTransportCredentials(creds), grpc.WithChainUnaryInterceptor(evidence.UnaryInterceptor), grpc.WithChainStreamInterceptor(evidence.StreamInterceptor))
} else {
result = append(result, option)
}
}
return result
}
// MasterConnectionAge is how long blockmaster keeps one client connection
@@ -0,0 +1,62 @@
package wsclient
import (
"context"
"crypto/x509"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
)
type failedWorkspaceRead struct {
control.WorkspaceServiceClient
err error
}
func (rpc failedWorkspaceRead) QueryWorkspace(context.Context, *control.WorkspaceVolume, ...grpc.CallOption) (*control.WorkspaceStatus, error) {
return nil, rpc.err
}
func TestWorkspaceUsesSharedCredentialPolicies(t *testing.T) {
ca := authtest.NewCA(t, "workspace")
leaf := ca.Issue(t, "peer", time.Now().Add(time.Hour))
_, trust := leaf.Cert.Verify(x509.VerifyOptions{Roots: x509.NewCertPool()})
if trust == nil {
t.Fatal("untrusted certificate verified")
}
dir := t.TempDir()
_, local := link.ClientCredentials(link.TLSFiles{Cert: filepath.Join(dir, "missing"), Key: filepath.Join(dir, "key"), CA: filepath.Join(dir, "ca")}, "")
if local == nil {
t.Fatal("missing credentials accepted")
}
for _, row := range []struct {
name string
err error
outcome Outcome
}{
{"trust", answer.Record(answer.Unsent, trust), OutcomeNotAuthorized},
{"local", local, OutcomeRefusedLocally},
} {
t.Run(row.name, func(t *testing.T) {
_, err := New(failedWorkspaceRead{err: row.err}).Show(context.Background(), "volume")
if got := OutcomeOf(err); got != row.outcome {
t.Fatalf("outcome=%v want=%v: %v", got, row.outcome, err)
}
})
}
}
func TestReviewUnsentCallerCancellationIsNotMasterRefusal(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := classifyCode("forced move", answer.RecordContext(ctx, answer.Unsent, context.Canceled))
if OutcomeOf(err) != OutcomeUnsent {
t.Fatalf("no master answer: outcome=%v err=%v", OutcomeOf(err), err)
}
}
@@ -13,14 +13,14 @@ import (
func (c *Client) CleanMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
const op = "clean move"
if q.GetKind() != "clean" || q.GetForce() || q.GetVolumeId() == "" || q.GetRequestId() == "" || q.GetExpectedReplicaId() == "" || q.GetExpectedEpoch() == 0 || q.GetTargetReplicaId() != q.GetExpectedReplicaId() || q.GetTargetServerId() == "" || q.GetTargetDataAddr() == "" || q.GetTargetCtrlAddr() == "" {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("clean move requires explicit identity, request id and target endpoints; force is not allowed")}
return nil, classifyLocal(op, "bad_request", errors.New("clean move requires explicit identity, request id and target endpoints; force is not allowed"))
}
g, err := c.rpc.MoveWorkspace(ctx, q)
if err != nil {
return nil, classify(op, err)
}
if err := checkGrant(g, q); err != nil {
return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%v; rerun with the same request id", err)}
return nil, classifyLocal(op, "outcome_unknown", fmt.Errorf("%v; rerun with the same request id", err))
}
return g, nil
}
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more