Files
seaweedfs/seaweed-block/cmd/sw-block/shell_test.go
T

407 lines
16 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"os"
"regexp"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
func requireInspectionOutput(t *testing.T, raw []byte) map[string]inspectionResult {
t.Helper()
want := []string{"master.reachable", "master.lifecycle", "master.version", "filer.single", "host.heartbeat", "volume.known", "volume.assigned", "volume.lease", "volume.frontend", "volume.chunkstore", "volume.cut", "volume.cleaning", "versions.equal", "clock.skew"}
var rows []inspectionResult
if err := json.Unmarshal(raw, &rows); err != nil {
t.Fatalf("invalid output: %v: %s", err, raw)
}
if len(rows) != len(want) {
t.Fatalf("output inventory got%d want%d: %s", len(rows), len(want), raw)
}
got := map[string]inspectionResult{}
for i, r := range rows {
if r.ID != want[i] {
t.Fatalf("output ID/order[%d]=%q want%q", i, r.ID, want[i])
}
if _, exists := got[r.ID]; exists {
t.Fatalf("duplicate ID %s", r.ID)
}
got[r.ID] = r
}
return got
}
func TestShellClusterStatusReadsTheMasterWithoutKubernetes(t *testing.T) {
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-c", "cluster.status -o json"}, &out, &errout)
if code != 0 {
t.Fatalf("exit=%d stderr=%s stdout=%s", code, &errout, &out)
}
var body map[string]any
if err := json.Unmarshal(out.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["schema_version"] == nil || body["volumes"] == nil {
t.Fatalf("not cluster evidence: %s", &out)
}
}
func startInspectionMaster(t *testing.T) (string, func()) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
control.RegisterEvidenceServiceServer(srv, cmdFakeEvidenceServer{})
control.RegisterClusterEvidenceServiceServer(srv, inspectionControlServer{})
go func() { _ = srv.Serve(ln) }()
return ln.Addr().String(), func() {
srv.Stop()
_ = ln.Close()
}
}
type inspectionControlServer struct {
cmdFakeClusterEvidenceServer
control.UnimplementedWorkspaceServiceServer
mode string
}
func (s inspectionControlServer) GetClusterStatus(ctx context.Context, q *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) {
r, err := s.cmdFakeClusterEvidenceServer.GetClusterStatus(ctx, q)
r.Volumes[0].ReplicationFactor = 1
r.Volumes[0].PrimaryNode = "host-b"
r.Volumes[0].Replicas = []*control.ReplicaEvidence{{ReplicaId: "r2", ServerId: "host-b", Observed: true}}
for _, event := range r.Events {
event.NodeName = "host-b"
}
return r, err
}
func (s inspectionControlServer) QueryWorkspace(_ context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) {
if s.mode == "disabled" {
return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled")
}
if q.GetVolumeId() == "__cluster_check__" {
return nil, status.Error(codes.NotFound, "not found")
}
l := &control.WorkspaceLeaseFact{ReplicaId: "r2", Epoch: 2, ValidForNs: int64(time.Second)}
switch s.mode {
case "lease-expired":
l.ValidForNs = 0
case "lease-revoking":
l.Revoking = true
case "lease-wrong-holder":
l.ReplicaId = "r3"
}
return &control.WorkspaceStatus{Lease: l}, nil
}
func TestShellCheckUsesTypedLeaseReadinessCutAndVersionAnswers(t *testing.T) {
for _, tc := range []struct{ mode, id string }{
{"healthy", ""}, {"disabled", "master.lifecycle"}, {"lease-expired", "volume.lease"}, {"lease-revoking", "volume.lease"}, {"lease-wrong-holder", "volume.lease"},
{"frontend-false", "volume.frontend"}, {"cut-pending", "volume.cut"}, {"snapshot-overdue", "volume.cut"}, {"missing-cut-fields", "volume.cut"}, {"version-missing", "versions.equal"}, {"version-mismatch", "versions.equal"},
{"cleaning-error", "volume.cleaning"}, {"cleaning-not-run", "volume.cleaning"}, {"cleaning-running", "volume.cleaning"}, {"cleaning-missing", "volume.cleaning"},
{"missing-cleaning-head-gen", "volume.cleaning"}, {"null-cleaning-head-gen", "volume.cleaning"}, {"missing-cleaning-breakdown", "volume.cleaning"}, {"retention-only", "volume.cleaning"}, {"missing-cleaning-error", "volume.cleaning"}, {"null-cleaning-error", "volume.cleaning"}, {"completed-empty", ""}, {"completed-head-gen-note", ""}, {"failed-head-gen-note", "volume.cleaning"}, {"no-chunk-store", "volume.cut"},
} {
t.Run(tc.mode, func(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
s := inspectionControlServer{mode: tc.mode}
srv := grpc.NewServer()
control.RegisterClusterEvidenceServiceServer(srv, s)
control.RegisterWorkspaceServiceServer(srv, s)
go func() { _ = srv.Serve(ln) }()
defer srv.Stop()
defer ln.Close()
h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/status" {
body := map[string]any{"VolumeID": "v1", "ReplicaID": "r2", "Epoch": 2, "FrontendPrimaryReady": tc.mode != "frontend-false", "Version": "test-rev"}
if tc.mode == "version-missing" {
delete(body, "Version")
}
if tc.mode == "version-mismatch" {
body["Version"] = "other-rev"
}
_ = json.NewEncoder(w).Encode(body)
return
}
stats := map[string]any{"LastCutNs": time.Now().UnixNano(), "CutsFailed": 0, "PendingUnresolved": tc.mode == "cut-pending"}
if tc.mode == "missing-cut-fields" {
delete(stats, "PendingUnresolved")
}
chunk := map[string]any{"Attached": true, "Stats": stats, "ScheduledSnapshot": map[string]any{"snapshot_overdue": tc.mode == "snapshot-overdue", "lastFailure": map[string]any{"code": "remote_unavailable"}}}
lastPass := map[string]any{"atNs": time.Now().UnixNano(), "planned": 11, "removed": 6, "plannedChunks": 3, "plannedRoots": 5, "plannedSegments": 3, "removedChunks": 2, "removedRoots": 1, "removedSegments": 3, "error": "", "headGen": 7, "headGenError": ""}
if tc.mode == "retention-only" || tc.mode == "completed-empty" {
lastPass["planned"] = 0
lastPass["removed"] = 0
for _, key := range []string{"plannedChunks", "plannedRoots", "plannedSegments", "removedChunks", "removedRoots", "removedSegments"} {
lastPass[key] = 0
}
}
if tc.mode == "missing-cleaning-head-gen" {
delete(lastPass, "headGen")
}
if tc.mode == "null-cleaning-head-gen" {
lastPass["headGen"] = nil
}
if tc.mode == "missing-cleaning-breakdown" {
delete(lastPass, "removedRoots")
}
if tc.mode == "completed-head-gen-note" || tc.mode == "failed-head-gen-note" {
lastPass["headGen"] = 0
lastPass["headGenError"] = "HEAD read unavailable after completed cleaning"
}
if tc.mode == "failed-head-gen-note" {
lastPass["error"] = "cleaning failed"
}
if tc.mode == "retention-only" {
lastPass["headGen"] = 0
}
if tc.mode == "missing-cleaning-error" {
delete(lastPass, "error")
}
if tc.mode == "null-cleaning-error" {
lastPass["error"] = nil
}
if tc.mode == "cleaning-error" {
lastPass["error"] = "filer unavailable"
}
maintenance := map[string]any{"passesOk": 1, "lastPass": lastPass, "inProgress": tc.mode == "cleaning-running", "currentStartNs": time.Now().UnixNano()}
if tc.mode == "cleaning-not-run" {
delete(maintenance, "lastPass")
maintenance["passesOk"] = 0
}
if tc.mode != "cleaning-missing" {
chunk["Maintenance"] = maintenance
}
var chunkValue any = chunk
impl := "walstore-chunk"
if tc.mode == "no-chunk-store" {
impl = "walstore"
chunkValue = nil
}
_ = json.NewEncoder(w).Encode(map[string]any{"Volumes": []any{map[string]any{"VolumeID": "v1", "Impl": impl, "Chunk": chunkValue}}})
}))
defer h.Close()
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", ln.Addr().String(), "-server-id", "host-b", "-status-addr", h.URL, "-c", "cluster.check -o json"}, &out, &errout)
rows := requireInspectionOutput(t, out.Bytes())
for _, r := range rows {
if r.Status == "FAIL" && (r.See != "docs/troubleshooting.md#"+strings.ReplaceAll(r.ID, ".", "") || r.Cure == "") {
t.Fatalf("failure lacks a working page link and cure: %+v", r)
}
}
if tc.id != "" {
want := "FAIL"
if tc.mode == "cleaning-running" || tc.mode == "cleaning-missing" || tc.mode == "retention-only" || tc.mode == "missing-cleaning-error" || tc.mode == "null-cleaning-error" || tc.mode == "missing-cleaning-head-gen" || tc.mode == "null-cleaning-head-gen" || tc.mode == "missing-cleaning-breakdown" || tc.mode == "no-chunk-store" {
want = "not checked here"
}
if tc.mode == "no-chunk-store" {
want = "not applicable"
}
r := rows[tc.id]
if r.Status != want {
t.Fatalf("typed outcome missing %+v want %s", r, want)
}
wantCode := 1
if want == "not checked here" || want == "not applicable" {
wantCode = 3
}
if code != wantCode {
t.Fatalf("exit=%d want%d out=%s", code, wantCode, &out)
}
if tc.mode == "no-chunk-store" {
capability := rows["volume.chunkstore"]
if capability.Status != "ok" || !strings.Contains(capability.Finding, "local engine only: no snapshots") {
t.Fatalf("local-engine capability wrong: %+v", capability)
}
for _, id := range []string{"volume.cut", "volume.cleaning"} {
r := rows[id]
if r.Status != "not applicable" || !strings.Contains(r.Finding, "no chunk store") {
t.Fatalf("local-engine operation not inapplicable: %+v", r)
}
}
}
return
}
if code != 3 {
t.Fatalf("expected incomplete only for missing filer, exit=%d out=%s", code, &out)
}
if tc.mode == "completed-head-gen-note" {
if finding := rows["volume.cleaning"].Finding; !strings.Contains(finding, "HEAD read unavailable after completed cleaning") {
t.Fatalf("completed cleaning lost generation-read note: %s", finding)
}
}
if tc.mode == "healthy" {
finding := rows["volume.cleaning"].Finding
for _, part := range []string{"planned=11", "removed=6", "plannedChunks=3", "plannedRoots=5", "plannedSegments=3", "removedChunks=2", "removedRoots=1", "removedSegments=3"} {
if !strings.Contains(finding, part) {
t.Fatalf("cleaning totals/breakdown omitted %s: %s", part, finding)
}
}
}
for _, r := range rows {
if r.ID != "filer.single" && r.Status != "ok" {
t.Fatalf("healthy typed source failed %+v", r)
}
}
})
}
}
type futureInspectionMaster struct{ inspectionControlServer }
func (futureInspectionMaster) GetClusterStatus(ctx context.Context, q *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) {
r, err := (inspectionControlServer{}).GetClusterStatus(ctx, q)
r.CapturedAt = timestamppb.New(time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC))
return r, err
}
func TestShellClockCannotCallAnOverflowingDifferenceOK(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
control.RegisterClusterEvidenceServiceServer(srv, futureInspectionMaster{})
go func() { _ = srv.Serve(ln) }()
defer srv.Stop()
defer ln.Close()
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", ln.Addr().String(), "-server-id", "host-b", "-c", "cluster.check -o json"}, &out, &errout)
rows := requireInspectionOutput(t, out.Bytes())
if r := rows["clock.skew"]; r.Status != "FAIL" || code != 1 {
t.Fatalf("impossible clock accepted: %+v exit%d", r, code)
}
}
func TestShellCheckNeverCallsOffHostChecksOK(t *testing.T) {
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
var out, errout bytes.Buffer
var requests atomic.Int32
holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
http.Error(w, "must not read off-host", 500)
}))
defer holder.Close()
code := run([]string{"shell", "-master", addr, "-server-id", "laptop", "-status-addr", holder.URL, "-c", "cluster.check -o json"}, &out, &errout)
if code == 2 || code == 0 {
t.Fatalf("command absent: %s", &errout)
}
rows := requireInspectionOutput(t, out.Bytes())
for _, r := range rows {
switch r.ID {
case "volume.frontend", "volume.chunkstore", "volume.cut", "volume.cleaning", "versions.equal", "clock.skew":
if r.Status != "not checked here" || !strings.Contains(r.Finding, "host-b") {
t.Fatalf("off-host claim: %+v", r)
}
}
}
if requests.Load() != 0 {
t.Fatal("read an off-host status page")
}
}
func TestShellCheckCuresAndOrderMatchTheTroubleshootingPage(t *testing.T) {
raw, err := os.ReadFile("../../docs/troubleshooting.md")
if err != nil {
t.Fatal(err)
}
sections := regexp.MustCompile(`(?m)^## `).Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), -1)[1:]
var checks []string
idHeading := regexp.MustCompile(`^[a-z]+\.[a-z]+$`)
for _, s := range sections {
name, _, _ := strings.Cut(s, "\n")
if idHeading.MatchString(strings.TrimSpace(name)) {
checks = append(checks, s)
}
}
if len(checks) != len(inspectionChecks) {
t.Fatal("page and command check counts differ")
}
for i, c := range inspectionChecks {
name, rest, _ := strings.Cut(checks[i], "\n")
paragraph, _, _ := strings.Cut(strings.TrimSpace(rest), "\n\n")
if strings.TrimSpace(name) != c.ID || strings.Join(strings.Fields(paragraph), " ") != c.Cure {
t.Fatalf("page/table mismatch at %s", c.ID)
}
}
}
func TestShellReadsQuotedCommandsFromStdinAndKeepsFailures(t *testing.T) {
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
var out, errout bytes.Buffer
code := runShell([]string{"-master", addr}, strings.NewReader("volume.delete 'v1'\nvolume.status 'v1' -o json\nquit\n"), &out, &errout)
if code != 2 || !strings.Contains(out.String(), `"volume_id":"v1"`) || !strings.Contains(errout.String(), "unknown inspection command") {
t.Fatalf("exit=%d out=%s err=%s", code, &out, &errout)
}
for _, bad := range []string{`volume.status 'v1`, `volume.status v1\`} {
if _, err := inspectionWords(bad); err == nil {
t.Fatalf("accepted %q", bad)
}
}
}
func TestShellCheckRefusesWrongHolderAndDoesNotFollowStatusRedirects(t *testing.T) {
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
for _, mode := range []string{"missing", "wrong-epoch", "missing-readiness", "redirect"} {
t.Run(mode, func(t *testing.T) {
var redirected atomic.Int32
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { redirected.Add(1) }))
defer target.Close()
h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if mode == "redirect" {
http.Redirect(w, r, target.URL, 302)
return
}
if r.URL.Path == "/status" {
body := map[string]any{"VolumeID": "v1", "ReplicaID": "r2", "Epoch": 2, "FrontendPrimaryReady": true, "Version": "test-rev"}
if mode == "wrong-epoch" {
body["Epoch"] = 3
}
if mode == "missing-readiness" {
delete(body, "FrontendPrimaryReady")
}
_ = json.NewEncoder(w).Encode(body)
return
}
fmtBody := map[string]any{"Volumes": []any{map[string]any{"VolumeID": "v1", "Chunk": map[string]any{"Stats": map[string]any{"LastCutNs": 1}}}}}
_ = json.NewEncoder(w).Encode(fmtBody)
}))
defer h.Close()
statusAddr := h.URL
if mode == "missing" {
statusAddr = ""
}
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", statusAddr, "-c", "cluster.check -o json"}, &out, &errout)
rows := requireInspectionOutput(t, out.Bytes())
if r := rows["volume.frontend"]; r.Status != "FAIL" || code != 1 {
t.Fatalf("wrong holder accepted %+v exit%d", r, code)
}
if redirected.Load() != 0 {
t.Fatal("followed a status redirect")
}
})
}
}