Repository navigation
[improve][broker] PIP-192 Added ServiceUnitStateChannelImpl - #18489
Conversation
|
this PR implements #18079 |
ad00e19 to
e2a9365
Compare
e2a9365 to
e26e290
Compare
| } | ||
|
|
||
| public String getChannelOwner() { | ||
| CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); |
There was a problem hiding this comment.
I think that we are not handling concurrent access on "leaderElectionService"
in "start" we re-assign the value to the variable.
I would make it final or properly handle concurrent access
There was a problem hiding this comment.
- Added a private variable
volatile boolean isActiveand set this flag in start() and close(). - Made start() and close() synchronized.
- Added validateChannel() to validate concurrent access to
leaderElectionService, producer, and tableviewwhileisActive=false. - Added a UT to cover this access logic.
There was a problem hiding this comment.
In fact, we need further the channel state breakdown (boolean isActive is not enough because getChannelOwner() should be accessible while creating the producer and tableview on the system topic -- the topic owner lookup will call getChannelOwner().
I added the enum StateChannel to differentiate the channel states.
There was a problem hiding this comment.
I wonder why spotbugs is not complaining about "unconsistent sync" on leaderElectionService.
because we still have an access without "synchonized".
I believe that you can add a getter
private synchronised LeaderElectionService leaderElectionService() { ... }
and call it here
There was a problem hiding this comment.
why can't we make it "final" and assign it in the constructor, without calling "start" in the constructor?
There was a problem hiding this comment.
Made it final.
Updated.
There was a problem hiding this comment.
About the concurrent access to the member variables, still 'tableview' and 'producer' are not final.
Could you explain why we need the synchronized access to the 'leaderElectionService' instance?
(Don't we also need to worry about the synchronized access to tableview and producer?)
As long as it's non-null, shouldn't it be ok whether the return(leader) is from the old or new instance of 'leaderElectionService'?
There was a problem hiding this comment.
You are correct we have to handle correctly synchronization around tableview and producer.
The reason is related to the Java Memory Model.
If you access a field from multiple threads you are not guaranteed that each threads see the same value if you use any synchronization mechanism (there are many)
Spot bugs usually finds this problems
There was a problem hiding this comment.
Aren't the current state channel validation and synchronized start/close func enough? The invalid channel state can throw exception when the getter funcs are called during start() and close(). AFAIK, the previous setter instructions (producer and tableview setter) should be piggybacked by the volatile channelState=Started flush(by the JMM happen-before piggyback)
If this is not sufficient, can you explain why? And do you suggest forcefully synchronized access like 'synchronized getProducer()/setProducer() and synchronized getTableView()/setTableView()?
We could use ReadWriteLock to optimize this, but isn't it an overkill?
| private CompletableFuture<MessageId> pubAsync(String serviceUnit, ServiceUnitStateData data) { | ||
| CompletableFuture<MessageId> future = new CompletableFuture<>(); | ||
| try { | ||
| outstandingPubMessages.acquire(); |
There was a problem hiding this comment.
blocking in a method that returns a CompletableFuture is usually a code smell and it leads to performance problems.
BUT At the moment I am not aware of a better way to do this in Pulsar codebase
There was a problem hiding this comment.
The intention was to limit the pubAsync concurrency from this channel not to exhaust the broker threads.
I removed this semaphore.
| if (broker == null) { | ||
| return false; | ||
| } | ||
| // TODO: remove broker port from the input broker |
There was a problem hiding this comment.
we should not remove the port, otherwise you won't be able to execute two brokers on the same host (I do it frequently with Pulsar standalone)
There was a problem hiding this comment.
Removed the comment.
shibd
left a comment
There was a problem hiding this comment.
I was confused reading the code related to the ServiceUnitState state machine:
publishUnloadEventAsyncmethod theAssignedevent is published. Although I eventually understood, this unloaded action came withdestBrokerand then retriggered the assigned.- Although you defined the
ServiceUnitState.isValidTransition()method, you did not use it when modifying the state.
Let's revisit the concept:
- Command(Action): assign, unload, release, own, etc.
- Status: owned, released, assigned, splitting, free
- Event: ServiceUnitStateData(Assigned, Splitting)
The state is command-driven, and then generates events that synchronize to other nodes.
My ideal approach would be something like this:
handleCommand(Command command) {
switch(command) {
case(assign):
// free --> assigned
transStatus(currentStatus, command);
publishEvent();
break;
case(unload):
// owned --> free
transStatus(currentStatus, command);
// trigger free --> assigned
handleCommand(assign);
break;
etc.
}
}For event, only sync status
handleEvent(Event event) {
switch(event) {
case(Assigned):
case(Splitting):
}
}| var assigned2 = channel2.publishAssignEventAsync(bundle, lookupServiceAddress2); | ||
| assertNotNull(assigned1); | ||
| assertNotNull(assigned2); | ||
| waitUntilOwnerChanges(channel2, bundle, null); |
There was a problem hiding this comment.
| waitUntilOwnerChanges(channel2, bundle, null); | |
| waitUntilOwnerChanges(channel1, bundle, null); |
There was a problem hiding this comment.
I think adding the Command layer is additional complexity and requires more lines of code. Also, the current approach does not need to store the additional Command info in the system topic(space optimized).
Regarding ServiceUnitState.isValidTransition(), the state validation(aka compaction) will happen in the tableview and topic compaction by TopicCompactionStrategy(which is in a separate PIP and PR here, #18099). This validation logic, ServiceUnitChannelCompactionStrategy will be added after this PR #18195 gets merged.
There was a problem hiding this comment.
Thanks for the waitUntilOwnerChanges(channel1, bundle, null); catch.
updated.
There was a problem hiding this comment.
I think adding the
Commandlayer is additional complexity and requires more lines of code. Also, the current approach does not need to store the additionalCommandinfo in the system topic(space optimized).Regarding
ServiceUnitState.isValidTransition(), the state validation(aka compaction) will happen in the tableview and topic compaction byTopicCompactionStrategy(which is in a separate PIP and PR here, #18099). This validation logic, ServiceUnitChannelCompactionStrategy will be added after this PR #18195 gets merged.
Thanks for the explanation, I'm not quite sure if my proposal is reasonable. I'll wait for other features to be added and revisit
| + "://" | ||
| + NamespaceName.SYSTEM_NAMESPACE | ||
| + "/service-unit-state-channel"; | ||
| private static final Schema<ServiceUnitStateData> SCHEMA = Schema.JSON(ServiceUnitStateData.class); |
There was a problem hiding this comment.
We should not cache Schema objects in "static" variables.
Schema is stateful and it is injected with a reference to the PulsarClient. Maybe this is not the case for JSON and for the current version, but it is better to not do it.
Please move this to a instance field
| } | ||
|
|
||
| public synchronized void start() throws PulsarServerException { | ||
| try { |
There was a problem hiding this comment.
we can add a check on channelState
| } | ||
|
|
||
| public String getChannelOwner() { | ||
| CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); |
There was a problem hiding this comment.
I wonder why spotbugs is not complaining about "unconsistent sync" on leaderElectionService.
because we still have an access without "synchonized".
I believe that you can add a getter
private synchronised LeaderElectionService leaderElectionService() { ... }
and call it here
| } | ||
|
|
||
| public String getChannelOwner() { | ||
| CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); |
There was a problem hiding this comment.
why can't we make it "final" and assign it in the constructor, without calling "start" in the constructor?
| .sendAsync() | ||
| .whenComplete((messageId, e) -> { | ||
| if (e != null) { | ||
| future.completeExceptionally(e); |
There was a problem hiding this comment.
what about logging the error here ?
| .whenComplete((__, ex) -> { | ||
| double splitBundleTime = TimeUnit.NANOSECONDS | ||
| .toMillis((System.nanoTime() - startTime)); | ||
| log.info("Splitting {} namespace-bundle completed in {} ms", |
There was a problem hiding this comment.
we should log it as ERROR and not "info" in case ex is not null (and log the error)
8b52326 to
07d6022
Compare
| } | ||
|
|
||
| public String getChannelOwner() { | ||
| CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); |
There was a problem hiding this comment.
You are correct we have to handle correctly synchronization around tableview and producer.
The reason is related to the Java Memory Model.
If you access a field from multiple threads you are not guaranteed that each threads see the same value if you use any synchronization mechanism (there are many)
Spot bugs usually finds this problems
eolivelli
left a comment
There was a problem hiding this comment.
+1
let's move forward.
I will probably post other comments later
| assertNotNull(channel.getChannelOwner()); | ||
|
|
||
| // start() -> start() test. | ||
| IllegalStateException ex = null; |
There was a problem hiding this comment.
Suggestion use: assertThrows(IllegalStateException.class, () -> channel.start());
| public String getChannelOwner() { | ||
| validateChannelState(LeaderElectionServiceStarted, true); | ||
| CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader(); | ||
| if (!future.isDone()) { |
There was a problem hiding this comment.
When the future is not done, we should wait for it, right? We should remove 255~257, otherwise unit test channelValidationTest doesn't pass.
There was a problem hiding this comment.
As PengHui suggested, we will make this return CompletedFuture.
| .setCompactionThreshold(TOPIC, COMPACTION_THRESHOLD); | ||
| log.info("Scheduled compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); | ||
| } else { | ||
| log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); |
There was a problem hiding this comment.
| log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD); | |
| log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, threshold); |
There was a problem hiding this comment.
removed this compaction schedule api as not required.
| } | ||
| } | ||
|
|
||
| public synchronized void scheduleCompaction() throws PulsarServerException { |
There was a problem hiding this comment.
Who called this method? It looks like we only need to call it once at the start.
There was a problem hiding this comment.
+1
If the namespace or top enabled the compaction task, it looks like we don't need to implement it again.
And the system topic has enabled the compaction be default
There was a problem hiding this comment.
Ack. Removing this api
| } | ||
| } | ||
|
|
||
| public synchronized void scheduleCompaction() throws PulsarServerException { |
There was a problem hiding this comment.
+1
If the namespace or top enabled the compaction task, it looks like we don't need to implement it again.
And the system topic has enabled the compaction be default
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #18489 +/- ##
============================================
+ Coverage 45.62% 46.95% +1.33%
- Complexity 10075 10490 +415
============================================
Files 697 699 +2
Lines 68024 68728 +704
Branches 7293 7374 +81
============================================
+ Hits 31033 32269 +1236
+ Misses 33413 32856 -557
- Partials 3578 3603 +25
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…8489) ### Modifications This PR Added ServiceUnitStateChannelImpl and its unit test. For the pip-192 project, this ServiceUnitStateChannelImpl - has a tableview and a producer on the system topic, persistent://pulsar/system/service-unit-state-channel - has a leader coordination service to elect the owner broker of the channel. - define message handlers according to the service unit state changes. - define ownership cleanup logic in case a broker is unregistered (dead).
Fixes #xyz
Master Issue: #16691
Motivation
We will start raising PRs to implement PIP-192, #16691
Modifications
This PR Added ServiceUnitStateChannelImpl and its unit test.
For the pip-192 project, this ServiceUnitStateChannelImpl
Verifying this change
This change added tests and can be verified as follows:
Does this pull request potentially affect one of the following parts:
If the box was checked, please highlight the changes
Documentation
docdoc-requireddoc-not-neededdoc-completeWe will have separate PRs to update the Doc later.
Matching PR in forked repository
PR in forked repository: heesung-sohn#14