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

213 lines
8.5 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"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
const chunkExitUnknown = 3
const chunkExitCutBusy = 4
// chunkObserveCut starts once, then reads status by the holder's in-memory ID.
// Only this cut's completed-step sequence renews observation.
// A chosen deadline remains absolute across every request.
func chunkObserveCut(addr string, window time.Duration, deadline time.Time, body map[string]any, stdout, stderr io.Writer) int {
return chunkObserveHandle("cut", "/chunk/cut", addr, window, deadline, body, stdout, stderr)
}
// chunkObserveHandle admits an observed operation at route (a cut, or a
// plain detach, CutTime r7) once, then reads its status by the handle's id
// on the shared /chunk/cut status route. Only this handle's sequence rises
// renew observation; a chosen deadline stays absolute.
func chunkObserveHandle(name, route, addr string, window time.Duration, deadline time.Time, body map[string]any, stdout, stderr io.Writer) int {
if window < time.Millisecond || window > time.Duration(1<<63-1)-cutObservationSlack {
return chunkFail(name, stdout, stderr, 2, codeBadRequestCLI, "--timeout must be at least 1ms and leave room for observation slack", false)
}
body["timeoutMs"] = window.Milliseconds()
if !deadline.IsZero() {
body["deadlineNs"] = deadline.UnixNano()
}
payload, err := json.Marshal(body)
if err != nil {
return chunkFail(name, stdout, stderr, 2, codeBadRequestCLI, err.Error(), false)
}
if !strings.Contains(addr, "://") {
addr = "http://" + addr
}
id := ""
last := time.Now()
seen := uint64(0)
bound := window + cutObservationSlack
// A 307/308 redirect can replay a POST inside Client.Do. An admission
// whose answer is ambiguous must remain unknown, never start again.
client := *chunkHTTPClient
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
unknown := func(why string) int {
if id != "" {
why += "; id " + id
}
return chunkFail(name, stdout, stderr, chunkExitUnknown, "outcome_unknown", why, true)
}
for {
until := last.Add(bound)
if !deadline.IsZero() && deadline.Before(until) {
until = deadline
}
if !time.Now().Before(until) {
return unknown(name + " observation window or explicit deadline expired")
}
ctx, cancel := context.WithDeadline(context.Background(), until)
method, endpoint := http.MethodPost, strings.TrimRight(addr, "/")+route
var requestBody io.Reader = bytes.NewReader(payload)
if id != "" {
method = http.MethodGet
endpoint = strings.TrimRight(addr, "/") + "/chunk/cut?" + url.Values{"volumeID": {fmt.Sprint(body["volumeID"])}, "cutID": {id}}.Encode()
requestBody = nil
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, requestBody)
if err != nil {
cancel()
return chunkFail(name, stdout, stderr, 2, codeBadRequestCLI, err.Error(), false)
}
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
phase := answer.Unsent
if id != "" {
phase = answer.PossiblyAdmitted
}
resp, err := answer.DoHTTP(&client, req, phase)
var raw []byte
if err != nil && id == "" {
cancel()
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")
}
if err == nil {
raw, err = io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit+1))
_ = resp.Body.Close()
if len(raw) > chunkResponseLimit {
err = fmt.Errorf("cut answer exceeds response limit")
}
}
cancel()
// Late sequence rises cannot revive silence already exhausted.
if !time.Now().Before(until) {
return unknown(name + " observation window or explicit deadline expired")
}
if err == nil {
var protocol struct {
Version json.RawMessage `json:"apiVersion"`
}
protocolErr := json.Unmarshal(raw, &protocol)
versionText := strings.TrimSpace(string(protocol.Version))
if versionText == "" {
versionText = "missing"
}
var version int
supported := protocolErr == nil && versionText != "null" && json.Unmarshal(protocol.Version, &version) == nil && version >= max(0, chunkstore.CutAPIVersion-1) && version <= chunkstore.CutAPIVersion
// Only an initial, unversioned synchronous 200 can be a v1.0 answer.
// A polling answer must always identify its response protocol.
legacy := protocolErr == nil && len(protocol.Version) == 0 && id == "" && resp.StatusCode == http.StatusOK
unsupported := func() int {
// An unsupported protocol cannot prove non-admission, even on
// an initial error: the worker may have finished before its reply.
return chunkFail("cut", stdout, stderr, chunkExitUnknown, "unsupported_api_version", fmt.Sprintf("server cut API version %s is unsupported by CLI version %d (supports %d and %d); cut outcome not established", versionText, chunkstore.CutAPIVersion, chunkstore.CutAPIVersion, max(0, chunkstore.CutAPIVersion-1)), false)
}
if !supported && !legacy {
return unsupported()
}
if resp.StatusCode == http.StatusOK {
var result struct {
VolumeID string `json:"volumeID"`
CutID string `json:"cutID"`
CutLSN *uint64 `json:"cutLSN"`
HeadGen *uint64 `json:"headGen"`
}
if json.Unmarshal(raw, &result) == nil && (id == "" || result.CutID == id) && result.VolumeID == body["volumeID"] && (result.CutLSN != nil || name == "detach") && result.HeadGen != nil && (!legacy || result.CutID == "") {
if err := writeAll(stdout, raw); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err)
return chunkExitFailed
}
return 0
}
}
if legacy {
return unsupported()
}
var answer struct {
Code string `json:"code"`
Message string `json:"message"`
ID string `json:"cutID"`
Sequence uint64 `json:"sequence"`
Retryable bool `json:"retryable"`
}
if json.Unmarshal(raw, &answer) == nil && answer.Code != "" {
if resp.StatusCode == http.StatusAccepted && answer.Code == "in_progress" {
if id == "" && answer.ID != "" {
id = answer.ID
fmt.Fprintf(stderr, "sw-block ops chunk "+name+": id %s\n", id)
}
if answer.ID == id && answer.Sequence > seen {
seen = answer.Sequence
last = time.Now()
}
} else if id == "" && answer.Code == "cut_busy" {
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, answer.Code, answer.Message)
if err := writeAll(stdout, raw); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err)
return chunkExitFailed
}
return chunkExitCutBusy
} else if id == "" && name == "detach" && resp.StatusCode != http.StatusAccepted && answer.ID == "" {
// A plain detach refused at admission started nothing: report the
// typed refusal as it is (the detach keeps its existing failure answer).
if err := writeAll(stdout, raw); err != nil {
return chunkExitFailed
}
return chunkExitFailed
} else if answer.Code == "unknown_cut_id" && answer.ID == id && id != "" {
return unknown("holder no longer knows this id")
} else if answer.Code == "outcome_unknown" && answer.ID == id && id != "" {
return unknown(name + " publication settlement exhausted its progress window")
} else if (id == "" || answer.ID == id) && (answer.Code == "cut_stalled" || (!answer.Retryable && answer.Code != "outcome_unknown")) {
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, answer.Code, answer.Message)
if err := writeAll(stdout, raw); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err)
return chunkExitFailed
}
return chunkExitFailed
}
}
}
if id == "" {
if err != nil {
return unknown(name + " admission answer could not be read: " + err.Error())
}
return unknown(name + " admission answer did not identify its outcome")
}
// Prompt short polling keeps the observation gap within the modeled slack.
next := last.Add(bound)
if !deadline.IsZero() && deadline.Before(next) {
next = deadline
}
pause := min(100*time.Millisecond, max(time.Duration(0), time.Until(next)))
if pause > 0 {
time.Sleep(pause)
}
}
}