You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by GitBox <gi...@apache.org> on 2022/10/31 08:07:09 UTC

[GitHub] [pulsar] Jason918 opened a new pull request, #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Jason918 opened a new pull request, #18265:
URL: https://github.com/apache/pulsar/pull/18265

   Master Issue: https://github.com/apache/pulsar/issues/16153
   
   ### Motivation
   
   After this PR, the basic function of `PIP-180 shadow topic` will be ready.
   
   ### Modifications
   
   - Add `ShadowManagedLedgerImpl`
   
   ### Verifying this change
   
   - [ ] Make sure that the change passes the CI checks.
   
   This change added tests and can be verified as follows:
     - see `ShadowTopicTest.java`
   
   ### 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
   
   <!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
   
   - [ ] `doc` <!-- Your PR contains doc changes. Please attach the local preview screenshots (run `sh start.sh` at `pulsar/site2/website`) to your PR description, or else your PR might not get merged. -->
   - [x] `doc-required` <!-- Your PR changes impact docs and you will update later -->
   - [ ] `doc-not-needed` <!-- Your PR changes do not impact docs -->
   - [ ] `doc-complete` <!-- Docs have been already added -->
   
   ### Matching PR in forked repository
   
   PR in forked repository: <!-- ENTER URL HERE -->
   
   <!--
   After opening this PR, the build in apache/pulsar will fail and instructions will
   be provided for opening a PR in the PR author's forked repository.
   
   apache/pulsar pull requests should be first tested in your own fork since the 
   apache/pulsar CI based on GitHub Actions has constrained resources and quota.
   GitHub Actions provides separate quota for pull requests that are executed in 
   a forked repository.
   
   The tests will be run in the forked repository until all PR review comments have
   been handled, the tests pass and the PR is approved by a reviewer.
   -->
   


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1025940771


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Producer.java:
##########
@@ -335,7 +348,7 @@ public TransportCnx getCnx() {
         return this.cnx;
     }
 
-    private static final class MessagePublishContext implements PublishContext, Runnable {
+    private static final class MessagePublishContext implements PublishContext, Runnable, Position {

Review Comment:
   > OK. I see. Should we write some comments to explain this?
   
   Sure.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] codecov-commenter commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
codecov-commenter commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1314707175

   # [Codecov](https://codecov.io/gh/apache/pulsar/pull/18265?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#18265](https://codecov.io/gh/apache/pulsar/pull/18265?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (d41427d) into [master](https://codecov.io/gh/apache/pulsar/commit/46c0438ccc1460e22fc437a626a8c9cb05f4d618?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (46c0438) will **increase** coverage by `7.87%`.
   > The diff coverage is `17.36%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/pulsar/pull/18265/graphs/tree.svg?width=650&height=150&src=pr&token=acYqCpsK9J&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)](https://codecov.io/gh/apache/pulsar/pull/18265?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #18265      +/-   ##
   ============================================
   + Coverage     38.84%   46.72%   +7.87%     
   - Complexity     8286    10338    +2052     
   ============================================
     Files           683      692       +9     
     Lines         67323    68012     +689     
     Branches       7215     7306      +91     
   ============================================
   + Hits          26152    31778    +5626     
   + Misses        38210    32660    -5550     
   - Partials       2961     3574     +613     
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | unittests | `46.72% <17.36%> (+7.87%)` | :arrow_up: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/pulsar/pull/18265?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [...che/bookkeeper/mledger/ManagedLedgerException.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bWFuYWdlZC1sZWRnZXIvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2Jvb2trZWVwZXIvbWxlZGdlci9NYW5hZ2VkTGVkZ2VyRXhjZXB0aW9uLmphdmE=) | `37.83% <0.00%> (-3.34%)` | :arrow_down: |
   | [.../org/apache/bookkeeper/mledger/impl/MetaStore.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bWFuYWdlZC1sZWRnZXIvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2Jvb2trZWVwZXIvbWxlZGdlci9pbXBsL01ldGFTdG9yZS5qYXZh) | `100.00% <ø> (ø)` | |
   | [...org/apache/bookkeeper/mledger/impl/OpAddEntry.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bWFuYWdlZC1sZWRnZXIvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2Jvb2trZWVwZXIvbWxlZGdlci9pbXBsL09wQWRkRW50cnkuamF2YQ==) | `65.59% <0.00%> (-2.19%)` | :arrow_down: |
   | [...okkeeper/mledger/impl/ShadowManagedLedgerImpl.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bWFuYWdlZC1sZWRnZXIvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2Jvb2trZWVwZXIvbWxlZGdlci9pbXBsL1NoYWRvd01hbmFnZWRMZWRnZXJJbXBsLmphdmE=) | `0.00% <0.00%> (ø)` | |
   | [...ache/pulsar/broker/namespace/NamespaceService.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cHVsc2FyLWJyb2tlci9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcHVsc2FyL2Jyb2tlci9uYW1lc3BhY2UvTmFtZXNwYWNlU2VydmljZS5qYXZh) | `57.79% <ø> (-0.22%)` | :arrow_down: |
   | [...va/org/apache/pulsar/client/impl/ProducerImpl.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cHVsc2FyLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcHVsc2FyL2NsaWVudC9pbXBsL1Byb2R1Y2VySW1wbC5qYXZh) | `15.83% <0.00%> (+15.83%)` | :arrow_up: |
   | [...ava/org/apache/pulsar/broker/service/Producer.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cHVsc2FyLWJyb2tlci9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcHVsc2FyL2Jyb2tlci9zZXJ2aWNlL1Byb2R1Y2VyLmphdmE=) | `61.75% <27.27%> (-0.38%)` | :arrow_down: |
   | [.../apache/bookkeeper/mledger/impl/MetaStoreImpl.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bWFuYWdlZC1sZWRnZXIvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2Jvb2trZWVwZXIvbWxlZGdlci9pbXBsL01ldGFTdG9yZUltcGwuamF2YQ==) | `48.20% <28.57%> (-2.20%)` | :arrow_down: |
   | [...sar/broker/service/persistent/PersistentTopic.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cHVsc2FyLWJyb2tlci9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcHVsc2FyL2Jyb2tlci9zZXJ2aWNlL3BlcnNpc3RlbnQvUGVyc2lzdGVudFRvcGljLmphdmE=) | `61.27% <33.33%> (+4.34%)` | :arrow_up: |
   | [...che/bookkeeper/mledger/impl/ManagedCursorImpl.java](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-bWFuYWdlZC1sZWRnZXIvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2Jvb2trZWVwZXIvbWxlZGdlci9pbXBsL01hbmFnZWRDdXJzb3JJbXBsLmphdmE=) | `36.81% <40.00%> (-0.13%)` | :arrow_down: |
   | ... and [260 more](https://codecov.io/gh/apache/pulsar/pull/18265/diff?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | |
   


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1314679506

   /pulsarbot run-failure-checks


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] AnonHxy commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
AnonHxy commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1023716092


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,365 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;

Review Comment:
   It seems that this variable is unused



##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Producer.java:
##########
@@ -335,7 +348,7 @@ public TransportCnx getCnx() {
         return this.cnx;
     }
 
-    private static final class MessagePublishContext implements PublishContext, Runnable {
+    private static final class MessagePublishContext implements PublishContext, Runnable, Position {

Review Comment:
   OK. I see. Should we write some comments to explain this?



##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,365 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                // Fails if init with empty ledger. Very small chance here, since shadow topic is
+                // created when source topic exists.
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+//                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerSourceNotReadyException(

Review Comment:
   Cleanup this commented code?



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1032413814


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }

Review Comment:
   Yes, exactly.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1032412045


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }
+        if (state != State.LedgerOpened) {
+            addOperation.failed(new ManagedLedgerException("Managed ledger is not opened"));
+            return;
+        }
+
+        if (addOperation.getCtx() == null || !(addOperation.getCtx() instanceof Position position)) {
+            addOperation.failed(new ManagedLedgerException("Illegal addOperation context object."));
+            return;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] Add entry into shadow ledger lh={} entries={}, pos=({},{})",
+                    name, currentLedger.getId(), currentLedgerEntries, position.getLedgerId(), position.getEntryId());
+        }
+        pendingAddEntries.add(addOperation);
+        if (position.getLedgerId() == currentLedger.getId()) {
+            // Write into lastLedger
+            addOperation.setLedger(currentLedger);
+            currentLedgerEntries = position.getEntryId();
+            currentLedgerSize += addOperation.data.readableBytes();
+            addOperation.initiateShadowWrite();
+        }
+        lastAddEntryTimeMs = System.currentTimeMillis();
+    }
+
+    /**
+     * Handle source ManagedLedgerInfo updates.
+     * Update types:
+     * 1. new ledgers.
+     * 2. old ledgers deleted.
+     * 3. old ledger offload info updated (including ledger deleted from bookie by offloader)
+     *
+     */
+    private synchronized void processSourceManagedLedgerInfo(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}][{}] new SourceManagedLedgerInfo:{}, prevStat={},stat={}", name, sourceMLName, mlInfo,
+                    sourceLedgersStat, stat);
+        }
+
+        sourceLedgersStat = stat;
+
+        if (mlInfo.hasTerminatedPosition()) {
+            state = State.Terminated;

Review Comment:
   Not needed actually, just keeping the original logic at first. 
   After another thought, we should remove this, because the source topic can be terminated but the replication to the shadow topic should go on.
   So comes these updates:
   1. Removed Terminated state from ShadowManagedLedger.
   2. Overrides `asyncTerminate` and return fail directly.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1016108439


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Producer.java:
##########
@@ -335,7 +348,7 @@ public TransportCnx getCnx() {
         return this.cnx;
     }
 
-    private static final class MessagePublishContext implements PublishContext, Runnable {
+    private static final class MessagePublishContext implements PublishContext, Runnable, Position {

Review Comment:
   It's tricky, `pulsar-broker` depends on `managed-ledger`, so we can't use `MessagePublishContext` directly in  `managed-ledger`, but I need to get position info from this context.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] StevenLuMT commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by "StevenLuMT (via GitHub)" <gi...@apache.org>.
StevenLuMT commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1434053737

   > Thanks @Jason918 @StevenLuMT. Feel free to ping me if you need any assistance with docs.
   
   Thanks @momo-jun ,my WeChat ID is 863199780, add me, keep fast communication


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] momo-jun commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
momo-jun commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1386737535

   Hi @Jason918, do you have any updates for documenting this feature? 
   Since 2.11 has been released, now it's good timing to start the doc update in the next version.


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] momo-jun commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by "momo-jun (via GitHub)" <gi...@apache.org>.
momo-jun commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1434026725

   Thanks @Jason918 @StevenLuMT. Feel free to ping me if you need any assistance with docs.


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] codelipenghui commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
codelipenghui commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1030475063


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {

Review Comment:
   Why the `name` is not able to be used? It's a little confusing that we need to introduce the topic name in `ManagedLedgerConfig`
   
   Or maybe we can introduce a `properties`?



##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }
+        if (state != State.LedgerOpened) {
+            addOperation.failed(new ManagedLedgerException("Managed ledger is not opened"));
+            return;
+        }
+
+        if (addOperation.getCtx() == null || !(addOperation.getCtx() instanceof Position position)) {
+            addOperation.failed(new ManagedLedgerException("Illegal addOperation context object."));
+            return;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] Add entry into shadow ledger lh={} entries={}, pos=({},{})",
+                    name, currentLedger.getId(), currentLedgerEntries, position.getLedgerId(), position.getEntryId());
+        }
+        pendingAddEntries.add(addOperation);
+        if (position.getLedgerId() == currentLedger.getId()) {
+            // Write into lastLedger
+            addOperation.setLedger(currentLedger);
+            currentLedgerEntries = position.getEntryId();
+            currentLedgerSize += addOperation.data.readableBytes();
+            addOperation.initiateShadowWrite();
+        }
+        lastAddEntryTimeMs = System.currentTimeMillis();
+    }
+
+    /**
+     * Handle source ManagedLedgerInfo updates.
+     * Update types:
+     * 1. new ledgers.
+     * 2. old ledgers deleted.
+     * 3. old ledger offload info updated (including ledger deleted from bookie by offloader)
+     *
+     */
+    private synchronized void processSourceManagedLedgerInfo(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}][{}] new SourceManagedLedgerInfo:{}, prevStat={},stat={}", name, sourceMLName, mlInfo,
+                    sourceLedgersStat, stat);
+        }
+
+        sourceLedgersStat = stat;

Review Comment:
   Do we need to check the data version?
   Maybe the watcher gets a notification first, and then we get the response from get managed ledger info operation. Will we add the deleted ledger back?



##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }

Review Comment:
   Looks like we don't need to check if the topic is terminated.
   And if the broker receives the zookeeper notification first, then the shadow topic changes to the terminated state. But the shadow replicator hasn't reached the end of the source topic. In this case, the consumer connected to the shadow topic will have a different view.



##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }
+        if (state != State.LedgerOpened) {
+            addOperation.failed(new ManagedLedgerException("Managed ledger is not opened"));
+            return;
+        }
+
+        if (addOperation.getCtx() == null || !(addOperation.getCtx() instanceof Position position)) {
+            addOperation.failed(new ManagedLedgerException("Illegal addOperation context object."));
+            return;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] Add entry into shadow ledger lh={} entries={}, pos=({},{})",
+                    name, currentLedger.getId(), currentLedgerEntries, position.getLedgerId(), position.getEntryId());
+        }
+        pendingAddEntries.add(addOperation);
+        if (position.getLedgerId() == currentLedger.getId()) {
+            // Write into lastLedger
+            addOperation.setLedger(currentLedger);
+            currentLedgerEntries = position.getEntryId();
+            currentLedgerSize += addOperation.data.readableBytes();
+            addOperation.initiateShadowWrite();
+        }

Review Comment:
   How about the position's ledger ID that is not equal to the current ledger ID? It looks like the `addOperation` will never be complete.



##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }
+        if (state != State.LedgerOpened) {
+            addOperation.failed(new ManagedLedgerException("Managed ledger is not opened"));
+            return;
+        }
+
+        if (addOperation.getCtx() == null || !(addOperation.getCtx() instanceof Position position)) {
+            addOperation.failed(new ManagedLedgerException("Illegal addOperation context object."));
+            return;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] Add entry into shadow ledger lh={} entries={}, pos=({},{})",
+                    name, currentLedger.getId(), currentLedgerEntries, position.getLedgerId(), position.getEntryId());
+        }
+        pendingAddEntries.add(addOperation);
+        if (position.getLedgerId() == currentLedger.getId()) {
+            // Write into lastLedger
+            addOperation.setLedger(currentLedger);
+            currentLedgerEntries = position.getEntryId();
+            currentLedgerSize += addOperation.data.readableBytes();
+            addOperation.initiateShadowWrite();
+        }
+        lastAddEntryTimeMs = System.currentTimeMillis();
+    }
+
+    /**
+     * Handle source ManagedLedgerInfo updates.
+     * Update types:
+     * 1. new ledgers.
+     * 2. old ledgers deleted.
+     * 3. old ledger offload info updated (including ledger deleted from bookie by offloader)
+     *
+     */
+    private synchronized void processSourceManagedLedgerInfo(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}][{}] new SourceManagedLedgerInfo:{}, prevStat={},stat={}", name, sourceMLName, mlInfo,
+                    sourceLedgersStat, stat);
+        }
+
+        sourceLedgersStat = stat;
+
+        if (mlInfo.hasTerminatedPosition()) {
+            state = State.Terminated;

Review Comment:
   Do you need Terminated state for a shadow ledger? If the source topic changes to the terminated state, the shadow topic will not get any new messages.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 merged pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 merged PR #18265:
URL: https://github.com/apache/pulsar/pull/18265


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1032212220


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {

Review Comment:
   > Why the `name` is not able to be used? It's a little confusing that we need to introduce the topic name in `ManagedLedgerConfig`
   
   Good point.
   
   1. We need to know the `TopicName` of the source topic in the shadow topic. But the `name` here is in the format of `PersistenceNamingEncoding`.
   2. I get that we'd better not introduce the concept of "topic" into managed-ledger. I will move this logic to the "broker" layer. So that the source topic name is in `properties` and the managedLedgerName of the source topic is stored in the new field `ManagedLedgerConfig.shadowSourceName`.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1032540409


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }
+        if (state != State.LedgerOpened) {
+            addOperation.failed(new ManagedLedgerException("Managed ledger is not opened"));
+            return;
+        }
+
+        if (addOperation.getCtx() == null || !(addOperation.getCtx() instanceof Position position)) {
+            addOperation.failed(new ManagedLedgerException("Illegal addOperation context object."));
+            return;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] Add entry into shadow ledger lh={} entries={}, pos=({},{})",
+                    name, currentLedger.getId(), currentLedgerEntries, position.getLedgerId(), position.getEntryId());
+        }
+        pendingAddEntries.add(addOperation);
+        if (position.getLedgerId() == currentLedger.getId()) {
+            // Write into lastLedger
+            addOperation.setLedger(currentLedger);
+            currentLedgerEntries = position.getEntryId();
+            currentLedgerSize += addOperation.data.readableBytes();
+            addOperation.initiateShadowWrite();
+        }

Review Comment:
   Fixed, and add ut in ShadowManagedLedgerImplTest



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1032296230


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,363 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;
 
     public ShadowManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper,
                                    MetaStore store, ManagedLedgerConfig config,
                                    OrderedScheduler scheduledExecutor,
                                    String name, final Supplier<Boolean> mlOwnershipChecker) {
         super(factory, bookKeeper, store, config, scheduledExecutor, name, mlOwnershipChecker);
-        this.shadowSource = TopicName.get(config.getShadowSource());
-        this.sourceMLName = shadowSource.getPersistenceNamingEncoding();
+        if (config.getTopicName().isPartitioned() && TopicName.getPartitionIndex(config.getShadowSource()) == -1) {
+            this.shadowSource =
+                    TopicName.get(config.getShadowSource()).getPartition(config.getTopicName().getPartitionIndex());
+        } else {
+            this.shadowSource = TopicName.get(config.getShadowSource());
+        }
+        this.sourceMLName =
+                shadowSource.getPersistenceNamingEncoding();
     }
 
+    /**
+     * ShadowManagedLedger init steps:
+     * 1. this.initialize : read source managedLedgerInfo
+     * 2. super.initialize : read its own read source managedLedgerInfo
+     * 3. this.initializeBookKeeper
+     * 4. super.initializeCursors
+     * @param callback
+     * @param ctx
+     */
     @Override
     synchronized void initialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
-        // TODO: ShadowManagedLedger has different initialize process from normal ManagedLedger,
-        //  which is complicated and will be implemented in the next PRs.
-        super.initialize(callback, ctx);
+        log.info("Opening shadow managed ledger {} with source={}", name, sourceMLName);
+
+        executor.executeOrdered(name, safeRun(() -> doInitialize(callback, ctx)));
+    }
+
+    private void doInitialize(ManagedLedgerInitializeLedgerCallback callback, Object ctx) {
+        // Fetch the list of existing ledgers in the source managed ledger
+        store.watchManagedLedgerInfo(sourceMLName, (managedLedgerInfo, stat) ->
+                executor.executeOrdered(name, safeRun(() -> processSourceManagedLedgerInfo(managedLedgerInfo, stat)))
+        );
+        store.getManagedLedgerInfo(sourceMLName, false, null, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+                if (log.isDebugEnabled()) {
+                    log.debug("[{}][{}] Source ML info:{}", name, sourceMLName, mlInfo);
+                }
+                sourceLedgersStat = stat;
+                if (mlInfo.getLedgerInfoCount() == 0) {
+                    // Small chance here, since shadow topic is created after source topic exists.
+                    log.warn("[{}] Source topic ledger list is empty! source={},mlInfo={},stat={}", name, sourceMLName,
+                            mlInfo, stat);
+                    ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    return;
+                }
+
+                if (mlInfo.hasTerminatedPosition()) {
+                    state = State.Terminated;
+                    lastConfirmedEntry = new PositionImpl(mlInfo.getTerminatedPosition());
+                    log.info("[{}][{}] Recovering managed ledger terminated at {}", name, sourceMLName,
+                            lastConfirmedEntry);
+                }
+
+                for (LedgerInfo ls : mlInfo.getLedgerInfoList()) {
+                    ledgers.put(ls.getLedgerId(), ls);
+                }
+
+                final long lastLedgerId = ledgers.lastKey();
+                mbean.startDataLedgerOpenOp();
+                AsyncCallback.OpenCallback opencb = (rc, lh, ctx1) -> executor.executeOrdered(name, safeRun(() -> {
+                    mbean.endDataLedgerOpenOp();
+                    if (log.isDebugEnabled()) {
+                        log.debug("[{}] Opened source ledger {}", name, lastLedgerId);
+                    }
+                    if (rc == BKException.Code.OK) {
+                        LedgerInfo info =
+                                LedgerInfo.newBuilder()
+                                        .setLedgerId(lastLedgerId)
+                                        .setEntries(lh.getLastAddConfirmed() + 1)
+                                        .setSize(lh.getLength())
+                                        .setTimestamp(clock.millis()).build();
+                        ledgers.put(lastLedgerId, info);
+
+                        //Always consider the last ledger is opened in source.
+                        STATE_UPDATER.set(ShadowManagedLedgerImpl.this, State.LedgerOpened);
+                        currentLedger = lh;
+
+                        if (managedLedgerInterceptor != null) {
+                            managedLedgerInterceptor.onManagedLedgerLastLedgerInitialize(name, lh)
+                                    .thenRun(() -> ShadowManagedLedgerImpl.super.initialize(callback, ctx))
+                                    .exceptionally(ex -> {
+                                        callback.initializeFailed(
+                                                new ManagedLedgerException.ManagedLedgerInterceptException(
+                                                        ex.getCause()));
+                                        return null;
+                                    });
+                        } else {
+                            ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                        }
+                    } else if (isNoSuchLedgerExistsException(rc)) {
+                        log.warn("[{}] Source ledger not found: {}", name, lastLedgerId);
+                        ledgers.remove(lastLedgerId);
+                        ShadowManagedLedgerImpl.super.initialize(callback, ctx);
+                    } else {
+                        log.error("[{}] Failed to open source ledger {}: {}", name, lastLedgerId,
+                                BKException.getMessage(rc));
+                        callback.initializeFailed(createManagedLedgerException(rc));
+                    }
+                }));
+                //open ledger in readonly mode.
+                bookKeeper.asyncOpenLedgerNoRecovery(lastLedgerId, digestType, config.getPassword(), opencb, null);
+
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                if (e instanceof ManagedLedgerException.MetadataNotFoundException) {
+                    callback.initializeFailed(new ManagedLedgerException.ManagedLedgerNotFoundException(e));
+                } else {
+                    callback.initializeFailed(new ManagedLedgerException(e));
+                }
+            }
+        });
     }
 
     public TopicName getShadowSource() {
         return shadowSource;
     }
+
+    @Override
+    protected boolean isLedgersReadonly() {
+        return true;
+    }
+
+    @Override
+    protected synchronized void initializeBookKeeper(ManagedLedgerInitializeLedgerCallback callback) {
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] initializing bookkeeper for shadowManagedLedger; ledgers {}", name, ledgers);
+        }
+
+        // Calculate total entries and size
+        Iterator<LedgerInfo> iterator = ledgers.values().iterator();
+        while (iterator.hasNext()) {
+            LedgerInfo li = iterator.next();
+            if (li.getEntries() > 0) {
+                NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
+                TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
+            } else if (li.getLedgerId() != currentLedger.getId()) {
+                //do not remove the last empty ledger.
+                iterator.remove();
+            }
+        }
+
+        initLastConfirmedEntry();
+        // Save it back to ensure all nodes exist and properties are persisted.
+        store.asyncUpdateLedgerIds(name, getManagedLedgerInfo(), ledgersStat, new MetaStore.MetaStoreCallback<>() {
+            @Override
+            public void operationComplete(Void result, Stat stat) {
+                ledgersStat = stat;
+                initializeCursors(callback);
+            }
+
+            @Override
+            public void operationFailed(ManagedLedgerException.MetaStoreException e) {
+                handleBadVersion(e);
+                callback.initializeFailed(new ManagedLedgerException(e));
+            }
+        });
+    }
+
+    private void initLastConfirmedEntry() {
+        if (lastConfirmedEntry != null || currentLedger == null) {
+            return;
+        }
+        lastConfirmedEntry = new PositionImpl(currentLedger.getId(), currentLedger.getLastAddConfirmed());
+        // bypass empty ledgers, find last ledger with Message if possible.
+        while (lastConfirmedEntry.getEntryId() == -1) {
+            Map.Entry<Long, LedgerInfo> formerLedger = ledgers.lowerEntry(lastConfirmedEntry.getLedgerId());
+            if (formerLedger != null) {
+                LedgerInfo ledgerInfo = formerLedger.getValue();
+                lastConfirmedEntry = PositionImpl.get(ledgerInfo.getLedgerId(), ledgerInfo.getEntries() - 1);
+            } else {
+                break;
+            }
+        }
+    }
+
+    @Override
+    protected synchronized void internalAsyncAddEntry(OpAddEntry addOperation) {
+        if (!beforeAddEntry(addOperation)) {
+            return;
+        }
+        if (state == State.Terminated) {
+            addOperation.failed(new ManagedLedgerException.ManagedLedgerTerminatedException(
+                    "Managed ledger was already terminated"));
+            return;
+        }
+        if (state != State.LedgerOpened) {
+            addOperation.failed(new ManagedLedgerException("Managed ledger is not opened"));
+            return;
+        }
+
+        if (addOperation.getCtx() == null || !(addOperation.getCtx() instanceof Position position)) {
+            addOperation.failed(new ManagedLedgerException("Illegal addOperation context object."));
+            return;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}] Add entry into shadow ledger lh={} entries={}, pos=({},{})",
+                    name, currentLedger.getId(), currentLedgerEntries, position.getLedgerId(), position.getEntryId());
+        }
+        pendingAddEntries.add(addOperation);
+        if (position.getLedgerId() == currentLedger.getId()) {
+            // Write into lastLedger
+            addOperation.setLedger(currentLedger);
+            currentLedgerEntries = position.getEntryId();
+            currentLedgerSize += addOperation.data.readableBytes();
+            addOperation.initiateShadowWrite();
+        }
+        lastAddEntryTimeMs = System.currentTimeMillis();
+    }
+
+    /**
+     * Handle source ManagedLedgerInfo updates.
+     * Update types:
+     * 1. new ledgers.
+     * 2. old ledgers deleted.
+     * 3. old ledger offload info updated (including ledger deleted from bookie by offloader)
+     *
+     */
+    private synchronized void processSourceManagedLedgerInfo(MLDataFormats.ManagedLedgerInfo mlInfo, Stat stat) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("[{}][{}] new SourceManagedLedgerInfo:{}, prevStat={},stat={}", name, sourceMLName, mlInfo,
+                    sourceLedgersStat, stat);
+        }
+
+        sourceLedgersStat = stat;

Review Comment:
   Nice catch. Added a version check.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1327616665

   @codelipenghui Comments all addressed. PTAL. 


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1025945834


##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ShadowManagedLedgerImpl.java:
##########
@@ -18,40 +18,365 @@
  */
 package org.apache.bookkeeper.mledger.impl;
 
+import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
 import java.util.function.Supplier;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.bookkeeper.client.AsyncCallback;
+import org.apache.bookkeeper.client.BKException;
 import org.apache.bookkeeper.client.BookKeeper;
 import org.apache.bookkeeper.common.util.OrderedScheduler;
+import org.apache.bookkeeper.mledger.AsyncCallbacks;
 import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
+import org.apache.bookkeeper.mledger.ManagedLedgerException;
+import org.apache.bookkeeper.mledger.Position;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats;
+import org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo;
 import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.Stat;
 
 /**
  * Working in progress until <a href="https://github.com/apache/pulsar/issues/16153">PIP-180</a> is finished.
- * Currently, it works nothing different with ManagedLedgerImpl.
  */
 @Slf4j
 public class ShadowManagedLedgerImpl extends ManagedLedgerImpl {
 
     private final TopicName shadowSource;
     private final String sourceMLName;
+    private volatile Stat sourceLedgersStat;

Review Comment:
   > It seems that this variable is unused
   
   It's useful for debugging purpose. let's keep it.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] AnonHxy commented on a diff in pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
AnonHxy commented on code in PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#discussion_r1015324604


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Producer.java:
##########
@@ -335,7 +348,7 @@ public TransportCnx getCnx() {
         return this.cnx;
     }
 
-    private static final class MessagePublishContext implements PublishContext, Runnable {
+    private static final class MessagePublishContext implements PublishContext, Runnable, Position {

Review Comment:
   I wonder why  `MessagePublishContext` implements `Position`



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by GitBox <gi...@apache.org>.
Jason918 commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1314680218

   @codelipenghui @eolivelli @michaeljmarshall @lhotari @mattisonchao PTAL


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] Jason918 commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by "Jason918 (via GitHub)" <gi...@apache.org>.
Jason918 commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1434007480

   > Hi @Jason918, do you have any updates for documenting this feature?
   > Since 2.11 has been released, now it's good timing to start the doc update in the next version.
   
   @momo-jun Thanks for the reminding, I will try to come up with the doc update before the 3.0.0 release.


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [pulsar] StevenLuMT commented on pull request #18265: [feat][broker] PIP-180 Part VI: Add ShadowManagedLedgerImpl

Posted by "StevenLuMT (via GitHub)" <gi...@apache.org>.
StevenLuMT commented on PR #18265:
URL: https://github.com/apache/pulsar/pull/18265#issuecomment-1434017303

   > > Hi @Jason918, do you have any updates for documenting this feature?
   > > Since 2.11 has been released, now it's good timing to start the doc update in the next version.
   > 
   > @momo-jun Thanks for the reminding, I will try to come up with the doc update before the 3.0.0 release.
   
   @momo-jun I have communicated with @Jason918 , I'll help him update the documentation


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org