Skip to content

[improve][broker] PIP-192 Added ServiceUnitStateChannelImpl - #18489

Merged
codelipenghui merged 6 commits into
apache:masterfrom
heesung-sohn:pip-192-bsc-impl
Dec 2, 2022
Merged

codelipenghui merged 6 commits into
apache:masterfrom
heesung-sohn:pip-192-bsc-impl

Conversation

@heesung-sohn

Copy link
Copy Markdown
Contributor

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

  • 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).

Verifying this change

  • Make sure that the change passes the CI checks.

This change added tests and can be verified as follows:

  • *Added unit tests for the new classes.

Does this pull request potentially affect one of the following parts:

If the box was checked, please highlight the changes

  • Dependencies (add or upgrade a dependency)
  • The public API
  • The schema
  • The default values of configurations
  • The threading model
  • The binary protocol
  • The REST endpoints
  • The admin CLI options
  • Anything that affects deployment

Documentation

  • doc
  • doc-required
  • doc-not-needed
  • doc-complete

We will have separate PRs to update the Doc later.

Matching PR in forked repository

PR in forked repository: heesung-sohn#14

@heesung-sohn

Copy link
Copy Markdown
Contributor Author

this PR implements #18079

}

public String getChannelOwner() {
CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Added a private variable volatile boolean isActive and set this flag in start() and close().
  • Made start() and close() synchronized.
  • Added validateChannel() to validate concurrent access to leaderElectionService, producer, and tableview while isActive=false.
  • Added a UT to cover this access logic.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why can't we make it "final" and assign it in the constructor, without calling "start" in the constructor?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made it final.

Updated.

@heesung-sohn heesung-sohn Nov 20, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@heesung-sohn heesung-sohn Nov 20, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the comment.

@shibd shibd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was confused reading the code related to the ServiceUnitState state machine:

  1. publishUnloadEventAsync method the Assigned event is published. Although I eventually understood, this unloaded action came with destBroker and then retriggered the assigned.
  2. 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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
waitUntilOwnerChanges(channel2, bundle, null);
waitUntilOwnerChanges(channel1, bundle, null);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the waitUntilOwnerChanges(channel1, bundle, null); catch.

updated.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated.

}

public synchronized void start() throws PulsarServerException {
try {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can add a check on channelState

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated.

}

public String getChannelOwner() {
CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about logging the error here ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated.

.whenComplete((__, ex) -> {
double splitBundleTime = TimeUnit.NANOSECONDS
.toMillis((System.nanoTime() - startTime));
log.info("Splitting {} namespace-bundle completed in {} ms",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should log it as ERROR and not "info" in case ex is not null (and log the error)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated.

}

public String getChannelOwner() {
CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@heesung-sohn
heesung-sohn requested review from eolivelli and shibd and removed request for eolivelli and shibd November 21, 2022 18:44

@eolivelli eolivelli left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

let's move forward.
I will probably post other comments later

@shibd shibd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left some minor comments.

assertNotNull(channel.getChannelOwner());

// start() -> start() test.
IllegalStateException ex = null;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion use: assertThrows(IllegalStateException.class, () -> channel.start());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated.

public String getChannelOwner() {
validateChannelState(LeaderElectionServiceStarted, true);
CompletableFuture<Optional<LeaderBroker>> future = leaderElectionService.readCurrentLeader();
if (!future.isDone()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the future is not done, we should wait for it, right? We should remove 255~257, otherwise unit test channelValidationTest doesn't pass.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, COMPACTION_THRESHOLD);
log.info("Already set compaction on topic:{}, threshold:{} bytes", TOPIC, threshold);

@heesung-sohn heesung-sohn Nov 29, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed this compaction schedule api as not required.

}
}

public synchronized void scheduleCompaction() throws PulsarServerException {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Who called this method? It looks like we only need to call it once at the start.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+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

public boolean isCompactionEnabled() {
// All system topics are using compaction except `HealthCheck`,
// even though is not explicitly set in the policies.
return !NamespaceService.isHeartbeatNamespace(TopicName.get(topic));
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ack. Removing this api

@codelipenghui codelipenghui added this to the 2.12.0 milestone Nov 23, 2022
@codelipenghui codelipenghui added type/feature The PR added a new feature or issue requested a new feature area/broker labels Nov 23, 2022
}
}

public synchronized void scheduleCompaction() throws PulsarServerException {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+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

public boolean isCompactionEnabled() {
// All system topics are using compaction except `HealthCheck`,
// even though is not explicitly set in the policies.
return !NamespaceService.isHeartbeatNamespace(TopicName.get(topic));
}

@codecov-commenter

codecov-commenter commented Nov 23, 2022 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 402 lines in your changes missing coverage. Please review.
✅ Project coverage is 46.95%. Comparing base (7975023) to head (154b7ba).
⚠️ Report is 3326 commits behind head on master.

Files with missing lines Patch % Lines
...xtensions/channel/ServiceUnitStateChannelImpl.java 0.00% 402 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             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     
Flag Coverage Δ
unittests 46.95% <0.00%> (+1.33%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...xtensions/channel/ServiceUnitStateChannelImpl.java 0.00% <0.00%> (ø)

... and 109 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@codelipenghui
codelipenghui merged commit 0278b7c into apache:master Dec 2, 2022
lifepuzzlefun pushed a commit to lifepuzzlefun/pulsar that referenced this pull request Jan 10, 2023
…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).
@heesung-sohn
heesung-sohn deleted the pip-192-bsc-impl branch April 2, 2024 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/broker doc-not-needed Your PR changes do not impact docs ready-to-test type/feature The PR added a new feature or issue requested a new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants