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][ml] Fix metadata listener leaks caused by unclosed temporary re… · apache/pulsar@d3c2d7e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • managed-ledger/src
    • main/java/org/apache/bookkeeper/mledger/impl
      • ManagedCursorImpl.java
      • ManagedLedgerImpl.java
      • ReadOnlyManagedLedgerImpl.java
    • test/java/org/apache/bookkeeper
      • client
        • TemporaryReadHandleLifecycleTest.java
      • mledger/impl
        • ManagedLedgerTest.java
        • TemporaryReadHandleTest.java
  • testmocks/src/main/java/org/apache/bookkeeper/client
    • PulsarMockBookKeeper.java
    • PulsarMockReadOnlyLedgerHandle.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java‎

Copy file name to clipboardExpand all lines: managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
+60-24Lines changed: 60 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ static final class WaitingRead {
206206
@VisibleForTesting
207207
volatile LedgerHandle cursorLedger;
208208

209-
// Wether the current cursorLedger is read-only or writable
209+
// Guard updates to the handle and its read-only flag with the cursor monitor.
210210
private boolean isCursorLedgerReadOnly = true;
211211
private boolean ledgerForceRecovery;
212212

@@ -685,6 +685,7 @@ protected void recoverFromLedger(final ManagedCursorInfo info, final VoidCallbac
685685
if (lastEntryInLedger < 0) {
686686
log.warn("[{}] Error reading from metadata ledger {} for cursor {}: No entries in ledger",
687687
ledger.getName(), ledgerId, name);
688+
ManagedLedgerImpl.closeReadHandleAsync(lh, log);
688689
// Rewind to last cursor snapshot available
689690
initialize(getRollbackPosition(info), rollbackProperties, cursorProperties, callback);
690691
return;
@@ -695,41 +696,47 @@ protected void recoverFromLedger(final ManagedCursorInfo info, final VoidCallbac
695696
log.debug("[{}} readComplete rc={} entryId={}", ledger.getName(), rc1, lh1.getLastAddConfirmed());
696697
}
697698
if (isBkErrorNotRecoverable(rc1) || (rc1 != BKException.Code.OK && ledgerForceRecovery)) {
699+
ManagedLedgerImpl.closeReadHandleAsync(lh, log);
698700
log.error("[{}] Error reading from metadata ledger {} for cursor {}: {}", ledger.getName(),
699701
ledgerId, name, BKException.getMessage(rc1));
700702
// Rewind to the oldest entry available
701703
initialize(getRollbackPosition(info), rollbackProperties, cursorProperties, callback);
702704
return;
703705
} else if (rc1 != BKException.Code.OK) {
706+
ManagedLedgerImpl.closeReadHandleAsync(lh, log);
704707
log.warn("[{}] Error reading from metadata ledger {} for cursor {}: {}", ledger.getName(),
705708
ledgerId, name, BKException.getMessage(rc1));
706709

707710
callback.operationFailed(createManagedLedgerException(rc1));
708711
return;
709712
}
710713

711-
LedgerEntry entry = seq.nextElement();
712-
mbean.addReadCursorLedgerSize(entry.getLength());
713-
PositionInfo positionInfo = new PositionInfo();
714714
try {
715+
LedgerEntry entry = seq.nextElement();
716+
mbean.addReadCursorLedgerSize(entry.getLength());
717+
PositionInfo positionInfo = new PositionInfo();
715718
positionInfo.parseFrom(entry.getEntry());
719+
720+
Map<String, Long> recoveredProperties =
721+
recoverProperties(positionInfo.getPropertiesCount(), positionInfo::getPropertyAt);
722+
723+
Position position = PositionFactory.create(positionInfo.getLedgerId(), positionInfo.getEntryId());
724+
recoverIndividualDeletedMessages(positionInfo);
725+
if (getConfig().isDeletionAtBatchIndexLevelEnabled()
726+
&& positionInfo.getBatchedEntryDeletionIndexInfosCount() > 0) {
727+
recoverBatchDeletedIndexes(positionInfo.getBatchedEntryDeletionIndexInfosCount(),
728+
positionInfo::getBatchedEntryDeletionIndexInfoAt);
729+
}
730+
recoverLastActive(positionInfo.getIdleSince());
731+
recoveredCursor(position, recoveredProperties, cursorProperties, lh);
716732
} catch (Exception e) {
733+
// Recovery owns the handle until recoveredCursor transfers it to the cursor.
734+
if (cursorLedger != lh) {
735+
ManagedLedgerImpl.closeReadHandleAsync(lh, log);
736+
}
717737
callback.operationFailed(new ManagedLedgerException(e));
718738
return;
719739
}
720-
721-
Map<String, Long> recoveredProperties =
722-
recoverProperties(positionInfo.getPropertiesCount(), positionInfo::getPropertyAt);
723-
724-
Position position = PositionFactory.create(positionInfo.getLedgerId(), positionInfo.getEntryId());
725-
recoverIndividualDeletedMessages(positionInfo);
726-
if (getConfig().isDeletionAtBatchIndexLevelEnabled()
727-
&& positionInfo.getBatchedEntryDeletionIndexInfosCount() > 0) {
728-
recoverBatchDeletedIndexes(positionInfo.getBatchedEntryDeletionIndexInfosCount(),
729-
positionInfo::getBatchedEntryDeletionIndexInfoAt);
730-
}
731-
recoverLastActive(positionInfo.getIdleSince());
732-
recoveredCursor(position, recoveredProperties, cursorProperties, lh);
733740
callback.operationComplete();
734741
}, null);
735742
};
@@ -911,8 +918,10 @@ private void recoveredCursor(Position position, Map<String, Long> properties,
911918
ledger.onCursorReadPositionUpdated(this, readPosition);
912919
lastMarkDeleteEntry = new MarkDeleteEntry(markDeletePosition, properties, null, null);
913920
// assign cursor-ledger so, it can be deleted when new ledger will be switched
914-
this.cursorLedger = recoveredFromCursorLedger;
915-
this.isCursorLedgerReadOnly = true;
921+
synchronized (this) {
922+
this.cursorLedger = recoveredFromCursorLedger;
923+
this.isCursorLedgerReadOnly = true;
924+
}
916925
changeStateIfNotClosed(State.NoLedger);
917926
}
918927

@@ -3108,6 +3117,7 @@ public void operationFailed(ManagedLedgerException e) {
31083117
public void operationComplete(Void result, Stat stat) {
31093118
log.info("[{}][{}] Closed cursor at md-position={}", ledger.getName(), name, markDeletePosition);
31103119
// At this point the position had already been safely stored in the cursor z-node
3120+
closeReadOnlyCursorLedger();
31113121
callback.closeComplete(ctx);
31123122
asyncDeleteLedger(cursorLedger);
31133123
}
@@ -3116,6 +3126,9 @@ public void operationComplete(Void result, Stat stat) {
31163126
public void operationFailed(MetaStoreException e) {
31173127
log.warn("[{}][{}] Failed to update cursor info when closing: {}", ledger.getName(), name,
31183128
e.getMessage());
3129+
// The cursor cannot be reused after a failed close. Release the local read handle,
3130+
// but preserve the ledger because its position is still needed for recovery.
3131+
closeReadOnlyCursorLedger();
31193132
callback.closeFailed(e, ctx);
31203133
}
31213134
}, true);
@@ -3125,8 +3138,7 @@ public void operationFailed(MetaStoreException e) {
31253138
private boolean shouldPersistUnackRangesToLedger() {
31263139
lock.readLock().lock();
31273140
try {
3128-
return cursorLedger != null
3129-
&& !isCursorLedgerReadOnly
3141+
return hasWritableCursorLedger()
31303142
&& getConfig().getMaxUnackedRangesToPersist() > 0
31313143
&& individualDeletedMessages.size() > getConfig().getMaxUnackedRangesToPersistInMetadataStore();
31323144
} finally {
@@ -3800,9 +3812,17 @@ void switchToNewLedger(final LedgerHandle lh, final VoidCallback callback) {
38003812
public void operationComplete(Void result, Stat stat) {
38013813
log.info("[{}] Updated cursor {} with ledger id {} md-position={} rd-position={}", ledger.getName(),
38023814
name, lh.getId(), markDeletePosition, readPosition);
3803-
final LedgerHandle oldLedger = cursorLedger;
3804-
cursorLedger = lh;
3805-
isCursorLedgerReadOnly = false;
3815+
final LedgerHandle oldLedger;
3816+
final boolean oldLedgerReadOnly;
3817+
synchronized (ManagedCursorImpl.this) {
3818+
oldLedger = cursorLedger;
3819+
oldLedgerReadOnly = isCursorLedgerReadOnly;
3820+
cursorLedger = lh;
3821+
isCursorLedgerReadOnly = false;
3822+
}
3823+
if (oldLedgerReadOnly && oldLedger != null) {
3824+
ManagedLedgerImpl.closeReadHandleAsync(oldLedger, log);
3825+
}
38063826

38073827
// At this point the position had already been safely markdeleted
38083828
callback.operationComplete();
@@ -3918,6 +3938,21 @@ void readOperationCompleted() {
39183938
}
39193939
}
39203940

3941+
private synchronized boolean hasWritableCursorLedger() {
3942+
return cursorLedger != null && !isCursorLedgerReadOnly;
3943+
}
3944+
3945+
/** Releases the local recovery handle without touching cursor metadata or deleting its ledger. */
3946+
void closeReadOnlyCursorLedger() {
3947+
final LedgerHandle lh;
3948+
synchronized (this) {
3949+
lh = isCursorLedgerReadOnly ? cursorLedger : null;
3950+
}
3951+
if (lh != null) {
3952+
ManagedLedgerImpl.closeReadHandleAsync(lh, log);
3953+
}
3954+
}
3955+
39213956
void asyncDeleteLedger(final LedgerHandle lh) {
39223957
asyncDeleteLedger(lh, DEFAULT_LEDGER_DELETE_RETRIES);
39233958
}
@@ -3949,6 +3984,7 @@ private void asyncDeleteLedger(final LedgerHandle lh, int retry) {
39493984
}
39503985

39513986
void asyncDeleteCursorLedger() {
3987+
closeReadOnlyCursorLedger();
39523988
asyncDeleteCursorLedger(DEFAULT_LEDGER_DELETE_RETRIES);
39533989
}
39543990

Collapse file

‎managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java‎

Copy file name to clipboardExpand all lines: managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
+68-11Lines changed: 68 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,8 @@ public void operationComplete(ManagedLedgerInfo mlInfo, Stat stat) {
517517
log.debug("[{}] Opened ledger {}: {}", name, id, BKException.getMessage(rc));
518518
}
519519
if (rc == BKException.Code.OK) {
520-
if (State.Terminated.equals(state)) {
520+
boolean retainHandle = State.Terminated.equals(state);
521+
if (retainHandle) {
521522
currentLedger = lh;
522523
}
523524
ledgers.compute(id, (ledgerId, oldInfo) -> {
@@ -531,15 +532,23 @@ public void operationComplete(ManagedLedgerInfo mlInfo, Stat stat) {
531532
.setSize(lh.getLength()).setTimestamp(clock.millis());
532533
});
533534
if (managedLedgerInterceptor != null) {
534-
managedLedgerInterceptor
535-
.onManagedLedgerLastLedgerInitialize(name, createLastEntryHandle(lh))
535+
FutureUtil.supplySafely(() -> managedLedgerInterceptor
536+
.onManagedLedgerLastLedgerInitialize(name, createLastEntryHandle(lh)))
537+
.whenComplete((ignored, error) -> {
538+
if (!retainHandle) {
539+
closeReadHandleAsync(lh, log);
540+
}
541+
})
536542
.thenRun(() -> initializeBookKeeper(callback))
537543
.exceptionally(ex -> {
538544
callback.initializeFailed(
539545
new ManagedLedgerInterceptException(ex.getCause()));
540546
return null;
541547
});
542548
} else {
549+
if (!retainHandle) {
550+
closeReadHandleAsync(lh, log);
551+
}
543552
initializeBookKeeper(callback);
544553
}
545554
} else if (isNoSuchLedgerExistsException(rc)) {
@@ -769,8 +778,14 @@ public void operationComplete() {
769778
log.info("[{}] Recovery for cursor {} completed. pos={} -- todo={}, cost {} ms", name,
770779
cursorName, cursor.getMarkDeletedPosition(), cursorCount.get() - 1,
771780
System.currentTimeMillis() - timestampStartRecoverCursor);
772-
cursor.setActive();
773-
addCursor(cursor);
781+
if (!tryRegisterRecoveredCursor(cursor)) {
782+
cursor.closeReadOnlyCursorLedger();
783+
if (cursorCount.getAndSet(-1) > 0) {
784+
callback.initializeFailed(
785+
new ManagedLedgerAlreadyClosedException("Managed ledger is closed"));
786+
}
787+
return;
788+
}
774789

775790
if (cursorCount.decrementAndGet() == 0) {
776791
// The initialization is now completed, register the jmx mbean
@@ -820,12 +835,19 @@ public void operationComplete() {
820835
log.info("[{}] Lazy recovery for cursor {} completed. pos={}, cost {} ms",
821836
name, cursorName, cursor.getMarkDeletedPosition(),
822837
System.currentTimeMillis() - timestampStartRecoverCursor);
823-
cursor.setActive();
824838
synchronized (ManagedLedgerImpl.this) {
825839
failedLazyRecoveryCursors.remove(cursorName);
826-
addCursor(cursor);
827-
uninitializedCursors.remove(cursorName).complete(cursor);
840+
if (tryRegisterRecoveredCursor(cursor)) {
841+
uninitializedCursors.remove(cursorName).complete(cursor);
842+
return;
843+
}
844+
uninitializedCursors.remove(cursorName);
828845
}
846+
// Close has already taken responsibility for the registered cursors. Only release the
847+
// local read handle here, since a new owner may already be recovering this cursor.
848+
cursor.closeReadOnlyCursorLedger();
849+
cursorRecoveryFuture.completeExceptionally(
850+
new ManagedLedgerAlreadyClosedException("Managed ledger is closed"));
829851
}
830852

831853
@Override
@@ -841,6 +863,16 @@ public void operationFailed(ManagedLedgerException exception) {
841863
return cursorRecoveryFuture;
842864
}
843865

866+
private synchronized boolean tryRegisterRecoveredCursor(ManagedCursorImpl cursor) {
867+
// Serialize registration with the transition to Closed in asyncClose.
868+
if (state == State.Closed) {
869+
return false;
870+
}
871+
cursor.setActive();
872+
addCursor(cursor);
873+
return true;
874+
}
875+
844876
private void addCursor(ManagedCursorImpl cursor) {
845877
Position positionForOrdering = null;
846878
if (cursor.isDurable()) {
@@ -1126,9 +1158,11 @@ public synchronized void asyncOpenCursor(final String cursorName, final InitialP
11261158
}
11271159

11281160
// A cursor whose lazy recovery failed still has its position persisted: recover it again rather than
1129-
// replacing it with a new one
1130-
CompletableFuture<ManagedCursor> uninitializedCursor = failedLazyRecoveryCursors.contains(cursorName)
1131-
? recoverCursorLazily(cursorName) : uninitializedCursors.get(cursorName);
1161+
// replacing it with a new one. Concurrent opens share any retry already in progress.
1162+
CompletableFuture<ManagedCursor> uninitializedCursor = uninitializedCursors.get(cursorName);
1163+
if (uninitializedCursor == null && failedLazyRecoveryCursors.contains(cursorName)) {
1164+
uninitializedCursor = recoverCursorLazily(cursorName);
1165+
}
11321166
if (uninitializedCursor != null) {
11331167
uninitializedCursor.whenComplete((cursor, error) -> {
11341168
if (error == null) {
@@ -1279,6 +1313,8 @@ public void operationFailed(MetaStoreException e) {
12791313
synchronized (ManagedLedgerImpl.this) {
12801314
deletingCursors.remove(consumerName, deleteFuture);
12811315
}
1316+
// Unload skips normal cursor cleanup in the DeletingFailed state.
1317+
cursor.closeReadOnlyCursorLedger();
12821318
callback.deleteCursorFailed(e, ctx);
12831319
deleteFuture.completeExceptionally(e);
12841320
}
@@ -1872,6 +1908,13 @@ public synchronized void asyncClose(final CloseCallback callback, final Object c
18721908
// Release the read handles even if the current ledger failed to close, as nothing would release them later
18731909
invalidateAllReadHandles();
18741910
if (rc != BKException.Code.OK) {
1911+
// Graceful cursor close is skipped on this path. Release local recovered handles without
1912+
// writing cursor metadata or deleting ledgers.
1913+
for (ManagedCursor cursor : cursors) {
1914+
if (cursor instanceof ManagedCursorImpl managedCursor) {
1915+
managedCursor.closeReadOnlyCursorLedger();
1916+
}
1917+
}
18751918
callback.closeFailed(createManagedLedgerException(rc), ctx);
18761919
return;
18771920
}
@@ -2600,6 +2643,16 @@ CompletableFuture<ReadHandle> getLedgerHandle(long ledgerId) {
26002643
});
26012644
}
26022645

2646+
// Temporary read handles have no cache owner to close them when the managed ledger is unloaded.
2647+
static CompletableFuture<Void> closeReadHandleAsync(ReadHandle handle, Logger log) {
2648+
return FutureUtil.supplySafely(handle::closeAsync).exceptionally(error -> {
2649+
if (log.isDebugEnabled()) {
2650+
log.debug("Failed to close temporary read handle for ledger {}", handle.getId(), error);
2651+
}
2652+
return null;
2653+
});
2654+
}
2655+
26032656
void invalidateReadHandle(long ledgerId) {
26042657
CompletableFuture<ReadHandle> rhf = ledgerCache.remove(ledgerId);
26052658
if (rhf != null) {
@@ -4998,6 +5051,10 @@ private void checkManagedLedgerIsOpen() throws ManagedLedgerException {
49985051

49995052
@VisibleForTesting
50005053
public synchronized void setFenced() {
5054+
if (state == State.Closed) {
5055+
// Preserve the terminal state so late cursor recovery releases its local handle.
5056+
return;
5057+
}
50015058
log.info("{} Moving to Fenced state", name);
50025059
State prev = STATE_UPDATER.getAndSet(this, State.Fenced);
50035060
if (prev != State.Fenced) {

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.