Repository navigation
feat(node)!: drain running views on shutdown - #2417
mbrandenburger merged 4 commits into
Conversation
On SIGTERM, SIGINT or `Node.Stop` a node now lets running views finish before it stops, and stops its components in an order where none outlives what it uses. Before, `Node.Stop` cancelled a context and returned, and the web, gRPC and operations servers, the KVS, the Fabric network provider and the comm service each tore down in a goroutine of their own, so the KVS could close under a component still using it. The shutdown runs in four steps: - Drain. `/readyz` answers 503 with reason `draining`, the gRPC health service reports `NOT_SERVING` and `fsc_shutdown_draining` is 1. A new view-API command gets gRPC `Unavailable` (HTTP 503, WebSocket close 1013). A new P2P protocol gets `draining: node is draining`, unless the sender already takes part in the responder context it names. - Wait for running views, for at most `fsc.shutdown.drainTimeout` (default 30s). At the deadline, initiator views still running are cancelled with `view.ErrCancelledByShutdown`, which the view API returns as gRPC `Aborted` (HTTP 409), since such a view may have submitted a transaction that still commits. - Cancel the node context. - Call `Stop()` on every SDK in reverse install order, within `fsc.shutdown.teardownTimeout` (default 30s). The Fabric SDK stops its networks, then the view SDK stops its servers, the comm service and the KVS. A second signal or `Stop` call skips the rest of the drain. `pkg/node` finds the drain as a `node.Drainer` in the node's registry, where the view SDK registers the view manager. Wrapper SDKs embed the `commondig.SDK` interface, so a method on the SDK itself would not reach `pkg/node` through them. No method is added to an SDK interface. The view manager counts initiator views, views the view service runs and responders from the moment the P2P service admits their first message. An initiator whose session gets a `draining: ` reply retires its cached WebSocket connections to that peer through the new optional `host.RetiringHost`. Open sessions keep their connection, and the next session dials again, so a load balancer can route it to another replica. Breaking for view-API clients: a view cancelled by shutdown ends the call with gRPC `Aborted` (HTTP 409) rather than an error response. The Go client reports it as a status error on both transports. docs/platform/view/services/shutdown.md describes the order, what clients and peers see, load balancers and Kubernetes settings. docs/upgrade/v0.26-to-v0.27.md lists the operator and developer changes. Fixes hyperledger-labs#2410 Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
|
Hey @mbrandenburger 👋 thanks for the PR! This comment updates automatically as you push changes -- think of it as your PR's live scoreboard! PR Checks✅ DCO Sign-off -- All commits have valid sign-offs. Nice work! ❌ GPG Signature -- Heads up! The following commits don't have a verified GPG signature:
You'll need to sign your commits with GPG (e.g. ✅ Merge Conflicts -- No merge conflicts detected. Smooth sailing! ✅ Issue Link -- Linked to #2410 (assigned to you). ⏳ All checks must pass before this PR can be reviewed. You've got this! |
Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
SaidAltury-ibm
left a comment
There was a problem hiding this comment.
thank you @mbrandenburger , i have left a comment
| // The SDK reports NOT_SERVING while the node drains. | ||
| HealthCheckEnabled: true, |
There was a problem hiding this comment.
HealthCheckEnabled: true here means fsc.grpc always registers grpc.health.v1.Health. That is the right default for the drain, but it is a second breaking change for embedders, and the commit body's "Breaking" paragraph mentions only the Aborted change — could you add it there too, since that text becomes the release note?
Also, the upgrade guide says a second registration "panics at startup". It is actually worse: gRPC reports duplicate registration through grpclog.Fatalf, so the process exits and the app cannot recover or defer around it:
FATA [grpc] [core] grpc: Server.RegisterService found duplicate service registration for "grpc.health.v1.Health"
Suggest "exits at startup" rather than "panics at startup" in docs/upgrade/v0.26-to-v0.27.md and docs/configuration.md, so readers don't plan to recover from it.
There was a problem hiding this comment.
Good catch, updated.
feat(node)!: drain running views on shutdown On SIGTERM, SIGINT or `Node.Stop` a node now lets running views finish before it stops, and stops its components in an order where none outlives what it uses. Before, `Node.Stop` cancelled a context and returned, and the web, gRPC and operations servers, the KVS, the Fabric network provider and the comm service each tore down in a goroutine of their own, so the KVS could close under a component still using it. The shutdown runs in four steps: - Drain. `/readyz` answers 503 with reason `draining`, the gRPC health service reports `NOT_SERVING` and `fsc_shutdown_draining` is 1. A new view-API command gets gRPC `Unavailable` (HTTP 503, WebSocket close 1013). A new P2P protocol gets `draining: node is draining`, unless the sender already takes part in the responder context it names. - Wait for running views, for at most `fsc.shutdown.drainTimeout` (default 30s). At the deadline, initiator views still running are cancelled with `view.ErrCancelledByShutdown`, which the view API returns as gRPC `Aborted` (HTTP 409), since such a view may have submitted a transaction that still commits. - Cancel the node context. - Call `Stop()` on every SDK in reverse install order, within `fsc.shutdown.teardownTimeout` (default 30s). The Fabric SDK stops its networks, then the view SDK stops its servers, the comm service and the KVS. A second signal or `Stop` call skips the rest of the drain. `pkg/node` finds the drain as a `node.Drainer` in the node's registry, where the view SDK registers the view manager. Wrapper SDKs embed the `commondig.SDK` interface, so a method on the SDK itself would not reach `pkg/node` through them. No method is added to an SDK interface. The view manager counts initiator views, view-API commands and responders from the moment they are admitted, checking for a drain and counting in one step. A view's context is cancelled only at the drain deadline, not when the view returns. The comm service runs until the view SDK's `Stop`, after the servers, so responders cancelled with the node context can still reply. An initiator whose session gets a `draining: ` reply retires its cached WebSocket connections to that peer through the new optional `host.RetiringHost`. Open sessions keep their connection, and the next session dials again, so a load balancer can route it to another replica. Breaking changes: - View-API clients: a view cancelled by shutdown ends the call with gRPC `Aborted` (HTTP 409, WebSocket close 1011) rather than an error response. The Go client reports it as a status error on both transports. - Embedders: the `fsc.grpc` listener always registers the gRPC health service (`grpc.health.v1.Health`), which reports `NOT_SERVING` while the node drains. An application that registers it on that listener itself must stop: gRPC reports the duplicate registration as fatal and the process exits at startup. docs/platform/view/services/shutdown.md describes the order, what clients and peers see, load balancers and Kubernetes settings. docs/upgrade/v0.26-to-v0.27.md lists the operator and developer changes. Fixes hyperledger-labs#2410 Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
|
This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again. |
v0.27.0 is tagged at hyperledger-labs#2415, so everything merged after it ships in v0.28.0. The drain on shutdown (hyperledger-labs#2417) merged after the tag but was documented in the v0.26 to v0.27 guide; its operator section, metric, developer note and checklist rows move to the v0.27 to v0.28 guide, and the v0.26 to v0.27 guide is back to its state at the tag. The v0.27 to v0.28 guide gains what it left out: - the view service symbols removed in hyperledger-labs#2426 - the websocket keepalive (hyperledger-labs#2428) - channel keys on transactions sent between nodes and their routing to the local network, with driver.Channel.ChannelKey, RequireChannelKey and NewTransactionFromEnvelopeBytesOn (hyperledger-labs#2466) - Fabric-x proposal responses without namespaces being refused, and session IDs kept apart per sender (hyperledger-labs#2419) - views that stop waiting for a reply when their context ends, and session.ReadMessageWithContext (hyperledger-labs#2471) - the vault keeping a Valid status on a Busy write (hyperledger-labs#2420) - node migrate --forget-opener, exit 12 with --check --contract, which stores node migrate reaches, and the limits of queryTimeout and migrationLockTimeout It also corrects claims that did not match the code: which endorse transactions stay JSON after the contract step (keyless Fabric rows convert), that stores keep bytes they cannot convert, gob metadata the protobuf form cannot carry, SQLite locking during a step, the error a recipient responder without a signer sends, how nwo starts nodes, the connection state component on Fabric-x, and the default channel RequestRecipientIdentity verifies on. Fabric-only and Fabric-x-only items are marked as such, and the warning about new stores during a mixed-version window is stated once. Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
v0.27.0 is tagged at #2415, so everything merged after it ships in v0.28.0. The drain on shutdown (#2417) merged after the tag but was documented in the v0.26 to v0.27 guide; its operator section, metric, developer note and checklist rows move to the v0.27 to v0.28 guide, and the v0.26 to v0.27 guide is back to its state at the tag. The v0.27 to v0.28 guide gains what it left out: - the view service symbols removed in #2426 - the websocket keepalive (#2428) - channel keys on transactions sent between nodes and their routing to the local network, with driver.Channel.ChannelKey, RequireChannelKey and NewTransactionFromEnvelopeBytesOn (#2466) - Fabric-x proposal responses without namespaces being refused, and session IDs kept apart per sender (#2419) - views that stop waiting for a reply when their context ends, and session.ReadMessageWithContext (#2471) - the vault keeping a Valid status on a Busy write (#2420) - node migrate --forget-opener, exit 12 with --check --contract, which stores node migrate reaches, and the limits of queryTimeout and migrationLockTimeout It also corrects claims that did not match the code: which endorse transactions stay JSON after the contract step (keyless Fabric rows convert), that stores keep bytes they cannot convert, gob metadata the protobuf form cannot carry, SQLite locking during a step, the error a recipient responder without a signer sends, how nwo starts nodes, the connection state component on Fabric-x, and the default channel RequestRecipientIdentity verifies on. Fabric-only and Fabric-x-only items are marked as such, and the warning about new stores during a mixed-version window is stated once. Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
Fixes #2410.
Problem
Node.Stopcancelled a context and returned at once. The web, gRPC and operations servers and the KVS stopped in one goroutine, the Fabric network provider in another, the comm service in a third, and nothing ordered them, so the KVS could close under a component still using it./readyzdid not change while the node stopped, so a load balancer kept sending traffic, and running views and view-API calls were cut off. Proof tests onmain(since replaced by the tests in this PR) showed thatNode.Stopreturned before any SDK tore down, that no SDK'sStop()was ever called, and that a second SDK's teardown found the KVS closed.Changes
Order (
pkg/node,node/start)Node.Stopdrains through thenode.Drainerin the node registry (fsc.shutdown.drainTimeout, default 30s, logging every 5s), cancels the node context, then callsStop()on every SDK in reverse install order (fsc.shutdown.teardownTimeout, default 30s) and logs the total time.Stopor signal skips the rest of the drain.node startuses its ownsignal.Notifychannel, becausesignal.NotifyContextreports only the first signal.Running views (
platform/view/services/view)Drain,Draining,Track,TryTrack,OnDrainandIsParty. It countsInitiateViewand its variants, view-API commands from the moment the gate admits them, and responders from the moment the P2P service admits them.TryTrackchecks for a drain and counts in one step, so a drain that starts concurrently either refuses new work or waits for it. While draining it logs every 5s how many views still run. A count with an idle channel replaces async.WaitGroup, which panicked when a view started whileDrainwaited (a stress test reproduced it).context.AfterFunc. At the deadlineDraincancels it withview.ErrCancelledByShutdownand waits at most one more second, so the view service still answers the cancelled views before the servers stop.DeleteContextonly unregisters a context and does not cancel it, so work a view leaves running keeps its caller's context. The returned error joinsErrCancelledByShutdownwith the view's own error.fsc_shutdown_draining.Readiness and refusing new work (
platform/view/sdk/dig,web/server,p2p, view API)server.ReadinessGateandReadyz(m, gates...): 503{"status":"not ready","reason":"draining"}./healthzstays 200.fsc.grpcserver enables its health service and turnsNOT_SERVINGwhen the drain starts (GRPCServer.SetNotServing).drainGatearound the view service refuses new commands withUnavailable. A view cancelled by shutdown ends withAborted. The HTTP binding maps them to 503 / close 1013 and 409 / close 1011 with the reasonprotos.AbortedByShutdownMessage. The Go HTTP client maps both back to gRPC statuses, forProcessCommandand for streams.draining: node is drainingunless its sender already takes part in the responder context (p2p.DrainState,p2p.WithDrainState). The draining rejection uses the existing reject path and its per-peer bounds.Teardown (
platform/view/sdk/dig,platform/fabric/sdk/dig)startServereturns a stop function.viewsdk.SDK.Stopstops the servers, then comm, then the KVS. Comm runs on a context of its own that onlyStopends, so responders cancelled with the node context can still reply. The exportedServekeeps its signature and behaviour.Stop()and then calls the wrappedStop(). Fabric-x needs no change: it embeds the Fabric SDK and its own providers only keep the context.Failover (
platform/view/services/comm)host.RetiringHost. The WebSocket multiplexed provider'sRetire(peerID)moves the cached websockets to a peer out of the lookup map. Their open sub-connections keep working,KillAllstill closes them, and the next stream dials again.P2PNoderetires the host's connections to a peer when one of its sessions gets a rejection (statusERROR, empty caller) starting withdraining:.Integration harness
fsc.Topology.Shutdownrendersfsc.shutdowninto every test node (5s drain, 10s teardown), so existing suites keep stopping well withinStopEventuallyTimeout.Deviations from the issue
Drainertype assertion on SDKs. Every wrapper SDK embeds thecommondig.SDKinterface, among them Panurus'stoken/sdk/dig.SDK, Fabric-x,vfsdkand the libp2p support SDK. Go promotes only the interface's methods through such an embedding, soDrainon the Fabric SDK would never reachpkg/nodeand the drain would silently not happen on a Panurus node.pkg/nodelooks theDrainerup in the registry instead, where the view manager already is. No SDK has to implement or pass anything through.fsc-drainersdig group is left to Version every FSC store and add themigratecommand #2412. As discussed in the #2410 comment, the group needspkg/nodeto reach the dig container, the same mechanismStoreOpenerneeds, so it is designed there once. The registry lookup already drains nested SDKs without a pass-through. It takes the firstDraineronly, which is enough while the view manager is the only one.dropStreams.StreamHashincludes the session and context IDs, so a new session never reuses a cached P2P stream. On WebSocket, the only transport with replicas, a new stream is a sub-connection of the cached websocket to the same replica, so dropping streams would not fail over. Retiring the websocket does.fsc_shutdown_draining, notfsc_draining. The Prometheus provider derives an empty subsystem from the package path. Changing that rule would rename any metric that sets only a namespace, so the gauge sets subsystemshutdownexplicitly.admitfunction. fix(view): reply to unknown views without loops #2415 merged the admission checks inline indispatch; the draining check is a branch there.HealthCheckEnabledofcommongrpcrather than a secondhealth.NewServer().drainTimeout: 2son the replicated network that every spec of thatDescribeshares. TheAbortedpath is covered by unit tests (TestManagerDrain_CancelsInitiatorsAtDeadline,TestProcessCommandAborted,TestProcessCommandHandlerDrainStatuses).Breaking changes
Aborted(HTTP 409, WebSocket close 1011 with the reason) rather than an error response. Clients that read onlyCommandResponse.errsee a call error instead. The Go client reports it as a status error on both transports.fsc.grpclistener always registersgrpc.health.v1.Health. An embedder that registers it on that listener itself must stop: gRPC reports the duplicate registration throughgrpclog.Fatalf, so the process exits at startup. No exported Go signature changes. New exported names:node.Drainer,view.ErrCancelledByShutdown,Manager.Drain/Draining/Track/TryTrack/OnDrain/IsParty,p2p.DrainState,p2p.WithDrainState,p2p.DrainingPrefix,comm.DrainingPrefix,server.ReadinessGate,viewsdk.ErrDraining,viewgrpcserver.ErrAbortedByShutdown,protos.AbortedByShutdownMessage,host.RetiringHost,MultiplexedProvider.Retire,GRPCServer.SetNotServing.Panurus
Checked against
LFDT-Panurus/panurusmain: its token SDK embedsdig2.SDK, so the registry lookup finds the drain, and its existingStop()(drift-check sweepers, thenp.SDK.Stop()) now runs at shutdown in the right order. It constructs neitherview.Metricsnorview.Managerdirectly and uses no changed signature.Behaviour worth reviewing
InitiateViewduring the drain are not refused; they run and are waited for.Stop()still running at the teardown timeout is logged and left running.teardownTimeout: 0returns while the SDKs, the KVS included, still stop.fsc.grpclistener always servesgrpc.health.v1.Health; an application that registers it there itself exits at startup, because gRPC reports the duplicate registration as fatal.drainTimeoutshould cover the longest view, typically the finality timeout. With the defaultsNode.Stopmay block up to 60s; Kubernetes needsterminationGracePeriodSeconds >= preStop + drainTimeout + teardownTimeout + 5s.Tests
go test -raceover every package of the root module passes.make integration-tests-fsc-stoprestartpasses 4/4, with the new spec "finishes a running view when its responder stops gracefully" on WebSocket and libp2p.make integration-tests-fabric-faultrecovery-replicationpasses 9/9, with the new spec "keeps committing through a rolling restart of one replica" (every committed tx settles on both replicas, at most one failed submission per restart).make checks(golangci-lint andgo fix) clean.fabric-faultrecovery,fabric-faultrecovery-postgres-outage,fabricx-faultrecovery.Docs
New
docs/platform/view/services/shutdown.md(order, clients, peers, load balancers, Kubernetes manifest, SDK authors). Updateddocs/configuration.md(fsc.shutdown,/readyz, health service),view-service-http.md(503, 409, 1013),monitoring_metrics.md,comm/readme.md(draining and the redial),docs/agents/architecture.md(lifecycle) anddocs/upgrade/v0.26-to-v0.27.md.