seaweed-block: unify operator answer policy with admission evidence

This commit is contained in:
pingqiu committed 2026-12-05 12:53:30 -08:00
1 parent 08aeac6b53
commit 46f2f80e80
99 files changed
+4804 -446

No files matched your search

@@ -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; recover the same operation by its replay key or poll its existing handle; do not start another operation"
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")
}
+16 -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,11 @@ 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): 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 +92,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 +120,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 +152,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
}
+27 -2
View File
@@ -19,6 +19,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"
@@ -202,8 +203,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 +289,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"
@@ -78,7 +79,7 @@ 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)
@@ -93,7 +94,7 @@ 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 chunkResult("snapshot", nil, err, stdout, stderr)
}
if current.ID != a.Answer.ID {
return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation status changed identity", false)
@@ -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
@@ -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"
)
@@ -299,7 +300,7 @@ func singleFilerContextError(ctx context.Context, err error) error {
}
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)
return fmt.Errorf("%w: %w: %w", done, cause, err)
}
@@ -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:
+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")
}
@@ -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 (
"errors"
"net"
"syscall"
"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 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")
}
})
}
}
}
// Port zero cannot identify a listening endpoint. Unlike a closed listener's
// former ephemeral port, it cannot be reallocated between setup and dialing.
const refusedTCPAddress = "127.0.0.1:0"
func refusedDial(t *testing.T) error {
t.Helper()
conn, err := net.DialTimeout("tcp", refusedTCPAddress, 5*time.Second)
if conn != nil {
conn.Close()
}
if !errors.Is(err, syscall.ECONNREFUSED) {
t.Fatalf("fixture did not produce a refused TCP dial: %v", err)
}
return err
}
@@ -0,0 +1,47 @@
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
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 {
return nil, err
}
count++
}
pool := x509.NewCertPool()
if count == 0 || !pool.AppendCertsFromPEM(raw) {
return nil, LocalCredential(fmt.Errorf("CA bundle holds no valid PEM certificate"))
}
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))
}
}
+109
View File
@@ -0,0 +1,109 @@
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
}
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,77 @@
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"},
{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" && 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 {
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,138 @@
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" {
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" && got.Retry != answer.Recover {
t.Fatalf("legacy exit weakened recovery: %+v", got)
}
})
}
}
}
func TestEveryLegacyExitHasADocumentedGridRow(t *testing.T) {
expected := []struct {
contract answer.Contract
err error
phase answer.Phase
exit int
}{
{answer.Failover, answer.Record(answer.Unsent, refusedDial(t)), 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)
}
+107
View File
@@ -0,0 +1,107 @@
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
}
if phase == Unsent {
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)
}
}
}
}
}
+61
View File
@@ -0,0 +1,61 @@
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 {
return resp, RecordContext(req.Context(), observed, err)
}
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,59 @@
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)
}
return Record(PossiblyAdmitted, &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)
}
})
}
}
+193
View File
@@ -0,0 +1,193 @@
package answer_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"strings"
"sync/atomic"
"syscall"
"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, 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 !errors.Is(err, syscall.ECONNREFUSED) {
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, 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{})
+264
View File
@@ -0,0 +1,264 @@
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) {
state.Picker = &evidencePicker{Picker: state.Picker, pool: cc.pool}
cc.ClientConn.UpdateState(state)
}
type evidencePicker struct {
balancer.Picker
pool *peerPool
}
func (p *evidencePicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
rpc, _ := info.Ctx.Value(rpcEvidenceKey{}).(*rpcEvidence)
if rpc != nil {
p.pool.mu.Lock()
generation := p.pool.generation
p.pool.mu.Unlock()
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)
}
})
}
}
+206
View File
@@ -0,0 +1,206 @@
// 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.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")
}
}
+135
View File
@@ -0,0 +1,135 @@
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
}
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()
}
}
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)
}
})
}
}
+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.
+41 -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,16 @@ 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))
}
for _, der := range c.Certificate {
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 +114,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,53 @@
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)
}
})
}
}
@@ -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
}
@@ -10,8 +10,8 @@ import (
)
// Refusals by authentication or authorization are "not authorized", and a
// plaintext client against a TLS master is told the cure; a transport error
// with a client identity configured stays unknown.
// concrete certificate rejection gets the cure. A preface EOF alone does
// not prove certificate rejection, with or without a configured identity.
func TestClassifyNotAuthorized(t *testing.T) {
preface := status.Error(codes.Unavailable, `connection error: desc = "error reading server preface: EOF"`)
for _, c := range []struct {
@@ -23,7 +23,7 @@ func TestClassifyNotAuthorized(t *testing.T) {
}{
{"unauthenticated", status.Error(codes.Unauthenticated, "certificate sha256:ab (CN=x) is not in the role file"), false, OutcomeNotAuthorized, "role file"},
{"permission denied", status.Error(codes.PermissionDenied, "operator alice may not do this: it needs admin"), false, OutcomeNotAuthorized, "needs admin"},
{"plaintext against TLS", preface, false, OutcomeNotAuthorized, link.EnvTLSCert},
{"opaque preface without identity", preface, false, OutcomeUnknown, "replay key"},
{"preface error with an identity configured", preface, true, OutcomeUnknown, ""},
{"master down", status.Error(codes.Unavailable, "connection refused"), false, OutcomeUnknown, ""},
} {
+2 -2
View File
@@ -12,14 +12,14 @@ import (
func (c *Client) Revoke(ctx context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
const op = "workspace revoke"
if id.GetVolumeId() == "" || id.GetReplicaId() == "" || id.GetEpoch() == 0 {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("volume, replica and positive epoch are required")}
return nil, classifyLocal(op, "bad_request", errors.New("volume, replica and positive epoch are required"))
}
lease, err := c.rpc.RevokeWorkspace(ctx, id)
if err != nil {
return nil, classify(op, err)
}
if lease.GetVolumeId() != id.GetVolumeId() || lease.GetReplicaId() != id.GetReplicaId() || lease.GetEpoch() != id.GetEpoch() || !lease.GetRevoking() {
return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: errors.New("reply does not match the requested revoking identity")}
return nil, classifyLocal(op, "outcome_unknown", errors.New("reply does not match the requested revoking identity"))
}
return lease, nil
}
+2 -2
View File
@@ -11,14 +11,14 @@ import (
func (c *Client) Show(ctx context.Context, volume string) (*control.WorkspaceStatus, error) {
const op = "workspace show"
if volume == "" {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("volume is required")}
return nil, classifyLocal(op, "bad_request", errors.New("volume is required"))
}
view, err := c.rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume})
if err != nil {
return nil, classify(op, err)
}
if view == nil {
return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: errors.New("missing workspace reply")}
return nil, classifyLocal(op, "outcome_unknown", errors.New("missing workspace reply"))
}
return view, nil
}
+57 -27
View File
@@ -12,11 +12,11 @@ import (
"context"
"errors"
"fmt"
"os"
"strconv"
"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/lifecycleclient"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
@@ -47,6 +47,8 @@ const (
// certificate, one not in its role file, or a role that may not do this);
// nothing was done.
OutcomeNotAuthorized
// OutcomeUnsent: transport proves no request was sent.
OutcomeUnsent
)
// ErrConfirmation refuses a forced move locally: the confirmation must be
@@ -55,11 +57,12 @@ var ErrConfirmation = errors.New("forced move confirmation")
// Error carries a classified failure.
type Error struct {
Outcome Outcome
Code string // original gRPC status code, when a remote call supplied one
Reason string // the master's typed refusal reason (its ErrorInfo detail), when it sent one
Op string
Err error
PolicyExit int // shared projection; zero for older local outcome-only errors
Outcome Outcome
Code string // original gRPC status code, when a remote call supplied one
Reason string // the master's typed refusal reason (its ErrorInfo detail), when it sent one
Op string
Err error
}
func (e *Error) Error() string { return e.Op + ": " + e.Err.Error() }
@@ -77,6 +80,15 @@ func OutcomeOf(err error) Outcome {
return OutcomeUnknown
}
// ExitOf returns an exit assigned by the shared policy projection.
func ExitOf(err error) (int, bool) {
var e *Error
if errors.As(err, &e) && e.PolicyExit != 0 {
return e.PolicyExit, true
}
return 0, false
}
// CodeOf preserves a remote status even when the operator-facing error text
// is rewritten. Client-side checks have typed outcome defaults; no prose is parsed.
func CodeOf(err error) string {
@@ -123,21 +135,39 @@ func ReasonOf(err error) string {
}
func classifyCode(op string, err error) error {
switch status.Code(err) {
case codes.Unauthenticated, codes.PermissionDenied:
return &Error{Outcome: OutcomeNotAuthorized, Code: status.Code(err).String(), Op: op, Err: fmt.Errorf("not authorized by blockmaster: %s (its role file must list this certificate's fingerprint with a role allowed to do this)", status.Convert(err).Message())}
case codes.Unavailable:
// A plaintext client against blockmaster with mutual TLS: the server
// closes the connection before its HTTP/2 preface.
if os.Getenv(link.EnvTLSCert) == "" && strings.Contains(status.Convert(err).Message(), "error reading server preface") {
return &Error{Outcome: OutcomeNotAuthorized, Code: status.Code(err).String(), Op: op, Err: fmt.Errorf("blockmaster refused this plaintext connection: it requires mutual TLS; set %s, %s and %s to a certificate in its role file and its CA", link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)}
}
case codes.FailedPrecondition, codes.InvalidArgument, codes.NotFound, codes.Unimplemented:
return &Error{Outcome: OutcomeRefused, Code: status.Code(err).String(), Op: op, Err: errors.New(status.Convert(err).Message())}
case codes.DataLoss:
return &Error{Outcome: OutcomeReadoutUnproven, Code: status.Code(err).String(), Op: op, Err: errors.New(status.Convert(err).Message())}
err = answer.EnsureEvidence(answer.PossiblyAdmitted, err)
policy, check := answer.PolicyOf(err, answer.Workspace)
if check != nil {
return &Error{Outcome: OutcomeUnknown, Code: status.Code(err).String(), Op: op, Err: fmt.Errorf("%w; %v", err, check)}
}
return &Error{Outcome: OutcomeUnknown, Code: status.Code(err).String(), Op: op, Err: err}
return policyError(op, err, policy, status.Code(err).String())
}
func classifyLocal(op, kind string, err error) error {
policy, check := answer.Lookup(answer.Unsent, answer.ForContract(answer.Workspace, answer.Guard(kind)))
if check != nil {
return &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%w; %v", err, check)}
}
return policyError(op, err, policy, "")
}
func policyError(op string, err error, policy answer.Policy, code string) error {
// Translate the existing workspace wire enum, not error causes. All
// classification, retry, cure and exit decisions came from the registry.
outcome := OutcomeUnknown
switch policy.Exit {
case 1:
outcome = OutcomeRefused
case 2, 78:
outcome = OutcomeRefusedLocally
case 4:
outcome = OutcomeReadoutUnproven
case 5:
outcome = OutcomeNotAuthorized
case 75:
outcome = OutcomeUnsent
}
return &Error{PolicyExit: policy.Exit, Outcome: outcome, Code: code, Op: op, Err: fmt.Errorf("%w; %s", err, policy.Cure)}
}
// ParseConfirmation checks that confirm is exactly "<volume>@<epoch>" for
@@ -182,7 +212,7 @@ func New(rpc control.WorkspaceServiceClient) *Client { return &Client{rpc: rpc}
func Dial(addr string) (*Client, error) {
conn, err := link.DialMasterFromEnv(addr)
if err != nil {
return nil, err
return nil, classify("workspace dial", err)
}
return &Client{rpc: control.NewWorkspaceServiceClient(conn), conn: conn}, nil
}
@@ -201,10 +231,10 @@ func (c *Client) Close() error {
func (c *Client) request(ctx context.Context, op string, m ForcedMove) (*control.WorkspaceMove, error) {
epoch, err := ParseConfirmation(m.Confirm, m.VolumeID)
if err != nil {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: err}
return nil, classifyLocal(op, "bad_request", err)
}
if m.RequestID == "" || m.TargetHost == "" || m.TargetDataAddr == "" || m.TargetCtrlAddr == "" {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("a request id, target host and target data/ctrl addresses are required")}
return nil, classifyLocal(op, "bad_request", errors.New("a request id, target host and target data/ctrl addresses are required"))
}
st, err := c.rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: m.VolumeID})
if err != nil {
@@ -221,7 +251,7 @@ func (c *Client) request(ctx context.Context, op string, m ForcedMove) (*control
if l := st.GetLease(); l != nil {
cur = fmt.Sprintf("%s@%d", l.GetReplicaId(), l.GetEpoch())
}
return nil, &Error{Outcome: OutcomeRefused, Op: op, Err: fmt.Errorf("the master knows no holder of volume %q at epoch %d (current lease: %s); nothing was sent", m.VolumeID, epoch, cur)}
return nil, classifyLocal(op, "not_admitted", fmt.Errorf("the master knows no holder of volume %q at epoch %d (current lease: %s); nothing was sent", m.VolumeID, epoch, cur))
}
return &control.WorkspaceMove{RequestId: m.RequestID, VolumeId: m.VolumeID, ExpectedReplicaId: replica, ExpectedEpoch: epoch, TargetReplicaId: replica,
TargetServerId: m.TargetHost, TargetDataAddr: m.TargetDataAddr, TargetCtrlAddr: m.TargetCtrlAddr, Kind: "forced", Force: true}, nil
@@ -260,10 +290,10 @@ func (c *Client) ForceMove(ctx context.Context, m ForcedMove) (*control.Workspac
return nil, classify(op, err)
}
if err := checkGrant(g, q); err != nil {
return g, &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%v; rerun with the same request id", err)}
return g, classifyLocal(op, "outcome_unknown", fmt.Errorf("%w; rerun with the same request id", err))
}
if err := checkRange(g.GetLostRange(), g); err != nil {
return g, &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: err}
return g, classifyLocal(op, "readout_unproven", err)
}
return g, nil
}
@@ -345,7 +375,7 @@ func (c *Client) LostRanges(ctx context.Context, volume, requestID string) ([]*c
}
for _, x := range r.GetRanges() {
if x.GetVolumeId() != volume || (requestID != "" && x.GetRequestId() != requestID) {
return nil, &Error{Outcome: OutcomeReadoutUnproven, Op: "lost range", Err: fmt.Errorf("the answer names another range (volume %q request %q)", x.GetVolumeId(), x.GetRequestId())}
return nil, classifyLocal("lost range", "readout_unproven", fmt.Errorf("the answer names another range (volume %q request %q)", x.GetVolumeId(), x.GetRequestId()))
}
}
return r.GetRanges(), nil
@@ -237,7 +237,7 @@ func TestForceMovePreservesRemoteCodesThroughOperatorTextAndWrapping(t *testing.
{codes.Unauthenticated, "no certificate", OutcomeNotAuthorized, "not authorized by blockmaster"},
{codes.PermissionDenied, "role denied", OutcomeNotAuthorized, "not authorized by blockmaster"},
{codes.DataLoss, "range unreadable", OutcomeReadoutUnproven, "range unreadable"},
{codes.Unavailable, "error reading server preface", OutcomeNotAuthorized, "requires mutual TLS"},
{codes.Unavailable, "error reading server preface", OutcomeUnknown, "replay key"},
} {
t.Run(tc.code.String(), func(t *testing.T) {
f := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}}, moveErr: status.Error(tc.code, tc.message)}
@@ -0,0 +1,227 @@
# Shared failure policy
The operator policy is a pure lookup of `(phase, error kind)`. Its result
contains a typed code, retryable flag, same-operation retry rule, cure and
exit code. Transport adapters retain facts and translate concrete errors
to kinds. They do not decide which operations may be resent.
A definite typed domain answer from the server takes precedence over a
local transport diagnosis. Otherwise an initial attempt is **unsent** only
when the transport proves that no request stream was sent. Missing evidence
is **possibly admitted**. A reset, EOF, cancellation or deadline after a
request may have left cannot authorize a second non-idempotent operation.
Recover through the original operation's replay key or existing poll handle.
This projects the existing CutTime `Poll` / `CliGiveUp` boundary and the
snapshot same-request-id replay contract. It introduces no server state or
authority transition.
## Transport registry
The registry is in `core/rpc/answer`. Classification precedes one global
class-to-exit projection. A short explicit legacy list preserves documented
v1.1.x exceptions; every row has a source, reason, test and v1.2 removal
boundary. An undocumented exit is canonicalized.
The common chunk contract is shown below. Thirteen wire contracts
(chunk, incomplete verify, workspace, create, resolve, cluster, restore, failover, whole-job
volume operations, stop, placement, shell and ops) remain explicit cells
in that same registry. The legacy exit never changes class or authorizes unsafe retry.
| Kind | Unsent | Possibly admitted |
| --- | --- | --- |
| Connection failure or EOF | `remote_unavailable`, retryable, resend the same operation, 75 | `outcome_unknown`, recover by replay key or poll, 3 |
| DNS failure | `remote_unavailable`, retryable, check resolution and resend the same operation, 75 | `outcome_unknown`, recover by replay key or poll, 3 |
| Timeout | `remote_unavailable`, retryable, resend the same operation, 75 | `outcome_unknown`, recover by replay key or poll, 3 |
| Caller-owned deadline | `deadline_exceeded`, resend the same operation with a sufficient caller window, 1 | `outcome_unknown`, recover by replay key or poll, 3 |
| Local credential load, parse or validity failure | `bad_request`, terminal until local credentials are fixed, 78 | The same local configuration provenance, with the wire contract preserved |
| Caller cancellation | `canceled`, no automatic retry, 1 | `outcome_unknown`, recover by replay key or poll, 3 |
| Certificate rejected or invalid | `not_authorized`, terminal until certificate configuration is fixed, 5 | The same terminal certificate policy, 5 |
| Unknown certificate authority | `not_authorized`, terminal until the CA is fixed, 5 | The same terminal CA policy, 5 |
| Certificate name mismatch | `not_authorized`, terminal until the address or names are fixed, 5 | The same terminal name policy, 5 |
TLS 1.3 can deliver a server's client-certificate rejection on the first
read after the client has written its request. That certificate-family
alert is a definite rejection of this connection, not an ambiguous applied
request. It remains terminal even in the post-write phase. The TLS adapter
recognizes the finite certificate-alert family at the structured TLS error
boundary; it does not search arbitrary gRPC diagnostic text.
HTTP records connection acquisition across the entire call. A missing
`WroteHeaders` callback never proves that a partial write did not happen.
Polling an admitted operation retains its admission evidence even if the
poll's own dial fails. Response-body read failures retain post-send evidence.
gRPC records `OutHeader` per RPC, monotonically across transparent retry
attempts. Unary and streaming failures preserve the original gRPC status
and details. Typed connection-attempt causes are captured before gRPC
flattens the final failure into `Unavailable`. Credentials options retain no
channel-wide last cause. Established RPCs use their own connection's
late-alert evidence; unsent calls require the fresh peer-set proof below. A two-peer control holds a trusted RPC open while another peer fails TLS
verification, then loses the trusted RPC answer. The trusted call remains
UNKNOWN; substituting the channel-wide last TLS error makes the control fail.
## Evidence and remaining work
Tests produce actual loopback TCP refusal and reset, owned DNS NXDOMAIN,
read timeout, caller cancellation, EOF and TLS verification failures. A TLS
1.3 test completes the client handshake and write before observing a missing
client-certificate alert. HTTP and gRPC tests distinguish an unsent call
from a received request whose answer is lost. Unlisted errors, kinds and
phases fail the registry check.
The registry now includes every gRPC status, typed domain answers, local
kernel refusals and caller-owned deadline provenance. Workspace rendering,
chunk catalog and partial verify errors, restore, volume create/resolve,
cluster finalize/retire and failover use the shared policy. HTTP boundaries
retain phase evidence, including snapshot polls and whole-job volume reads.
A thirteen-contract grid checks produced TCP refusal/reset, DNS and timeout
errors in both phases, with an unlisted-row negative for each contract.
The transport semantics correction is `Unavailable` after a
request stream may have been sent: it is UNKNOWN, never proof of safe resend.
A bare status without evidence is conservative. TLS certificate rejection
is a terminal, not-admitted exception even after a TLS 1.3 request write.
Whole-job backup, restore, cut and stop presentation, shell inspection,
and the older ops HTTP/RPC clients use the shared registry. All owned RPC
constructors and HTTP request boundaries are inventoried by a source census;
a raw-client bypass is a failing control. Generated code and explicitly
inventoried non-network sync.Once callbacks are excluded. The inventory
pins current entries; aliases, reflection and future transport libraries
require a new entry and an admission-evidence control.
Typed server codes have a finite registry inventory. A source census checks
constant domain codes and an actual HTTP unlisted-code answer fails closed.
Unknown errors, status codes and output contracts never acquire a safe-resend
default. HTTP protocol callers retain their existing 404/409 state rules;
only responses they already treat as failures enter the registry. The
registered HTTP error statuses project definite rejection or conservative
UNKNOWN according to [HTTP semantics](https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5);
the retry rule follows the [non-idempotent retry constraint](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2).
Native short tests cover the registry, RPC, ops, CSI and launcher packages.
Linux/race and whole CLI qualification remain pending. Native Windows cannot
qualify real-master fixtures that require directory Sync. Transport evidence
and presentation do not change server admission, cleanup or authority guards.
## Cost cells
| Operation | Formula and bound | Exhaustion | Attribution |
| --- | --- | --- | --- |
| Policy lookup | O(1) lookup and fixed registry space, independent of S/C/N/V/H/T | Unlisted key is an explicit check error; never a safe-resend default | Shared registry |
| HTTP evidence | O(1) state per in-flight request, independent of S/C/N/V/H/T | Unsupported trace evidence remains possibly admitted | Calling command |
| RPC evidence | O(1) state per in-flight RPC and per TLS connection, plus O(P) peer-attempt state per channel | Missing provenance cannot prove unsent or certificate rejection | Calling RPC client |
| Local credential validation | O(config bytes) parsing; runs before dialing, independent of stored S/C/N/V/H/T | Invalid or expired material is terminal with local provenance | Client constructor |
| Error presentation | O(diagnostic bytes), with existing caller response limits | Unlisted code fails closed; diagnostic text never authorizes retry | Calling command |
| Command-family policy grid | Thirteen compatibility projections, two admission phases, produced failure controls | Linux/race qualification pending; source census does not prove alias/reflection coverage | CLI adapters |
## Exit compatibility
`exit_projection.go` maps unsent remote failure to 75, possibly-admitted
UNKNOWN to 3, certificate/trust/name rejection to 5, and typed local
credential/configuration failure to 78. Local command syntax and definite
server argument refusals remain distinct from credential validation.
`LegacyExits()` is the complete exception inventory. The documented
`ops volume create` and read-only `ops volume resolve` exceptions retain
75 for UNKNOWN and 78 for definite refusal. Cluster finalize/retire typed
precondition refusal retains 2. Incomplete verify UNKNOWN retains 1 (3 means completed findings); failover unsent remote failure retains 3 with read-before-another-move recovery. Every exception is removed in v1.2. Typed non-retryable remote-unavailable answers are definite refusals, never exit 75.
The create exception is safe only for identical name, geometry and placement:
`FileStore.CreateVolume` returns the existing compatible record and layout
identity or refuses a conflict. `RegisterWorkspaceBinding` and placement
preserve conflicting assignments. `TestOpsVolumeCreateAndPlaceRetriesAgainstRunningMaster`
loses each of the three replies and proves a same-input rerun converges;
its Linux qualification remains required. This is not permission to change
settings or issue a different operation as a retry.
`TestCanonicalExitProjectionGrid` covers every changed transport class across
the command contracts; `TestEveryLegacyExitHasADocumentedGridRow` covers each
legacy row and its source/removal metadata. Actual credential-file failures
also traverse command entry points, including workspace, create/resolve,
cluster and failover. See the [v1.1.2 corrections](../releases/v1.1.2.md).
## Multi-peer attempt evidence
Connection-attempt facts come from the public gRPC SubConn state listener,
including the typed Origin of TCP/TLS failures before a stream exists. Its
notifications are asynchronous, so delivery time never proves freshness.
The TLS credential/read boundary stamps the actual attempt start and failure;
a terminal certificate proof requires that attempt to have started after
the RPC. An older attempt or a missing source stamp stays conservative. A
Picker associates that peer set with the RPC that is waiting for it. The
observer delegates the existing pick-first algorithm; it does not replace
the dialer, proxy handling, backoff or admission. Established RPCs continue
to use only their own connection's late TLS fact.
Terminal certificate rejection requires fresh certificate-family failures
for every peer attempted for the call, with no pending, unknown or network
failure. Resolver changes during the call invalidate that proof. A mixed
certificate/network failure remains unsent/retryable and reports both peer
causes. Unsupported custom policies lack this proof and remain conservative.
| Evidence operation | Formula / bound | Exhaustion or uncertainty | Attribution |
| --- | --- | --- | --- |
| Peer attempt tracking | O(P) state per channel, P = resolved peers; fixed counters and last typed causes per peer, no history growing with retries | Resolver change, duplicate peer identity, multi-address SubConn or missing cause cannot prove every attempt was certificate-rejected | Resolver-owned peer set |
| Picker observation | O(P) scan on a failed pick; O(1) retained evidence per RPC | No fresh complete set means retryable unsent failure | Waiting RPC |
| Peer diagnostic | At most 8 peer causes plus omitted count; existing individual diagnostics retained | Truncation never authorizes terminal classification | Failing call |
## Plaintext preface compatibility correction
The configured gRPC transport supplies one additional fact: plaintext mode.
An observed unsent connection failure in that mode retains `remote_unavailable`
and same-operation retry. Its shared cure adds a conditional hint to configure
`SW_BLOCK_TLS_CERT`, `SW_BLOCK_TLS_KEY` and `SW_BLOCK_TLS_CA` if the endpoint
requires TLS. A closed preface cannot prove that requirement: a restarting or
closing plaintext endpoint looks identical. Workspace's old heuristic terminal
5 therefore becomes 75 when unsent is proven (3 without admission evidence).
No handshake probe, string-based TLS diagnosis or extra network request is
introduced. `TestPlaintextPrefaceFailureKeepsUnsentRetryAndTLSHint` exercises
both a real TLS server and a closing plaintext peer. The channel retains one
immutable transport-mode boolean; no per-attempt history or new cost bound.
## Trusting HTTP trace evidence
Only `NewHTTPTransport`'s privately owned native path supplies positive
GetConn/GotConn no-send evidence. A concrete `*http.Transport` can delegate
through `RegisterProtocol` before native tracing; its type alone proves nothing.
All caller-supplied transports, including unmodified standard transports, stay
possibly admitted on transport errors unless cancellation prevented dispatch.
A client with nil Transport uses the adapter's owned standard-default transport,
not the mutable global `http.DefaultTransport`. Caller client options (timeout,
redirect policy, jar) are retained. Redirect connection evidence stays monotone.
The owned transport exposes only RoundTrip and CloseIdleConnections, with no
protocol registration, custom dial callback, or inner transport access. It is
constructed from standard default settings, never from a caller's transport.
HTTPPool exposes idle retention limits only; the blob client retains its current
256 total / 64 per-host idle limits. Defaults remain 100 total / 2 per-host;
request concurrency and per-call bounds are unchanged. No new RPC or retry.
The real received-POST/lost-answer controls cover both a GetConn-only custom
transport and that same custom transport registered on a concrete Transport.
Both remain UNKNOWN. The native refused-dial positive still yields UNSENT75.
A separate control poisons the mutable global's protocol registration and proves
a newly owned transport receives the original server answer instead.
`TestDelayedPeerNotificationCannotRefreshAnOldTLSFailure` queues the
SubConn notifications of a failed TLS attempt until after a new RPC starts;
the delayed failure cannot become a terminal answer for that RPC. A fresh
attempt remains eligible, while an unobserved failure lacks proof. This
projects the existing admission/recovery obligation with no new state
machine or request. Source stamps add only fixed counters per TLS attempt
and connection, preserving O(1) connection/RPC state and O(P) peer state.
The observed TLS auth info forwards the underlying `AuthorityValidator`.
A matching per-RPC authority override still reaches the server; a mismatching
name is refused by the original certificate validator before any RPC receipt.
No validator means refusal, never an implicit authorization.
`TestObservedTLSForwardsPerCallAuthorityValidation` exercises the wrapped
master link with matching DNS/IP names and a mismatching name.
An already-ended single-filer preflight records UNSENT and both the context's
completion and its opaque caller cause. No census request starts. The owned
verify-silence sentinel retains its documented deadline mapping.
`TestChunkCensusPreflightPreservesOpaqueContextCause` covers custom cancellation
and deadline causes with zero census calls.
@@ -52,9 +52,7 @@ These are control-plane tests, not guest-I/O acceptance.
The default protocol is `nvme` with `tcp`, the supported guest path.
Success prints one JSON object with `status: "placement_recorded"`, `volume`,
`layout_id`, `server_id` and `replica_id`. Exit 2 means invalid arguments or
connection configuration, 78 means a definite refusal, and 75 means an unknown
RPC outcome or a not-ready store. On an error, the command stops before the
`layout_id`, `server_id` and `replica_id`. Exit 2 means local invalid arguments; 78 means local credential/configuration failure or a definite server refusal (including authentication); 75 means an unknown RPC outcome, a proven unsent outage or a not-ready store; 4 means unproven integrity readout; 1 means caller cancellation/deadline before send. On an error, the command stops before the
next step. Earlier acknowledged steps remain recorded; retry the same name,
geometry and placement. There is no automatic retry or rollback.
+3 -3
View File
@@ -1130,7 +1130,7 @@ Notes:
| `INV-WS-LOST-RANGE-CLIENT-GRANT-001` | The operator client accepts a forced grant only if it is issued, of kind forced, and matches the request's id, volume, expected holder and epoch, target replica and host, with a higher new epoch; otherwise the outcome is unknown. | M2 lease: Moved → epoch issued (client side) | `core/rpc/wsclient/wsclient.go` `checkGrant`, `ForceMove` | `TestForceMoveBindsGrantAndRange` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMoveRejectsAMismatchedAnswer` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE |
| `INV-WS-LOST-RANGE-CLIENT-RANGE-001` | The operator client accepts a grant's lost range only if it names the grant's volume, request id, old and new epochs, old replica and HEAD generation, and starts at the grant's remote LSN; otherwise the readout is unproven. | M2 lease: Moved → epoch issued (client side) | `core/rpc/wsclient/wsclient.go` `checkRange`, `ForceMove` | `TestForceMoveBindsGrantAndRange`, `TestForceMoveGrantWithoutRangeIsUnproven` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE |
| `INV-CLI-FORCED-LOSS-001` | An issued forced-move JSON answer retains the kept HEAD generation and LSN; proven lost ranges carry their kept-through LSN and time bound, while unproven ranges are explicit and supply no guessed bounds. | M2 forced move readout, output only | `cmd/sw-block/workspace.go` `workspaceForceMoveAnswer.issued` | `TestWorkspaceForceMoveJSONGoldenAnswers`, `TestWorkspaceForceMoveJSONKeepsLocalConfirmationAndIssuedReadoutExits` | MoveAdmission.ReadForMove; no transition change | ACTIVE |
| `INV-CLI-FORCED-JSON-001` | Force-move JSON reports typed admission, barrier and refusal code; only a validated issued grant supplies a move id and target epoch, host and replica. Text output and exit codes keep their existing meanings. | M2 Expired → Moved (forced), output only | `cmd/sw-block/workspace.go`; `core/rpc/wsclient/wsclient.go`; `core/host/master/workspace_service.go` | `TestWorkspaceForceMoveJSONGoldenAnswers`, `TestWorkspaceForceMoveJSONDoesNotGuessAdmission`, `TestWorkspaceForceMoveJSONKeepsLocalConfirmationAndIssuedReadoutExits`, `TestWorkspaceForcedMoveLostRangeOverRPC` | MoveAdmission.ReadForMove; no transition change | ACTIVE |
| `INV-CLI-FORCED-JSON-001` | Force-move JSON reports typed admission, barrier and refusal code; only a validated issued grant supplies a move id and target epoch, host and replica. Failure exits use the shared policy and documented compatibility rows. | M2 Expired → Moved (forced), output only | `cmd/sw-block/workspace.go`; `core/rpc/wsclient/wsclient.go`; `core/host/master/workspace_service.go` | `TestWorkspaceForceMoveJSONGoldenAnswers`, `TestWorkspaceForceMoveJSONDoesNotGuessAdmission`, `TestWorkspaceForceMoveJSONKeepsLocalConfirmationAndIssuedReadoutExits`, `TestWorkspaceForcedMoveLostRangeOverRPC` | MoveAdmission.ReadForMove; no transition change | ACTIVE |
| `INV-WS-FORCED-CONFIRM-001` | The OSS operator client (`sw-block ops workspace force-move`, `wsclient.ForceMove`) sends `force: true` only when `--confirm-forced` is exactly `<volume>@<expected epoch>` (that volume, a positive decimal epoch), and then as kind forced at that epoch with the operator's request id. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request`, `ForceMove`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove` | `TestParseConfirmation`, `TestForceMoveSendsForceOnlyWithTheConfirmation` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE |
| `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE |
| `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE |
@@ -1269,7 +1269,7 @@ Notes:
| `INV-CLI-DELETE-RETRY-001` | Only the final lease barrier after a committed volume-delete reservation permits retryable true/exit 75 at its horizon. A live-holder Reserve refusal requires stopping the volume first (not_admitted, non-retryable, exit 1). No lease guard is bypassed. | M9 delete admission result projection | `cmd/sw-block/chunk_volume_delete.go` `authorityErr`; `cmd/sw-block/chunk.go` `chunkResult` | `TestVolumeDeleteAdmissionRetryAnswer`; `TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted` | MoveAdmission.DelRead; MoveAdmission.DelMark (unchanged guards) | STUB |
| `INV-SNAPSHOT-REPLAY-FLAG-001` | A successful same-ID snapshot admission reports replayed true without changing HEAD or its retained outcome. First creation reports false; the flag decorates only the response. | M9 snapshot outcome projection | `core/host/volume/snapshot_operation.go`, `chunk_control.go`; `cmd/sw-block/snapshot_operation.go` | `TestSnapshotReplayFlagDoesNotRewriteOutcome`, `TestSnapshotCLIUsesReplayedAdmissionAnswer` | SnapOps.Poll; SnapOps.Start (no transition change) | STUB |
| `INV-CLI-UNSENT-REQUEST-001` | An observed operation's initial typed dial failure sends no admission and is remote_unavailable (75) through the shared classifier. A lost answer after send, or a dial failure while polling an admitted handle, retains outcome_unknown. | CLI pre-admission error projection; no server transition | `cmd/sw-block/cut_progress_poll.go` `chunkObserveHandle`; `chunkTransportFailure`, `chunkFail` | `TestPlainDetachRefusedDialIsRemoteUnavailable`, `TestPlainDetachLostAnswerAfterSendStaysUnknown`, `TestPlainDetachPollDialFailureKeepsAdmittedOutcomeUnknown`, `TestOpsChunk_ErrorsAreJSONOnStdout` | CutTime Poll/CliGiveUp boundary; pre-admission transport proof | ACTIVE |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI reports filer/master transport failures as retryable remote_unavailable (exit 75), including census, dial, resolve and read failures; configuration refusals stay distinct. An absent v1.1 delete reports snapshot_not_found; its not_found receipt stays unchanged. | M9 client error projection; M4 census refusal, no transition change | `cmd/sw-block/chunk_transport.go` `chunkTransportFailure`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`, `TestSingleFilerConfigurationErrorDeadlineBetweenReads`, `TestCheckSingleFilerSlowDialOrdering`, `TestDialBCatalogKeepsCustomCallerDeadline`, `TestMasterCensusKeepsCustomCallerDeadline`, `TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt` | SnapOps.Poll | STUB |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI preserves admission evidence and definite domain/certificate answers. Possibly-sent requests require replay/poll. Incomplete verify never exits 3; non-retryable server answers never exit 75. Absent snapshot delete is snapshot_not_found. | M9 client error projection; M4 census refusal, no transition change | `core/rpc/answer` `Lookup`; `cmd/sw-block/chunk_answer.go` `chunkAnswer`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`, `TestSingleFilerConfigurationErrorDeadlineBetweenReads`, `TestCheckSingleFilerSlowDialOrdering`, `TestDialBCatalogKeepsCustomCallerDeadline`, `TestMasterCensusKeepsCustomCallerDeadline`, `TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt`; `TestLinkNeverTurnsASentRequestIntoSafeResend`; `TestChunkHTTPPostLostAnswerIsUnknown`; `TestCommandFamilyTransportGrid`; `TestLocalCredentialsFailBeforeDialWithTypedPolicy`; `TestHTTPCancellationBeforeDispatchKeepsOperationPhase`; `TestDeclaredDomainCodesHaveRegistryRows`; `TestOwnedClientTransportsKeepAdmissionEvidence`; `TestPresentationFailsClosedForUnknownContract`; `TestUnsentRPCWithMixedPeerFailuresIsRetryable`; `TestRPCPeerCertificateFailureDoesNotHideHandshakeTimeout`; `TestRPCSucceedsOnGoodPeerAfterBadCertificate`; `TestPeerCertificateProofRequiresEveryFreshCompletedAttempt`; `TestPeerDiagnosticTruncationNeverAuthorizesTerminalClassification`; `TestTypedRemoteUnavailableRespectsRetryable`; `TestNonRetryableServerAnswerNeverInvitesTemporaryRetry`; `TestVerifyStartCheckLostAnswerNeverLooksLikeFindings`; `TestVerifyIncompleteTransportPreservesPartialProgress`; `TestOpsFailoverUsesSharedDefiniteExitProjection`; `TestBlobHTTPAnswerSurvivesLayoutFetch`; `TestPlaintextPrefaceFailureKeepsUnsentRetryAndTLSHint`; `TestHTTPPartialCustomTraceCannotProveUnsentAfterReceivedPOST`; `TestHTTPRegisteredProtocolCannotProveUnsentAfterReceivedPOST`; `TestHTTPOwnedTransportDoesNotInheritRegisteredDefault`; `TestDelayedPeerNotificationCannotRefreshAnOldTLSFailure`; `TestObservedTLSForwardsPerCallAuthorityValidation`; `TestChunkCensusPreflightPreservesOpaqueContextCause` | SnapOps.Poll; CutTime.Poll; CutTime.CliGiveUp (result projection; no new transition) | STUB |
| `INV-CLI-CHUNK-LOOP-001` | Above the per-request bound, sw-block ops chunk snapshot\|detach repeats the SAME request (same name and request id) only after a retryable or outcome_unknown answer. Manual cut and plain detach use the separate one-POST/read-only-poll contract. | client (no state machine): the CLI side of M5 requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody`, `TestChunkSnapshotLoopReusesTheGeneratedRequestID`, `TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable` (`cmd/sw-block`) | — | ACTIVE |
| `INV-CLI-CHUNK-LOOP-002` | Above the per-request bound, sw-block ops chunk snapshot\|detach stops at the first definite answer (success or non-retryable refusal). | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop` | `TestChunkLoopStopsOnANonRetryableRefusal`, `TestChunkDetachOutcomeUnknownSettles` (`cmd/sw-block`) | — | ACTIVE |
| `INV-CLI-CHUNK-LOOP-003` | Non-plain detach and snapshot admission obey a positive total --timeout. Snapshot observation keeps the same ID with bounded calls and no total deadline. Manual cut and plain detach use the separate inactivity-window contract. | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkLoopEndsAtTheTimeout`, `TestChunkLoopHeldProgressReadSendsNoRequestAfterTheTimeout`, `TestChunkLoopSlowAnswersAreBoundedByTheTimeout`, `TestChunkNonPositiveTimeoutIsRefused` (`cmd/sw-block`) | — | ACTIVE |
@@ -1281,7 +1281,7 @@ A guest read has a cooperative arrival budget; internal contextless readers keep
Notes:
- `INV-CLI-CATALOG-ERROR-001`: Linux qualification remains pending; native CLI and receipt controls alone do not activate this row. A failed NoLiveLease observation keeps its transport cause under ErrHolderActive: the wrapper refuses progress but does not prove a live holder. Typed transport failures remain retryable; actual authority refusals stay definite. The existing volume-delete retry window now presents its exhausted remote failure as remote_unavailable rather than unavailable.
- `INV-CLI-CATALOG-ERROR-001`: Linux qualification remains pending; native CLI and receipt controls alone do not activate this row. A failed NoLiveLease observation keeps its transport cause under ErrHolderActive: the wrapper refuses progress but does not prove a live holder. Unsent transport failures permit the same operation to be resent; possibly-admitted failures require replay or polling; actual authority refusals stay definite. The existing volume-delete retry window now presents its exhausted remote failure as remote_unavailable rather than unavailable.
- `INV-CUT-TIMER-RESTART-001`, `INV-CUT-TIMER-SKIP-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: a new attachment seeds its due time at the next stable per-volume grid slot after HEAD's newest scheduled snapshot, or is due immediately without scheduled history. Future creation times are clamped to now. A re-armed loop on the same handle keeps its schedule (failures, retry time); a restart restores the last success and overdue age from HEAD. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`.
- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` (except its estimate and quiesce-slack report, which every successful cut returns) and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal. So do `INV-WS-FREEZE-REFUSAL-INPUTS-001` and `INV-WS-FREEZE-REFUSAL-PRECEDENCE-001`.
- `INV-WS-FREEZE-REFUSAL-001`: a generic `bad_request` is not proof of a clean refusal. The validation also refuses a non-frozen request that carries a freeze origin (`handleChunkDetach`). `INV-WS-FREEZE-REFUSAL-INPUTS-001` compares the caller's Unix-nanosecond origin with blockvolume's `time.Now`, with no skew bound.
+4 -6
View File
@@ -451,7 +451,7 @@ sw-block ops chunk verify --master 127.0.0.1:9180 --volume v1 --chunk-filer 127.
sw-block ops chunk verify --master 127.0.0.1:9180 --volume v1 --chunk-filer 127.0.0.1:18888 --depth data --timeout 10m
```
- **Exit codes:** 0 clean; 3 completed with findings; 1 could not complete (the answer says why); 2 usage.
- **Exit codes:** 0 complete and clean; 3 complete with findings; 1 incomplete operational/unknown answer; 2 usage or server argument refusal; 4 unproven integrity readout; 5 authentication rejection; 75 unsent/retryable remote failure; 78 local credential/configuration failure. An incomplete scan never exits 3; inspect its JSON `code` and partial `verify` result.
- **`--depth data`** needs `--timeout`.
- **`--timeout` and `--deadline`.** `--timeout` is a no-progress window: each completed read renews it.
`--deadline` optionally bounds the whole pass.
@@ -624,8 +624,7 @@ writing the v1.0 format until you finalize. Until then you can go back.
volume, and run the finalize again.
- **`listed`** names the hosts the master cannot confirm but that do not block the finalize: a held volume with no
report or a stale one, a host with no report, and an old process that holds no volume.
- **Exit codes:** **0** finalized or already finalized; **2** refused; **75** blockmaster unreachable, retry; **1**
any other failure (the level is unchanged).
- **Exit codes:** **0** finalized or already finalized; **2** typed precondition/argument refusal; **75** proven unsent remote failure; **3** unknown answer (read the current level before retrying); **5** authentication rejection; **78** local credential/configuration failure; **4** unproven integrity readout; **1** other definite failure or caller cancellation/deadline before send. An unknown answer does not prove the level unchanged.
- **JSON only.** The typed codes (`FORMAT_HOSTS_TOO_OLD`, and `HOST_HOLDS_WORK` below) appear only with `--json`.
Plain output says `refused`.
@@ -781,8 +780,7 @@ Volume status (`/status?volume=<id>`, heartbeats, cluster status):
| `io_error` | A local I/O error latched the store. | Check the disk. Restart the volume once the disk is healthy. |
| `store_format_newer`, `head_newer_version` (exit 78) | A later version wrote the store or HEAD. | Run the later version. The unit does not restart after a final exit. |
`sw-block` commands. The JSON answer carries a typed `code` or `reason`. `ops chunk` refusals exit 1 unless the row
says otherwise.
`sw-block` commands. The JSON answer carries a typed `code` or `reason`. ordinary definite `ops chunk` refusals exit 1; server argument refusals exit 2, authentication rejections 5, and local credential/configuration failures 78. A possibly admitted unknown answer exits 3, except incomplete verify uses 1 so it cannot be mistaken for completed findings.
| Code or reason | Seen from | Meaning | What to do |
|---|---|---|---|
@@ -791,7 +789,7 @@ says otherwise.
| `BINARY_TOO_OLD` | move preview | The move target runs an older binary. | Upgrade the target, or choose another. |
| `SIZE_REQUIRES_FORMAT_LEVEL_1` (exit 78) | `ops volume create` | A volume above 256 GiB before the finalize. | Finalize (section 7), or use a smaller volume. (From the cluster spec, this is a blockmaster log line, section 3.) |
| `deadline_exceeded` (retryable) | verify and others | The window or deadline passed: a verify pass stopped without progress. | Retry. If it repeats, look for a slow filer or a starved disk. |
| `remote_unavailable` (retryable) | holder calls; from v1.1.1 every `ops chunk` command that contacts a filer or master | The filer or master could not be reached. From v1.1.1 the CLI exits 75. | Retry once it is reachable, with the same request id. |
| `remote_unavailable` (retryable) | holder calls; from v1.1.1 every `ops chunk` command that contacts a filer or master | Proven unsent failure, or a definite server answer that permits retry: exit 75. A possibly admitted failure is `outcome_unknown`, exit 3 (incomplete verify: 1); a non-retryable typed `remote_unavailable` exits 1. | Restore connectivity. For an unknown answer, replay the original request id or poll/read the original operation; never start another non-idempotent operation. |
| `internal` | `ops chunk` commands with `--chunk-filer` | v1.1.0 only: also what an unreachable filer gives, and `ops chunk verify` and `ops chunk snapshot-delete` instead answer `bad_request: ... needs exactly one filer ... connection refused` (exit 2) after 30-60 s. From v1.1.1 these are `remote_unavailable`. | Check the filer address and that the filer runs, then retry. |
| `not_admitted` | restore | The target is not in the cluster spec. The printed cure (`--lifecycle-product-loop-interval`) does not apply to this setup. | Add the target without `size_bytes` and restart blockmaster (section 5). |
| `not_admitted ... live until <time>` | volume-delete | The volume's lease horizon has not passed. In v1.1.1 the answer's `retryable` field says which case applies: `true` (exit 75) means the delete is admitted and waits for its final lease barrier; `false` (exit 1, "stop the volume first") means a serving holder still holds the lease, so the delete was not admitted. | `true`: repeat with the same request id after that time. `false`: stop the holder (section 6, steps 1 and 2), then repeat (section 6). |
@@ -8,13 +8,13 @@ v1.0.1 gives two refusals a code of their own:
refusal with a typed reason, which the CLI maps; other refusals of the same kind stay `not_admitted`.
- **A volume the master does not know** (catalog commands such as `ops chunk snapshots --volume NAME`):
`"code":"volume_not_found"`, **exit 1**. It was `"code":"bad_request"` with **exit 2**. This is a contract change
for scripts that check the exit status: exit 2 now means only a malformed command or another resolve failure.
for scripts that check the exit status: in v1.0.1 exit 2 meant a malformed command or another resolve failure; the later policy below distinguishes those failures.
See [restore a snapshot into a new volume](../standalone-deployment.md#restoring-a-snapshot-into-a-new-volume).
## v1.1.1 corrections: retry advice and snapshot replay
For every `ops chunk` command, a remote transport outage answers
In v1.1.1, every `ops chunk` command mapped a remote transport outage to
`remote_unavailable`, `retryable: true`, exit **75** (temporary failure).
The message advises repeating the same operation after the remote is reachable;
keep the same request ID when the operation has one. This includes a filer
@@ -46,4 +46,8 @@ the original operation retains its original result; it is not a new admission.
The manual cut observation protocol keeps its own `outcome_unknown`, `cut_busy`
and `cut_stalled` answers; this correction does not change that admission or
observation protocol. HTTP snapshot/detach error bodies are relayed unchanged;
the temporary exit code and retry advice on stderr follow the same rule.
v1.1.1 temporary exit code and retry advice on stderr follow the same rule.
## v1.1.2 admission-aware correction
The v1.1.1 table above is historical. In v1.1.2 a proven unsent outage remains `remote_unavailable`, retryable, exit 75; a possibly admitted request is `outcome_unknown`, exit 3, with replay-key/poll recovery. Incomplete verify uses exit 1 for that class; 3 always means completed with findings. A typed server `remote_unavailable` with `retryable: false` exits 1. Caller cancellation/deadline before send exits 1; after possible admission it uses UNKNOWN. Authentication rejection exits 5, local credential/configuration failure 78, server argument refusal 2 and unproven integrity readout 4. Dated delete lease-barrier advice and stop-first refusal remain distinct. The full [per-family old-to-new inventory](v1.1.2.md) also lists the compatibility exceptions; never infer safe resend from exit status alone.
+146
View File
@@ -7,3 +7,149 @@ v1.1.2 is not yet released.
- **Trigger:** blockmaster's state directory or its ancestors share a filesystem with heavy writes, such as the holders' local data.
- **Effect:** blockmaster's start syncs its state directories, which can wait for the filesystem journal. When the import has changed records, it also runs a `syncfs` for each store with changed records on ext4, XFS, btrfs or tmpfs (Linux 5.8 or later), which waits for every pending write on that filesystem, including the holders' data. Starts took from about 20 seconds to over 150 seconds in our tests (one start was not ready after 2 minutes); this is not an upper bound. A volume whose lease expires stops serving until blockmaster is back; it is then granted again on the same holder, with its data. A forced move during that time can lose writes after the last published HEAD (see [forced move](../volume-lifecycle.md#after-a-crash)).
- **What to do:** keep the holders' data off both the state directory's filesystem and the filesystem holding its ancestor directories. In practice, put the holders' data on its own filesystem, not the root filesystem. A different directory on the same filesystem is not enough. A dedicated state-directory mount alone does not isolate every startup sync: opening the store also syncs ancestors up to `/`, including `/var/lib` and `/var` with the shipped layout. Restart blockmaster at low write load on all those filesystems. This limitation also applies when the cluster spec has not changed.
## CLI answer classification
The shared operator failure policy now distinguishes admission evidence from
transport status. A gRPC `Unavailable` after a request may have been sent is
`outcome_unknown`: recover the same operation by its replay key or poll/read
before proceeding. It is never proof that a new non-idempotent operation is
safe. Typed server refusals retain their own contract.
One global projection gives these exits:
| Failure class | Exit | Same-operation action |
| --- | --- | --- |
| Proven unsent `remote_unavailable` | 75 | Retry the same operation after connectivity recovers. |
| Possibly admitted `outcome_unknown` | 3 | Replay the original key or poll/read; do not start another operation. |
| Certificate, trust or name rejection, `not_authorized` | 5 | Fix authentication/configuration first. TLS1.3 certificate rejection remains definite even if its alert follows a request write. |
| Typed local credential or connection configuration failure | 78 | Fix local files/configuration before dialing. This is distinct from command syntax or a typed server argument refusal. |
The table below compares the shipped v1.1.1 CLI (the compatibility baseline)
with this correction. Admission phase is evidence, not the gRPC status name.
A definite typed server answer still wins over transport evidence. Exit 75
permits retry only under the printed same-operation rule; it never permits a
second non-idempotent operation after an uncertain answer.
| Command family / failure | v1.1.1 exit | v1.1.2 exit | Meaning and recovery |
| --- | --- | --- | --- |
| Workspace: proven unsent connection/DNS/handshake timeout | 3 | 75 | Nothing sent; retry the same operation. |
| Workspace: caller cancellation/deadline before send | 3 | 1 | Caller ended the attempt before dispatch. |
| Workspace: server InvalidArgument | 1 | 2 | Fix the server's stated argument error. |
| Workspace: server AlreadyExists | 3 | 1 | Read/reconcile the existing target, not another move. |
| Workspace: certificate/trust/name rejection | 3 for TLS transport rejection; 5 for typed auth refusal | 5 | Fix the certificate, trust or name; role refusals remain 5. |
| Workspace: plaintext preface EOF (including an mTLS endpoint or a peer restarting/closing) | 5 under the old no-client-certificate heuristic | 75 with observed unsent phase; 3 without admission evidence | Deliberate correction: EOF does not prove a TLS requirement. Retry connectivity; if this endpoint requires TLS, configure certificate/key/CA. No automatic handshake probe is added in this round. |
| Workspace: local credential/connection configuration | 2 | 78 | Fix local files/configuration before dialing. Confirmation/syntax stays 2. |
| Cluster: possibly admitted transport/internal failure | 75 or 1 | 3 | Read the current cluster result before another mutation. |
| Cluster: caller cancellation/deadline before send | 75 | 1 | Caller ended the attempt. |
| Cluster: server InvalidArgument | 1 | 2 | Fix arguments. Typed finalize/retire precondition stays 2. |
| Cluster: PermissionDenied/Unauthenticated or TLS certificate rejection | 1 or 75 | 5 | Fix authentication/authorization. |
| Cluster: local credential/configuration | 2 | 78 | Fix local setup. |
| Chunk: possibly admitted transport failure, including snapshot observation polls | 75 | 3 | Recover the original request id/handle; do not issue another operation. |
| Chunk: typed server `outcome_unknown` | 1 | 3 | Preserve the server's class and recover the original operation. |
| Chunk: unlisted server error code | 1 | 3 | Client cannot interpret the answer; upgrade/read/recover, never blind resend. |
| Chunk: server `bad_request` | 1 | 2 | Fix arguments; ordinary definite refusals stay 1. |
| Chunk: retryable server `not_admitted` outside volume-delete | 1 | 75 | Follow the same-operation cure; the retryable flag must be true. |
| Chunk: typed non-retryable `remote_unavailable` | 1 | 1 | A definite refusal is not permission to retry; it never receives 75. |
| Chunk: PermissionDenied/Unauthenticated | 1 (or 2 through master resolve) | 5 | Fix role/certificate. |
| Chunk: master-resolve refusal | 2 | 1 ordinary refusal; 2 arguments; 4 integrity; 5 auth; 3 unknown | Resolve failures use their actual class, not a blanket usage error. |
| Chunk: caller cancellation/deadline before send | 75 on gRPC/HTTP paths | 1 | Caller ended the attempt. Possible admission instead means UNKNOWN/3. |
| Snapshot observation: malformed/incomplete answer | 75 | 1 | Inspect the original operation; do not treat a bad answer as success. |
| Chunk verify: incomplete lost answer | 75 for transport; 1 for other incomplete failure | 1 with JSON `outcome_unknown` | Read-only retry is safe; **3 is reserved for a completed scan with findings**. Proven unsent/retryable remote failure remains 75. |
| Chunk verify: authentication/configuration/argument/integrity failure | 1 or 2 | 5 / 78 / 2 / 4 respectively | The JSON retains the failure and partial result. No incomplete path uses findings exit 3. |
| Chunk blob HTTP failure through layout adapters | usually 1 (or 75 for recognized outage) | 500/503: 3 (verify incomplete: 1); 401/403: 5; 400: 2 | HTTP response facts use the same registry; 404/409 protocol-state handling is unchanged. |
| `volume restore`: typed refusal, including placement step | 2 | 1 | Resolve the stated prerequisite; no new restore after an unknown result. |
| `volume restore`: PermissionDenied/Unauthenticated, including placement | 2 | 5 | Fix the caller role/certificate. |
| `volume restore` and interrupted backup: ambiguous transport/workflow answer | 1 or 2 | 3 | Keep the original derived request identity and resume/abort instructions. |
| `ops chunk restore`: authentication or TLS certificate rejection | 1 or 2 | 5 | Fix role/certificate. |
| Create/resolve: TLS certificate rejection | 75 | 78 | Definite authentication/configuration refusal; documented refusal exception. |
| Create/resolve: DataLoss | 78 | 4 | Integrity readout is unproven. |
| Create/resolve: ResourceExhausted, Aborted or OutOfRange | 78 | 75 with recovery cure | Reconcile identical inputs; UNKNOWN is not a new-operation retry. |
| Create/resolve: caller cancellation/deadline before send | 75 | 1 | Caller ended the attempt; after possible admission UNKNOWN stays 75 by compatibility. |
| Create/resolve: local credential/connection configuration | 2 | 78 | Fix local setup. |
| Failover: certificate/role rejection | 1 (TLS could be 3) | 5 | Terminal auth refusal. |
| Failover: DataLoss | 3 | 4 | Unproven integrity readout; inspect the line. |
| Failover: Aborted or OutOfRange | 1 | 3 | Read the current authority line before another move. |
| Failover: server InvalidArgument | 1 | 2 | Correct the server's stated argument error. |
| Failover: caller cancellation before send | 3 | 1 | Caller ended the attempt; possible admission remains 3. |
| Failover: local identity/connection configuration | 2 | 78 | Fix local files/configuration. Unsent remote failure stays 3/read-before-move. |
| Shell inspection: authentication rejection | 1 or 2 | 5 | Fix auth; polling the same read-only record remains safe. |
| Whole-job volume/shell errors that reach the shared projection | 1 or 2 | 75 proven unsent, 3 ambiguous, 5 auth, 78 local configuration | Recover the same workflow or inspection; command-level business refusals retain their documented exits. |
| `volume stop`: guest-read or cut-step refusal | 2 | 2 | The command refuses to stop; nested diagnostics may carry the shared class, but its refusal exit is unchanged. |
| Older `ops` entry points in `main.go` | command-specific 1 or 2 | unchanged outer exits | Their transport diagnostics use shared classes; the outer business-command exits are not newly canonicalized. |
Caller deadlines with custom causes retain caller provenance. After possible
admission, cancellation/deadline is UNKNOWN; before send the canonical exit
is 1 (not a claim that every family previously used 1). Typed domain answers
preserve their own documented handling. The complete compatibility list is
below; no adapter owns a second exit table.
A non-retryable typed server answer never receives 75, including a typed UNKNOWN from create/resolve (canonical 3 instead of the retryable UNKNOWN exception).
The complete v1.1.x legacy list is in the same projection, with a matching
independent test row per entry. These exceptions are removed in v1.2:
| Command | Class | Legacy exit | Documented reason |
| --- | --- | --- | --- |
| `ops failover` | Proven unsent remote failure | 3 | Read the current authority line before another move; Recover, not blind resend. |
| `ops chunk verify` incomplete answer | UNKNOWN | 1 | Exit 3 means a completed scan with findings; JSON keeps the failure class. |
| `ops volume create` | UNKNOWN | 75 | Identical name, geometry and placement reuse the compatible recorded identity or refuse a conflict; never change inputs during recovery. |
| `ops volume create` | Server argument refusal | 78 | The standalone create contract documents definite refusal as 78; local syntax remains 2. |
| `ops volume create` | Other definite server refusal | 78 | Preserve the standalone create contract. |
| `ops volume create` | Typed server precondition refusal | 78 | Preserve format/admission refusal. |
| `ops volume create` | Authentication refusal | 78 | Preserve its documented definite-refusal contract. |
| `ops volume resolve` | UNKNOWN | 75 | It is a read-only query; repeating it cannot create work. |
| `ops volume resolve` | Server argument refusal | 78 | Preserve the documented definite-refusal contract; local syntax remains 2. |
| `ops volume resolve` | Other definite refusal | 78 | Preserve not-found and invalid-identity refusal. |
| `ops volume resolve` | Typed server precondition refusal | 78 | Preserve the documented definite-refusal contract. |
| `ops volume resolve` | Authentication refusal | 78 | Preserve the documented definite-refusal contract. |
| `cluster finalize-format` / `retire-host` | Typed server precondition refusal | 2 | Preserve `FORMAT_HOSTS_TOO_OLD` / `HOST_HOLDS_WORK`. |
The dated volume-delete lease barrier remains a definite `not_admitted`
answer: retry the same request id after its horizon, exit 75. A serving
holder refusal still says stop first and exits 1. Volume-stop guest refusal
still exits 2. No authority, lease or cleanup guard is relaxed by this change.
TLS cause provenance is per connection attempt and peer. Initial terminal
certificate rejection requires fresh certificate-family failures for the
call's complete observed peer set. A mix of a rejected certificate and a TCP
failure or handshake timeout remains unsent/retryable and names the peer
causes. A working peer can still serve the call; an established RPC never
borrows another connection's TLS failure. The observation layer delegates
pick-first and preserves gRPC's dialer, proxy, backoff and retry behavior.
Custom policies without this evidence cannot prove terminal certificate
rejection. Diagnostic truncation never weakens the all-peer check.
A plaintext client's failed preface does not identify the server protocol.
The fallback adds a conditional plaintext/TLS mismatch hint to observed
unsent connection failures and retains retryable exit 75. A peer closing
or restarting gets the same treatment. This deliberately replaces workspace's
old unproven terminal exit 5; it is not a terminal certificate refusal.
There is no new TLS probe or RPC. Configured TLS certificate-family failures
continue to use the per-peer evidence above.
Custom HTTP transports with partial trace support no longer receive an
UNSENT classification from GetConn alone: a received POST whose answer was
lost is UNKNOWN, with the original operation's recovery rule (canonical 3,
or a documented command exception). Owned native refused dials remain UNSENT/75.
A delayed gRPC state notification also cannot make an old TLS rejection
fresh for a newer call. Actual TLS attempt timestamps must establish that
freshness; old or missing evidence stays retryable unsent rather than a
terminal certificate diagnosis. These changes correct evidence attribution;
they add no request or retry and preserve the existing replay requirement.
The observed TLS connection preserves per-call authority validation: matching
certificate names work, and mismatches remain refused. A single-filer preflight
whose caller already ended preserves opaque cancellation/deadline causes and
starts no census call.
HTTP no-send proof comes only from the adapter's privately owned native
transport. A caller-supplied transport, including a concrete `http.Transport`
with a registered protocol, cannot authorize resend from partial trace events.
Such an ambiguous failure is UNKNOWN (canonical exit 3, or its documented
command exception), rather than temporary exit 75.
Nil-transport clients use the adapter's standard-default transport; changing
the global `http.DefaultTransport` does not replace that owned request path.
The blob client's existing idle connection limits are unchanged.
+3 -5
View File
@@ -767,8 +767,7 @@ Perform a clean hand-over in this order:
new epoch and the normal workspace-lease options. The move command only
transfers authority; it does not start the target or reconnect clients.
Workspace commands exit 0 on success, 1 on a definite server refusal, 2 on local
usage refusal, 3 on an unknown outcome, and 4 on an unproven readout. Plain
Workspace commands exit 0 on success, 1 on an ordinary definite refusal or caller cancellation/deadline before send, 2 on local usage/confirmation or a server argument refusal, 3 on an unknown outcome, 4 on an unproven readout, 5 on authentication rejection, 75 on proven unsent remote failure, and 78 on local credential/configuration failure. Plain
detach keeps the chunk CLI's existing JSON error and exit policy. Neither CLI
retries or polls automatically.
@@ -895,8 +894,7 @@ read and decoded, and shared immutable objects are checked once per pass.
Inline filer entries are checked directly from the content returned by the
lookup; they have no backing needle and require no needle HEAD.
Verify is read-only: exit 0 means complete with no findings, 3 means complete
with findings, 1 means incomplete, and 2 means invalid arguments. `--depth data`
Verify is read-only. Its exits are 0 complete and clean; 3 complete with findings; 1 incomplete operational/unknown answer; 2 usage or server argument refusal; 4 unproven integrity readout; 5 authentication rejection; 75 unsent/retryable remote failure; 78 local credential/configuration failure. An incomplete scan never exits 3; inspect its JSON `code` and partial `verify` result. `--depth data`
checks chunk hashes and requires an explicit timeout. `--orphans` only reports;
it never deletes anything. Verify checks every named snapshot in turn, without
pacing; it has no flag to choose snapshots or to set a pace, and a command that
@@ -905,7 +903,7 @@ passes one is refused (exit 2), even with its default value.
`MISSING` and `ORPHAN` findings require matching nonzero generations on the
HEAD read before the walk and the confirmation read after it. Live dependent
HEADs used for orphan reachability are confirmed too. A changed, absent,
unreadable or generation-less HEAD makes the pass incomplete (exit 1), with
unreadable or generation-less HEAD makes the pass incomplete (exit 1 for an unknown/unstable observation; transport/authentication/configuration failures retain the classes above), with
those findings suppressed; retry against a stable volume. HEAD generation advances
on every cut, snapshot and cleaning pass, so MISSING/ORPHAN verification may never
complete on a served volume; run it on a stopped volume or between cuts, snapshots
+1 -1
View File
@@ -249,7 +249,7 @@ core/ops/frontend_publication_runtime_http.go NewHTTPFrontendPublicationRuntime
core/ops/frontend_publication_runtime_http.go HTTPFrontendPublicationRuntime.ExecuteFrontendPublication http.Client.Timeout 1 per-call NONE: no model row maps this file yet one HTTP request
core/ops/k8s_inventory.go statusAddressForKubernetesInventory time.After 1 per-call NONE: no model row maps this file yet one status address lookup
core/ops/k8s_inventory.go waitInventoryTCPReady time.Now().Add 1 per-call NONE: no model row maps this file yet one TCP readiness wait
core/ops/kubernetes_status_writer.go NewInClusterKubernetesStatusClient http.Client.Timeout 1 per-call NONE: no model row maps this file yet one HTTP request
core/ops/kubernetes_status_writer.go newKubernetesStatusClient http.Client.Timeout 1 per-call NONE: no model row maps this file yet one HTTP request
core/ops/live_sources.go NewLiveVolumeStatusReportCollector http.Client.Timeout 1 per-call NONE: no model row maps this file yet one HTTP request
core/ops/server.go NewServer http.Server.ReadHeaderTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
core/replication/component/cluster.go Cluster.CatchUpReplica time.After 1 per-call NONE: no model row maps this file yet component test cluster: one catch-up wait
Can't render this file because it contains an unexpected character in line 50 and column 123.
+3 -5
View File
@@ -425,16 +425,14 @@ An unknown real outcome has `admitted: false` and no move id: rerun the same
request id. A move with an unproven lost-range readout still reports its known
issued move id and `admitted: true`, with `code: "DataLoss"` and exit 4. Its kept HEAD fields remain available,
but `lost_range` is `{proven: false}` with no guessed loss bounds.
The default text output and all exit codes are unchanged, including exit 0
for a successfully answered dry-run that says `admitted: false`.
The successful dry-run output keeps exit 0
when it answers `admitted: false`. Failure exit changes are listed in [v1.1.2 corrections](releases/v1.1.2.md).
Run the command again without `--dry-run`. It prints the lost
range, for example `volume v1 restored to the last published image at <time>
(gen N, LSN L): writes with LSN <= L are preserved; writes acknowledged by r1@E
after that and before <time>, master clock, may be lost; ...`, and `next: start
volume v1 on S2`. Read it later with `sw-block ops workspace lost-range
--master MASTER --volume v1`. Then do step 7 on `S2`. Exit codes: 0 done, 1
refused (nothing moved), 2 refused locally, 3 unknown (rerun with the same
`--request-id`), 4 issued but the lost range is not proven.
--master MASTER --volume v1`. Then do step 7 on `S2`. Exit codes: 0 done; 1 ordinary definite refusal or caller cancellation/deadline before send; 2 local usage/confirmation or server argument refusal; 3 unknown (rerun with the same `--request-id`); 4 unproven lost-range readout; 5 authentication rejection; 75 proven unsent remote failure; 78 local credential/configuration failure.
The product does not power off an old holder that is still alive: it stops
serving when its lease ends. Make sure it stays down.