GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][broker] Revalidate ownership before loading fenced topics (#27285) · apache/pulsar@b7f7f9e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pulsar-broker/src
    • main/java/org/apache/pulsar/broker
      • namespace
        • NamespaceService.java
        • OwnershipCache.java
      • service
        • BrokerService.java
        • TopicLoadingContext.java
        • persistent
          • PersistentTopic.java
    • test/java/org/apache/pulsar/broker
      • loadbalance/extensions
        • ExtensibleLoadManagerCloseTest.java
      • namespace
        • OwnershipCacheTest.java
      • service
        • BrokerServiceTest.java
        • BrokerServiceTopicDeletionTest.java
        • NamespaceReadmissionAfterFencingTest.java
        • PersistentTopicTest.java
        • ServerCnxTest.java
      • transaction/buffer
        • TopicTransactionBufferTest.java
  • pulsar-metadata/src
    • main/java/org/apache/pulsar/metadata
      • api/coordination
        • ResourceLock.java
      • coordination/impl
        • ResourceLockImpl.java
    • test/java/org/apache/pulsar/metadata
      • ResourceLockValidationTest.java
      • impl
        • DualMetadataStoreSyncTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/NamespaceService.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/NamespaceService.java
+16-1Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,20 @@ public void handleOwnershipTakenOver(TopicName topicName) {
309309
});
310310
}
311311

312+
/** A loaded fenced topic must verify its legacy namespace lock before it can be loaded again. */
313+
public void requireFreshOwnershipBeforeReadmission(TopicName topicName) {
314+
if (!ExtensibleLoadManagerImpl.isLoadManagerExtensionEnabled(pulsar)) {
315+
ownershipCache.requireFreshOwnershipBeforeReadmission(topicName);
316+
}
317+
}
318+
319+
public Supplier<CompletableFuture<Boolean>> newTopicOwnershipChecker(TopicName topicName) {
320+
if (ExtensibleLoadManagerImpl.isLoadManagerExtensionEnabled(pulsar)) {
321+
return () -> checkTopicOwnership(topicName);
322+
}
323+
return ownershipCache.newTopicOwnershipChecker(topicName);
324+
}
325+
312326
public NamespaceBundle getBundle(TopicName topicName) {
313327
return bundleFactory.getBundles(topicName.getNamespaceObject()).findBundle(topicName);
314328
}
@@ -1385,7 +1399,7 @@ public CompletableFuture<Boolean> checkBundleOwnership(TopicName topicName, Name
13851399
// TODO: Add unit tests cover it.
13861400
return loadManager.get().checkOwnershipAsync(Optional.of(topicName), bundle);
13871401
} else {
1388-
return ownershipCache.checkOwnershipAsync(bundle);
1402+
return ownershipCache.checkOwnershipAsync(topicName, bundle);
13891403
}
13901404
}
13911405

@@ -2021,6 +2035,7 @@ public boolean registerSLANamespace() throws PulsarServerException {
20212035

20222036
@Override
20232037
public void close() {
2038+
ownershipCache.clearFencedTopicReadmissions();
20242039
namespaceClients.forEach((cluster, client) -> {
20252040
try {
20262041
client.shutdown();
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/OwnershipCache.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/namespace/OwnershipCache.java
+231Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,12 @@
2121
import com.github.benmanes.caffeine.cache.AsyncCacheLoader;
2222
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
2323
import com.github.benmanes.caffeine.cache.Caffeine;
24+
import com.github.benmanes.caffeine.cache.RemovalCause;
2425
import com.google.common.annotations.VisibleForTesting;
2526
import com.google.common.util.concurrent.MoreExecutors;
27+
import java.time.Duration;
2628
import java.util.ArrayList;
29+
import java.util.HashMap;
2730
import java.util.List;
2831
import java.util.Map;
2932
import java.util.Optional;
@@ -40,6 +43,7 @@
4043
import lombok.CustomLog;
4144
import org.apache.pulsar.broker.PulsarService;
4245
import org.apache.pulsar.broker.service.BrokerServiceException.MetadataSessionLostException;
46+
import org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException;
4347
import org.apache.pulsar.broker.service.Topic;
4448
import org.apache.pulsar.common.naming.NamespaceBundle;
4549
import org.apache.pulsar.common.naming.NamespaceBundles;
@@ -101,6 +105,28 @@ public class OwnershipCache {
101105
*/
102106
private final AsyncLoadingCache<NamespaceBundle, OwnedBundle> ownedBundlesCache;
103107

108+
// Markers retain no Topic and are removed with the captured ownership generation.
109+
private final Map<String, FencedTopicReadmission> fencedTopicReadmissions = new ConcurrentHashMap<>();
110+
111+
private static final class FencedTopicReadmission {
112+
private final NamespaceBundle bundle;
113+
private final CompletableFuture<OwnedBundle> ownership;
114+
private final Map<NamespaceBundle, CompletableFuture<OwnedBundle>> unresolvedOwnerships;
115+
private CompletableFuture<Boolean> verification;
116+
117+
private FencedTopicReadmission(NamespaceBundle bundle, CompletableFuture<OwnedBundle> ownership) {
118+
this.bundle = bundle;
119+
this.ownership = ownership;
120+
this.unresolvedOwnerships = Map.of();
121+
}
122+
123+
private FencedTopicReadmission(Map<NamespaceBundle, CompletableFuture<OwnedBundle>> unresolvedOwnerships) {
124+
this.bundle = null;
125+
this.ownership = null;
126+
this.unresolvedOwnerships = unresolvedOwnerships;
127+
}
128+
}
129+
104130
/**
105131
* The <code>NamespaceService</code> which using <code>OwnershipCache</code>.
106132
*/
@@ -202,6 +228,8 @@ public OwnershipCache(PulsarService pulsar, NamespaceService namespaceService) {
202228
this.ownedBundlesCache = Caffeine.newBuilder()
203229
.executor(MoreExecutors.directExecutor())
204230
.recordStats()
231+
.removalListener((NamespaceBundle bundle, OwnedBundle ownedBundle, RemovalCause cause) ->
232+
discardFencedTopicReadmissions(ownedBundle))
205233
.buildAsync(new OwnedServiceUnitCacheLoader());
206234
CacheMetricsCollector.CAFFEINE.addCache("owned-bundles", this.ownedBundlesCache);
207235
}
@@ -221,6 +249,209 @@ public CompletableFuture<Boolean> checkOwnershipAsync(NamespaceBundle bundle) {
221249
.thenApply(bd -> bd != null && bd.isActive());
222250
}
223251

252+
/** Bind every stage of a pending load to the ownership that existed before its topic future was published. */
253+
Supplier<CompletableFuture<Boolean>> newTopicOwnershipChecker(TopicName topicName) {
254+
FencedTopicReadmission readmission = fencedTopicReadmissions.get(topicName.toString());
255+
Optional<NamespaceBundle> resolved = namespaceService.getBundleIfPresent(topicName);
256+
if (resolved.isEmpty()) {
257+
// Only the cold-cache fallback snapshots local generations. Resolve through the configured strategy
258+
// asynchronously, without adopting ownership acquired after this load began.
259+
Map<NamespaceBundle, CompletableFuture<OwnedBundle>> captured = captureNamespaceOwnerships(topicName);
260+
CompletableFuture<Supplier<CompletableFuture<Boolean>>> checker =
261+
FutureUtil.supplySafely(() -> namespaceService.getBundleAsync(topicName))
262+
.thenApply(bundle -> newTopicOwnershipChecker(topicName, bundle, captured.get(bundle),
263+
readmission));
264+
return () -> checker.thenCompose(Supplier::get);
265+
}
266+
NamespaceBundle bundle = resolved.get();
267+
return newTopicOwnershipChecker(topicName, bundle, ownedBundlesCache.getIfPresent(bundle), readmission);
268+
}
269+
270+
private Supplier<CompletableFuture<Boolean>> newTopicOwnershipChecker(TopicName topicName, NamespaceBundle bundle,
271+
CompletableFuture<OwnedBundle> ownership, FencedTopicReadmission readmission) {
272+
if (ownership == null) {
273+
return () -> CompletableFuture.completedFuture(false);
274+
}
275+
return () -> {
276+
if (ownedBundlesCache.getIfPresent(bundle) != ownership
277+
|| (readmission != null
278+
&& fencedTopicReadmissions.get(topicName.toString()) != readmission)) {
279+
return CompletableFuture.completedFuture(false);
280+
}
281+
return ownership.thenCompose(ownedBundle -> {
282+
if (ownedBundle == null || !ownedBundle.isActive()
283+
|| ownedBundlesCache.getIfPresent(bundle) != ownership) {
284+
return CompletableFuture.completedFuture(false);
285+
}
286+
return checkOwnershipAsync(topicName, bundle).thenApply(owned -> owned
287+
&& ownedBundlesCache.getIfPresent(bundle) == ownership && ownedBundle.isActive()
288+
&& (readmission == null
289+
|| fencedTopicReadmissions.get(topicName.toString()) == readmission));
290+
});
291+
};
292+
}
293+
294+
private Map<NamespaceBundle, CompletableFuture<OwnedBundle>> captureNamespaceOwnerships(TopicName topicName) {
295+
Map<NamespaceBundle, CompletableFuture<OwnedBundle>> captured = new HashMap<>();
296+
ownedBundlesCache.asMap().forEach((bundle, ownership) -> {
297+
if (bundle.getNamespaceObject().equals(topicName.getNamespaceObject())
298+
&& (!ownership.isDone()
299+
|| (!ownership.isCompletedExceptionally() && ownership.join().isActive()))) {
300+
captured.put(bundle, ownership);
301+
}
302+
});
303+
return Map.copyOf(captured);
304+
}
305+
306+
/** Capture locally; the namespace bundle metadata cache may be cold during an outage. */
307+
void requireFreshOwnershipBeforeReadmission(TopicName topicName) {
308+
String topic = topicName.toString();
309+
Optional<NamespaceBundle> resolved = namespaceService.getBundleIfPresent(topicName);
310+
if (resolved.isEmpty()) {
311+
// Do not lose the gate when an invalidation made the bundle metadata unavailable. Bind it to the
312+
// strategy-selected bundle on the next check, before allowing authoritative validation to proceed.
313+
Map<NamespaceBundle, CompletableFuture<OwnedBundle>> captured = captureNamespaceOwnerships(topicName);
314+
if (!captured.isEmpty()) {
315+
FencedTopicReadmission check = new FencedTopicReadmission(captured);
316+
FencedTopicReadmission installed = fencedTopicReadmissions.compute(topic, (name, previous) ->
317+
previous != null && previous.ownership != null
318+
&& captured.get(previous.bundle) == previous.ownership ? previous : check);
319+
if (installed == check && !hasCapturedOwnership(check)) {
320+
// A release can finish between the snapshot and publication of this marker.
321+
fencedTopicReadmissions.remove(topic, check);
322+
}
323+
}
324+
return;
325+
}
326+
NamespaceBundle bundle = resolved.get();
327+
ownedBundlesCache.asMap().computeIfPresent(bundle, (key, current) -> {
328+
if (current.isDone() && !current.isCompletedExceptionally() && current.join().isActive()) {
329+
fencedTopicReadmissions.compute(topic, (name, previous) ->
330+
previous != null && previous.ownership == current
331+
? previous : new FencedTopicReadmission(bundle, current));
332+
}
333+
return current;
334+
});
335+
}
336+
337+
CompletableFuture<Boolean> checkOwnershipAsync(TopicName topicName, NamespaceBundle bundle) {
338+
String topic = topicName.toString();
339+
FencedTopicReadmission check = fencedTopicReadmissions.get(topic);
340+
if (check == null) {
341+
return checkOwnershipAsync(bundle);
342+
}
343+
if (check.ownership == null) {
344+
CompletableFuture<OwnedBundle> ownership = ownedBundlesCache.getIfPresent(bundle);
345+
if (ownership != check.unresolvedOwnerships.get(bundle)) {
346+
fencedTopicReadmissions.remove(topic, check);
347+
return CompletableFuture.completedFuture(false);
348+
}
349+
if (ownership == null || !ownership.isDone() || ownership.isCompletedExceptionally()
350+
|| !ownership.join().isActive()) {
351+
return CompletableFuture.completedFuture(false);
352+
}
353+
FencedTopicReadmission resolved = new FencedTopicReadmission(bundle, ownership);
354+
if (!fencedTopicReadmissions.replace(topic, check, resolved)) {
355+
return CompletableFuture.completedFuture(false);
356+
}
357+
check = resolved;
358+
}
359+
if (!bundle.equals(check.bundle) || ownedBundlesCache.getIfPresent(check.bundle) != check.ownership) {
360+
fencedTopicReadmissions.remove(topic, check);
361+
return CompletableFuture.completedFuture(false);
362+
}
363+
return verifyFencedTopicOwnership(topic, check);
364+
}
365+
366+
private CompletableFuture<Boolean> verifyFencedTopicOwnership(String topic, FencedTopicReadmission check) {
367+
final CompletableFuture<Boolean> result;
368+
try {
369+
synchronized (check) {
370+
if (check.verification != null) {
371+
return check.verification;
372+
}
373+
result = FutureUtil.createFutureWithTimeout(
374+
Duration.ofSeconds(pulsar.getConfiguration().getMetadataStoreOperationTimeoutSeconds()),
375+
pulsar.getExecutor(), () -> new ServiceUnitNotReadyException(
376+
"Timed out verifying namespace ownership before reloading fenced topic " + topic));
377+
check.verification = result;
378+
}
379+
// The lock serializes its authoritative read with in-place revalidation, updates and release.
380+
// Foreign ownership expires it through the normal lock-manager and namespace expiry callbacks.
381+
FutureUtil.supplySafely(() -> check.ownership.join().getResourceLock().validate())
382+
.whenComplete((__, error) -> {
383+
try {
384+
if (error != null) {
385+
result.completeExceptionally(new ServiceUnitNotReadyException(
386+
"Cannot verify namespace ownership before reloading fenced topic " + topic,
387+
FutureUtil.unwrapCompletionException(error)));
388+
return;
389+
}
390+
synchronized (check) {
391+
if (check.verification != result || result.isDone()) {
392+
return;
393+
}
394+
if (fencedTopicReadmissions.get(topic) != check
395+
|| ownedBundlesCache.getIfPresent(check.bundle) != check.ownership) {
396+
// This pending load cannot become a load of a later ownership generation.
397+
result.complete(false);
398+
return;
399+
}
400+
fencedTopicReadmissions.remove(topic, check);
401+
// The next attempt starts after this proof. Do not authorize a pending future that an
402+
// earlier unload may already have captured, even if this lock was restored in place.
403+
result.complete(false);
404+
}
405+
} finally {
406+
// A caller timeout does not cancel the lock's queued operation. Keep sharing that
407+
// timed-out future until the actual operation ends instead of adding more validations.
408+
synchronized (check) {
409+
if (check.verification == result) {
410+
check.verification = null;
411+
}
412+
}
413+
}
414+
});
415+
return result;
416+
} catch (RuntimeException error) {
417+
return FutureUtil.failedFuture(new ServiceUnitNotReadyException(
418+
"Cannot verify namespace ownership before reloading fenced topic " + topic, error));
419+
}
420+
}
421+
422+
private void discardFencedTopicReadmissions(OwnedBundle ownedBundle) {
423+
fencedTopicReadmissions.forEach((topic, check) -> {
424+
boolean obsolete = check.ownership != null ? check.ownership.getNow(null) == ownedBundle
425+
: !hasCapturedOwnership(check);
426+
if (obsolete && fencedTopicReadmissions.remove(topic, check)) {
427+
completeObsoleteReadmission(check);
428+
}
429+
});
430+
}
431+
432+
private boolean hasCapturedOwnership(FencedTopicReadmission check) {
433+
return check.unresolvedOwnerships.entrySet().stream()
434+
.anyMatch(entry -> ownedBundlesCache.getIfPresent(entry.getKey()) == entry.getValue());
435+
}
436+
437+
private static void completeObsoleteReadmission(FencedTopicReadmission check) {
438+
CompletableFuture<Boolean> pending;
439+
synchronized (check) {
440+
pending = check.verification;
441+
}
442+
if (pending != null) {
443+
pending.complete(false);
444+
}
445+
}
446+
447+
void clearFencedTopicReadmissions() {
448+
fencedTopicReadmissions.forEach((topic, check) -> {
449+
if (fencedTopicReadmissions.remove(topic, check)) {
450+
completeObsoleteReadmission(check);
451+
}
452+
});
453+
}
454+
224455
/**
225456
* Method to get the current owner of the <code>ServiceUnit</code>.
226457
*

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.