From ccff48ea29b4dfec3344127dacbea4b3f60cfd2a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 13:51:54 -0800 Subject: [PATCH] ublk, volume: request counters and /status/ublk for the fsync gate The ublk handler counts every received request by kind before the backend call (reads, writes, FUA writes, flushes, other) and the requests that completed with an error. blockvolume wires the device as the status server's ublk source: GET /status/ublk?volume= returns them, as /status/nvme returns the NVMe target's, so the D0 gate can show every guest fsync reaching the ublk FLUSH and Backend.Sync. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 3 + .../core/frontend/ublk/device_linux.go | 7 ++- .../core/frontend/ublk/device_unsupported.go | 3 + seaweed-block/core/frontend/ublk/dispatch.go | 58 ++++++++++++++++++- .../core/frontend/ublk/dispatch_test.go | 23 ++++++++ seaweed-block/core/frontend/ublk/target.go | 11 ++++ .../core/host/volume/status_server.go | 51 ++++++++++++++++ .../core/host/volume/status_server_test.go | 44 ++++++++++++++ 8 files changed, 198 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 8baac43025..78a505bf74 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1199,6 +1199,9 @@ func run(f flags) int { _ = h.Close() return 1 } + if status != nil { + status.SetUblkStatusSource(ublkTarget) + } _ = json.NewEncoder(os.Stdout).Encode(ublkReadyLine{ Component: "blockvolume", Phase: "ublk-ready", diff --git a/seaweed-block/core/frontend/ublk/device_linux.go b/seaweed-block/core/frontend/ublk/device_linux.go index 9f0d56f0ff..16b9bce72a 100644 --- a/seaweed-block/core/frontend/ublk/device_linux.go +++ b/seaweed-block/core/frontend/ublk/device_linux.go @@ -28,6 +28,7 @@ type Device struct { ctrl *uring charFD int queues []*queue + stats *counters cancel context.CancelFunc closeOnce sync.Once @@ -121,7 +122,8 @@ func Start(cfg Config) (*Device, error) { ctx, cancel := context.WithCancel(context.Background()) d.cancel = cancel - h := handler{backend: cfg.Backend, size: cfg.Size} + d.stats = &counters{} + h := handler{backend: cfg.Backend, size: cfg.Size, stats: d.stats} for q := 0; q < cfg.Queues; q++ { qu, err := newQueue(q, cfg, d.charFD, h) if err != nil { @@ -144,6 +146,9 @@ func Start(cfg Config) (*Device, error) { // Path is the block device, /dev/ublkbN. func (d *Device) Path() string { return d.path } +// Stats returns the request counters since the device started. +func (d *Device) Stats() Stats { return d.stats.snapshot() } + // Close stops the device (outstanding fetches abort), waits for the queue // threads, and deletes the device. func (d *Device) Close() error { diff --git a/seaweed-block/core/frontend/ublk/device_unsupported.go b/seaweed-block/core/frontend/ublk/device_unsupported.go index 4baa8d53a1..18b0d08366 100644 --- a/seaweed-block/core/frontend/ublk/device_unsupported.go +++ b/seaweed-block/core/frontend/ublk/device_unsupported.go @@ -21,5 +21,8 @@ func Start(cfg Config) (*Device, error) { // Path is empty off Linux. func (d *Device) Path() string { return "" } +// Stats is empty off Linux. +func (d *Device) Stats() Stats { return Stats{} } + // Close is a no-op off Linux. func (d *Device) Close() error { return nil } diff --git a/seaweed-block/core/frontend/ublk/dispatch.go b/seaweed-block/core/frontend/ublk/dispatch.go index 8292ffdeb2..0904262661 100644 --- a/seaweed-block/core/frontend/ublk/dispatch.go +++ b/seaweed-block/core/frontend/ublk/dispatch.go @@ -2,6 +2,7 @@ package ublk import ( "context" + "sync/atomic" "syscall" ) @@ -38,13 +39,68 @@ type request struct { // handler maps ublk requests onto a Backend. type handler struct { backend Backend - size uint64 // device size in bytes + size uint64 // device size in bytes + stats *counters // nil: not counted +} + +// Stats are the device's request counters since it started. A request is +// counted when it is received, before the backend call; Errors counts the +// requests that completed with a negative result. +type Stats struct { + ReadRequests uint64 `json:"read_requests"` + WriteRequests uint64 `json:"write_requests"` + FlushRequests uint64 `json:"flush_requests"` + FUAWrites uint64 `json:"fua_writes"` + OtherRequests uint64 `json:"other_requests"` + Errors uint64 `json:"errors"` +} + +type counters struct { + reads, writes, flushes, fuaWrites, others, errors atomic.Uint64 +} + +func (c *counters) snapshot() Stats { + if c == nil { + return Stats{} + } + return Stats{ + ReadRequests: c.reads.Load(), WriteRequests: c.writes.Load(), FlushRequests: c.flushes.Load(), + FUAWrites: c.fuaWrites.Load(), OtherRequests: c.others.Load(), Errors: c.errors.Load(), + } +} + +func (c *counters) count(r request) { + if c == nil { + return + } + switch r.op { + case ioOpRead: + c.reads.Add(1) + case ioOpWrite: + c.writes.Add(1) + if r.flags&ioFlagFUA != 0 { + c.fuaWrites.Add(1) + } + case ioOpFlush: + c.flushes.Add(1) + default: + c.others.Add(1) + } } // handle serves one request against buf (len >= nrSectors<<9 for reads // and writes) and returns the ublk result: bytes transferred, 0 for a // flush, or a negative errno. func (h handler) handle(ctx context.Context, r request, buf []byte) int32 { + h.stats.count(r) + res := h.serve(ctx, r, buf) + if res < 0 && h.stats != nil { + h.stats.errors.Add(1) + } + return res +} + +func (h handler) serve(ctx context.Context, r request, buf []byte) int32 { switch r.op { case ioOpFlush: if err := h.backend.Sync(ctx); err != nil { diff --git a/seaweed-block/core/frontend/ublk/dispatch_test.go b/seaweed-block/core/frontend/ublk/dispatch_test.go index 309b0400c3..12eda08572 100644 --- a/seaweed-block/core/frontend/ublk/dispatch_test.go +++ b/seaweed-block/core/frontend/ublk/dispatch_test.go @@ -164,3 +164,26 @@ func TestDispatch_UnsupportedOperations(t *testing.T) { } } } + +// The counters the fsync gate reads: every received request is counted +// by kind before the backend call, FUA writes separately, and failures. +func TestDispatch_CountersCountReceivedRequests(t *testing.T) { + c := &counters{} + h := handler{backend: &failingBackend{failSync: true, err: errors.New("boom")}, size: testSize, stats: c} + ctx := context.Background() + buf := make([]byte, 4096) + h.handle(ctx, request{op: ioOpRead, nrSectors: 8}, buf) + h.handle(ctx, request{op: ioOpWrite, nrSectors: 8}, buf) + h.handle(ctx, request{op: ioOpWrite, flags: ioFlagFUA, nrSectors: 8}, buf) // sync fails -> error + h.handle(ctx, request{op: ioOpFlush}, nil) // sync fails -> error + h.handle(ctx, request{op: ioOpFlush}, nil) + h.handle(ctx, request{op: ioOpDiscard, nrSectors: 8}, buf) // -EOPNOTSUPP -> error + got := c.snapshot() + want := Stats{ReadRequests: 1, WriteRequests: 2, FUAWrites: 1, FlushRequests: 2, OtherRequests: 1, Errors: 4} + if got != want { + t.Fatalf("counters %+v, want %+v", got, want) + } + if (handler{backend: &failingBackend{}, size: testSize}).handle(ctx, request{op: ioOpFlush}, nil) != 0 { + t.Fatal("an uncounted handler failed a flush") + } +} diff --git a/seaweed-block/core/frontend/ublk/target.go b/seaweed-block/core/frontend/ublk/target.go index 451e267041..a8721e6f84 100644 --- a/seaweed-block/core/frontend/ublk/target.go +++ b/seaweed-block/core/frontend/ublk/target.go @@ -59,6 +59,17 @@ func (t *Target) Start() (string, error) { return d.Path(), nil } +// Stats returns the device's request counters (zero before Start). +func (t *Target) Stats() Stats { + t.mu.Lock() + d := t.device + t.mu.Unlock() + if d == nil { + return Stats{} + } + return d.Stats() +} + // Close stops and deletes the device. func (t *Target) Close() error { if t == nil { diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 2f9df2b7db..4b0d8e193e 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -14,6 +14,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/frontend/ublk" "github.com/seaweedfs/seaweed-block/core/replication" ) @@ -45,6 +46,10 @@ import ( // -> 200 JSON read-only NVMe target counters (when a TCP target is wired) // -> 404 (wrong volume or no TCP source) // +// GET /status/ublk?volume= +// -> 200 JSON read-only ublk device request counters (when wired) +// -> 404 (wrong volume or no ublk device) +// // The server binds on a caller-supplied addr (":0" for tests); // the actual bound addr is available via Addr() after Start. type StatusServer struct { @@ -60,6 +65,7 @@ type StatusServer struct { peerSource peerStatusSource durableSource durableStatusSource nvmeSource nvmeStatusSource + ublkSource ublkStatusSource runtimeSource runtimeRecoverySource frontendCaps []FrontendTransportCapability chunkEnabled bool // gates /chunk/*; off by default @@ -78,6 +84,10 @@ type nvmeStatusSource interface { Stats() nvme.Stats } +type ublkStatusSource interface { + Stats() ublk.Stats +} + type runtimeRecoverySource interface { StartRuntimeRecovery(context.Context, replication.RuntimeRecoveryRequest) error RuntimeRecoveryStatus(context.Context, replication.RuntimeRecoveryRequest) (replication.RuntimeRecoveryStatus, error) @@ -139,6 +149,12 @@ type NVMeStatus struct { Stats nvme.Stats `json:"stats"` } +// UblkStatus is the /status/ublk body: the ublk device's request counters. +type UblkStatus struct { + VolumeID string `json:"volumeID"` + Stats ublk.Stats `json:"stats"` +} + const ( AuthorityRolePrimary = "primary" AuthorityRoleSuperseded = "superseded" @@ -228,6 +244,14 @@ func (s *StatusServer) SetDurableStatusSource(src durableStatusSource) { s.durableSource = src } +// SetUblkStatusSource enables /status/ublk with the ublk device's counters. +// It may be called before or after Start. +func (s *StatusServer) SetUblkStatusSource(src ublkStatusSource) { + s.mu.Lock() + defer s.mu.Unlock() + s.ublkSource = src +} + // SetNVMeStatusSource enables /status/nvme with a read-only target snapshot. // It may be called before or after Start. func (s *StatusServer) SetNVMeStatusSource(src nvmeStatusSource) { @@ -280,6 +304,7 @@ func (s *StatusServer) Start(addr string) (string, error) { mux.HandleFunc("/status/peers", s.handleStatusPeers) mux.HandleFunc("/status/durable", s.handleStatusDurable) mux.HandleFunc("/status/nvme", s.handleStatusNVMe) + mux.HandleFunc("/status/ublk", s.handleStatusUblk) mux.HandleFunc("/status/frontend-capabilities", s.handleFrontendCapabilities) if s.recoveryEnabled { mux.HandleFunc("/status/recovery", s.handleStatusRecovery) @@ -367,6 +392,32 @@ func (s *StatusServer) handleFrontendCapabilities(w http.ResponseWriter, r *http }) } +func (s *StatusServer) handleStatusUblk(w http.ResponseWriter, r *http.Request) { + if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { + http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden) + return + } + vol := r.URL.Query().Get("volume") + if vol == "" { + http.Error(w, "missing volume query param", http.StatusBadRequest) + return + } + p := s.statusProjection() + if p.VolumeID != vol { + http.Error(w, fmt.Sprintf("volume %q not served by this host (serves %q)", vol, p.VolumeID), http.StatusNotFound) + return + } + s.mu.Lock() + src := s.ublkSource + s.mu.Unlock() + if src == nil { + http.Error(w, "ublk status source unavailable", http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(UblkStatus{VolumeID: p.VolumeID, Stats: src.Stats()}) +} + func (s *StatusServer) handleStatusNVMe(w http.ResponseWriter, r *http.Request) { if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden) diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index e0b1843556..50fffb65d1 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -17,6 +17,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/frontend/ublk" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -1133,3 +1134,46 @@ func containsString(values []string, want string) bool { } return false } + +type stubUblkStatusSource struct{ stats ublk.Stats } + +func (s stubUblkStatusSource) Stats() ublk.Stats { return s.stats } + +func TestStatusServer_UblkStatusEndpoint(t *testing.T) { + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatalf("start: %v", err) + } + defer func() { _ = s.Close(context.Background()) }() + resp, err := http.Get("http://" + addr + "/status/ublk?volume=v1") + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("without a ublk device: %d, want 404", resp.StatusCode) + } + s.SetUblkStatusSource(stubUblkStatusSource{stats: ublk.Stats{FlushRequests: 4002, FUAWrites: 3, WriteRequests: 9}}) + for _, tc := range []struct { + vol string + code int + }{{"v2", http.StatusNotFound}, {"v1", http.StatusOK}} { + resp, err := http.Get("http://" + addr + "/status/ublk?volume=" + tc.vol) + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != tc.code { + resp.Body.Close() + t.Fatalf("volume %s: %d, want %d", tc.vol, resp.StatusCode, tc.code) + } + if tc.code == http.StatusOK { + var body UblkStatus + err := json.NewDecoder(resp.Body).Decode(&body) + if err != nil || body.VolumeID != "v1" || body.Stats.FlushRequests != 4002 || body.Stats.FUAWrites != 3 { + t.Fatalf("body %+v err %v", body, err) + } + } + resp.Body.Close() + } +}