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

658 lines
23 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"reflect"
"strings"
"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"
"google.golang.org/grpc/status"
)
type inspectionCheck struct {
ID, Title, Reach, Cure string
Run func(*inspectionObservation) checkFinding
}
// checkFinding is one check's outcome. Cure, when set, replaces the check's
// own cure: it names the cause this finding actually found (a holder that
// does not answer is not the check's usual fault).
type checkFinding struct{ Status, Finding, Cure string }
type inspectionResult struct {
ID, Title, Reach, Status, Finding string
Cure, See string `json:",omitempty"`
}
func checkOK(s string) checkFinding { return checkFinding{"ok", s, ""} }
func checkFail(s string) checkFinding { return checkFinding{"FAIL", s, ""} }
func checkElsewhere(s string) checkFinding { return checkFinding{"not checked here", s, ""} }
// stoppedFinding is every per-volume check's answer for a volume the master
// reports stopped cleanly: nothing serves it, on purpose. Not a FAIL.
var stoppedFinding = checkFinding{"stopped", "stopped cleanly (its holder released the lease); attach it to serve it", ""}
// holderUnreachableCure is the cure of every holder check whose holder status
// page did not answer: the check's own cure would name a fault it never saw.
const holderUnreachableCure = "the volume's holder did not answer its status page: check that its blockvolume runs (systemctl status) and that -status-addr is that holder's --status-addr, then run the check again."
// checkHolderFail is a holder check's FAIL for a status page that did not
// answer.
func checkHolderFail(err error) checkFinding {
return checkFinding{"FAIL", err.Error(), holderUnreachableCure}
}
type holderInspection struct {
VolumeID, ReplicaID, Version, NotReadyReason string
Epoch uint64
FrontendPrimaryReady *bool
}
type durableInspection struct {
ProcessID string
Volumes []struct {
VolumeID string
Impl string
Chunk *struct {
Maintenance *struct {
PassesOK *uint64 `json:"passesOk"`
InProgress *bool `json:"inProgress"`
CurrentStartNs *int64 `json:"currentStartNs"`
LastPass *struct {
AtNs *int64 `json:"atNs"`
Planned *uint64 `json:"planned"`
Removed *uint64 `json:"removed"`
Error *string `json:"error"`
HeadGen *uint64 `json:"headGen"`
HeadGenError *string `json:"headGenError"`
PlannedChunks *uint64 `json:"plannedChunks"`
PlannedRoots *uint64 `json:"plannedRoots"`
PlannedSegments *uint64 `json:"plannedSegments"`
RemovedChunks *uint64 `json:"removedChunks"`
RemovedRoots *uint64 `json:"removedRoots"`
RemovedSegments *uint64 `json:"removedSegments"`
} `json:"lastPass"`
}
Attached bool
Stats *struct {
LastCutNs *int64
CutsFailed *uint64
PendingUnresolved *bool
}
ScheduledSnapshot *struct {
Overdue bool `json:"snapshot_overdue"`
LastFailure *struct{ Code string } `json:"lastFailure"`
}
CurrentCut *struct {
Phase string `json:"phase"`
AttemptStartedAt time.Time `json:"attempt_started_at"`
}
}
}
}
type inspectedVolume struct {
evidence ops.VolumeEvidence
lease *control.WorkspaceStatus
leaseErr error
holder holderInspection
durable durableInspection
holderErr, durableErr error
notServed string // a local volume no given -status-addr serves
local bool
}
type inspectionObservation struct {
shell inspectionShell
cluster ops.ClusterEvidence
masterErr, lifecycleErr, filerErr error
filerChecked bool
started, ended time.Time
volumes []inspectedVolume
requested string
}
func (s inspectionShell) check(volume, format string, stdout, stderr io.Writer) int {
ctx, cancel := context.WithTimeout(context.Background(), s.timeout)
defer cancel()
return s.checkContext(ctx, volume, format, stdout, stderr)
}
func (s inspectionShell) checkContext(ctx context.Context, volume, format string, stdout, stderr io.Writer, volumeLimits ...int) int {
o := &inspectionObservation{shell: s, requested: volume, started: time.Now()}
o.cluster, o.masterErr = readMasterClusterEvidence(ctx, s.master)
o.ended = time.Now()
return s.checkObservation(ctx, o, format, stdout, stderr, volumeLimits...)
}
func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObservation, format string, stdout, stderr io.Writer, volumeLimits ...int) int {
volume := o.requested
if o.masterErr == nil {
conn, err := link.DialMasterFromEnv(s.master)
o.lifecycleErr = err
if err == nil {
defer conn.Close()
client := control.NewWorkspaceServiceClient(conn)
// A nonexistent name still distinguishes a missing lifecycle store or
// disabled RPC: blockmaster refuses those first, and answers an absent
// name only once both are in place.
_, err = client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "__cluster_check__"})
if status.Code(err) == codes.NotFound || (status.Code(err) == codes.FailedPrecondition && status.Convert(err).Message() == ops.WorkspaceVolumeAbsent) {
err = nil
}
o.lifecycleErr = err
volumes := o.cluster.Volumes
if len(volumeLimits) > 0 && volumeLimits[0] > 0 && len(volumes) > volumeLimits[0] {
volumes = volumes[:volumeLimits[0]]
}
for _, v := range volumes {
if volume != "" && v.VolumeID != volume {
continue
}
iv := inspectedVolume{evidence: v}
if v.Status == ops.ObservationStatusDeleting || v.Status == ops.ObservationStatusDeleted {
o.volumes = append(o.volumes, iv)
continue // no lease/status RPC of a deleted holder can delay another volume's checks
}
iv.lease, iv.leaseErr = client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: v.VolumeID})
iv.local = primaryInspectionHost(v) != "" && primaryInspectionHost(v) == s.serverID
if iv.local && v.Status != ops.ObservationStatusStopped {
addr, err := s.holderAddress(ctx, v.VolumeID, &iv.holder)
switch {
case errors.Is(err, errVolumeNotServedHere):
// Another holder on this host serves it; its address was not given.
iv.notServed = "no given -status-addr serves " + v.VolumeID + "; add its holder's status address"
case err != nil:
iv.holderErr, iv.durableErr = err, err
default:
if iv.holder.VolumeID != v.VolumeID || iv.holder.ReplicaID != v.PrimaryReplica || iv.holder.Epoch != v.Epoch {
iv.holderErr = errors.New("holder status identity differs from master's primary")
}
iv.durableErr = s.readHolderAt(ctx, addr, "/status/durable", v.VolumeID, &iv.durable)
}
}
o.volumes = append(o.volumes, iv)
}
}
}
if s.filer != "" {
o.filerChecked = true
f, closeF, err := dialChunkFiler(s.filer)
if err == nil {
err = checkSingleFiler(ctx, f)
_ = closeF()
}
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 {
f := c.Run(o)
if o.masterErr != nil && c.ID != "master.reachable" && c.ID != "filer.single" {
f = checkElsewhere("master did not answer; prerequisite unavailable")
}
r := inspectionResult{ID: c.ID, Title: c.Title, Reach: c.Reach, Status: f.Status, Finding: f.Finding}
r.Finding = strings.Join(strings.Fields(r.Finding), " ")
if f.Status == "FAIL" {
code = 1
r.Cure = c.Cure
if f.Cure != "" {
r.Cure = f.Cure
}
r.See = "docs/troubleshooting.md#" + strings.ReplaceAll(c.ID, ".", "")
} else if f.Status == "not checked here" && code == 0 {
code = 3
}
rows = append(rows, r)
}
if format == "json" {
if err := json.NewEncoder(stdout).Encode(rows); err != nil {
fmt.Fprintln(stderr, err)
return 1
}
} else {
for _, r := range rows {
fmt.Fprintf(stdout, "%s %s: %s\n", r.Status, r.ID, r.Finding)
if r.Status == "FAIL" {
fmt.Fprintf(stdout, " cure: %s; see %s\n", r.Cure, r.See)
}
}
}
return code
}
// errHolderStatusNotFound is a holder's 404: it does not serve that volume.
var errHolderStatusNotFound = errors.New("holder does not serve this volume")
// errVolumeNotServedHere: none of the given status addresses serves the volume.
var errVolumeNotServedHere = errors.New("no given status address serves this volume")
// holderAddress finds which given status address serves volume (one holder
// per volume) and reads its /status into dst.
func (s inspectionShell) holderAddress(ctx context.Context, volume string, dst any) (string, error) {
return s.holderRead(ctx, "/status", volume, dst)
}
// readHolder reads path for volume from whichever given status address
// serves it.
func (s inspectionShell) readHolder(ctx context.Context, path, volume string, dst any) error {
_, err := s.holderRead(ctx, path, volume, dst)
return err
}
// holderRead tries every given status address and returns the first that
// answers path for volume. An address that does not answer (a stopped holder
// on the same host) does not hide a later one that serves the volume. When
// none serves it, the first failure other than 404 is returned; only when
// every address answered 404 is it errVolumeNotServedHere.
func (s inspectionShell) holderRead(ctx context.Context, path, volume string, dst any) (string, error) {
if len(s.statusAddrs) == 0 {
return "", errors.New("status page is off: start blockvolume with --status-addr 127.0.0.1:<port>")
}
var failed error
for _, addr := range s.statusAddrs {
if v := reflect.ValueOf(dst); v.Kind() == reflect.Pointer && !v.IsNil() {
v.Elem().SetZero() // nothing a failed address decoded survives
}
err := s.readHolderAt(ctx, addr, path, volume, dst)
if err == nil {
return addr, nil
}
if !errors.Is(err, errHolderStatusNotFound) && failed == nil {
failed = err
}
}
if failed != nil {
return "", failed
}
return "", errVolumeNotServedHere
}
func (s inspectionShell) readHolderAt(ctx context.Context, addr, path, volume string, dst any) error {
base := addr
if !strings.Contains(base, "://") {
base = "http://" + base
}
u, err := url.Parse(base)
if err != nil {
return err
}
ip := net.ParseIP(u.Hostname())
if u.Scheme != "http" || ip == nil || !ip.IsLoopback() || u.User != nil || u.RawQuery != "" || (u.Path != "" && u.Path != "/") {
return errors.New("holder status requires an explicit loopback HTTP address")
}
u.Path = path
q := url.Values{}
q.Set("volume", volume)
u.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return err
}
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("status redirects are refused") }}
resp, err := answer.DoHTTP(client, req, answer.Unsent)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("%s returned HTTP 404: %w", path, errHolderStatusNotFound)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s returned HTTP %d", path, resp.StatusCode)
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, (2<<20)+1))
if err != nil {
return err
}
if len(raw) > 2<<20 {
return errors.New("status exceeds 2 MiB")
}
return json.Unmarshal(raw, dst)
}
func primaryInspectionHost(v ops.VolumeEvidence) string {
if v.PrimaryNode != "" {
return v.PrimaryNode
}
for _, r := range v.Replicas {
if r.ReplicaID == v.PrimaryReplica {
return r.ServerID
}
}
return ""
}
func (o *inspectionObservation) each(local bool, run func(inspectedVolume) checkFinding) checkFinding {
if len(o.volumes) == 0 {
return checkElsewhere("no selected volume evidence")
}
state := "ok"
allNotApplicable, allStopped := true, true
allDeleting, allDeleted := true, true
cure, plain := "", false // the failing volumes' cause-specific cure; plain: one failed for the check's own reason
parts := []string{}
for _, v := range o.volumes {
var f checkFinding
if v.evidence.Status == ops.ObservationStatusStopped {
f = stoppedFinding
} else if v.evidence.Status == ops.ObservationStatusDeleting || v.evidence.Status == ops.ObservationStatusDeleted {
f = checkFinding{Status: v.evidence.Status, Finding: "volume deletion admitted; no serving checks apply"}
} else if local && !v.local {
host := primaryInspectionHost(v.evidence)
if host == "" {
host = "unknown holder host"
}
f = checkElsewhere("run on " + host)
} else if local && v.notServed != "" {
f = checkElsewhere(v.notServed)
} else {
f = run(v)
}
if f.Status != "not applicable" {
allNotApplicable = false
}
if f.Status != "stopped" {
allStopped = false
}
if f.Status != ops.ObservationStatusDeleting {
allDeleting = false
}
if f.Status != ops.ObservationStatusDeleted {
allDeleted = false
}
if f.Status == "FAIL" {
state = "FAIL"
if f.Cure != "" && cure == "" {
cure = f.Cure
} else if f.Cure == "" {
plain = true
}
} else if f.Status == "not checked here" && state != "FAIL" {
state = "not checked here"
}
parts = append(parts, v.evidence.VolumeID+": "+f.Status+" "+f.Finding)
}
if state == "ok" && allNotApplicable {
state = "not applicable"
} else if state == "ok" && allStopped {
state = "stopped"
} else if state == "ok" && allDeleting {
state = ops.ObservationStatusDeleting
} else if state == "ok" && allDeleted {
state = ops.ObservationStatusDeleted
}
if plain {
cure = "" // a volume failed for the check's own reason: its own cure applies
}
return checkFinding{state, strings.Join(parts, "; "), cure}
}
func (o *inspectionObservation) reachable() checkFinding {
if o.masterErr != nil {
return checkFail(o.masterErr.Error())
}
return checkOK(o.shell.master + " answered")
}
func (o *inspectionObservation) lifecycle() checkFinding {
if o.lifecycleErr != nil {
return checkFail(o.lifecycleErr.Error())
}
return checkOK("workspace query accepted")
}
func (o *inspectionObservation) version() checkFinding {
if unknownInspectionVersion(o.cluster.ProductRevision) {
return checkFail("no version reported")
}
return checkOK(o.cluster.ProductRevision)
}
func unknownInspectionVersion(v string) bool {
return v == "" || strings.Contains(strings.ToLower(v), "unknown")
}
func (o *inspectionObservation) filer() checkFinding {
if !o.filerChecked {
return checkElsewhere("set shell -filer for the single-filer check")
}
if o.filerErr != nil {
return checkFail(o.filerErr.Error())
}
return checkOK("one filer in its group at this moment")
}
func (o *inspectionObservation) heartbeat() checkFinding {
return o.each(false, func(v inspectedVolume) checkFinding {
if len(v.evidence.Replicas) == 0 {
return checkFail("no slot observations")
}
for _, r := range v.evidence.Replicas {
if !r.Observed {
return checkFail(r.ServerID + " not observed")
}
}
return checkOK("all slots observed; age not available")
})
}
func (o *inspectionObservation) known() checkFinding {
if o.requested != "" && len(o.volumes) == 0 {
return checkFail(o.requested + " not found")
}
if len(o.volumes) == 0 {
return checkElsewhere("no volumes registered")
}
count := 0
for _, v := range o.volumes {
if v.evidence.Status != ops.ObservationStatusDeleting && v.evidence.Status != ops.ObservationStatusDeleted {
count++
}
}
return checkOK(fmt.Sprintf("%d volume records", count))
}
func (o *inspectionObservation) assigned() checkFinding {
return o.each(false, func(v inspectedVolume) checkFinding {
if v.evidence.Epoch == 0 || v.evidence.PrimaryReplica == "" {
return checkFail("no primary (epoch 0)")
}
return checkOK(fmt.Sprintf("%s@%d on %s", v.evidence.PrimaryReplica, v.evidence.Epoch, primaryInspectionHost(v.evidence)))
})
}
func (o *inspectionObservation) lease() checkFinding {
return o.each(false, func(v inspectedVolume) checkFinding {
if v.evidence.ReplicationFactor != 1 {
return checkElsewhere("workspace lease check applies to RF1")
}
if v.leaseErr != nil {
return checkFail(v.leaseErr.Error())
}
l := v.lease.GetLease()
if l == nil || l.GetEpoch() != v.evidence.Epoch || l.GetReplicaId() != v.evidence.PrimaryReplica || l.GetValidForNs() <= 0 || l.GetRevoking() {
return checkFail("lease absent, expired, revoking or differs from the observed primary")
}
return checkOK("granted, not revoking (master observation)")
})
}
func (o *inspectionObservation) frontend() checkFinding {
return o.each(true, func(v inspectedVolume) checkFinding {
if v.holderErr != nil {
return checkHolderFail(v.holderErr)
}
if v.holder.FrontendPrimaryReady == nil {
return checkFail("frontend readiness field unavailable")
}
if !*v.holder.FrontendPrimaryReady {
return checkFail(v.holder.NotReadyReason)
}
return checkOK("holder's frontend serves")
})
}
func (o *inspectionObservation) chunkstore() checkFinding {
return o.each(true, func(v inspectedVolume) checkFinding {
if v.holderErr != nil {
return checkHolderFail(v.holderErr)
}
if v.durableErr != nil {
return checkHolderFail(v.durableErr)
}
for _, d := range v.durable.Volumes {
if d.VolumeID != v.evidence.VolumeID {
continue
}
switch d.Impl {
case "walstore-chunk":
if d.Chunk == nil {
return checkElsewhere("chunk store status unavailable")
}
return checkOK("chunk store configured; snapshot observations follow")
case "walstore":
return checkOK("local engine only: no snapshots; not the supported configuration (start with a filer, see sw-block mini --weed)")
default:
return checkElsewhere("chunk store implementation unavailable")
}
}
return checkElsewhere("selected volume absent from durable status")
})
}
func (o *inspectionObservation) cut() checkFinding {
return o.each(true, func(v inspectedVolume) checkFinding {
if v.holderErr != nil {
return checkHolderFail(v.holderErr)
}
if v.durableErr != nil {
return checkHolderFail(v.durableErr)
}
for _, d := range v.durable.Volumes {
if d.VolumeID != v.evidence.VolumeID {
continue
}
if d.Impl == "walstore" {
return checkFinding{"not applicable", "no chunk store", ""}
}
if d.Chunk == nil || d.Chunk.Stats == nil {
return checkFail("cut counters unavailable")
}
c := d.Chunk
st := c.Stats
if st.LastCutNs == nil || st.CutsFailed == nil || st.PendingUnresolved == nil {
return checkFail("cut counter fields unavailable")
}
finding := fmt.Sprintf("last_cut_ns=%d historical_failures=%d", *st.LastCutNs, *st.CutsFailed)
if c.CurrentCut != nil {
finding += fmt.Sprintf(" cut in phase %s since %s", c.CurrentCut.Phase, c.CurrentCut.AttemptStartedAt.UTC().Format(time.RFC3339Nano))
}
if *st.PendingUnresolved {
return checkFail(finding + " pending HEAD outcome unresolved")
}
if c.ScheduledSnapshot != nil && c.ScheduledSnapshot.Overdue {
code := ""
if c.ScheduledSnapshot.LastFailure != nil {
code = c.ScheduledSnapshot.LastFailure.Code
}
return checkFail(finding + " snapshot_overdue " + code)
}
if *st.CutsFailed > 0 {
return checkElsewhere(finding + "; one observation cannot prove a new failure; see the holder log")
}
if *st.LastCutNs == 0 {
return checkElsewhere(finding + "; no completed cut since start")
}
return checkOK(finding)
}
return checkFail("selected volume absent from durable status")
})
}
func (o *inspectionObservation) cleaning() checkFinding {
return o.each(true, func(v inspectedVolume) checkFinding {
if v.holderErr != nil {
return checkHolderFail(v.holderErr)
}
if v.durableErr != nil {
return checkHolderFail(v.durableErr)
}
for _, d := range v.durable.Volumes {
if d.VolumeID != v.evidence.VolumeID {
continue
}
if d.Impl == "walstore" {
return checkFinding{"not applicable", "no chunk store", ""}
}
if d.Chunk == nil || d.Chunk.Maintenance == nil {
return checkElsewhere("last cleaning result not exposed by this build; see maintenance log")
}
m := d.Chunk.Maintenance
if m.PassesOK == nil || m.InProgress == nil || m.CurrentStartNs == nil {
return checkFail("maintenance counter fields unavailable")
}
if m.LastPass != nil && m.LastPass.Error != nil && *m.LastPass.Error != "" {
return checkFail("last cleaning pass: " + *m.LastPass.Error)
}
if *m.InProgress {
return checkElsewhere(fmt.Sprintf("cleaning in progress since %d; passesOk=%d", *m.CurrentStartNs, *m.PassesOK))
}
p := m.LastPass
if p == nil {
return checkFail("no cleaning pass completed since start")
}
if p.AtNs == nil || p.Planned == nil || p.Removed == nil || p.HeadGen == nil || p.Error == nil || p.PlannedChunks == nil || p.PlannedRoots == nil || p.PlannedSegments == nil || p.RemovedChunks == nil || p.RemovedRoots == nil || p.RemovedSegments == nil {
return checkElsewhere("last cleaning result fields unavailable")
}
if *p.HeadGen == 0 && (p.HeadGenError == nil || *p.HeadGenError == "") {
return checkElsewhere("cleaning HEAD generation unavailable; no observed cleaning pass")
}
if *p.AtNs <= 0 || *m.PassesOK == 0 {
return checkFail("no successful cleaning pass recorded")
}
finding := fmt.Sprintf("last pass at_ns=%d planned=%d removed=%d plannedChunks=%d plannedRoots=%d plannedSegments=%d removedChunks=%d removedRoots=%d removedSegments=%d head_gen=%d passesOk=%d", *p.AtNs, *p.Planned, *p.Removed, *p.PlannedChunks, *p.PlannedRoots, *p.PlannedSegments, *p.RemovedChunks, *p.RemovedRoots, *p.RemovedSegments, *p.HeadGen, *m.PassesOK)
if p.HeadGenError != nil && *p.HeadGenError != "" {
finding += fmt.Sprintf(" headGenError=%q", *p.HeadGenError)
}
return checkOK(finding)
}
return checkFail("selected volume absent from durable status")
})
}
func (o *inspectionObservation) versions() checkFinding {
return o.each(true, func(v inspectedVolume) checkFinding {
if v.holderErr != nil {
return checkHolderFail(v.holderErr)
}
if unknownInspectionVersion(o.cluster.ProductRevision) || unknownInspectionVersion(v.holder.Version) {
return checkFail("master or holder revision unavailable")
}
if o.cluster.ProductRevision != v.holder.Version {
return checkFail("blockmaster " + o.cluster.ProductRevision + ", blockvolume " + v.holder.Version)
}
return checkOK(v.holder.Version)
})
}
func (o *inspectionObservation) clock() checkFinding {
return o.each(true, func(v inspectedVolume) checkFinding {
if o.cluster.CapturedAt.IsZero() {
return checkFail("master time unavailable")
}
rtt := o.ended.Sub(o.started)
mid := o.started.Add(rtt / 2)
diff := mid.Sub(o.cluster.CapturedAt)
if diff < 0 {
diff = -diff
}
if diff < 0 {
return checkFail("clock difference exceeds the duration range")
}
finding := fmt.Sprintf("local clock difference %s plus RTT uncertainty %s; configured max skew %s", diff, rtt/2, o.shell.maxClockSkew)
limit := o.shell.maxClockSkew / 2
if diff >= limit || rtt/2 >= limit-diff {
return checkFail(finding)
}
return checkOK(finding)
})
}