codelipenghui commented on code in PR #25219: URL: https://github.com/apache/pulsar/pull/25219#discussion_r2873865584
########## pulsar-metadata/src/main/java/org/apache/pulsar/metadata/impl/DualMetadataStore.java: ########## @@ -0,0 +1,434 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pulsar.metadata.impl; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.netty.util.concurrent.DefaultThreadFactory; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.pulsar.common.migration.MigrationPhase; +import org.apache.pulsar.common.migration.MigrationState; +import org.apache.pulsar.common.util.FutureUtil; +import org.apache.pulsar.metadata.api.GetResult; +import org.apache.pulsar.metadata.api.MetadataCache; +import org.apache.pulsar.metadata.api.MetadataCacheConfig; +import org.apache.pulsar.metadata.api.MetadataEvent; +import org.apache.pulsar.metadata.api.MetadataEventSynchronizer; +import org.apache.pulsar.metadata.api.MetadataSerde; +import org.apache.pulsar.metadata.api.MetadataStore; +import org.apache.pulsar.metadata.api.MetadataStoreConfig; +import org.apache.pulsar.metadata.api.MetadataStoreException; +import org.apache.pulsar.metadata.api.MetadataStoreLifecycle; +import org.apache.pulsar.metadata.api.Notification; +import org.apache.pulsar.metadata.api.Stat; +import org.apache.pulsar.metadata.api.extended.CreateOption; +import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended; +import org.apache.pulsar.metadata.api.extended.SessionEvent; + +/** + * Wrapper around a metadata store that provides transparent migration capability. + * + * <p>When migration is not active, all operations are forwarded to the source store. + * When migration starts (detected via flag in source store), this wrapper: + * <ul> + * <li>Initializes connection to target store</li> + * <li>Recreates ephemeral nodes in target store</li> + * <li>Routes reads/writes based on migration phase</li> + * </ul> + */ +@Slf4j +public class DualMetadataStore implements MetadataStoreExtended { + + @Getter + final MetadataStoreExtended sourceStore; + volatile MetadataStoreExtended targetStore = null; + + private volatile MigrationState migrationState = MigrationState.NOT_STARTED; + + private final MetadataStoreConfig config; + private String participantId; + private final Set<String> localEphemeralPaths = ConcurrentHashMap.newKeySet(); + + private final ScheduledExecutorService executor; + + private final MetadataCache<MigrationState> migrationStateCache; + + private final Set<Consumer<Notification>> listeners = ConcurrentHashMap.newKeySet(); + private final Set<Consumer<SessionEvent>> sessionListeners = ConcurrentHashMap.newKeySet(); + + private final AtomicInteger pendingSourceWrites = new AtomicInteger(); Review Comment: Should we check `pendingSourceWrites` before starting the migration? Otherwise, updates might be written to ZooKeeper after the migration has begun. ########## pulsar-metadata/src/main/java/org/apache/pulsar/metadata/impl/DualMetadataStore.java: ########## @@ -0,0 +1,434 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pulsar.metadata.impl; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.netty.util.concurrent.DefaultThreadFactory; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.pulsar.common.migration.MigrationPhase; +import org.apache.pulsar.common.migration.MigrationState; +import org.apache.pulsar.common.util.FutureUtil; +import org.apache.pulsar.metadata.api.GetResult; +import org.apache.pulsar.metadata.api.MetadataCache; +import org.apache.pulsar.metadata.api.MetadataCacheConfig; +import org.apache.pulsar.metadata.api.MetadataEvent; +import org.apache.pulsar.metadata.api.MetadataEventSynchronizer; +import org.apache.pulsar.metadata.api.MetadataSerde; +import org.apache.pulsar.metadata.api.MetadataStore; +import org.apache.pulsar.metadata.api.MetadataStoreConfig; +import org.apache.pulsar.metadata.api.MetadataStoreException; +import org.apache.pulsar.metadata.api.MetadataStoreLifecycle; +import org.apache.pulsar.metadata.api.Notification; +import org.apache.pulsar.metadata.api.Stat; +import org.apache.pulsar.metadata.api.extended.CreateOption; +import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended; +import org.apache.pulsar.metadata.api.extended.SessionEvent; + +/** + * Wrapper around a metadata store that provides transparent migration capability. + * + * <p>When migration is not active, all operations are forwarded to the source store. + * When migration starts (detected via flag in source store), this wrapper: + * <ul> + * <li>Initializes connection to target store</li> + * <li>Recreates ephemeral nodes in target store</li> + * <li>Routes reads/writes based on migration phase</li> + * </ul> + */ +@Slf4j +public class DualMetadataStore implements MetadataStoreExtended { + + @Getter + final MetadataStoreExtended sourceStore; + volatile MetadataStoreExtended targetStore = null; + + private volatile MigrationState migrationState = MigrationState.NOT_STARTED; + + private final MetadataStoreConfig config; + private String participantId; + private final Set<String> localEphemeralPaths = ConcurrentHashMap.newKeySet(); + + private final ScheduledExecutorService executor; + + private final MetadataCache<MigrationState> migrationStateCache; + + private final Set<Consumer<Notification>> listeners = ConcurrentHashMap.newKeySet(); + private final Set<Consumer<SessionEvent>> sessionListeners = ConcurrentHashMap.newKeySet(); + + private final AtomicInteger pendingSourceWrites = new AtomicInteger(); + + private final Set<DualMetadataCache<?>> caches = ConcurrentHashMap.newKeySet(); + + private static final IllegalStateException READ_ONLY_STATE_EXCEPTION = + new IllegalStateException("Write operations not allowed during migrations"); + + public DualMetadataStore(MetadataStore sourceStore, MetadataStoreConfig config) throws MetadataStoreException { + this.sourceStore = (MetadataStoreExtended) sourceStore; + this.config = config; + this.executor = new ScheduledThreadPoolExecutor(1, + new DefaultThreadFactory("pulsar-dual-metadata-store", true)); + this.migrationStateCache = sourceStore.getMetadataCache(MigrationState.class); + + if (sourceStore instanceof MetadataStoreLifecycle msl) { + msl.initializeCluster(); + } + + readCurrentState(); + registerAsParticipant(); + + // Watch for migration events + watchForMigrationEvents(); + } + + private void readCurrentState() throws MetadataStoreException { + try { + // Read the current state, force ZK to sync to read the latest value + sourceStore.sync(MigrationState.MIGRATION_FLAG_PATH).get(); + var initialState = migrationStateCache.get(MigrationState.MIGRATION_FLAG_PATH).get(); + initialState.ifPresent(state -> this.migrationState = state); + + if (migrationState.getPhase() == MigrationPhase.COMPLETED) { + initializeTargetStore(migrationState.getTargetUrl()); + } + + } catch (Exception e) { + throw new MetadataStoreException(e); + } + } + + private void registerAsParticipant() throws MetadataStoreException { + try { + // Register ourselves as participant in an eventual migration + Stat stat = this.sourceStore.put(MigrationState.PARTICIPANTS_PATH + "/id-", new byte[0], + Optional.empty(), EnumSet.of(CreateOption.Sequential, CreateOption.Ephemeral)).get(); + participantId = stat.getPath(); + log.info("Participant metadata store created: {}", participantId); + } catch (Throwable e) { + throw new MetadataStoreException(e); + } + } + + private void watchForMigrationEvents() { + // Register listener for migration-related paths + sourceStore.registerListener(notification -> { + if (!MigrationState.MIGRATION_FLAG_PATH.equals(notification.getPath())) { + return; + } + + migrationStateCache.get(MigrationState.MIGRATION_FLAG_PATH) + .thenAccept(migrationState -> { + this.migrationState = migrationState.orElse(MigrationState.NOT_STARTED); + + switch (this.migrationState.getPhase()) { + case PREPARATION -> executor.execute(this::handleMigrationStart); + case COMPLETED -> executor.execute(this::handleMigrationComplete); + case FAILED -> executor.execute(this::handleMigrationFailed); + default -> { + // no-op + } + } + }); + }); + } + + private void handleMigrationStart() { + try { + log.info("=== Starting Metadata Migration Preparation ==="); + log.info("Target metadata store URL: {}", migrationState.getTargetUrl()); + + // Mark the session as lost so that all the component will avoid trying to make metadata writes + // for anything that can be deferred (eg: ledgers rollovers) + sessionListeners.forEach(listener -> listener.accept(SessionEvent.SessionLost)); + + // Initialize target store + initializeTargetStore(migrationState.getTargetUrl()); + + this.recreateEphemeralNodesInTarget(); + + // Acknowledge preparation by deleting the participant id + sourceStore.delete(participantId, Optional.empty()).get(); Review Comment: If there is any exception happened before this line, the waitForPreparation() method from MigrationCoordinator runs an infinite loop. It seems missed retry for the failures (or timeout from the waitForPreparation in MigrationCoordinator) ########## pulsar-metadata/src/main/java/org/apache/pulsar/metadata/coordination/impl/MigrationCoordinator.java: ########## @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pulsar.metadata.coordination.impl; + +import io.oxia.client.api.AsyncOxiaClient; +import io.oxia.client.api.options.defs.OptionOverrideModificationsCount; +import io.oxia.client.api.options.defs.OptionOverrideVersionId; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import lombok.extern.slf4j.Slf4j; +import org.apache.pulsar.common.migration.MigrationPhase; +import org.apache.pulsar.common.migration.MigrationState; +import org.apache.pulsar.common.util.ObjectMapperFactory; +import org.apache.pulsar.metadata.api.MetadataCache; +import org.apache.pulsar.metadata.api.MetadataStore; +import org.apache.pulsar.metadata.api.MetadataStoreException; +import org.apache.pulsar.metadata.api.extended.CreateOption; +import org.apache.pulsar.metadata.impl.oxia.OxiaMetadataStoreProvider; + +/** + * Coordinates metadata store migration process. + */ +@Slf4j +public class MigrationCoordinator { + private final MetadataStore sourceStore; + private final String targetUrl; + private final AsyncOxiaClient oxiaClient; + private final MetadataCache<MigrationState> migrationStateCache; + + private static final int MAX_PENDING_OPS = 1000; + + public MigrationCoordinator(MetadataStore sourceStore, String targetUrl) throws MetadataStoreException { + this.sourceStore = sourceStore; + this.targetUrl = targetUrl; + this.migrationStateCache = sourceStore.getMetadataCache(MigrationState.class); + + if (!targetUrl.startsWith("oxia://")) { + throw new MetadataStoreException("Expected target metadata store to be Oxia"); + } + + this.oxiaClient = new OxiaMetadataStoreProvider().getOxiaClient(targetUrl); + } + + /** + * Start the migration process. + * + * @throws Exception if migration fails + */ + public void startMigration() throws Exception { + log.info("=== Starting Migration ==="); + log.info("Source: {} (current)", sourceStore.getClass().getSimpleName()); + log.info("Target: {}", targetUrl); + + try { + // 1. Create migration flag + setInitialMigrationPhase(); + + // 2. Wait for participants to prepare + waitForPreparation(); + + // 3. Copy persistent data + updatePhase(MigrationPhase.COPYING); + copyPersistentData(); + + // 4. Set state to completed + updatePhase(MigrationPhase.COMPLETED); + + log.info("=== Migration Complete ==="); + } catch (Exception e) { + log.error("Migration failed", e); + updatePhase(MigrationPhase.FAILED); + throw e; + } + } + + private void setInitialMigrationPhase() throws MetadataStoreException { + try { + sourceStore.put(MigrationState.MIGRATION_FLAG_PATH, + ObjectMapperFactory.getMapper().writer() + .writeValueAsBytes(new MigrationState(MigrationPhase.PREPARATION, targetUrl)), + Optional.of(-1L)).get(); + } catch (Exception e) { + throw new MetadataStoreException(e); + } + } + + private void updatePhase(MigrationPhase phase) throws MetadataStoreException { + try { + migrationStateCache.put(MigrationState.MIGRATION_FLAG_PATH, + new MigrationState(phase, targetUrl), EnumSet.noneOf(CreateOption.class)).get(); + } catch (Exception e) { + throw new MetadataStoreException(e); + } + } + + private void waitForPreparation() throws Exception { + log.info("Waiting for all participants to prepare..."); + + while (true) { + List<String> pending = sourceStore.getChildren(MigrationState.PARTICIPANTS_PATH).get(); + if (pending.isEmpty()) { + break; + } + + log.info("Waiting for participants to prepare. pending: {}", pending); + Thread.sleep(1000); + } + + log.info("All migration participants ready"); + } + + private void copyPersistentData() throws Exception { + log.info("Starting persistent data copy..."); + + AtomicLong copiedCount = new AtomicLong(0); + Semaphore semaphore = new Semaphore(MAX_PENDING_OPS); + AtomicReference<Throwable> exception = new AtomicReference<>(); + + // Bootstrap first level + BlockingQueue<String> workQueue = new LinkedBlockingQueue<>(getChildren("/").get()); + + while (true) { + String path = workQueue.poll(1, TimeUnit.SECONDS); + if (path == null) { + // Wait until all pending ops are done + if (semaphore.availablePermits() != MAX_PENDING_OPS) { + continue; + } else { + break; + } + } + + semaphore.acquire(); + copy(path).whenComplete((res, e) -> { + semaphore.release(); + if (e != null) { + exception.compareAndSet(null, e); + } + + copiedCount.incrementAndGet(); + }); + + semaphore.acquire(); + getChildren(path).whenComplete((res, e) -> { + if (e != null) { + exception.compareAndSet(null, e); + } + + workQueue.addAll(res); + semaphore.release(); Review Comment: If getChildren fails, e is non-null and res is null. Calling workQueue.addAll(null) throws a NullPointerException. Because this throws before semaphore.release() is called, the semaphore permit is leaked. The coordinator's while (true) loop relies on semaphore.availablePermits() == MAX_PENDING_OPS to break out when the queue is empty. With a leaked permit, this condition will never be met, and the migration will deadlock. ########## pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/MetadataMigrationBase.java: ########## @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pulsar.broker.admin.impl; + +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import lombok.extern.slf4j.Slf4j; +import org.apache.pulsar.broker.admin.AdminResource; +import org.apache.pulsar.broker.web.RestException; +import org.apache.pulsar.common.migration.MigrationState; +import org.apache.pulsar.common.util.ObjectMapperFactory; +import org.apache.pulsar.metadata.coordination.impl.MigrationCoordinator; +import org.apache.pulsar.metadata.impl.DualMetadataStore; + +/** + * Admin resource for metadata store migration operations. + */ +@Slf4j +public class MetadataMigrationBase extends AdminResource { + + @GET + @Path("/status") + @ApiOperation(value = "Get current migration status", response = MigrationState.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Migration status retrieved successfully"), + @ApiResponse(code = 500, message = "Internal server error") + }) + public MigrationState getStatus() { + validateSuperUserAccess(); + + try { + var ogr = pulsar().getLocalMetadataStore().get(MigrationState.MIGRATION_FLAG_PATH).get(); + if (ogr.isPresent()) { + return ObjectMapperFactory.getMapper().reader().readValue(ogr.get().getValue(), MigrationState.class); + } else { + return MigrationState.NOT_STARTED; + } + } catch (Exception e) { + log.error("Failed to get migration status", e); + throw new RestException(e); + } + } + + @POST + @Path("/start") + @ApiOperation(value = "Start metadata store migration") + @ApiResponses(value = { + @ApiResponse(code = 204, message = "Migration started successfully"), + @ApiResponse(code = 400, message = "Invalid target URL"), + @ApiResponse(code = 409, message = "Migration already in progress"), + @ApiResponse(code = 500, message = "Internal server error") + }) + public void startMigration( + @ApiParam(value = "Target metadata store URL", required = true) + @QueryParam("target") + String targetUrl) { + validateSuperUserAccess(); + + if (targetUrl == null || targetUrl.trim().isEmpty()) { + throw new RestException(Response.Status.BAD_REQUEST, "Target URL is required"); + } + + try { + // Check if metadata store is wrapped with DualMetadataStore + if (!(pulsar().getLocalMetadataStore() instanceof DualMetadataStore)) { + throw new RestException(Response.Status.BAD_REQUEST, "Metadata store is not configured for migration. " + + "Please ensure you're using a supported source metadata store (e.g., ZooKeeper)."); + } + + // Create coordinator + MigrationCoordinator coordinator = new MigrationCoordinator(pulsar().getLocalMetadataStore(), targetUrl); + + // Start migration in background thread + pulsar().getExecutor().submit(() -> { + try { + log.info("Starting metadata migration to: {}", targetUrl); + coordinator.startMigration(); + log.info("Metadata migration completed successfully"); + } catch (Exception e) { + log.error("Metadata migration failed", e); Review Comment: Because coordinator.startMigration() is executed asynchronously, the HTTP response is returned immediately as a success (204 No Content). If there is any exception happened when starting the migration, we should return the corresponding exception messages to the client side. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
