kgyrtkirk commented on code in PR #18147: URL: https://github.com/apache/druid/pull/18147#discussion_r2151806213
########## simulation-tests/src/test/java/org/apache/druid/testing/simulate/embedded/DruidServerJunitResource.java: ########## @@ -0,0 +1,181 @@ +/* + * 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.druid.testing.simulate.embedded; + +import com.google.common.base.Throwables; +import com.google.inject.Injector; +import com.google.inject.Module; +import org.apache.druid.cli.ServerRunnable; +import org.apache.druid.guice.StartupInjectorBuilder; +import org.apache.druid.java.util.common.concurrent.Execs; +import org.apache.druid.java.util.common.lifecycle.Lifecycle; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.metadata.TestDerbyConnector; +import org.apache.druid.utils.JvmUtils; +import org.apache.druid.utils.RuntimeInfo; +import org.junit.rules.ExternalResource; Review Comment: for new frameworks I think it would be best to utilize `junit5` ########## simulation-tests/src/test/java/org/apache/druid/testing/simulate/embedded/EmbeddedOverlord.java: ########## @@ -0,0 +1,303 @@ +/* + * 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.druid.testing.simulate.embedded; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Supplier; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.Module; +import com.google.inject.Provider; +import org.apache.curator.framework.CuratorFramework; +import org.apache.druid.cli.CliOverlord; +import org.apache.druid.cli.ServerRunnable; +import org.apache.druid.curator.ZkEnablementConfig; +import org.apache.druid.discovery.DruidNodeDiscoveryProvider; +import org.apache.druid.guice.LazySingleton; +import org.apache.druid.guice.PolyBind; +import org.apache.druid.guice.annotations.EscalatedGlobal; +import org.apache.druid.guice.annotations.Smile; +import org.apache.druid.indexer.TaskLocation; +import org.apache.druid.indexer.TaskStatus; +import org.apache.druid.indexing.overlord.IndexerMetadataStorageCoordinator; +import org.apache.druid.indexing.overlord.TaskRunnerFactory; +import org.apache.druid.indexing.overlord.TaskRunnerListener; +import org.apache.druid.indexing.overlord.TaskStorage; +import org.apache.druid.indexing.overlord.autoscaling.ProvisioningSchedulerConfig; +import org.apache.druid.indexing.overlord.autoscaling.ProvisioningStrategy; +import org.apache.druid.indexing.overlord.config.HttpRemoteTaskRunnerConfig; +import org.apache.druid.indexing.overlord.hrtr.HttpRemoteTaskRunner; +import org.apache.druid.indexing.overlord.hrtr.HttpRemoteTaskRunnerFactory; +import org.apache.druid.indexing.overlord.setup.WorkerBehaviorConfig; +import org.apache.druid.java.util.common.lifecycle.Lifecycle; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.java.util.emitter.service.ServiceEmitter; +import org.apache.druid.java.util.http.client.HttpClient; +import org.apache.druid.metadata.TestDerbyConnector; +import org.apache.druid.query.DruidProcessingConfigTest; +import org.apache.druid.rpc.indexing.OverlordClient; +import org.apache.druid.server.initialization.IndexerZkConfig; +import org.apache.druid.utils.RuntimeInfo; +import org.jetbrains.annotations.Nullable; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Embedded mode of {@link CliOverlord} used in simulation tests. + */ +public class EmbeddedOverlord extends EmbeddedDruidServer +{ + private static final Logger log = new Logger(EmbeddedOverlord.class); + + private static final Map<String, String> DEFAULT_PROPERTIES = Map.of( + "druid.indexer.runner.type", "simulation", + "druid.indexer.queue.startDelay", "PT0S", + "druid.indexer.queue.restartDelay", "PT0S", + // Keep a small sync timeout so that Peons and Indexers are not stuck + // handling a change request when Overlord has already shutdown + "druid.indexer.runner.syncRequestTimeout", "PT1S" + ); + + private final Map<String, String> overrideProperties; + private final ReferenceHolder referenceHolder; + private final TaskRunnerListener taskRunnerListener; + private final ConcurrentHashMap<String, CountDownLatch> taskHasCompleted; + + public static EmbeddedOverlord create() + { + return withProps(Map.of()); + } + + public static EmbeddedOverlord withProps( + Map<String, String> properties + ) + { + return new EmbeddedOverlord(properties); + } + + private EmbeddedOverlord(Map<String, String> overrideProperties) + { + this.overrideProperties = overrideProperties; + this.referenceHolder = new ReferenceHolder(); + this.taskHasCompleted = new ConcurrentHashMap<>(); + this.taskRunnerListener = new TaskRunnerListener() + { + @Override + public String getListenerId() + { + return "EmbeddedOverlord.TaskRunnerListener"; + } + + @Override + public void locationChanged(String taskId, TaskLocation newLocation) + { + + } + + @Override + public void statusChanged(String taskId, TaskStatus status) + { + log.info("Task[%s] has updated status[%s]", taskId, status); + if (status.isComplete()) { + taskHasCompleted.compute( + taskId, + (t, existingLatch) -> { + final CountDownLatch latch = Objects.requireNonNullElse( + existingLatch, + new CountDownLatch(1) + ); + latch.countDown(); + return latch; + } + ); + } + } + }; + } + + @Override + ServerRunnable createRunnable(LifecycleInitHandler handler) + { + return new Overlord(handler); + } + + @Override + RuntimeInfo getRuntimeInfo() + { + final long mem1gb = 1_000_000_000; + return new DruidProcessingConfigTest.MockRuntimeInfo(4, mem1gb, mem1gb); + } + + @Override + Properties buildStartupProperties( + TemporaryFolder tempDir, + EmbeddedZookeeper zk, + @Nullable TestDerbyConnector.DerbyConnectorRule dbRule + ) throws IOException + { + final Properties properties = super.buildStartupProperties(tempDir, zk, dbRule); + properties.putAll(DEFAULT_PROPERTIES); + properties.putAll(overrideProperties); + return properties; + } + + /** + * Client to communicate with the leader Overlord, which may not be the same + * as this one. + */ + public OverlordClient client() + { + return leaderOverlord(); + } + + /** + * Metadata storage coordinator to query and update segment metadata directly + * in the metadata store. + */ + public IndexerMetadataStorageCoordinator segmentsMetadataStorage() + { + return referenceHolder.indexerMetadataStorageCoordinator; + } + + public void waitUntilTaskFinishes(String taskId) + { + try { + final CountDownLatch latch = taskHasCompleted.computeIfAbsent(taskId, t -> new CountDownLatch(1)); + if (!latch.await(30, TimeUnit.SECONDS)) { + log.error("Timed out waiting for task[%s] to finish.", taskId); + } + } + catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + /** + * Extends {@link CliOverlord} to for the following: + * <ul> + * <li>Get reference to lifecycle and other dependencies used by the server.</li> + * <li>Override {@link HttpRemoteTaskRunnerFactory} to register a + * {@link TaskRunnerListener} to get completion callbacks.</li> + * </ul> + */ + private class Overlord extends CliOverlord + { + private final LifecycleInitHandler handler; + + private Overlord(LifecycleInitHandler handler) + { + this.handler = handler; + } + + @Override + public Lifecycle initLifecycle(Injector injector) + { + final Lifecycle lifecycle = super.initLifecycle(injector); + handler.onLifecycleInit(lifecycle); + return lifecycle; + } + + @Override + protected List<? extends Module> getModules() + { + final List<Module> modules = new ArrayList<>(handler.getInitModules()); + modules.addAll(super.getModules()); + modules.add( + binder -> binder.bind(ReferenceHolder.class).toInstance(referenceHolder) + ); + + // Override TaskRunnerFactory to register a TaskRunnerListener + modules.add( + binder -> binder.bind(TaskRunnerListener.class).toInstance(taskRunnerListener) + ); + modules.add( + binder -> PolyBind.optionBinder(binder, Key.get(TaskRunnerFactory.class)) + .addBinding("simulation") + .to(TestHttpRemoteTaskRunnerFactory.class) + .in(LazySingleton.class) + ); + return modules; + } + } + + /** + * Overrides {@link HttpRemoteTaskRunnerFactory} to be able to register the + * {@link #taskRunnerListener} on the created {@link HttpRemoteTaskRunner}. + */ + private static class TestHttpRemoteTaskRunnerFactory extends HttpRemoteTaskRunnerFactory + { + private final TaskRunnerListener listener; + + @Inject + public TestHttpRemoteTaskRunnerFactory( + @Smile final ObjectMapper smileMapper, Review Comment: maybe use a delegate instead a subclass? ########## simulation-tests/src/test/java/org/apache/druid/testing/simulate/embedded/EmbeddedDruidServer.java: ########## @@ -0,0 +1,265 @@ +/* + * 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.druid.testing.simulate.embedded; + +import com.google.inject.Binder; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.Module; +import org.apache.druid.cli.ServerRunnable; +import org.apache.druid.client.broker.BrokerClient; +import org.apache.druid.client.coordinator.CoordinatorClient; +import org.apache.druid.guice.LazySingleton; +import org.apache.druid.guice.PolyBind; +import org.apache.druid.guice.SQLMetadataStorageDruidModule; +import org.apache.druid.java.util.common.StringUtils; +import org.apache.druid.java.util.common.lifecycle.Lifecycle; +import org.apache.druid.java.util.common.logger.Logger; +import org.apache.druid.metadata.DerbyMetadataStorageActionHandlerFactory; +import org.apache.druid.metadata.MetadataStorage; +import org.apache.druid.metadata.MetadataStorageActionHandlerFactory; +import org.apache.druid.metadata.MetadataStorageConnector; +import org.apache.druid.metadata.MetadataStorageProvider; +import org.apache.druid.metadata.NoopMetadataStorageProvider; +import org.apache.druid.metadata.SQLMetadataConnector; +import org.apache.druid.metadata.TestDerbyConnector; +import org.apache.druid.metadata.storage.derby.DerbyMetadataStorageProvider; +import org.apache.druid.rpc.indexing.OverlordClient; +import org.apache.druid.utils.RuntimeInfo; +import org.junit.rules.ExternalResource; +import org.junit.rules.TemporaryFolder; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * An embedded Druid server used in simulation tests. + * This class and its methods (except a couple) are kept package protected as + * they are used only by the specific server implementations. + */ +abstract class EmbeddedDruidServer implements EmbeddedServiceClientProvider +{ + private static final Logger log = new Logger(EmbeddedDruidServer.class); + + /** + * A static incremental ID is used instead of a random number to ensure that + * tests are more deterministic and easier to debug. + */ + private static final AtomicInteger SERVER_ID = new AtomicInteger(0); + + private final String name; + + private final ServiceClientHolder clientHolder = new ServiceClientHolder(); + + EmbeddedDruidServer() + { + this.name = StringUtils.format( + "%s-%d", + this.getClass().getSimpleName(), + SERVER_ID.incrementAndGet() + ); + } + + /** + * @return Name of this server = type + 2-digit ID. + */ + public String getName() + { + return name; + } + + @Override + public CoordinatorClient leaderCoordinator() + { + return clientHolder.coordinator; + } + + @Override + public OverlordClient leaderOverlord() + { + return clientHolder.overlord; + } + + @Override + public BrokerClient anyBroker() + { + return clientHolder.broker; + } + + /** + * Creates a {@link ServerRunnable} corresponding to a specific Druid service. + */ + abstract ServerRunnable createRunnable( + LifecycleInitHandler handler + ); + + /** + * {@link RuntimeInfo} to use for this server. + */ + abstract RuntimeInfo getRuntimeInfo(); + + /** + * Builds properties to be used in the {@code StartupInjectorBuilder} while + * launching this server. + */ + Properties buildStartupProperties( + TemporaryFolder tempDir, + EmbeddedZookeeper zk, + @Nullable TestDerbyConnector.DerbyConnectorRule dbRule + ) throws IOException + { + final Properties serverProperties = new Properties(); + + // Add properties for temporary directories used by the servers + final String logsDirectory = tempDir.getRoot().getAbsolutePath(); + final String taskDirectory = tempDir.newFolder().getAbsolutePath(); + final String storageDirectory = tempDir.newFolder().getAbsolutePath(); + log.info( + "Server[%s] using directories: task directory[%s], logs directory[%s], storage directory[%s].", + name, taskDirectory, logsDirectory, storageDirectory + ); + serverProperties.setProperty("druid.indexer.task.baseDir", taskDirectory); + serverProperties.setProperty("druid.indexer.logs.directory", logsDirectory); + serverProperties.setProperty("druid.storage.storageDirectory", storageDirectory); + + // Add properties for Zookeeper and metadata store + serverProperties.setProperty("druid.zk.service.host", zk.getConnectString()); + if (dbRule != null) { + serverProperties.setProperty("druid.metadata.storage.type", TestDerbyModule.TYPE); + serverProperties.setProperty( + "druid.metadata.storage.tables.base", + dbRule.getConnector().getMetadataTablesConfig().getBase() + ); + } + + return serverProperties; + } + + /** + * @see LifecycleInitHandler#getInitModules() + */ + List<? extends Module> getInitModules( + @Nullable TestDerbyConnector.DerbyConnectorRule dbRule + ) + { + final Module referenceHolderModule + = binder -> binder.bind(ServiceClientHolder.class).toInstance(clientHolder); + + return dbRule == null + ? List.of(referenceHolderModule) + : List.of(referenceHolderModule, new TestDerbyModule(dbRule.getConnector())); + } + + /** + * Creates a JUnit {@link ExternalResource} for this server that can be used + * with {@code Rule}, {@code ClassRule} or in a {@code RuleChain}. + */ + ExternalResource junitResource( + TemporaryFolder tempDir, + EmbeddedZookeeper zk, + @Nullable TestDerbyConnector.DerbyConnectorRule dbRule + ) + { + return new DruidServerJunitResource(this, tempDir, zk, dbRule); + } + + /** + * Handler used during initialization of the lifecycle of an embedded server. + */ + interface LifecycleInitHandler + { + /** + * @return Modules that should be used in {@link ServerRunnable#getModules()}. + * This list contains modules that cannot be injected into the + * {@code StartupInjectorBuilder} as they need dependencies that are only + * bound later either in {@link ServerRunnable#getModules()} itself or via + * the {@code CoreInjectorBuilder}. + */ + List<? extends Module> getInitModules(); + + /** + * All implementations of {@link EmbeddedDruidServer} must call this method + * from {@link ServerRunnable#initLifecycle(Injector)}. + */ + void onLifecycleInit(Lifecycle lifecycle); + } + + /** + * Guice module to bind {@link SQLMetadataConnector} to {@link TestDerbyConnector}. + * Used in Coordinator and Overlord simulations to connect to an in-memory Derby + * database. + */ + private static class TestDerbyModule extends SQLMetadataStorageDruidModule + { + public static final String TYPE = "derbyInMemory"; + private final TestDerbyConnector connector; + + public TestDerbyModule(TestDerbyConnector connector) + { + super(TYPE); + this.connector = connector; + } + + @Override + public void configure(Binder binder) + { + super.configure(binder); + + binder.bind(MetadataStorage.class).toProvider(NoopMetadataStorageProvider.class); + + PolyBind.optionBinder(binder, Key.get(MetadataStorageProvider.class)) + .addBinding(TYPE) + .to(DerbyMetadataStorageProvider.class) + .in(LazySingleton.class); + + PolyBind.optionBinder(binder, Key.get(MetadataStorageConnector.class)) + .addBinding(TYPE) + .toInstance(connector); + + PolyBind.optionBinder(binder, Key.get(SQLMetadataConnector.class)) + .addBinding(TYPE) + .toInstance(connector); + + PolyBind.optionBinder(binder, Key.get(MetadataStorageActionHandlerFactory.class)) + .addBinding(TYPE) + .to(DerbyMetadataStorageActionHandlerFactory.class) + .in(LazySingleton.class); + } + } + + /** + * Holder for the service client instances that are being used by this server. + */ + private static class ServiceClientHolder + { + @Inject + CoordinatorClient coordinator; Review Comment: I don't really understand why this injection will happen - an instance of it is only present as a private field of this class - could you give a hint? :) -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
