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

350 lines
13 KiB
Go

package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"sort"
"strings"
"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/status"
)
// clusterLifecycleDial opens the master's lifecycle service; a test
// replaces it.
var clusterLifecycleDial = func(addr string) (control.LifecycleServiceClient, func() error, error) {
conn, err := link.DialMasterFromEnv(addr)
if err != nil {
return nil, nil, err
}
return control.NewLifecycleServiceClient(conn), conn.Close, nil
}
// runCluster is "sw-block cluster finalize-format|format-level|retire-host".
func runCluster(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
fmt.Fprintln(stderr, "sw-block: expected subcommand cluster finalize-format|format-level|retire-host")
return ops.VolumeStatusExitInvalid
}
switch args[0] {
case "finalize-format":
return runClusterFinalizeFormat(args[1:], stdout, stderr)
case "format-level":
return runClusterFormatLevel(args[1:], stdout, stderr)
case "retire-host":
return runClusterRetireHost(args[1:], stdout, stderr)
}
fmt.Fprintf(stderr, "sw-block: unknown subcommand cluster %q\n", args[0])
return ops.VolumeStatusExitInvalid
}
// clusterFormatLevel reads the cluster's format level from the master.
func clusterFormatLevel(ctx context.Context, master string) (uint32, error) {
c, closeFn, err := clusterLifecycleDial(master)
if err != nil {
return 0, err
}
defer closeFn()
resp, err := c.FormatLevel(ctx, &control.FormatLevelRequest{})
if err != nil {
return 0, err
}
return resp.GetFormatLevel(), nil
}
// runClusterFormatLevel prints the cluster's format level: 0 (v1.0
// semantics; an upgraded cluster before its finalize) or 1.
func runClusterFormatLevel(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block cluster format-level", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster format-level --master host:port [--timeout 30s]")
return ops.VolumeStatusExitInvalid
}
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
level, err := clusterFormatLevel(ctx, *master)
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster format-level:", err)
return ops.VolumeStatusExitUnhealthy
}
fmt.Fprintf(stdout, "format level %d\n", level)
return 0
}
// finalize-format's exit codes, part of its contract: a script decides by
// them and by the --json answer, never by message text.
const (
finalizeExitOK = 0 // finalized, or already finalized
finalizeExitFailed = 1 // any other failure, a failed durable write included
finalizeExitRefused = 2 // the master refused: hosts below the level
finalizeExitTempFail = 75 // transient: the master unreachable (EX_TEMPFAIL)
)
// finalizeAnswer is finalize-format's --json answer, one shape for every
// outcome. Result is finalized, already, refused, unavailable or failed;
// Reason the master's typed reason (or the gRPC code, "" on success); Hosts
// the refused hosts, each with what it reported (empty otherwise); Listed the
// hosts the master could not confirm and did not block on (a held volume
// with no report, a host with no report, an old process holding no volume),
// on a refusal and on a finalize alike.
type finalizeAnswer struct {
Result string `json:"result"`
Reason string `json:"reason"`
Hosts []finalizeHost `json:"hosts"`
Listed []finalizeHost `json:"listed"`
FormatLevel uint32 `json:"format_level"`
Message string `json:"message"`
}
type finalizeHost struct {
Server string `json:"server"`
Reported string `json:"reported"`
}
// runClusterFinalizeFormat raises the cluster's format level to 1. Going
// back to v1.0.x works only before it: afterwards a v1.0.x master or holder
// refuses the store (an expected refusal, not damage). The master refuses
// it only while a process holding a volume reports a lower level, naming
// each one; the hosts it could not confirm are listed, not blocking.
func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int) {
fs := flag.NewFlagSet("sw-block cluster finalize-format", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
// The flag is declared for parsing and help only: the mode comes from the
// arguments as a whole, read before parsing, so a bad option in any
// position cannot leave it half-parsed.
fs.Bool("json", false, "print the typed answer as JSON: result, reason, hosts, listed, format_level, message")
jsonMode := jsonRequested(args)
jsonOut := &jsonMode
answer := finalizeAnswer{Hosts: []finalizeHost{}, Listed: []finalizeHost{}}
defer func() {
if *jsonOut {
if err := json.NewEncoder(stdout).Encode(answer); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster finalize-format: JSON output:", err)
if code == finalizeExitOK {
code = finalizeExitFailed // the answer a script reads was not written
}
}
}
}()
fail := func(result, reason, msg string, code int) int {
answer.Result, answer.Reason, answer.Message = result, reason, msg
fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", msg)
return code
}
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster finalize-format --master host:port [--timeout 30s] [--json]")
answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master is required"
return finalizeExitFailed
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
resp, err := c.FinalizeFormat(ctx, &control.FinalizeFormatRequest{Level: 1}, grpc.WaitForReady(false))
if err != nil {
msg := status.Convert(err).Message()
reason, md := lifecycleclient.ReasonDetail(err)
if reason == "" {
reason = status.Code(err).String()
}
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(clusterPolicyResult(p), reason, msg+"; "+p.Cure, p.Exit)
}
answer.FormatLevel = resp.GetFormatLevel()
for _, u := range resp.GetUnconfirmed() {
answer.Listed = append(answer.Listed, finalizeHost{Server: u.GetServerId(), Reported: u.GetDetail()})
if !*jsonOut {
fmt.Fprintf(stdout, "not confirmed, not blocking: %s (%s)\n", u.GetServerId(), u.GetDetail())
}
}
if resp.GetAlready() {
answer.Result, answer.Message = "already", "already finalized; nothing written"
if !*jsonOut {
fmt.Fprintf(stdout, "format level %d (already finalized; nothing written)\n", resp.GetFormatLevel())
}
return finalizeExitOK
}
answer.Result, answer.Message = "finalized", "v1.0.x binaries now refuse this cluster's stores; running v1.1 holders adopt the level at their next lease renewal"
if !*jsonOut {
fmt.Fprintf(stdout, "format level %d finalized: v1.0.x binaries now refuse this cluster's stores; running v1.1 holders adopt the level at their next lease renewal\n", resp.GetFormatLevel())
}
return finalizeExitOK
}
// jsonRequested says whether args ask for JSON output (-json, --json, or
// either with =true), read before flag parsing; the last one counts, and
// nothing after a "--" terminator does.
func jsonRequested(args []string) bool {
want := false
for _, a := range args {
if a == "--" {
break
}
name := strings.TrimLeft(a, "-")
if name == a {
continue // not an option
}
val := ""
if i := strings.IndexByte(name, '='); i >= 0 {
name, val = name[:i], name[i+1:]
}
if name != "json" {
continue
}
switch val {
case "", "1", "t", "T", "true", "TRUE", "True":
want = true
default:
want = false
}
}
return want
}
// metadataHosts reads the hosts keyed by prefix from the refusal's typed
// metadata, sorted by server id.
func metadataHosts(md map[string]string, prefix string) []finalizeHost {
hosts := []finalizeHost{}
for k, v := range md {
if server, ok := strings.CutPrefix(k, prefix); ok {
hosts = append(hosts, finalizeHost{Server: server, Reported: v})
}
}
sort.Slice(hosts, func(i, j int) bool { return hosts[i].Server < hosts[j].Server })
return hosts
}
// retireAnswer is retire-host's --json answer, one shape for every outcome.
// Result is retired, refused, unavailable or failed; Reason the master's
// typed reason (or the gRPC code, "" on success); Volumes the volumes the
// host still holds when the retire is refused for them (empty otherwise).
type retireAnswer struct {
Result string `json:"result"`
Reason string `json:"reason"`
Server string `json:"server"`
Volumes []string `json:"volumes"`
Message string `json:"message"`
}
// runClusterRetireHost removes a registered host from the node inventory.
// The master refuses it while the host holds a lease or an assignment. Exit
// codes as finalize-format's: 0 retired, 2 refused, 75 the master could not
// be reached (EX_TEMPFAIL), 1 any other failure, a usage error included.
func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) {
fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
server := fs.String("server", "", "the server id to retire (required)")
confirm := fs.String("confirm", "", "the same server id again (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
// Declared for parsing and help only; the mode is read from the
// arguments as a whole, so a bad option in any position cannot half-parse it.
fs.Bool("json", false, "print the typed answer as JSON: result, reason, server, volumes, message")
jsonMode := jsonRequested(args)
answer := retireAnswer{Volumes: []string{}}
defer func() {
if jsonMode {
if err := json.NewEncoder(stdout).Encode(answer); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host: JSON output:", err)
if code == finalizeExitOK {
code = finalizeExitFailed // the answer a script reads was not written
}
}
}
}()
fail := func(result, reason, msg string, code int) int {
answer.Result, answer.Reason, answer.Message = result, reason, msg
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", msg)
return code
}
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s] [--json]")
answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master, --server and --confirm are required"
return finalizeExitFailed
}
answer.Server = *server
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
p, detail := operatorAnswer(err, policy.Cluster)
return fail("failed", p.Code, detail.Error(), p.Exit)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
if _, err := c.RetireHost(ctx, &control.RetireHostRequest{ServerId: *server, Confirm: *confirm}); err != nil {
msg := status.Convert(err).Message()
reason, md := lifecycleclient.ReasonDetail(err)
if reason == "" {
reason = status.Code(err).String()
}
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.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 {
fmt.Fprintf(stdout, "host %s retired\n", *server)
}
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 {
vols := []string{}
for k := range md {
if v, ok := strings.CutPrefix(k, lifecycleclient.VolumeMetadataPrefix); ok {
vols = append(vols, v)
}
}
sort.Strings(vols)
return vols
}