Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
imbajin merged PR #3185: URL: https://github.com/apache/hugegraph/pull/3185 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3957146829
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +230,130 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null &&
this.stateMachine.getProbeView().seesLeader;
+}
+
+/**
+ * Take a view of the local raft state from the volatile copies the state
machine
+ * callbacks maintain, never from the raft node itself. During an election
jraft holds
+ * the node lock while it reconnects to peers, so a probe that read the
node stalled for
+ * the connect timeout instead of answering its 503 promptly. All fields
derive from one
+ * read of one immutable view, swapped in whole per callback, so they
cannot contradict
+ * each other.
+ *
+ * The state reported is the last one a callback announced: leader,
follower, error or
+ * shutdown. jraft emits no callback for candidacy or leadership transfer,
so a candidate
+ * reads as a follower that sees no leader, which yields the same
not-ready answer. The
+ * view trails the node by whatever sits in the FSM queue ahead of the
announcement,
+ * which is the price of never waiting on the node lock.
+ */
+public RaftStatus getRaftStatus() {
Review Comment:
Fixed. The PR body now names `getRaftStatus()` and the nested `RaftStatus`
view (`isReady()`, `getState()`, `isLocalLeader()`), drops the
`isReady()`/`getNodeState()` claim, lists the twelve `RaftEngineReadinessTest`
cases actually in the file at `eb6de8f`, and adds `StoreAPIReadyTest`.
The local-verification line was rewritten to only what was measured at
`eb6de8f`: `pd-core-test` 104/104 (2 skipped) and `test-start-hugegraph-pd.sh`
13/13 against a PD built from this tree. The `pd-rest-test` count came from an
earlier head, so it now points at CI instead. Mirror #220 carries the same body
with the sync line kept first.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +230,130 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null &&
this.stateMachine.getProbeView().seesLeader;
+}
Review Comment:
Applied in 667b6fb, as suggested: `hasLeader()` is now
`getRaftStatus().isReady()`, with the javadoc rewritten to say it answers
readiness. Verified at `eb6de8f`: `mvn test -pl hugegraph-pd/hg-pd-test -am -P
pd-core-test` passes 104/104 (2 skipped). Reasoning is on the earlier thread.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -182,6 +196,19 @@ public List backChannelHandlers() {
}
public void shutDown() {
+if (this.alivePeersRefresher != null) {
+this.alivePeersRefresher.shutdownNow();
+try {
+// shutdownNow only interrupts; a refresh already inside
+// listAlivePeers could otherwise publish a positive count
+// after the reset below.
+this.alivePeersRefresher.awaitTermination(1, TimeUnit.SECONDS);
+} catch (InterruptedException e) {
+Thread.currentThread().interrupt();
+}
Review Comment:
Applied in 667b6fb, as suggested: the wait stays, the comment states what it
actually buys, and an overrun logs a warning naming the gauge. The generation
token is left for when `shutDown()`
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3957144743
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +230,130 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
Review Comment:
Fixed in 667b6fb. `hasLeader()` is now `getRaftStatus().isReady()`, so
`hg_raft_has_leader` and `GET /v1/ready` answer the same predicate and cannot
split if a future callback pairs an inactive state with `seesLeader`. Behaviour
is unchanged today. Javadoc updated to say the method answers readiness rather
than bare leader visibility.
Verified at `eb6de8f` on JDK 11: `mvn test -pl hugegraph-pd/hg-pd-test -am
-P pd-core-test` passes 104/104 (2 skipped), including all twelve
`RaftEngineReadinessTest` cases. `testProbeNeverTouchesTheRaftNode` still
holds: the method no longer reads the `raftNode` field at all.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -182,6 +196,19 @@ public List backChannelHandlers() {
}
public void shutDown() {
+if (this.alivePeersRefresher != null) {
+this.alivePeersRefresher.shutdownNow();
+try {
+// shutdownNow only interrupts; a refresh already inside
+// listAlivePeers could otherwise publish a positive count
+// after the reset below.
+this.alivePeersRefresher.awaitTermination(1, TimeUnit.SECONDS);
Review Comment:
Fixed in 667b6fb, the minimal version from the suggestion. The wait stays,
the comment now says what it actually buys (a refresh parked in
`listAlivePeers()` sits on a lock acquire the interrupt does not break, for up
to the raft rpc connect timeout per unreachable peer), and the return value is
checked so an overrun logs a warning naming the gauge that may go stale.
Took the minimal fix over the generation token deliberately: the token needs
a second field and a change in `refreshAlivePeerCount()`, whose signature the
core tests call directly, and `shutDown()` still has no production caller.
Worth revisiting when it gains one.
Verified at `eb6de8f`: `pd-core-test` 104/104 (2 skipped).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3956277746
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +230,130 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null &&
this.stateMachine.getProbeView().seesLeader;
+}
Review Comment:
Applyable form of the earlier `hasLeader()` comment on this method: derive
the gauge from the predicate `/v1/ready` answers with, so `hg_raft_has_leader`
cannot drift from the endpoint it is documented to mirror if a future callback
pairs an inactive state with `seesLeader`. Behaviour today is identical: a null
`raftNode` still answers false, and every callback that sets `seesLeader` pairs
it with an active state. Traced through all ten `RaftEngineReadinessTest`
cases; the no-node-lock verification still holds because reading the `raftNode`
field is not a mock interaction. If a one-line alias next to its only caller
reads as too thin, inlining `getRaftStatus().isReady()` at the `PDMetrics` call
site works just as well.
```suggestion
/**
* Whether this PD is ready in the sense {@code GET /v1/ready} answers:
the raft node
* is active and sees a leader.
*
* A follower only keeps its leader while heartbeats keep arriving
inside the election
* timeout, and a leader only keeps its role while it can reach a
quorum. Seeing a leader
* therefore means this node is part of a quorum from its own point of
view, which is the
* signal a readiness probe needs. Served from the state machine
callbacks, not from the
* raft node, so it never waits on the node lock.
*/
public boolean hasLeader() {
return getRaftStatus().isReady();
}
```
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -182,6 +196,19 @@ public List backChannelHandlers() {
}
public void shutDown() {
+if (this.alivePeersRefresher != null) {
+this.alivePeersRefresher.shutdownNow();
+try {
+// shutdownNow only interrupts; a refresh already inside
+// listAlivePeers could otherwise publish a positive count
+// after the reset below.
+this.alivePeersRefresher.awaitTermination(1, TimeUnit.SECONDS);
+} catch (InterruptedException e) {
+Thread.currentThread().interrupt();
+}
Review Comment:
Applyable form of the earlier `shutDown()` comment, the minimal version:
keep the wait, stop claiming it prevents the late publish (the blocked refresh
sits in a lock acquire that ignores the interrupt, for up to PD's
`raft.rpc-timeout`, default 10 s, per unreachable peer), and log when the
refresher outlives the wait. The stronger fix, publishing only while a
generation token captured at schedule time is current, needs a second field and
a change in `refreshAlivePeerCount()`; worth doing once `shutDown()` gains a
production caller, which today it does not have.
```suggestion
try {
// Best effort: shutdownNow only interrupts, and a refresh
parked in
// listAlivePeers waits on a lock acquire the interrupt does
not break,
// for up to the raft rpc connect timeout per unreachable
peer. A refresh
// that outlives this wait may publish one stale count over
the reset
// below; acceptable while shutDown has no production caller.
if (!this.alivePeersRefresher.awaitTermination(1,
TimeUnit.SECONDS)) {
log.warn("Raft alive-peers refresher still running after
shutdown; " +
"hg_raft_alive_peers may briefly report a stale
value");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3954360894
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +230,130 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
Review Comment:
🧹 `hasLeader()` omits the `state.isActive()` guard that `getRaftStatus()`
applies at L264 (`view.state.isActive() && view.seesLeader`), yet
`PDMetrics.registerRaftMeters()` documents the gauges as mirroring what `GET
/v1/ready` answers — and `hg_raft_has_leader` is fed by this method while
`/v1/ready` is fed by `getRaftStatus()`.
The two agree today only by accident of which callbacks write what: the two
that set `seesLeader = true` (`onLeaderStart`, `onStartFollowing`) happen to
pair it with an active state, and the two that force an inactive state
(`onError`, `onShutdown`) happen to clear it. `ProbeView` does not enforce that
pairing, so a future callback writing an inactive state without clearing
`seesLeader` would silently split the gauge from the endpoint it is documented
to mirror.
Requested change: derive this from the same predicate the endpoint uses,
e.g. `return getRaftStatus().isReady();`, or say in the javadoc why the
active-state guard is deliberately omitted here.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +230,130 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null &&
this.stateMachine.getProbeView().seesLeader;
+}
+
+/**
+ * Take a view of the local raft state from the volatile copies the state
machine
+ * callbacks maintain, never from the raft node itself. During an election
jraft holds
+ * the node lock while it reconnects to peers, so a probe that read the
node stalled for
+ * the connect timeout instead of answering its 503 promptly. All fields
derive from one
+ * read of one immutable view, swapped in whole per callback, so they
cannot contradict
+ * each other.
+ *
+ * The state reported is the last one a callback announced: leader,
follower, error or
+ * shutdown. jraft emits no callback for candidacy or leadership transfer,
so a candidate
+ * reads as a follower that sees no leader, which yields the same
not-ready answer. The
+ * view trails the node by whatever sits in the FSM queue ahead of the
announcement,
+ * which is the price of never waiting on the node lock.
+ */
+public RaftStatus getRaftStatus() {
Review Comment:
🧹 The PR description no longer describes this head, and since the repository
squash-merges, the body becomes the commit message.
"Main Changes" says `RaftEngine` gains "`hasLeader()`, `isReady()`,
`getNodeState()` and `getAlivePeerCount()`". At `63a2690` the new public
surface is `hasLeader()`, `getRaftStatus()` and `getAlivePeerCount()` plus the
nested `RaftStatus`; there is no `RaftEngine.isReady()` and no `getNodeState()`
(`isReady()` lives only on `RaftStatus`, L290).
"Verify the Changes" lists `RaftEngineReadinessTest` cases for "empty leader
id, candidate, transferring" that the file does not contain — its ten tests are
`testNotReadyBeforeRaftNodeStarts`,
`testStartedNodeWithoutAnyCallbackIsNotReady`, `testLeaderIsReady`,
`testFollowerWithLeaderIsReady`, `testFollowerLosingItsLeaderTurnsNotReady`,
`testLeaderSteppingDownTurnsNotReady`,
`testErrorAndShutdownAreNotReadyEvenAfterLeadership`,
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3952111886
##
hugegraph-server/hugegraph-dist/src/assembly/travis/test-start-hugegraph-pd.sh:
##
@@ -111,6 +111,23 @@ wait_for_pd() {
return 1
}
+# Wait until PD readiness answers, or timeout. Same gate the docs recommend:
+# -f rejects the 503, the body match rejects a 200 that is an auth envelope
rather
+# than a readiness answer. No credentials, and a single-node group elects
itself.
+# Captured rather than piped: under pipefail a grep -q SIGPIPE could misread a
+# ready PD, and wait_for_pd() above uses the same shape.
+wait_for_pd_ready() {
+local elapsed=0
+while (( elapsed < STARTUP_WAIT )); do
+local body
+body=$(curl -fsS "$PD_URL/v1/ready" 2>/dev/null || true)
+grep -q '"ready":true' <<<"$body" && return 0
Review Comment:
Fixed in `8c6f0a363`. It now matches `"ready"[[:space:]]*:[[:space:]]*true`
with `grep -Eq`, so compact, spaced and pretty-printed bodies all match while
`"ready":false` still does not.
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -62,6 +62,56 @@ public void testQueryClusterInfo() throws
URISyntaxException, IOException, Inter
assert obj.getInt("status") == 0;
}
+@Test
+public void testHealthNeedsNoAuth() throws URISyntaxException, IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/health";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200;
+// A 200 alone does not prove the path is anonymous: as of 1.7.0 the
auth interceptor
+// refuses with 200 and an error envelope. checkHealthy() returns an
empty body, which
+// separates the two whichever status a refusal carries.
+assert response.body().isEmpty() : "expected an empty body, got " +
response.body();
+}
+
+@Test
+public void testReadyNeedsNoAuthAndReflectsRaft() throws
URISyntaxException, IOException,
+
InterruptedException, JSONException {
+// The CI PD is a single-node raft group, so it is its own leader and
must be ready
+String url = pdRestAddr + "/v1/ready";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200 : "expected 200, got " +
response.statusCode() +
+ " body=" + response.body();
+JSONObject obj = new JSONObject(response.body());
+assert obj.getBoolean("ready");
+assert obj.getBoolean("isLeader");
+assert "STATE_LEADER".equals(obj.getString("state"));
+// Unauthenticated, so it must not disclose cluster addresses
+assert !obj.has("leader") : "the anonymous body must not carry the
leader address";
+}
Review Comment:
Added in `41318057b`. New `StoreAPIReadyTest` with three cases: raft not
started (503, `state=STATE_UNINITIALIZED`), a follower that lost its leader
(503, `STATE_FOLLOWER`), and a leader (200, `ready` and `isLeader` true) so an
inverted ternary fails too. Each asserts the body keys, not just the status.
Proved it catches the regression rather than assuming: forcing
`HttpStatus.OK` makes two of the three fail, restoring makes them pass.
It lives in `hg-pd-service`'s own test source set, since `hg-pd-service` is
repackaged by `spring-boot-maven-plugin` and a test under `hg-pd-test` cannot
resolve the service classes. It uses a `reflect.Proxy` `Node` that throws on
any call, so it also pins that the endpoint never touches the raft node. No
mockito.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3952111034
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,97 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null &&
this.stateMachine.getProbeView().seesLeader;
+}
+
+/**
+ * Take a view of the local raft state from the volatile copies the state
machine
+ * callbacks maintain, never from the raft node itself. During an election
jraft holds
+ * the node lock while it reconnects to peers, so a probe that read the
node stalled for
+ * the connect timeout instead of answering its 503 promptly. All fields
derive from one
+ * read of one immutable view, swapped in whole per callback, so they
cannot contradict
+ * each other.
+ *
+ * The state reported is the last one a callback announced: leader,
follower, error or
+ * shutdown. jraft emits no callback for candidacy or leadership transfer,
so a candidate
+ * reads as a follower that sees no leader, which yields the same
not-ready answer. The
+ * view trails the node by whatever sits in the FSM queue ahead of the
announcement,
+ * which is the price of never waiting on the node lock.
+ */
+public RaftStatus getRaftStatus() {
+if (this.raftNode == null) {
+return new RaftStatus(false, State.STATE_UNINITIALIZED.name(),
false);
+}
+RaftStateMachine.ProbeView view = this.stateMachine.getProbeView();
+return new RaftStatus(view.state.isActive() && view.seesLeader,
+ view.state.name(), State.STATE_LEADER ==
view.state);
+}
+
+/**
+ * Immutable view of the raft state behind {@code GET /v1/ready}. It
carries no cluster
+ * addresses: the endpoint is unauthenticated, and the leader's address
stays on the
+ * authenticated {@code /v1/members}.
+ */
+public static final class RaftStatus {
+
+private final boolean ready;
+private final String state;
+private final boolean localLeader;
+
+RaftStatus(boolean ready, String state, boolean localLeader) {
+this.ready = ready;
+this.state = state;
+this.localLeader = localLeader;
+}
+
+public boolean isReady() {
+return this.ready;
+}
+
+/**
+ * @return the jraft node state name, never null
+ */
+public String getState() {
+return this.state;
+}
+
+public boolean isLocalLeader() {
+return this.localLeader;
+}
+}
+
+/**
+ * Number of raft peers, this node included, that the leader has heard
from within the
+ * leader lease timeout, which jraft derives as 90% of the election
timeout by default.
+ * Only the leader tracks replication state, so any other node returns -1.
The leader
+ * check is the state machine's lock-free term flag, so a scrape on a
non-leader never
+ * waits on the node lock; {@code listAlivePeers} itself only runs on a
settled leader.
+ */
+public int getAlivePeerCount() {
Review Comment:
Fixed in `2ac8f6c9e`. Checked it against the jraft 1.3.13 sources first and
the claim holds: `NodeImpl.listAlivePeers()` takes `readLock` before it checks
state, so no guard can keep a caller off the lock.
`getAlivePeerCount()` now returns a volatile field, published by a refresher
on its own daemon thread, and the javadoc says the value is the last published
one instead of promising a settled leader. The `-1` to `NaN` contract is
unchanged and is still what you get before the first refresh.
I did add a periodic refresh rather than a callback. jraft announces
leadership transitions but never announces a follower dropping out of the
replication set, so a callback-driven count would freeze at election-time
membership, which is wrong for exactly the quorum-loss case this gauge exists
for.
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -62,6 +62,56 @@ public void testQueryClusterInfo() throws
URISyntaxException, IOException,
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
imbajin commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3951334521
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -62,6 +62,56 @@ public void testQueryClusterInfo() throws
URISyntaxException, IOException, Inter
assert obj.getInt("status") == 0;
}
+@Test
+public void testHealthNeedsNoAuth() throws URISyntaxException, IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/health";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200;
+// A 200 alone does not prove the path is anonymous: as of 1.7.0 the
auth interceptor
+// refuses with 200 and an error envelope. checkHealthy() returns an
empty body, which
+// separates the two whichever status a refusal carries.
+assert response.body().isEmpty() : "expected an empty body, got " +
response.body();
+}
+
+@Test
+public void testReadyNeedsNoAuthAndReflectsRaft() throws
URISyntaxException, IOException,
+
InterruptedException, JSONException {
+// The CI PD is a single-node raft group, so it is its own leader and
must be ready
+String url = pdRestAddr + "/v1/ready";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200 : "expected 200, got " +
response.statusCode() +
+ " body=" + response.body();
+JSONObject obj = new JSONObject(response.body());
+assert obj.getBoolean("ready");
+assert obj.getBoolean("isLeader");
+assert "STATE_LEADER".equals(obj.getString("state"));
+// Unauthenticated, so it must not disclose cluster addresses
+assert !obj.has("leader") : "the anonymous body must not carry the
leader address";
+}
Review Comment:
🧹 Could we also add a test case to verify the `503 Service Unavailable`
response when the node is not ready (e.g., when quorum is lost or before raft
initialization)? Currently `RestApiTest` only verifies the 200 OK leader path.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
Copilot commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3949052379
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -62,6 +62,56 @@ public void testQueryClusterInfo() throws
URISyntaxException, IOException, Inter
assert obj.getInt("status") == 0;
}
+@Test
+public void testHealthNeedsNoAuth() throws URISyntaxException, IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/health";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200;
+// A 200 alone does not prove the path is anonymous: as of 1.7.0 the
auth interceptor
+// refuses with 200 and an error envelope. checkHealthy() returns an
empty body, which
+// separates the two whichever status a refusal carries.
+assert response.body().isEmpty() : "expected an empty body, got " +
response.body();
+}
+
+@Test
+public void testReadyNeedsNoAuthAndReflectsRaft() throws
URISyntaxException, IOException,
+
InterruptedException, JSONException {
+// The CI PD is a single-node raft group, so it is its own leader and
must be ready
+String url = pdRestAddr + "/v1/ready";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200 : "expected 200, got " +
response.statusCode() +
+ " body=" + response.body();
+JSONObject obj = new JSONObject(response.body());
+assert obj.getBoolean("ready");
+assert obj.getBoolean("isLeader");
+assert "STATE_LEADER".equals(obj.getString("state"));
+// Unauthenticated, so it must not disclose cluster addresses
+assert !obj.has("leader") : "the anonymous body must not carry the
leader address";
+}
+
+@Test
+public void testRaftGaugesExported() throws URISyntaxException,
IOException,
+ InterruptedException {
+String url = pdRestAddr + "/actuator/prometheus";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200;
+String body = response.body();
+assert body.contains("hg_raft_leader{") : "missing hg_raft_leader
gauge";
+assert body.contains("hg_raft_has_leader{") : "missing
hg_raft_has_leader gauge";
+assert body.contains("hg_raft_alive_peers{") : "missing
hg_raft_alive_peers gauge";
+// Single-node CI cluster: this PD is the leader and hears from itself
+assert body.matches("(?s).*hg_raft_leader\\{[^}]*\\} 1\\.0.*") :
+"hg_raft_leader should be 1 on a single-node leader";
+assert body.matches("(?s).*hg_raft_has_leader\\{[^}]*\\} 1\\.0.*") :
+"hg_raft_has_leader should be 1 on a single-node leader";
+assert body.matches("(?s).*hg_raft_alive_peers\\{[^}]*\\} 1\\.0.*") :
+"hg_raft_alive_peers should be 1 on a single-node leader";
Review Comment:
These checks assume the Prometheus exposition always includes a `{...}`
label block (e.g., `hg_raft_leader{...}`), but Micrometer may emit
`hg_raft_leader 1.0` when there are no tags. To avoid brittle failures across
registry/library versions, match the metric name with an optional `{...}`
section (and keep the value assertion).
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -62,6 +62,56 @@ public void testQueryClusterInfo() throws
URISyntaxException, IOException, Inter
assert obj.getInt("status") == 0;
}
+@Test
+public void testHealthNeedsNoAuth() throws URISyntaxException, IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/health";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200;
+// A 200 alone does not prove the path is anonymous: as of 1.7.0 the
auth interceptor
+// refuses with 200 and an error envelope. checkHealthy() returns an
empty body, which
+// separates the two whichever status a refusal carries.
+assert response.body().isEmpty() : "expected an empty body, got " +
response.body();
Review Comment:
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3947215693
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,97 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null &&
this.stateMachine.getProbeView().seesLeader;
+}
+
+/**
+ * Take a view of the local raft state from the volatile copies the state
machine
+ * callbacks maintain, never from the raft node itself. During an election
jraft holds
+ * the node lock while it reconnects to peers, so a probe that read the
node stalled for
+ * the connect timeout instead of answering its 503 promptly. All fields
derive from one
+ * read of one immutable view, swapped in whole per callback, so they
cannot contradict
+ * each other.
+ *
+ * The state reported is the last one a callback announced: leader,
follower, error or
+ * shutdown. jraft emits no callback for candidacy or leadership transfer,
so a candidate
+ * reads as a follower that sees no leader, which yields the same
not-ready answer. The
+ * view trails the node by whatever sits in the FSM queue ahead of the
announcement,
+ * which is the price of never waiting on the node lock.
+ */
+public RaftStatus getRaftStatus() {
+if (this.raftNode == null) {
+return new RaftStatus(false, State.STATE_UNINITIALIZED.name(),
false);
+}
+RaftStateMachine.ProbeView view = this.stateMachine.getProbeView();
+return new RaftStatus(view.state.isActive() && view.seesLeader,
+ view.state.name(), State.STATE_LEADER ==
view.state);
+}
+
+/**
+ * Immutable view of the raft state behind {@code GET /v1/ready}. It
carries no cluster
+ * addresses: the endpoint is unauthenticated, and the leader's address
stays on the
+ * authenticated {@code /v1/members}.
+ */
+public static final class RaftStatus {
+
+private final boolean ready;
+private final String state;
+private final boolean localLeader;
+
+RaftStatus(boolean ready, String state, boolean localLeader) {
+this.ready = ready;
+this.state = state;
+this.localLeader = localLeader;
+}
+
+public boolean isReady() {
+return this.ready;
+}
+
+/**
+ * @return the jraft node state name, never null
+ */
+public String getState() {
+return this.state;
+}
+
+public boolean isLocalLeader() {
+return this.localLeader;
+}
+}
+
+/**
+ * Number of raft peers, this node included, that the leader has heard
from within the
+ * leader lease timeout, which jraft derives as 90% of the election
timeout by default.
+ * Only the leader tracks replication state, so any other node returns -1.
The leader
+ * check is the state machine's lock-free term flag, so a scrape on a
non-leader never
+ * waits on the node lock; {@code listAlivePeers} itself only runs on a
settled leader.
+ */
+public int getAlivePeerCount() {
Review Comment:
⚠️ The javadoc promises that `listAlivePeers` "only runs on a settled
leader", but no guard can give this method the lock-free property the rest of
the readiness path has: `NodeImpl.listAlivePeers()` (jraft-core 1.3.13,
`NodeImpl.java:2974-2984`) takes `readLock` *before* it checks state and throws.
Two ways a scrape blocks there:
- No FSM lag needed. `stepDown` runs under the caller's write lock
(`NodeImpl.java:1268-1289`) and on a term bump writes raft metadata before
releasing, so a scrape that passed the guard on a genuinely settled leader
waits out the rest of it.
- With FSM lag. `stateMachine.isLeader()` is `leaderTerm.get() > 0`, reset
only in `onLeaderStop`, which jraft enqueues on the FSM disruptor, while
`stepDown` sets `state = STATE_FOLLOWER` synchronously. Should that backlog
outlive one election timeout, the scrape reaches `preVote()`, which holds the
write lock across `rpcService.connect(...)` per peer (`NodeImpl.java:2698`);
that call blocks for
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#issuecomment-5560515804
@imbajin Ready for a review pass when you have time. Pushed `2df9a55`, five
added lines in `hugegraph-pd/docs/api-reference.md`.
**Why.** `hg_raft_alive_peers` is backed by `Node.listAlivePeers()`, so it
can only answer on the leader and returns `Double.NaN` elsewhere. Prometheus
renders that as `NaN`, and `NaN` propagates through `sum()` and `avg()`,
poisoning the aggregate. The doc gave no query form for that gauge at all,
which is the gap that leads someone to `sum()` it, so `2df9a55` adds one. I
left `PDMetrics` alone: `NaN` is the honest encoding for "this node cannot
answer", where `0` would read as "no peers alive" and poison an aggregate more
quietly.
**On the two red codecov marks.** `codecov/patch` reports one missing line,
and it is the `excludePathPatterns` registration in
`AuthenticationConfigurer.addInterceptors`. That is a Spring `WebMvcConfigurer`
callback which only runs inside the live PD process, and CI starts that process
separately. An in-JVM interceptor test was tried and reverted in `f4fb4ea`, for
a different reason worth stating accurately: `hg-pd-service` is repackaged by
`spring-boot-maven-plugin`, so a full `mvn install` leaves an executable jar
with classes under `BOOT-INF/classes` where javac cannot see them, and
`build-commons` plus both macOS server jobs failed with cannot-find-symbol. The
behaviour that line configures is covered end to end by
`testReadyNeedsNoAuthAndReflectsRaft`. `codecov/project` is a ratchet of a few
hundredths of a point, not a coverage cliff.
**What I checked on the branch.** `ProbeView` publication across all six
JRaft callbacks: `onLeaderStart`, `onLeaderStop`, `onStartFollowing`,
`onStopFollowing`, `onError`, `onShutdown`. No ordering yields a torn read,
since each announcement replaces the whole view.
`onStopFollowing` is the one place a view mixes fields from two
announcements, via `new ProbeView(this.probeView.state, false)`. The field that
would actually hurt is `isLeader`: a carried `STATE_LEADER` would serve
`{"ready":false,"state":"STATE_LEADER","isLeader":true}` and make
`hg_raft_leader` read 1 on a non-leader. That is unreachable in the jraft
1.3.13 that `hg-pd-core` pins. `onStopFollowing` is only emitted from
`resetLeaderId` under `state.compareTo(STATE_TRANSFERRING) > 0` at
`NodeImpl.java:1197`, which excludes both `STATE_LEADER` and
`STATE_TRANSFERRING`; and although `transferLeadershipTo` sets the state to
`TRANSFERRING` before firing `onLeaderStop`, `stepDown` announces
`onLeaderStop` while the state is still `LEADER`, ahead of `resetLeaderId`. So
the reachable carried states are `FOLLOWER`, `ERROR`, `SHUTDOWN` and
`UNINITIALIZED`, all of which give `ready=false` and `isLeader=false`.
`RaftEngineReadinessTest` asserts on `isReady()` in seven methods, and
`testReadyNeedsNoAuthAndReflectsRaft` asserts the body keys and the 200 path
against a live PD.
**Merge-order conflict with #3189, worth deciding before either lands.**
Both PRs rewrite the same line. This one makes it
`excludePathPatterns("/actuator/*", "/v1/health", "/v1/ready",
"/v1/prom/targets/*")`; #3189 makes it `excludePathPatterns("/actuator/**",
"/v1/health", "/v1/prom/targets/*")`. Whichever lands second conflicts, and the
two changes disagree about two independent things at once. The correct union is:
```java
excludePathPatterns("/actuator/**", "/v1/health", "/v1/ready",
"/v1/prom/targets/*")
```
Dropping `/v1/ready` puts the readiness endpoint back behind authentication
and defeats this PR; keeping the single star re-breaks the doc lines #3189
corrects.
**Two follow-ups I would not hold the merge for.**
1. The 200 versus 503 mapping in `checkReady()` has no direct test. An
inverted ternary would fail CI today, so only an "always return 200" regression
could ship undetected. Future test debt rather than a present defect, but it is
the branch most worth pinning later, given what the endpoint gates.
2. `LEADER_STOP` and `STOP_FOLLOWING` ride the same `FSMCallerImpl`
disruptor as `onApply` and `onSnapshotLoad`, so a follower in a long
`onSnapshotLoad` can keep answering 200 until the queue drains. The
`getRaftStatus` javadoc discloses this; `api-reference.md` only hints at it,
saying the state is the last change raft announced. Staleness is bounded, PD
metadata snapshots are small, and a node mid-snapshot-load is not servable
anyway, so I left it. Worth remembering if PD snapshots ever grow.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3943251810
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,94 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null && this.stateMachine.seesLeader();
+}
+
+/**
+ * Take a view of the local raft state from the volatile copies the state
machine
+ * callbacks maintain, never from the raft node itself. During an election
jraft holds
+ * the node lock while it reconnects to peers, so a probe that read the
node stalled for
+ * the connect timeout instead of answering its 503 promptly. All fields
derive from the
+ * same callback-written values, so they cannot contradict each other.
+ *
+ * The state reported is the last one a callback announced: leader,
follower, error or
+ * shutdown. jraft emits no callback for candidacy or leadership transfer,
so a candidate
+ * reads as a follower that sees no leader, which yields the same
not-ready answer.
+ */
+public RaftStatus getRaftStatus() {
+if (this.raftNode == null) {
+return new RaftStatus(false, State.STATE_UNINITIALIZED.name(),
false);
+}
+State state = this.stateMachine.getProbeState();
+return new RaftStatus(state.isActive() &&
this.stateMachine.seesLeader(),
Review Comment:
Fixed in b6ad26c with the requested single-snapshot shape.
`RaftStateMachine` now holds one immutable `ProbeView` of state plus leader
visibility, written once per callback on the FSM thread (`onStopFollowing`
carries the previous state forward, so an error state is not masked), and
`getRaftStatus()` and `hasLeader()` read the field once. Fair point that this
is the a3b9395 reincarnation of the overpromise 7074440 closed. The javadoc
also now says the view trails the node by whatever sits in the FSM queue,
rather than implying it is current. 9/9 readiness tests on JDK 11.
##
hugegraph-pd/docs/api-reference.md:
##
@@ -774,6 +774,54 @@ curl http://localhost:8620/actuator/health
}
```
+### Liveness and Readiness
+
+Two unauthenticated endpoints are meant for probes and startup gates:
+
+| Endpoint | Meaning | Status |
+|--|-||
+| `GET /v1/health` | Liveness: the REST listener is up. Does not consult raft.
| always `200` |
+| `GET /v1/ready` | Readiness: the raft node is active and sees a leader, so
this PD is inside a quorum. | `200` when ready, `503` otherwise |
+
+```bash
+curl -i http://localhost:8620/v1/ready
+```
+
+**Response** (leader of a healthy cluster):
+```json
+{
+ "ready": true,
+ "state": "STATE_LEADER",
+ "isLeader": true
+}
+```
+
+A follower reports `"state": "STATE_FOLLOWER"` with `"isLeader": false`. When
+the quorum is lost the PD keeps answering `/v1/health` with `200` but
+`/v1/ready` turns into `503` with `"ready": false`. Being unauthenticated, the
+body carries no cluster addresses; the leader's address stays on `/v1/members`.
+
+The answer is served from state the raft callbacks maintain rather than from
+the raft node, so it stays prompt while an election is running and never waits
+on the node lock. `state` is therefore the last change raft announced: jraft
+emits no callback for candidacy or leadership transfer, so a candidate reports
+`STATE_FOLLOWER` with `"ready": false`.
Review Comment:
Fixed in b6ad26c. The section now names `STATE_UNINITIALIZED` as what a PD
reports from process start until its first raft callback, tied to the
pre-quorum startup window the compose docs describe. I left the `raftNode ==
null` branch returning the same string: by the time the REST listener can
answer at all, the two cases differ only for the instant between servlet start
and `RaftEngine.init`, and both mean the same thing to a caller, do not gate on
this PD yet.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3941071813
##
hugegraph-pd/docs/api-reference.md:
##
@@ -774,6 +774,54 @@ curl http://localhost:8620/actuator/health
}
```
+### Liveness and Readiness
+
+Two unauthenticated endpoints are meant for probes and startup gates:
+
+| Endpoint | Meaning | Status |
+|--|-||
+| `GET /v1/health` | Liveness: the REST listener is up. Does not consult raft.
| always `200` |
+| `GET /v1/ready` | Readiness: the raft node is active and sees a leader, so
this PD is inside a quorum. | `200` when ready, `503` otherwise |
+
+```bash
+curl -i http://localhost:8620/v1/ready
+```
+
+**Response** (leader of a healthy cluster):
+```json
+{
+ "ready": true,
+ "state": "STATE_LEADER",
+ "isLeader": true
+}
+```
+
+A follower reports `"state": "STATE_FOLLOWER"` with `"isLeader": false`. When
+the quorum is lost the PD keeps answering `/v1/health` with `200` but
+`/v1/ready` turns into `503` with `"ready": false`. Being unauthenticated, the
+body carries no cluster addresses; the leader's address stays on `/v1/members`.
+
+The answer is served from state the raft callbacks maintain rather than from
+the raft node, so it stays prompt while an election is running and never waits
+on the node lock. `state` is therefore the last change raft announced: jraft
+emits no callback for candidacy or leadership transfer, so a candidate reports
+`STATE_FOLLOWER` with `"ready": false`.
Review Comment:
🧹 `STATE_UNINITIALIZED` is absent from this section, and it is what a PD
reports for the whole window the endpoint exists to cover.
`RaftStateMachine.probeState` starts at `State.STATE_UNINITIALIZED`
(`RaftStateMachine.java:63`) and is only ever written by a callback, so a PD
whose raft node is up but has never seen a leader answers `"state":
"STATE_UNINITIALIZED"`.
`RaftEngineReadinessTest.testStartedNodeWithoutAnyCallbackIsNotReady` in this
PR asserts that `ready` is false and `state` is `STATE_UNINITIALIZED` for
exactly that case. That is the ordinary pre-quorum startup `docker/README.md`
describes ("three PDs become ready once two of them can talk to each other"),
yet this section names only `STATE_LEADER` and `STATE_FOLLOWER`, and the
sentence above it covers a candidate that had already been following a leader,
not a node that has never seen one.
`RaftEngine.getRaftStatus()` returns the same string on its `raftNode ==
null` branch (`RaftEngine.java:236-237`), so the body cannot separate "raft
never started" from "raft running, no quorum yet".
Requested change: name `STATE_UNINITIALIZED` here as the state a PD reports
until its first raft callback. If the two cases are worth telling apart, given
that `state` was kept in the anonymous body because it "is what makes a `503`
diagnosable", returning `this.stateMachine.getProbeState().name()` on the
`raftNode == null` branch would leave `STATE_UNINITIALIZED` for a node that
never started.
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,94 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently sees a raft leader.
+ *
+ * A follower only keeps its leader while heartbeats keep arriving inside
the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
Seeing a leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs. Served from the state machine
callbacks, not from the
+ * raft node, so it never waits on the node lock.
+ */
+public boolean hasLeader() {
+return this.raftNode != null && this.stateMachine.seesLeader();
+}
+
+/**
+ * Take a view of the local raft state from the volatile copies the state
machine
+ * callbacks maintain, never from the raft node itself. During an election
jraft holds
+ * the node lock while it reconnects to peers, so a probe that read the
node stalled for
+ * the connect timeout instead of answering its 503 promptly. All fields
derive from the
+ * same callback-written values, so they cannot contradict each other.
+ *
+ * The state reported is the last one a callback announced: leader,
follower, error or
+ * shutdown. jraft emits no callback for candidacy or leadership transfer,
so a candidate
+ * reads as a follower that sees no leader, which yields the same
not-ready answer.
+ */
+public RaftStatus getRaftStatus() {
+if (this.raftNode == null) {
+return new RaftStatus(false, State.STATE_UNINITIALIZED.name(),
false);
+}
+State state =
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on PR #3185: URL: https://github.com/apache/hugegraph/pull/3185#issuecomment-5550666000 Fixed in a3b9395, taking the callback approach from the end-to-end report above. `RaftStateMachine` keeps a volatile copy of the last announced state and leader visibility, written by `onLeaderStart`, `onLeaderStop`, `onStartFollowing`, `onStopFollowing`, `onError` and `onShutdown`, and `getRaftStatus()`, `hasLeader()` and all three gauges read only that copy. The probe path no longer touches the raft node at all; the unit tests pin that with `verifyNoInteractions` on the node mock. Reproduced the stall shape locally before pushing: a PD electing against two blackholed peers, so every reconnect hangs the way connects to deleted pods do. 15 consecutive `/v1/ready` samples during the perpetual election all answered `503` in under 21 ms (the K8s run measured 9.79 s on the same path), a `/actuator/prometheus` scrape took 51 ms, and the healthy single-node answer stays at about 2 ms. Two behaviour notes. `state` is now the last role raft announced, so a candidate reports `STATE_FOLLOWER` with `"ready": false` (jraft has no candidacy callback), and a node that has never joined a quorum reports `STATE_UNINITIALIZED`; the docs say so. And `hg_raft_leader` now reflects the term flag rather than `isLeader(true)`, so it can lag a partitioned stale leader by up to the lease window, in exchange for scrapes that never block. Production callers of `RaftEngine.isLeader()` are untouched. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on PR #3185: URL: https://github.com/apache/hugegraph/pull/3185#issuecomment-5550492151 Logs and scripts from the two runs above, hosted on my fork (branch `logs/pr-3185`, [index](https://github.com/bitflicker64/hugegraph/tree/logs/pr-3185)): - [d3q-samples.log](https://raw.githubusercontent.com/bitflicker64/hugegraph/logs/pr-3185/d3q-samples.log) and [d3q-b-samples.log](https://raw.githubusercontent.com/bitflicker64/hugegraph/logs/pr-3185/d3q-b-samples.log): one line per 2 s on the surviving PD: epoch, `/v1/ready`, `/v1/health`, the `hg_raft_*` gauges, the Pod Ready condition. Run 2 appends `time_total` to the ready column as `code/seconds`. - [d3q.log](https://raw.githubusercontent.com/bitflicker64/hugegraph/logs/pr-3185/d3q.log) and [d3q-b.log](https://raw.githubusercontent.com/bitflicker64/hugegraph/logs/pr-3185/d3q-b.log): script output (pre-fault uids and IPs, T0, the Store gate, post-recovery checks, blocked-line counts). - [d3q.sh](https://raw.githubusercontent.com/bitflicker64/hugegraph/logs/pr-3185/d3q.sh) and [d3q-b.sh](https://raw.githubusercontent.com/bitflicker64/hugegraph/logs/pr-3185/d3q-b.sh): the scenario scripts, oracle declared before the fault. The stall, from run 2 (`ready=/`): ``` 1788593443.186162738 ready=200/0.003056 health=200 hg_raft_has_leader=1.0 podReady=True 1788593445.237568308 ready=200/0.002668 health=200 hg_raft_has_leader=1.0 podReady=True 1788593447.290482850 ready=200/0.003203 health=200 hg_raft_has_leader=1.0 podReady=True 1788593449.335970063 ready=503/9.792368 health=200 hg_raft_has_leader=1.0 podReady=True 1788593461.199044573 ready=200/0.002740 health=200 hg_raft_has_leader=1.0 podReady=True 1788593463.250381323 ready=200/0.002739 health=200 hg_raft_has_leader=1.0 podReady=True ``` T0 was 1788593447, the third line's timestamp. The fourth line's request went out at about T0+2.3 s and got its 503 at about T0+12.1 s, 9.79 s later; the gauge on that same line was read after the stall, once the replacements were back, which is why it already shows `has_leader 1.0`. The fifth line answered 200 in 2.7 ms. Run 1 shows the same window as `ready=000` (2 s timeouts) from T0+4.6 s to T0+22.8 s after one prompt 503 at T0+2.6 s with `has_leader 0.0`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#issuecomment-5550447092
Tested end to end on Kubernetes on 2026-09-05, with this branch merged into
the hugegraph/hugegraph testing tree.
**Build under test.** Tag
[`helm-dev-20260905`](https://github.com/hugegraph/hugegraph/releases/tag/helm-dev-20260905),
commit `6ec19838`: apache master `36811483` plus this PR at `70744406`, #3187
and #3189. PD, Store and Server images built from that tree with `docker buildx
bake -f docker/bake.hcl pd store server-hstore` (linux/amd64), labelled
`org.opencontainers.image.revision=6ec1983889f58a52995b27a4e1ea89bd00932396`,
and the label read back from every running pod. kind v0.33.0, Kubernetes
1.37.0, 1 control-plane + 3 workers, the #3132 Helm chart with
`pd.readinessPath=/v1/ready` and `store.waitPath=/v1/ready`, 3 PD + 3 Store + 3
Server + Hubble.
**What held.** Deleting two of three PDs with `kubectl delete pod`, the
survivor sampled every 2 s through a port-forward, two runs:
- `/v1/ready` on the survivor: 503 with `hg_raft_has_leader 0` 2.6 s after
the delete, back to 200 with `hg_raft_has_leader 1` once the replacements
rejoined, 12 to 20 s later.
- `/v1/health` on the same pod: 200 on all 313 samples of run one and all 90
of run two, so liveness and readiness now disagree exactly when they should.
- A Store deleted inside the window sat in its `wait-for-pd` init container
(`Waiting for 2 PD peers to answer /v1/ready`) from T0+7 s and passed at T0+23
s, the same second the first 200 came back. Schema writes through the Server
hung inside the window and returned 202 after it.
- The gauges behaved as documented: `hg_raft_alive_peers` read 3.0 while the
sampled node was leader and NaN once leadership moved to a replacement.
**One thing worth a look before merge: the handler stalls during the
election.** With `curl -m 10 -w '%{time_total}'`, the first `/v1/ready` request
after the delete took 9.79 s to return its 503; every 200 before and after
answered in under 5 ms. In the first run, with a 2 s client timeout, every
sample inside the leaderless window except the first came back as a timeout
rather than a 503. A kubelet probe with `timeoutSeconds: 5` fails either way,
so the readiness contract is met, but the endpoint promises a prompt 503, not a
stall. Reading the path: `StoreAPI.checkReady` calls
`RaftEngine.getRaftStatus`, which reads `node.getNodeState()` and
`node.getLeaderId()`, both under `NodeImpl`'s lock; while the node runs its
election it holds the write lock and opens connections to two peers that no
longer exist. I have not profiled it, so treat the lock as the lead and the
9.79 s as the measurement. One way out is to keep a volatile copy of the last
known state and leader, updated from
the state machine callbacks (`onLeaderStart`, `onLeaderStop`,
`onStartFollowing`, `onStopFollowing`), and serve the probe from that, so it
never waits on the node lock.
The sample logs and scripts are kept with the campaign notes; I can attach
them here if useful.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3939611529
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,101 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently knows a raft leader.
+ *
+ * A follower only keeps its leader id while heartbeats keep arriving
inside the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
A non-null leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs.
+ */
+public boolean hasLeader() {
+return hasLeader(this.raftNode);
+}
+
+private static boolean hasLeader(Node node) {
+if (node == null) {
+return false;
+}
+PeerId leader = node.getLeaderId();
+return leader != null && !leader.isEmpty();
+}
+
+/**
+ * Take a consistent view of the local raft state. Every field is derived
from one
+ * {@link Node} reference and a single {@code getLeaderId()} read, so a
step-down while
+ * the view is being built cannot report a ready node that knows no leader.
+ *
+ * A node is ready when it has been started, is in an active state, which
jraft's
+ * {@code State.isActive()} takes to mean leader, transferring, candidate
or follower,
+ * and sees a leader. Unlike a plain liveness check this turns false as
soon as the
+ * quorum is lost.
+ */
+public RaftStatus getRaftStatus() {
+Node node = this.raftNode;
+if (node == null) {
+return new RaftStatus(false, State.STATE_UNINITIALIZED.name(),
false);
+}
+State state = node.getNodeState();
+boolean active = state != null && state.isActive();
+return new RaftStatus(active && hasLeader(node),
+ state == null ? State.STATE_UNINITIALIZED.name()
: state.name(),
+ node.isLeader(true));
Review Comment:
Fixed in 7074440 with the suggested derivation, and the javadoc now states
the guarantee the code actually provides: one node reference, one
getNodeState() read, one getLeaderId() read, leader flag derived from that
state. Checked jraft 1.3.13 bytecode before applying: isLeader(true) is exactly
state == STATE_LEADER under the read lock, so the value is unchanged, including
reporting false during STATE_TRANSFERRING, and one lock acquisition per probe
and scrape goes away. Readiness tests 10/10 on JDK 11.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/metrics/PDMetrics.java:
##
@@ -76,7 +77,28 @@ private void registerMeters() {
Gauge.builder(PREFIX + ".terms", () -> setTerms())
.description("term of partitions in PD")
.register(registry);
+registerRaftMeters();
+}
+/**
+ * Raft membership gauges so operators can alert on quorum loss. They
mirror what
+ * {@code GET /v1/ready} answers: a PD that sees no leader is outside a
quorum.
+ */
+private void registerRaftMeters() {
+RaftEngine raft = RaftEngine.getInstance();
+Gauge.builder(PREFIX + ".raft.leader", () -> raft.isLeader() ? 1 : 0)
+ .description("1 if this PD is the raft leader, 0 otherwise")
+ .register(registry);
+Gauge.builder(PREFIX + ".raft.has_leader", () -> raft.hasLeader() ? 1
: 0)
Review Comment:
Fixed in 7074440 for both gauges, hg.raft.has.leader and
hg.raft.alive.peers. Verified against a live PD built from the branch that the
Prometheus rendering is byte-identical (hg_raft_has_leader,
hg_raft_alive_peers), so the docs table and the RestApiTest assertions stand as
they are.
##
hugegraph-server/hugegraph-dist/src/assembly/travis/test-start-hugegraph-pd.sh:
##
@@ -111,6 +111,19 @@ wait_for_pd() {
return 1
}
+# Wait until PD readiness answers, or timeout. This is the gate the docs
recommend:
+# -f rejects the 503, the body match rejects a 200 that is an auth envelope
rather
+# than a readiness answer. No credentials, and a single-node group elects
itself.
+wait_for_pd_ready() {
+local elapsed=0
+while (( elapsed < STARTUP_WAIT )); do
+curl -fsS "$PD_URL/v1/ready" 2>/dev/null | grep -q '"ready":true' &&
return 0
Review Comment:
Fixed in 7074440 with the suggested capture shape, plus a comment naming the
pipefail reason so the pipe does not creep back in. Full startup script passes
13/13 against a source-built PD, including the readiness wait.
##
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
imbajin commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3935589583
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/interceptor/AuthenticationConfigurerTest.java:
##
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hugegraph.pd.rest.interceptor;
+
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.springframework.util.AntPathMatcher;
+import org.springframework.util.PathMatcher;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.handler.MappedInterceptor;
+
+import static org.mockito.Mockito.mock;
+
+/**
+ * The probe endpoints have to stay outside the auth interceptor. If one of
them slips back
+ * behind it, PD answers a probe with 200 and an error envelope instead of a
readiness
+ * answer, so every healthcheck gating on the body holds forever while the
status still
+ * looks fine. That failure is silent, hence a check here rather than only in
the live
+ * REST suite.
+ */
+public class AuthenticationConfigurerTest {
+
+private static final PathMatcher MATCHER = new AntPathMatcher();
+
+/**
+ * {@code InterceptorRegistry.getInterceptors()} is protected, so read it
from a subclass.
+ */
+private static final class TestRegistry extends InterceptorRegistry {
+
+List registered() {
+return getInterceptors();
+}
+}
+
+private static MappedInterceptor authInterceptor() {
+AuthenticationConfigurer configurer = new AuthenticationConfigurer();
Review Comment:
‼️ This new test does not compile in the selected CI build. Run 33839755062
fails in hg-pd-test with `cannot find symbol` for `AuthenticationConfigurer`
and `RestAuthentication` at lines 53-54; the same failure appears in both macOS
server jobs. Both classes are defined under hg-pd-service, but this test is
compiled in hg-pd-test. Please move this test into the service test module or
make the service classes available in hg-pd-test's compile path, then rerun the
PD/server CI.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3934249051
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,101 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently knows a raft leader.
+ *
+ * A follower only keeps its leader id while heartbeats keep arriving
inside the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
A non-null leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs.
+ */
+public boolean hasLeader() {
+return hasLeader(this.raftNode);
+}
+
+private static boolean hasLeader(Node node) {
+if (node == null) {
+return false;
+}
+PeerId leader = node.getLeaderId();
+return leader != null && !leader.isEmpty();
+}
+
+/**
+ * Take a consistent view of the local raft state. Every field is derived
from one
+ * {@link Node} reference and a single {@code getLeaderId()} read, so a
step-down while
+ * the view is being built cannot report a ready node that knows no leader.
+ *
+ * A node is ready when it has been started, is in an active state, which
jraft's
+ * {@code State.isActive()} takes to mean leader, transferring, candidate
or follower,
+ * and sees a leader. Unlike a plain liveness check this turns false as
soon as the
+ * quorum is lost.
+ */
+public RaftStatus getRaftStatus() {
+Node node = this.raftNode;
+if (node == null) {
+return new RaftStatus(false, State.STATE_UNINITIALIZED.name(),
false);
+}
+State state = node.getNodeState();
+boolean active = state != null && state.isActive();
+return new RaftStatus(active && hasLeader(node),
+ state == null ? State.STATE_UNINITIALIZED.name()
: state.name(),
+ node.isLeader(true));
Review Comment:
🧹 The javadoc above says "Every field is derived from one `Node` reference
and a single `getLeaderId()` read, so a step-down while the view is being built
cannot report a ready node that knows no leader." The `ready` flag does hold
that property, but the snapshot as a whole does not: this method takes three
independent reads of the node, each acquiring `NodeImpl`'s read lock separately
— `getNodeState()` on L246, `getLeaderId()` via `hasLeader(node)`, and
`isLeader(true)` here. Constructor arguments evaluate left to right, so a
step-down between the `hasLeader` and `isLeader` reads emits a
self-contradictory body such as
`{"ready":true,"state":"STATE_LEADER","isLeader":false}`.
Harmless for a probe that only reads `ready`, but the javadoc promises a
guarantee the code does not provide, and a later reader may lean on it. Since
`state` has already been read one line up, `localLeader` can just be derived
from it — that makes all three fields genuinely consistent and drops a
redundant read-lock acquisition on every `/v1/ready` request and every metrics
scrape:
```suggestion
State.STATE_LEADER == state);
```
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/metrics/PDMetrics.java:
##
@@ -76,7 +77,28 @@ private void registerMeters() {
Gauge.builder(PREFIX + ".terms", () -> setTerms())
.description("term of partitions in PD")
.register(registry);
+registerRaftMeters();
+}
+/**
+ * Raft membership gauges so operators can alert on quorum loss. They
mirror what
+ * {@code GET /v1/ready} answers: a PD that sees no leader is outside a
quorum.
+ */
+private void registerRaftMeters() {
+RaftEngine raft = RaftEngine.getInstance();
+Gauge.builder(PREFIX + ".raft.leader", () -> raft.isLeader() ? 1 : 0)
+ .description("1 if this PD is the raft leader, 0 otherwise")
+ .register(registry);
+Gauge.builder(PREFIX + ".raft.has_leader", () -> raft.hasLeader() ? 1
: 0)
Review Comment:
🧹 `hg.raft.has_leader` (and `hg.raft.alive_peers` on L95) embed an
underscore inside a dot-delimited name segment. Micrometer's convention is
lowercase dot-separated words, with each registry's `NamingConvention` doing
the separator translation — that is why `hg.raft.leader` on L89 needs nothing.
The Prometheus output is the intended `hg_raft_has_leader` either way, but on
any other registry the underscore renders literally and yields a
mixed-separator name.
`hg.raft.has.leader` and `hg.raft.alive.peers` produce byte-identical
Prometheus output (so the
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3930909486
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,105 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently knows a raft leader.
+ *
+ * A follower only keeps its leader id while heartbeats keep arriving
inside the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
A non-null leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs.
+ */
+public boolean hasLeader() {
+return hasLeader(this.raftNode);
+}
+
+private static boolean hasLeader(Node node) {
+if (node == null) {
+return false;
+}
+PeerId leader = node.getLeaderId();
+return leader != null && !leader.isEmpty();
+}
+
+/**
+ * Whether this node can take part in serving requests: the raft node has
been started,
+ * is in an active state (leader, follower or transferring leadership) and
sees a leader.
Review Comment:
Fixed in 7a6dbb8 with the suggested wording. Confirmed the enum order
against jraft-core 1.3.13: `LEADER, TRANSFERRING, CANDIDATE, FOLLOWER, ERROR,
...` with `isActive()` as `ordinal() < STATE_ERROR.ordinal()`, so the javadoc
was a state short.
Took both halves on the tests. Renamed to
`testCandidateWithoutLeaderIsNotReady`, with a comment that jraft clears the
leader id before starting an election so this is the only candidate shape it
reaches, and added `testCandidateCountsAsActive` covering `STATE_CANDIDATE`
with a leader id, which does read as ready and records the scope of the state
check. Marked `testEmptyLeaderIdIsNotReady` as guarding the `Node` contract
rather than a value `NodeImpl` returns. 11/11 pass on JDK 11.
##
docker/README.md:
##
@@ -202,6 +202,24 @@ done
curl -fsS http://localhost:8088/about
```
+PD answers two unauthenticated probe endpoints. `/v1/health` is liveness only:
+it returns `200` as soon as the REST listener is up, even when the PD has no
+raft leader. `/v1/ready` returns `200` only while the PD sees a raft leader,
+and `503` otherwise. A single PD elects itself; three PDs become ready once
+two of them can talk to each other.
+
+The healthchecks in these files still gate on `/v1/health`, because
Review Comment:
Fixed in 7a6dbb8. Added a paragraph after the two bullets saying the
`HEALTHCHECK` baked into `hugegraph-pd/Dockerfile` is `/v1/health` as well,
that both compose files override it, and that it therefore governs `docker run`
and anything else inheriting the image probe, which keeps reading a quorum-less
PD as healthy.
Agreed the version-skew argument does not cover it, since that probe ships
with the image. Left the Dockerfile alone to keep this diff to one decision;
happy to file the follow-up, or fold it in here if you would rather it landed
together.
##
hugegraph-pd/docs/api-reference.md:
##
@@ -774,6 +774,46 @@ curl http://localhost:8620/actuator/health
}
```
+### Liveness and Readiness
+
+Two unauthenticated endpoints are meant for probes and startup gates:
+
+| Endpoint | Meaning | Status |
+|--|-||
+| `GET /v1/health` | Liveness: the REST listener is up. Does not consult raft.
| always `200` |
+| `GET /v1/ready` | Readiness: the raft node is active and sees a leader, so
this PD is inside a quorum. | `200` when ready, `503` otherwise |
+
+```bash
+curl -i http://localhost:8620/v1/ready
+```
+
+**Response** (leader of a healthy cluster):
+```json
+{
+ "ready": true,
+ "state": "STATE_LEADER",
+ "isLeader": true
+}
+```
+
+A follower reports `"state": "STATE_FOLLOWER"` with `"isLeader": false`. When
+the quorum is lost the PD keeps answering `/v1/health` with `200` but
+`/v1/ready` turns into `503` with `"ready": false`. Being unauthenticated, the
+body carries no cluster addresses; the leader's address stays on `/v1/members`.
+
+Point Kubernetes readiness probes, `depends_on` healthchecks and any
+"wait for PD" script at `/v1/ready`; keep liveness probes on `/v1/health`
+so a PD that merely lost its leader is not restarted.
+
+Match on the body rather than on the status code alone. PD's auth interceptor
+rejects a request it does not exclude by writing an error envelope without
Review Comment:
Fixed in 7a6dbb8, in all three places. Each now dates the behaviour rather
than asserting it: "as of 1.7.0" a refusal carries `200` and an error envelope,
followed by the point that the body match holds whichever status a refusal
carries. `api-reference.md` also attributes it to
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3930889346
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,105 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently knows a raft leader.
+ *
+ * A follower only keeps its leader id while heartbeats keep arriving
inside the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
A non-null leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs.
+ */
+public boolean hasLeader() {
+return hasLeader(this.raftNode);
+}
+
+private static boolean hasLeader(Node node) {
+if (node == null) {
+return false;
+}
+PeerId leader = node.getLeaderId();
+return leader != null && !leader.isEmpty();
+}
+
+/**
+ * Whether this node can take part in serving requests: the raft node has
been started,
+ * is in an active state (leader, follower or transferring leadership) and
sees a leader.
Review Comment:
🧹 The list of active states is short by one. `isReady()` gates on
`State.isActive()`, which jraft-core 1.3.13 defines as `this.ordinal() <
STATE_ERROR.ordinal()` over `STATE_LEADER, STATE_TRANSFERRING, STATE_CANDIDATE,
STATE_FOLLOWER, STATE_ERROR, ...`, so a candidate is active too.
Nothing is broken: `NodeImpl.handleElectionTimeout` calls
`resetLeaderId(PeerId.emptyPeer(), ...)` before `preVote()`, so a candidate has
no leader id left. But that means `testCandidateIsNotReady` passes on its
`null` stub, not on the state check. Same shape at line 228:
`NodeImpl.getLeaderId()` returns `this.leaderId.isEmpty() ? null :
this.leaderId`, so `testEmptyLeaderIdIsNotReady` exercises a value a real node
never returns.
Requested change: name the real set here, and either rename
`testCandidateIsNotReady` to `testCandidateWithoutLeaderIsNotReady` or add a
`STATE_CANDIDATE` plus leader-id case that records what the code actually does.
```suggestion
* is in an active state, which jraft's {@code State.isActive()} takes
to mean leader,
* transferring, candidate or follower, and sees a leader.
```
##
docker/README.md:
##
@@ -202,6 +202,24 @@ done
curl -fsS http://localhost:8088/about
```
+PD answers two unauthenticated probe endpoints. `/v1/health` is liveness only:
+it returns `200` as soon as the REST listener is up, even when the PD has no
+raft leader. `/v1/ready` returns `200` only while the PD sees a raft leader,
+and `503` otherwise. A single PD elects itself; three PDs become ready once
+two of them can talk to each other.
+
+The healthchecks in these files still gate on `/v1/health`, because
Review Comment:
🧹 One PD probe in the repository sits outside this reasoning.
`hugegraph-pd/Dockerfile:68-69` bakes `HEALTHCHECK ... CMD curl -fsS
http://localhost:8620/v1/health >/dev/null` into the image, and that image is
built from this tree, so it always carries `/v1/ready`. The version-skew
argument for keeping the compose files on liveness does not apply to a probe
shipped inside the image.
Both compose files override it (`docker/docker-compose-hstore.yml:47`,
`docker/docker-compose-3pd-3store-3server.yml:40`), so it only governs `docker
run` and orchestration that inherits the image probe. Those users still read a
quorum-less PD as healthy.
Requested change: add a sentence here saying the image's own HEALTHCHECK
stays on liveness too. Changing the Dockerfile is outside this diff; worth a
follow-up issue.
##
hugegraph-pd/docs/api-reference.md:
##
@@ -774,6 +774,46 @@ curl http://localhost:8620/actuator/health
}
```
+### Liveness and Readiness
+
+Two unauthenticated endpoints are meant for probes and startup gates:
+
+| Endpoint | Meaning | Status |
+|--|-||
+| `GET /v1/health` | Liveness: the REST listener is up. Does not consult raft.
| always `200` |
+| `GET /v1/ready` | Readiness: the raft node is active and sees a leader, so
this PD is inside a quorum. | `200` when ready, `503` otherwise |
+
+```bash
+curl -i http://localhost:8620/v1/ready
+```
+
+**Response** (leader of a healthy cluster):
+```json
+{
+ "ready": true,
+ "state": "STATE_LEADER",
+ "isLeader": true
+}
+```
+
+A follower reports `"state": "STATE_FOLLOWER"` with `"isLeader": false`. When
+the quorum is lost the PD keeps answering `/v1/health` with `200` but
+`/v1/ready` turns into `503` with `"ready": false`. Being unauthenticated, the
+body carries no cluster addresses; the leader's address stays on `/v1/members`.
+
+Point
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3928120253
##
hugegraph-store/docs/deployment-guide.md:
##
@@ -719,7 +719,7 @@ environment:
```
**Startup ordering** is enforced via `depends_on` with `condition:
service_healthy`:
-1. PD nodes start first and must pass healthchecks (`/v1/health`)
+1. PD nodes start first and must pass healthchecks (`/v1/ready`, answered
`200` only once the PD sees a raft leader)
Review Comment:
Good catch, fixed in ffa13f9. This line was left behind when c8adc85
reverted both compose healthchecks to `/v1/health`, so the guide described a
gate the repository does not have.
Took your first option. Step 1 now reads `/v1/health`, liveness only,
followed by a sentence saying it answers `200` before a quorum forms and
pointing at `docker/README.md` for what switching the healthchecks to
`/v1/ready` requires: a body match on `"ready":true`, because PD answers `200`
on any non-excluded path, plus an image carrying the endpoint.
Swept the rest of the diff for the same mistake. The only other mentions are
the endpoint reference itself and operator guidance, not claims about these
compose files.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/interceptor/AuthenticationConfigurer.java:
##
@@ -32,6 +32,7 @@ public class AuthenticationConfigurer implements
WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(restAuthentication)
.addPathPatterns("/**")
-.excludePathPatterns("/actuator/*", "/v1/health",
"/v1/prom/targets/*");
+.excludePathPatterns("/actuator/*", "/v1/health", "/v1/ready",
+ "/v1/prom/targets/*");
Review Comment:
Settling on the shape in c8adc85, so resolving this. The address, the one
thing anonymous callers could not learn before, is gone; `ready`, `state` and
`isLeader` stay.
To recap the reasoning: `ready` has to be in the body because PD answers
`200` on rejection, so a status-only probe cannot gate on it. `isLeader`
duplicates `hg_raft_leader`, which is anonymous on `/actuator/prometheus` by
design. `state` is what makes a `503` diagnosable without shell access to the
pod.
Reopen if you would rather it were `ready` alone; that would still leave the
compose gate workable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
imbajin commented on code in PR #3185: URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3926064340 ## hugegraph-store/docs/deployment-guide.md: ## @@ -719,7 +719,7 @@ environment: ``` **Startup ordering** is enforced via `depends_on` with `condition: service_healthy`: -1. PD nodes start first and must pass healthchecks (`/v1/health`) +1. PD nodes start first and must pass healthchecks (`/v1/ready`, answered `200` only once the PD sees a raft leader) Review Comment: 🧹 This line says the `depends_on` healthchecks gate on `/v1/ready`, but the compose files in this repository still probe `/v1/health` (`docker/docker-compose-hstore.yml:47` and `docker/docker-compose-3pd-3store-3server.yml:40`). `docker/README.md:211-213` in the same PR explicitly documents that choice, so the deployment guide currently tells operators a readiness gate exists when it does not. Please either keep this as `/v1/health` with a note that it is liveness-only, or update both compose healthchecks with body matching and image-version compatibility before documenting `/v1/ready` here. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3923362919
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/StoreAPI.java:
##
@@ -386,4 +396,30 @@ class StoreStatistics {
public Serializable checkHealthy() {
return "";
}
+
+/**
+ * Check Service Readiness
+ * Answers 200 only when this PD is part of a raft quorum, that is, the
raft node is active
+ * and knows the current leader. Otherwise answers 503 so that anything
gating on PD
+ * (the compose healthcheck in front of Stores, a Kubernetes readiness
probe)
+ * is held back until the PD can serve. Like /health this endpoint needs
no authentication.
+ *
+ * @return JSON with the readiness flag, the local raft state and the raft
address of the
+ * leader (null when there is none)
+ */
+@GetMapping(value = "/ready", produces = MediaType.APPLICATION_JSON_VALUE)
+public ResponseEntity> checkReady() {
+RaftEngine raft = RaftEngine.getInstance();
+boolean ready = raft.isReady();
+State state = raft.getNodeState();
+PeerId leader = raft.getLeader();
Review Comment:
Fixed in c8adc85. Added `RaftEngine.getRaftStatus()`, which derives every
field from one `Node` reference and a single `getLeaderId()` read via the
`hasLeader(Node)` overload, and returns an immutable `RaftStatus`.
`checkReady()` now builds the body from that one snapshot and no longer imports
any jraft type, so the raft logic stays in the engine. `isReady()` delegates to
it, and the now-redundant `getNodeState()` is gone.
The specific inconsistency you named is also structurally impossible now,
since the leader address left the body (see the `AuthenticationConfigurer`
thread). New unit test `testStatusNeverReportsReadyWithoutALeader` covers the
invariant; 10/10 pass on JDK 11.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/interceptor/AuthenticationConfigurer.java:
##
@@ -32,6 +32,7 @@ public class AuthenticationConfigurer implements
WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(restAuthentication)
.addPathPatterns("/**")
-.excludePathPatterns("/actuator/*", "/v1/health",
"/v1/prom/targets/*");
+.excludePathPatterns("/actuator/*", "/v1/health", "/v1/ready",
+ "/v1/prom/targets/*");
Review Comment:
Partly taken, in c8adc85. Dropped `leader` from the anonymous body, which
was the one genuinely new disclosure: it pointed at a specific node, and
nothing anonymous exposed a raft address before. The leader address stays on
the authenticated `/v1/members`, which the issue already noted carries
`pdLeader` with role and state.
Kept `ready`, `state` and `isLeader`. `ready` is load-bearing for probes,
because the `200`-on-rejection behaviour means a status-only check cannot gate.
`isLeader` reveals nothing beyond the `hg_raft_leader` gauge, which is
anonymous on `/actuator/prometheus` by design (option 3 of the issue), and
`state` is what makes a `503` diagnosable.
Body is now `{"ready":true,"state":"STATE_LEADER","isLeader":true}`. Happy
to trim further if you would rather it were only `ready`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
-
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3923360619
##
docker/docker-compose-hstore.yml:
##
@@ -44,7 +44,7 @@ services:
volumes:
- pd-data:/hugegraph-pd/pd_data
healthcheck:
- test: ["CMD-SHELL", "curl -fsS http://localhost:8620/v1/health
>/dev/null"]
+ test: ["CMD-SHELL", "curl -fsS http://localhost:8620/v1/ready
>/dev/null"]
Review Comment:
Reverted in c8adc85: both compose files are byte-identical to master again,
and the manual verification calls in the README go back to `/v1/health`.
Reproduced your finding locally against a source-built PD: an auth-gated
path and a path that does not exist both answer `200` with
`{"error":"Unauthorized!","status":-1}`, and `curl -fsS` exits 0 on it. The
payload grep rejects it.
I took the second option rather than pinning smoke to source-built images,
because the hardened probe would also hang the documented quickstart for anyone
on published images until the endpoint ships. The README now records the body
match and the image requirement for whoever switches them over.
Root cause is `RestAuthentication.preHandle` never calling `setStatus`. Out
of scope here; happy to file it separately.
##
docker/README.md:
##
@@ -202,6 +202,15 @@ done
curl -fsS http://localhost:8088/about
```
+PD answers two unauthenticated probe endpoints. `/v1/health` is liveness only:
+it returns `200` as soon as the REST listener is up, even when the PD has no
+raft leader. `/v1/ready` returns `200` only while the PD sees a leader and
+`503` otherwise, so the compose healthchecks gate Stores on `/v1/ready`. A
+single PD elects itself; three PDs become ready once two can talk to each
+other. `/v1/ready` first ships in 1.8.0: with an older `HUGEGRAPH_VERSION`
+the PD healthcheck never passes and the Stores never start, so pin 1.8.0
+or newer, or build the images from source with `docker-compose.dev.yml`.
Review Comment:
Rewritten in c8adc85. The paragraph no longer claims a hang. It now says the
healthchecks stay on `/v1/health` because these files run published images, and
lists the two things needed before switching: match on the body with `grep -q
'"ready":true'` (with the reason, since PD answers `200` and an error envelope
on any non-excluded path), and an image that carries the endpoint.
Lines 134 and 189 are back on `/v1/health`. Dropped the "1.8.0" guess for
"from the next release onwards".
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -62,6 +62,51 @@ public void testQueryClusterInfo() throws
URISyntaxException, IOException, Inter
assert obj.getInt("status") == 0;
}
+@Test
+public void testHealthNeedsNoAuth() throws URISyntaxException, IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/health";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200;
Review Comment:
Fixed in c8adc85 with the suggested assertion, plus a comment recording why
the status alone is not enough. Verified against a live PD that `/v1/health`
returns an empty body.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/metrics/PDMetrics.java:
##
@@ -76,7 +77,28 @@ private void registerMeters() {
Gauge.builder(PREFIX + ".terms", () -> setTerms())
.description("term of partitions in PD")
.register(registry);
+registerRaftMeters();
+}
+/**
+ * Raft membership gauges so operators can alert on quorum loss. They
mirror what
+ * {@code GET /v1/ready} answers: a PD that sees no leader is outside a
quorum.
+ */
+private void registerRaftMeters() {
+RaftEngine raft = RaftEngine.getInstance();
+Gauge.builder(PREFIX + ".raft.leader", () -> raft.isLeader() ? 1 : 0)
+ .description("1 if this PD is the raft leader, 0 otherwise")
+ .register(registry);
+Gauge.builder(PREFIX + ".raft.has_leader", () -> raft.hasLeader() ? 1
: 0)
+ .description("1 if this PD sees a raft leader, i.e. is part of a
quorum, 0 otherwise")
+ .register(registry);
+Gauge.builder(PREFIX + ".raft.alive_peers", () -> {
+ int alive = raft.getAlivePeerCount();
+ return alive < 0 ? Double.NaN : alive;
+ })
+ .description("Number of raft peers, itself included, the leader
has heard from " +
+ "within the election timeout; NaN on non-leader
nodes")
Review Comment:
Fixed in c8adc85 with the suggested wording. Confirmed against jraft-core
1.3.13:
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3918294000
##
docker/docker-compose-hstore.yml:
##
@@ -44,7 +44,7 @@ services:
volumes:
- pd-data:/hugegraph-pd/pd_data
healthcheck:
- test: ["CMD-SHELL", "curl -fsS http://localhost:8620/v1/health
>/dev/null"]
+ test: ["CMD-SHELL", "curl -fsS http://localhost:8620/v1/ready
>/dev/null"]
Review Comment:
⚠️ This probe cannot tell a ready PD from one that has no `/v1/ready` at
all, so the gate in front of `store` still checks only liveness.
PD's auth interceptor rejects an unauthenticated request by writing a JSON
error body and returning `false` without calling `response.setStatus(...)`
(`hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/interceptor/RestAuthentication.java:61-66`),
so the response commits with the servlet default 200. On a build that lacks
the new `/v1/ready` exclusion, `curl -fsS` exits 0 on
`{"status":-1,"error":"Unauthorized!"}`.
Measured here. `docker/test-compose.sh:270` defaults `HUGEGRAPH_VERSION` to
`latest` and nothing under `.github/` sets it, so `smoke` pulls Docker Hub
`hugegraph/pd:latest`, which predates this PR (`git grep '/v1/ready'
origin/master -- hugegraph-pd` is empty). Run 33642694186, job `build-server
(rocksdb, 11)`: pd `Started` 14:39:17, `Healthy` 14:39:28. Eleven seconds,
against an image with no readiness endpoint, so `Compose smoke passed: hstore`
does not exercise this change.
Not a regression, since the pre-PR `/v1/health` probe was liveness-only too.
But as written the switch buys nothing.
Requested change: check the payload, the way
`test-start-hugegraph-pd.sh:123` already does with `[[ "$body" ==
*'"ready":true'* ]]`. For this line:
test: ["CMD-SHELL", "curl -fsS http://localhost:8620/v1/ready | grep -q
'\"ready\":true'"]
and for `docker-compose-3pd-3store-3server.yml:40`, where the trailing `||
exit 1` has to sit after the pipeline:
test: ["CMD-SHELL", "curl -fsS http://localhost:8620/v1/ready | grep -q
'\"ready\":true' || exit 1"]
Left as plain blocks rather than committable suggestions on purpose:
applying them reds `docker/test-compose.sh smoke` until an image carrying
`/v1/ready` is published. Pin the smoke run to source-built images at the same
time, or keep the compose files on `/v1/health` and land the endpoint, gauges
and docs first.
##
hugegraph-pd/hg-pd-test/src/main/java/org/apache/hugegraph/pd/rest/RestApiTest.java:
##
@@ -62,6 +62,51 @@ public void testQueryClusterInfo() throws
URISyntaxException, IOException, Inter
assert obj.getInt("status") == 0;
}
+@Test
+public void testHealthNeedsNoAuth() throws URISyntaxException, IOException,
+ InterruptedException {
+String url = pdRestAddr + "/v1/health";
+HttpRequest request = HttpRequest.newBuilder().uri(new
URI(url)).GET().build();
+HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
+assert response.statusCode() == 200;
Review Comment:
🧹 `statusCode() == 200` cannot tell "no auth required" apart from "auth
rejected": PD's interceptor answers an unauthenticated request with `200` and
an error envelope, per the comment on `docker-compose-hstore.yml:47`. This test
would still pass if `/v1/health` were dropped from `AuthenticationConfigurer`.
`testReadyNeedsNoAuthAndReflectsRaft` is fine, because
`obj.getBoolean("ready")` would throw on that envelope.
Requested change: assert the body too. `checkHealthy()` returns `""`.
```suggestion
assert response.statusCode() == 200;
assert response.body().isEmpty() : "expected an empty body, got " +
response.body();
```
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/StoreAPI.java:
##
@@ -386,4 +396,30 @@ class StoreStatistics {
public Serializable checkHealthy() {
return "";
}
+
+/**
+ * Check Service Readiness
+ * Answers 200 only when this PD is part of a raft quorum, that is, the
raft node is active
+ * and knows the current leader. Otherwise answers 503 so that anything
gating on PD
+ * (the compose healthcheck in front of Stores, a Kubernetes readiness
probe)
+ * is held back until the PD can serve. Like /health this endpoint needs
no authentication.
+ *
+ * @return JSON with the readiness flag, the local raft state and the raft
address of the
+ * leader (null when there is none)
+ */
+@GetMapping(value = "/ready", produces = MediaType.APPLICATION_JSON_VALUE)
+public ResponseEntity> checkReady() {
+RaftEngine raft = RaftEngine.getInstance();
+boolean ready = raft.isReady();
+State state = raft.getNodeState();
+PeerId leader = raft.getLeader();
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
codecov[bot] commented on PR #3185: URL: https://github.com/apache/hugegraph/pull/3185#issuecomment-5510831418 ## [Codecov](https://app.codecov.io/gh/apache/hugegraph/pull/3185?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report :white_check_mark: All modified and coverable lines are covered by tests. :white_check_mark: Project coverage is 93.25%. Comparing base ([`98477f0`](https://app.codecov.io/gh/apache/hugegraph/commit/98477f0f56a3ad49593ec7632f2f0ee13e72f0dd?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`4dd7e71`](https://app.codecov.io/gh/apache/hugegraph/commit/4dd7e71c978e7c11f29be8bcad31b5d154da614c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)). Additional details and impacted files ```diff @@ Coverage Diff @@ ## master#3185 +/- ## = + Coverage 37.78% 93.25% +55.47% + Complexity 6556 65 -6491 = Files 8009 -791 Lines 68929 267-68662 Branches 9157 22 -9135 = - Hits 26046 249-25797 + Misses398248-39816 + Partials 3059 10 -3049 ``` [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/hugegraph/pull/3185?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache). :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache). :rocket: New features to boost your workflow: - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3915218299
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,67 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently knows a raft leader.
+ *
+ * A follower only keeps its leader id while heartbeats keep arriving
inside the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
A non-null leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs.
+ */
+public boolean hasLeader() {
+Node node = this.raftNode;
Review Comment:
Fixed in 5bd1b96. `raftNode` is now `private volatile Node raftNode`, and
`isReady()` passes its snapshot to a private static `hasLeader(Node)` that the
public `hasLeader()` also delegates to, so the field is read once per call.
Readiness unit tests still pass on JDK 11.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/StoreAPI.java:
##
@@ -386,4 +396,30 @@ class StoreStatistics {
public Serializable checkHealthy() {
return "";
}
+
+/**
+ * Check Service Readiness
+ * Answers 200 only when this PD is part of a raft quorum, that is, the
raft node is active
+ * and knows the current leader. Otherwise answers 503 so that anything
gating on PD
+ * (a Store waiting to register, the Server's wait-storage.sh, a
Kubernetes readiness probe)
Review Comment:
Fixed in 5bd1b96 with the suggested wording. The javadoc now names the
compose healthcheck in front of Stores and Kubernetes readiness probes as the
consumers, since `wait-storage.sh` polls `/v1/stores` and Stores register over
gRPC.
##
hugegraph-pd/docs/api-reference.md:
##
@@ -774,12 +774,54 @@ curl http://localhost:8620/actuator/health
}
```
+### Liveness and Readiness
+
+Two unauthenticated endpoints are meant for probes and startup gates:
+
+| Endpoint | Meaning | Status |
+|--|-||
+| `GET /v1/health` | Liveness: the REST listener is up. Does not consult raft.
| always `200` |
+| `GET /v1/ready` | Readiness: the raft node is active and sees a leader, so
this PD is inside a quorum. | `200` when ready, `503` otherwise |
+
+```bash
+curl -i http://localhost:8620/v1/ready
+```
+
+**Response** (leader of a healthy cluster):
+```json
+{
+ "ready": true,
+ "state": "STATE_LEADER",
+ "leader": "192.168.1.1:8610",
+ "isLeader": true
+}
+```
+
+A follower reports `"state": "STATE_FOLLOWER"` with the leader's raft address.
+When the quorum is lost the PD keeps answering `/v1/health` with `200` but
+`/v1/ready` turns into `503` with `"ready": false` and `"leader": null`.
+Point Kubernetes readiness probes, `depends_on` healthchecks and any
+"wait for PD" script at `/v1/ready`; keep liveness probes on `/v1/health`
+so a PD that merely lost its leader is not restarted.
+
### Metrics
```bash
curl http://localhost:8620/actuator/metrics
```
+Raft membership gauges (Prometheus names, scraped from `/actuator/prometheus`)
+for alerting on quorum loss:
+
+| Gauge | Value |
+|---|---|
+| `hg_raft_leader` | `1` on the raft leader, `0` elsewhere |
+| `hg_raft_has_leader` | `1` while this PD sees a leader (is inside a quorum),
`0` otherwise |
+| `hg_raft_alive_peers` | On the leader, the number of peers (itself included)
heard from within the election timeout; `NaN` on other nodes |
+
+A cluster has lost its quorum when `sum(hg_raft_leader) == 0` or when
+`hg_raft_has_leader == 0` on every member.
Review Comment:
Fixed in 5bd1b96. Took the suggested paragraph about the `for:` clause, and
moved the whole gauge block under a new "Raft membership gauges" heading after
the existing `/actuator/metrics` response example, so the `curl` fence and its
response stay together and the `pd_*` example no longer reads as output for the
`hg_*` table.
##
docker/README.md:
##
@@ -202,6 +202,14 @@ done
curl -fsS http://localhost:8088/about
```
+PD answers two unauthenticated probe endpoints. `/v1/health` is liveness only:
+it returns `200` as soon as the REST listener is up, even when the PD has no
+raft leader. `/v1/ready` returns `200` only while the PD sees a leader and
+`503` otherwise, so the compose healthchecks gate Stores on `/v1/ready`. A
+single PD elects itself; three PDs become ready once two can talk to each
+other.
Review Comment:
Fixed in 5bd1b96. The paragraph now says `/v1/ready` first ships in 1.8.0,
spells out the failure mode with an older `HUGEGRAPH_VERSION` (PD healthcheck
never passes, Stores never start), and points at pinning 1.8.0
Re: [PR] feat(pd): add quorum-aware /v1/ready endpoint and raft gauges [hugegraph]
bitflicker64 commented on code in PR #3185:
URL: https://github.com/apache/hugegraph/pull/3185#discussion_r3915168039
##
hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftEngine.java:
##
@@ -203,7 +204,67 @@ public void shutDown() {
}
public boolean isLeader() {
-return this.raftNode.isLeader(true);
+Node node = this.raftNode;
+return node != null && node.isLeader(true);
+}
+
+/**
+ * Whether this node currently knows a raft leader.
+ *
+ * A follower only keeps its leader id while heartbeats keep arriving
inside the election
+ * timeout, and a leader only keeps its role while it can reach a quorum.
A non-null leader
+ * therefore means this node is part of a quorum from its own point of
view, which is the
+ * signal a readiness probe needs.
+ */
+public boolean hasLeader() {
+Node node = this.raftNode;
Review Comment:
🧹 `raftNode` (line 73) is a plain field. It is written inside `synchronized
init(...)`, and read without synchronization here and in `isReady()`,
`getNodeState()`, `isLeader()`, `getLeader()` and `getAlivePeerCount()`.
Publication is safe today, but only incidentally: all three callers of
`init(...)` are `@PostConstruct` (`PDService:179`, `DiscoveryService:59`,
`KvServiceGrpcImpl:75`), so the write happens during context refresh, before
the Tomcat connector accepts and before the gRPC server starts. The null checks
this PR adds are now the contract behind `/v1/ready` and the `hg.raft.*`
gauges, both read from threads that never touch the write lock, so it is worth
not depending on that ordering.
Requested change: declare the field `private volatile Node raftNode;` at
line 73.
While here: `isReady()` snapshots the field into `node`, then delegates to
`hasLeader()`, which reads it a second time. Harmless, but a private
`hasLeader(Node)` overload would keep the snapshot idiom consistent.
##
hugegraph-pd/hg-pd-service/src/main/java/org/apache/hugegraph/pd/rest/StoreAPI.java:
##
@@ -386,4 +396,30 @@ class StoreStatistics {
public Serializable checkHealthy() {
return "";
}
+
+/**
+ * Check Service Readiness
+ * Answers 200 only when this PD is part of a raft quorum, that is, the
raft node is active
+ * and knows the current leader. Otherwise answers 503 so that anything
gating on PD
+ * (a Store waiting to register, the Server's wait-storage.sh, a
Kubernetes readiness probe)
Review Comment:
🧹 `wait-storage.sh` does not gate on this endpoint. It polls
`http://${peer}/v1/stores` and greps for `"state":"Up"`
(`hugegraph-server/hugegraph-dist/src/assembly/static/bin/wait-storage.sh:104-110`),
and this PR does not change it. The Store itself registers over gRPC, so the
only thing actually held back by `/v1/ready` today is the compose healthcheck.
Requested change: drop the `wait-storage.sh` reference.
```suggestion
* (the compose healthcheck in front of Stores, a Kubernetes readiness
probe)
```
##
hugegraph-pd/docs/api-reference.md:
##
@@ -774,12 +774,54 @@ curl http://localhost:8620/actuator/health
}
```
+### Liveness and Readiness
+
+Two unauthenticated endpoints are meant for probes and startup gates:
+
+| Endpoint | Meaning | Status |
+|--|-||
+| `GET /v1/health` | Liveness: the REST listener is up. Does not consult raft.
| always `200` |
+| `GET /v1/ready` | Readiness: the raft node is active and sees a leader, so
this PD is inside a quorum. | `200` when ready, `503` otherwise |
+
+```bash
+curl -i http://localhost:8620/v1/ready
+```
+
+**Response** (leader of a healthy cluster):
+```json
+{
+ "ready": true,
+ "state": "STATE_LEADER",
+ "leader": "192.168.1.1:8610",
+ "isLeader": true
+}
+```
+
+A follower reports `"state": "STATE_FOLLOWER"` with the leader's raft address.
+When the quorum is lost the PD keeps answering `/v1/health` with `200` but
+`/v1/ready` turns into `503` with `"ready": false` and `"leader": null`.
+Point Kubernetes readiness probes, `depends_on` healthchecks and any
+"wait for PD" script at `/v1/ready`; keep liveness probes on `/v1/health`
+so a PD that merely lost its leader is not restarted.
+
### Metrics
```bash
curl http://localhost:8620/actuator/metrics
```
+Raft membership gauges (Prometheus names, scraped from `/actuator/prometheus`)
+for alerting on quorum loss:
+
+| Gauge | Value |
+|---|---|
+| `hg_raft_leader` | `1` on the raft leader, `0` elsewhere |
+| `hg_raft_has_leader` | `1` while this PD sees a leader (is inside a quorum),
`0` otherwise |
+| `hg_raft_alive_peers` | On the leader, the number of peers (itself included)
heard from within the election timeout; `NaN` on other nodes |
+
+A cluster has lost its quorum when `sum(hg_raft_leader) == 0` or when
+`hg_raft_has_leader == 0` on every member.
Review Comment:
🧹 Both expressions
