Repository: aurora Updated Branches: refs/heads/master 782f8832c -> 85f995447
http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/main/java/org/apache/aurora/common/zookeeper/ServerSetImpl.java ---------------------------------------------------------------------- diff --git a/commons/src/main/java/org/apache/aurora/common/zookeeper/ServerSetImpl.java b/commons/src/main/java/org/apache/aurora/common/zookeeper/ServerSetImpl.java index 9a33d3e..cb0f3ec 100644 --- a/commons/src/main/java/org/apache/aurora/common/zookeeper/ServerSetImpl.java +++ b/commons/src/main/java/org/apache/aurora/common/zookeeper/ServerSetImpl.java @@ -33,7 +33,6 @@ import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; @@ -49,25 +48,19 @@ import com.google.common.collect.Sets.SetView; import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.gson.Gson; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.KeeperException.NoNodeException; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.ZooDefs; -import org.apache.zookeeper.data.ACL; - -import org.apache.aurora.common.args.Arg; -import org.apache.aurora.common.args.CmdLine; import org.apache.aurora.common.base.Command; import org.apache.aurora.common.base.Function; import org.apache.aurora.common.base.Supplier; import org.apache.aurora.common.io.Codec; -import org.apache.aurora.common.io.CompatibilityCodec; -import org.apache.aurora.common.io.ThriftCodec; -import org.apache.aurora.common.util.BackoffHelper; - import org.apache.aurora.common.thrift.Endpoint; import org.apache.aurora.common.thrift.ServiceInstance; import org.apache.aurora.common.thrift.Status; +import org.apache.aurora.common.util.BackoffHelper; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.KeeperException.NoNodeException; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.data.ACL; import static com.google.common.base.Preconditions.checkNotNull; @@ -77,11 +70,6 @@ import static com.google.common.base.Preconditions.checkNotNull; public class ServerSetImpl implements ServerSet { private static final Logger LOG = Logger.getLogger(ServerSetImpl.class.getName()); - @CmdLine(name = "serverset_encode_json", - help = "If true, use JSON for encoding server set information." - + " Defaults to true (use JSON).") - private static final Arg<Boolean> ENCODE_JSON = Arg.create(true); - private final ZooKeeperClient zkClient; private final Group group; private final Codec<ServiceInstance> codec; @@ -105,7 +93,7 @@ public class ServerSetImpl implements ServerSet { * @param path the name-service path of the service to connect to */ public ServerSetImpl(ZooKeeperClient zkClient, Iterable<ACL> acl, String path) { - this(zkClient, new Group(zkClient, acl, path), createDefaultCodec()); + this(zkClient, new Group(zkClient, acl, path), createCodec()); } /** @@ -115,7 +103,7 @@ public class ServerSetImpl implements ServerSet { * @param group the server group */ public ServerSetImpl(ZooKeeperClient zkClient, Group group) { - this(zkClient, group, createDefaultCodec()); + this(zkClient, group, createCodec()); } /** @@ -553,50 +541,12 @@ public class ServerSetImpl implements ServerSet { } } - private static Codec<ServiceInstance> createCodec(final boolean useJsonEncoding) { - final Codec<ServiceInstance> json = new AdaptedJsonCodec(); - final Codec<ServiceInstance> thrift = - ThriftCodec.create(ServiceInstance.class, ThriftCodec.BINARY_PROTOCOL); - final Predicate<byte[]> recognizer = new Predicate<byte[]>() { - public boolean apply(byte[] input) { - return (input.length > 1 && input[0] == '{' && input[1] == '\"') == useJsonEncoding; - } - }; - - if (useJsonEncoding) { - return CompatibilityCodec.create(json, thrift, 2, recognizer); - } - return CompatibilityCodec.create(thrift, json, 2, recognizer); - } - - /** - * Creates a codec for {@link ServiceInstance} objects that uses Thrift binary encoding, and can - * decode both Thrift and JSON encodings. - * - * @return a new codec instance. - */ - public static Codec<ServiceInstance> createThriftCodec() { - return createCodec(false); - } - - /** - * Creates a codec for {@link ServiceInstance} objects that uses JSON encoding, and can decode - * both Thrift and JSON encodings. - * - * @return a new codec instance. - */ - public static Codec<ServiceInstance> createJsonCodec() { - return createCodec(true); - } - /** - * Returns a codec for {@link ServiceInstance} objects that uses either the Thrift or the JSON - * encoding, depending on whether the command line argument <tt>serverset_json_encofing</tt> is - * set to <tt>true</tt>, and can decode both Thrift and JSON encodings. + * Returns a codec for {@link ServiceInstance} objects that translates to and from JSON. * * @return a new codec instance. */ - public static Codec<ServiceInstance> createDefaultCodec() { - return createCodec(ENCODE_JSON.get()); + public static Codec<ServiceInstance> createCodec() { + return new AdaptedJsonCodec(); } } http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/main/java/org/apache/aurora/common/zookeeper/SingletonService.java ---------------------------------------------------------------------- diff --git a/commons/src/main/java/org/apache/aurora/common/zookeeper/SingletonService.java b/commons/src/main/java/org/apache/aurora/common/zookeeper/SingletonService.java index 660f3d6..110c9ef 100644 --- a/commons/src/main/java/org/apache/aurora/common/zookeeper/SingletonService.java +++ b/commons/src/main/java/org/apache/aurora/common/zookeeper/SingletonService.java @@ -16,27 +16,19 @@ package org.apache.aurora.common.zookeeper; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.Watcher.Event.EventType; -import org.apache.zookeeper.Watcher.Event.KeeperState; -import org.apache.zookeeper.ZooDefs; -import org.apache.zookeeper.data.ACL; - import org.apache.aurora.common.base.ExceptionalCommand; +import org.apache.aurora.common.thrift.Status; import org.apache.aurora.common.zookeeper.Candidate.Leader; import org.apache.aurora.common.zookeeper.Group.JoinException; - -import org.apache.aurora.common.thrift.Status; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.data.ACL; /** * A service that uses master election to only allow a single instance of the server to join @@ -214,81 +206,6 @@ public class SingletonService { } /** - * A leadership listener that decorates another listener by automatically defeating a - * leader that has dropped its connection to ZooKeeper. - * Note that the decision to use this over session-based mutual exclusion should not be taken - * lightly. Any momentary connection loss due to a flaky network or a ZooKeeper server process - * exit will cause a leader to abort. - */ - public static class DefeatOnDisconnectLeader implements LeadershipListener { - - private final LeadershipListener wrapped; - private Optional<LeaderControl> maybeControl = Optional.absent(); - - /** - * Creates a new leadership listener that will delegate calls to the wrapped listener, and - * invoke {@link #onDefeated(ServerSet.EndpointStatus)} if a ZooKeeper disconnect is observed while - * leading. - * - * @param zkClient The ZooKeeper client to watch for disconnect events. - * @param wrapped The leadership listener to wrap. - */ - public DefeatOnDisconnectLeader(ZooKeeperClient zkClient, LeadershipListener wrapped) { - this.wrapped = Preconditions.checkNotNull(wrapped); - - zkClient.register(new Watcher() { - @Override public void process(WatchedEvent event) { - if ((event.getType() == EventType.None) - && (event.getState() == KeeperState.Disconnected)) { - disconnected(); - } - } - }); - } - - private synchronized void disconnected() { - if (maybeControl.isPresent()) { - LOG.warning("Disconnected from ZooKeeper while leading, committing suicide."); - try { - wrapped.onDefeated(null); - maybeControl.get().leave(); - } catch (ServerSet.UpdateException e) { - LOG.log(Level.WARNING, "Failed to leave singleton service: " + e, e); - } catch (JoinException e) { - LOG.log(Level.WARNING, "Failed to leave singleton service: " + e, e); - } finally { - setControl(null); - } - } else { - LOG.info("Disconnected from ZooKeeper, but that's fine because I'm not the leader."); - } - } - - private synchronized void setControl(@Nullable LeaderControl control) { - this.maybeControl = Optional.fromNullable(control); - } - - @Override public void onLeading(final LeaderControl control) { - setControl(control); - wrapped.onLeading(new LeaderControl() { - @Override public void advertise() throws JoinException, InterruptedException { - control.advertise(); - } - - @Override public void leave() throws ServerSet.UpdateException, JoinException { - setControl(null); - control.leave(); - } - }); - } - - @Override public void onDefeated(@Nullable ServerSet.EndpointStatus status) { - setControl(null); - wrapped.onDefeated(status); - } - } - - /** * A controller for the state of the leader. This will be provided to the leader upon election, * which allows the leader to decide when to advertise in the underlying {@link ServerSet} and * terminate leadership at will. http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/ServerSetModule.java ---------------------------------------------------------------------- diff --git a/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/ServerSetModule.java b/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/ServerSetModule.java deleted file mode 100644 index c8a3214..0000000 --- a/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/ServerSetModule.java +++ /dev/null @@ -1,267 +0,0 @@ -/** - * Licensed 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.aurora.common.zookeeper.guice; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.annotation.Nullable; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.Atomics; -import com.google.inject.AbstractModule; -import com.google.inject.BindingAnnotation; -import com.google.inject.Inject; -import com.google.inject.Key; -import com.google.inject.Singleton; -import com.google.inject.TypeLiteral; - -import org.apache.aurora.common.application.ShutdownRegistry; -import org.apache.aurora.common.application.modules.LifecycleModule; -import org.apache.aurora.common.application.modules.LocalServiceRegistry; -import org.apache.aurora.common.args.Arg; -import org.apache.aurora.common.args.CmdLine; -import org.apache.aurora.common.args.constraints.NotNegative; -import org.apache.aurora.common.base.Command; -import org.apache.aurora.common.base.ExceptionalCommand; -import org.apache.aurora.common.base.Supplier; -import org.apache.aurora.common.zookeeper.Group; -import org.apache.aurora.common.zookeeper.ServerSet; - -import static com.google.common.base.Preconditions.checkNotNull; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * A module that registers all ports in the {@link LocalServiceRegistry} in an {@link ServerSet}. - * <p/> - * Required bindings: - * <ul> - * <li> {@link ServerSet} - * <li> {@link ShutdownRegistry} - * <li> {@link LocalServiceRegistry} - * </ul> - * <p/> - * {@link LifecycleModule} must also be included by users so a startup action may be registered. - * <p/> - * Provided bindings: - * <ul> - * <li> {@link Supplier}<{@link ServerSet.EndpointStatus}> - * </ul> - */ -public class ServerSetModule extends AbstractModule { - - /** - * BindingAnnotation for defaults to use in the service instance node. - */ - @BindingAnnotation @Target({PARAMETER, METHOD, FIELD}) @Retention(RUNTIME) - private @interface Default {} - - /** - * Binding annotation to give the ServerSetJoiner a fixed known ServerSet that is appropriate to - * {@link ServerSet#join} on. - */ - @BindingAnnotation @Target({METHOD, PARAMETER}) @Retention(RUNTIME) - private @interface Joinable {} - - private static final Key<ServerSet> JOINABLE_SS = Key.get(ServerSet.class, Joinable.class); - - @CmdLine(name = "aux_port_as_primary", - help = "Name of the auxiliary port to use as the primary port in the server set." - + " This may only be used when no other primary port is specified.") - private static final Arg<String> AUX_PORT_AS_PRIMARY = Arg.create(null); - - @NotNegative - @CmdLine(name = "shard_id", help = "Shard ID for this application.") - private static final Arg<Integer> SHARD_ID = Arg.create(); - - private static final Logger LOG = Logger.getLogger(ServerSetModule.class.getName()); - - /** - * Builds a Module tht can be used to join a {@link ServerSet} with the ports configured in a - * {@link LocalServiceRegistry}. - */ - public static class Builder { - private Key<ServerSet> key = Key.get(ServerSet.class); - private Optional<String> auxPortAsPrimary = Optional.absent(); - - /** - * Sets the key of the ServerSet to join. - * - * @param key Key of the ServerSet to join. - * @return This builder for chaining calls. - */ - public Builder key(Key<ServerSet> key) { - this.key = key; - return this; - } - - /** - * Allows joining an auxiliary port with the specified {@code name} as the primary port of the - * ServerSet. - * - * @param auxPortName The name of the auxiliary port to join as the primary ServerSet port. - * @return This builder for chaining calls. - */ - public Builder namedPrimaryPort(String auxPortName) { - this.auxPortAsPrimary = Optional.of(auxPortName); - return this; - } - - /** - * Creates a Module that will register a startup action that joins a ServerSet when installed. - * - * @return A Module. - */ - public ServerSetModule build() { - return new ServerSetModule(key, auxPortAsPrimary); - } - } - - /** - * Creates a builder that can be used to configure and create a ServerSetModule. - * - * @return A ServerSetModule builder. - */ - public static Builder builder() { - return new Builder(); - } - - private final Key<ServerSet> serverSetKey; - private final Optional<String> auxPortAsPrimary; - - /** - * Constructs a ServerSetModule that registers a startup action to register this process in - * ZooKeeper, with the specified initial status and auxiliary port to represent as the primary - * service port. - * - * @param serverSetKey The key the ServerSet to join is bound under. - * @param auxPortAsPrimary Name of the auxiliary port to use as the primary port. - */ - ServerSetModule(Key<ServerSet> serverSetKey, Optional<String> auxPortAsPrimary) { - - this.serverSetKey = checkNotNull(serverSetKey); - this.auxPortAsPrimary = checkNotNull(auxPortAsPrimary); - } - - @Override - protected void configure() { - requireBinding(serverSetKey); - requireBinding(ShutdownRegistry.class); - requireBinding(LocalServiceRegistry.class); - - LifecycleModule.bindStartupAction(binder(), ServerSetJoiner.class); - - bind(new TypeLiteral<Supplier<ServerSet.EndpointStatus>>() { }).to(EndpointSupplier.class); - bind(EndpointSupplier.class).in(Singleton.class); - - Optional<String> primaryPortName; - if (AUX_PORT_AS_PRIMARY.hasAppliedValue()) { - primaryPortName = Optional.of(AUX_PORT_AS_PRIMARY.get()); - } else { - primaryPortName = auxPortAsPrimary; - } - - bind(new TypeLiteral<Optional<String>>() { }).annotatedWith(Default.class) - .toInstance(primaryPortName); - - bind(JOINABLE_SS).to(serverSetKey); - } - - static class EndpointSupplier implements Supplier<ServerSet.EndpointStatus> { - private final AtomicReference<ServerSet.EndpointStatus> reference = Atomics.newReference(); - - @Nullable - @Override public ServerSet.EndpointStatus get() { - return reference.get(); - } - - void set(ServerSet.EndpointStatus endpoint) { - reference.set(endpoint); - } - } - - private static class ServerSetJoiner implements Command { - private final ServerSet serverSet; - private final LocalServiceRegistry serviceRegistry; - private final ShutdownRegistry shutdownRegistry; - private final EndpointSupplier endpointSupplier; - private final Optional<String> auxPortAsPrimary; - - @Inject - ServerSetJoiner( - @Joinable ServerSet serverSet, - LocalServiceRegistry serviceRegistry, - ShutdownRegistry shutdownRegistry, - EndpointSupplier endpointSupplier, - @Default Optional<String> auxPortAsPrimary) { - - this.serverSet = checkNotNull(serverSet); - this.serviceRegistry = checkNotNull(serviceRegistry); - this.shutdownRegistry = checkNotNull(shutdownRegistry); - this.endpointSupplier = checkNotNull(endpointSupplier); - this.auxPortAsPrimary = checkNotNull(auxPortAsPrimary); - } - - @Override public void execute() { - Optional<InetSocketAddress> primarySocket = serviceRegistry.getPrimarySocket(); - Map<String, InetSocketAddress> auxSockets = serviceRegistry.getAuxiliarySockets(); - - InetSocketAddress primary; - if (primarySocket.isPresent()) { - primary = primarySocket.get(); - } else if (auxPortAsPrimary.isPresent()) { - primary = auxSockets.get(auxPortAsPrimary.get()); - if (primary == null) { - throw new IllegalStateException("No auxiliary port named " + auxPortAsPrimary.get()); - } - } else { - throw new IllegalStateException("No primary service registered with LocalServiceRegistry," - + " and -aux_port_as_primary was not specified."); - } - - final ServerSet.EndpointStatus endpointStatus; - try { - if (SHARD_ID.hasAppliedValue()) { - endpointStatus = serverSet.join(primary, auxSockets, SHARD_ID.get()); - } else { - endpointStatus = serverSet.join(primary, auxSockets); - } - - endpointSupplier.set(endpointStatus); - } catch (Group.JoinException e) { - LOG.log(Level.WARNING, "Failed to join ServerSet.", e); - throw new RuntimeException(e); - } catch (InterruptedException e) { - LOG.log(Level.WARNING, "Interrupted while joining ServerSet.", e); - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - } - - shutdownRegistry.addAction(new ExceptionalCommand<ServerSet.UpdateException>() { - @Override public void execute() throws ServerSet.UpdateException { - LOG.info("Leaving ServerSet."); - endpointStatus.leave(); - } - }); - } - } -} http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/client/ZooKeeperClientModule.java ---------------------------------------------------------------------- diff --git a/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/client/ZooKeeperClientModule.java b/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/client/ZooKeeperClientModule.java index 08cdf55..b44e09e 100644 --- a/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/client/ZooKeeperClientModule.java +++ b/commons/src/main/java/org/apache/aurora/common/zookeeper/guice/client/ZooKeeperClientModule.java @@ -126,23 +126,6 @@ public class ZooKeeperClientModule extends PrivateModule { * * @param servers ZooKeeper server addresses. * @param inProcess Whether to run and create clients for an in-process ZooKeeper server. - * @param sessionTimeout Timeout duration for established sessions. - * @param credentials ZooKeeper authentication credentials. - */ - public ClientConfig( - Iterable<InetSocketAddress> servers, - boolean inProcess, - Amount<Integer, Time> sessionTimeout, - Credentials credentials) { - - this(servers, Optional.<String>absent(), inProcess, sessionTimeout, credentials); - } - - /** - * Creates a new client configuration. - * - * @param servers ZooKeeper server addresses. - * @param inProcess Whether to run and create clients for an in-process ZooKeeper server. * @param chrootPath an optional chroot path * @param sessionTimeout Timeout duration for established sessions. * @param credentials ZooKeeper authentication credentials. @@ -178,17 +161,6 @@ public class ZooKeeperClientModule extends PrivateModule { /** * Creates a new configuration identical to this configuration, but with the provided - * session timeout. - * - * @param sessionTimeout Timeout duration for established sessions. - * @return A modified clone of this configuration. - */ - public ClientConfig withSessionTimeout(Amount<Integer, Time> sessionTimeout) { - return new ClientConfig(servers, chrootPath, inProcess, sessionTimeout, credentials); - } - - /** - * Creates a new configuration identical to this configuration, but with the provided * credentials. * * @param credentials ZooKeeper authentication credentials. @@ -197,39 +169,5 @@ public class ZooKeeperClientModule extends PrivateModule { public ClientConfig withCredentials(Credentials credentials) { return new ClientConfig(servers, chrootPath, inProcess, sessionTimeout, credentials); } - - /** - * Convenience method for calling {@link #withCredentials(Credentials)} with digest credentials. - * - * @param username Digest authentication user. - * @param password Digest authentication raw password. - * @return A modified clone of this configuration. - */ - public ClientConfig withDigestCredentials(String username, String password) { - return withCredentials(ZooKeeperClient.digestCredentials(username, password)); - } - - /** - * Creates a new configuration identical to this configuration, but with the provided - * in-process setting. - * - * @param inProcess If {@code true}, an in-process ZooKeeper server server will be used, - * and all clients will connect to it. - * @return A modified clone of this configuration. - */ - public ClientConfig inProcess(boolean inProcess) { - return new ClientConfig(servers, chrootPath, inProcess, sessionTimeout, credentials); - } - - /** - * Creates a new configuration identical to this configuration, but with the provided - * chroot path setting. - * - * @param chrootPath a valid ZooKeeper path used as a chroot for ZooKeeper connections. - * @return A modified clone of this configuration. - */ - public ClientConfig withChrootPath(String chrootPath) { - return new ClientConfig(servers, Optional.of(chrootPath), inProcess, sessionTimeout, credentials); - } } } http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/application/modules/LifecycleModuleTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/application/modules/LifecycleModuleTest.java b/commons/src/test/java/org/apache/aurora/common/application/modules/LifecycleModuleTest.java index fdbef6f..940607e 100644 --- a/commons/src/test/java/org/apache/aurora/common/application/modules/LifecycleModuleTest.java +++ b/commons/src/test/java/org/apache/aurora/common/application/modules/LifecycleModuleTest.java @@ -68,7 +68,7 @@ public class LifecycleModuleTest extends EasyMockTest { final ServiceRunner runner = createMock(ServiceRunner.class); Command shutdown = createMock(Command.class); - expect(runner.launch()).andReturn(LocalService.primaryService(100, shutdown)); + expect(runner.launch()).andReturn(LocalService.auxiliaryService("a", 100, shutdown)); shutdown.execute(); Module testModule = new AbstractModule() { @@ -82,7 +82,8 @@ public class LifecycleModuleTest extends EasyMockTest { control.replay(); - assertEquals(Optional.of(getLocalAddress(100)), registry.getPrimarySocket()); + assertEquals(Optional.<InetSocketAddress>absent(), registry.getPrimarySocket()); + assertEquals(ImmutableMap.of("a", getLocalAddress(100)), registry.getAuxiliarySockets()); injector.getInstance(ShutdownRegistry.ShutdownRegistryImpl.class).execute(); } http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/application/modules/LocalServiceRegistryTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/application/modules/LocalServiceRegistryTest.java b/commons/src/test/java/org/apache/aurora/common/application/modules/LocalServiceRegistryTest.java index a9fe793..7f679cb 100644 --- a/commons/src/test/java/org/apache/aurora/common/application/modules/LocalServiceRegistryTest.java +++ b/commons/src/test/java/org/apache/aurora/common/application/modules/LocalServiceRegistryTest.java @@ -72,19 +72,13 @@ public class LocalServiceRegistryTest extends EasyMockTest { @Test public void testCreate() throws LaunchException { - expect(serviceProvider.get()).andReturn(ImmutableSet.of(runner1, runner2)); - expect(runner1.launch()).andReturn(primary(1)); - expect(runner2.launch()).andReturn(auxiliary(A, 2)); + expect(serviceProvider.get()).andReturn(ImmutableSet.of(runner1)); + expect(runner1.launch()).andReturn(auxiliary(A, 2)); shutdownRegistry.addAction(Commands.NOOP); - expectLastCall().times(2); control.replay(); - checkPorts(Optional.of(1), ImmutableMap.of(A, 2)); - } - - private LocalService primary(int port) { - return LocalService.primaryService(port, Commands.NOOP); + checkPorts(ImmutableMap.of(A, 2)); } private LocalService auxiliary(String name, int port) { @@ -108,19 +102,6 @@ public class LocalServiceRegistryTest extends EasyMockTest { } @Test(expected = IllegalArgumentException.class) - public void testMultiplePrimaries() throws LaunchException { - expect(serviceProvider.get()).andReturn(ImmutableSet.of(runner1, runner2)); - expect(runner1.launch()).andReturn(primary(1)); - expect(runner2.launch()).andReturn(primary(2)); - shutdownRegistry.addAction(Commands.NOOP); - expectLastCall().times(2); - - control.replay(); - - registry.getPrimarySocket(); - } - - @Test(expected = IllegalArgumentException.class) public void testDuplicateName() throws LaunchException { expect(serviceProvider.get()).andReturn(ImmutableSet.of(runner1, runner2)); expect(runner1.launch()).andReturn(auxiliary(A, 1)); @@ -143,7 +124,7 @@ public class LocalServiceRegistryTest extends EasyMockTest { control.replay(); - checkPorts(Optional.<Integer>absent(), ImmutableMap.of(A, 2, B, 2)); + checkPorts(ImmutableMap.of(A, 2, B, 2)); } @Test @@ -156,15 +137,11 @@ public class LocalServiceRegistryTest extends EasyMockTest { control.replay(); - checkPorts(Optional.<Integer>absent(), ImmutableMap.of(A, 2, B, 6, C, 6)); + checkPorts(ImmutableMap.of(A, 2, B, 6, C, 6)); } - private void checkPorts(Optional<Integer> primary, Map<String, Integer> expected) { - Optional<InetSocketAddress> registeredSocket = registry.getPrimarySocket(); - Optional<Integer> registeredPort = registeredSocket.isPresent() - ? Optional.of(registeredSocket.get().getPort()) : Optional.<Integer>absent(); - - assertEquals(primary, registeredPort); + private void checkPorts(Map<String, Integer> expected) { + assertEquals(Optional.<InetSocketAddress>absent(), registry.getPrimarySocket()); assertEquals(expected, Maps.transformValues(registry.getAuxiliarySockets(), INET_TO_PORT)); } } http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/base/ClosuresTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/base/ClosuresTest.java b/commons/src/test/java/org/apache/aurora/common/base/ClosuresTest.java index d2c9565..574ab40 100644 --- a/commons/src/test/java/org/apache/aurora/common/base/ClosuresTest.java +++ b/commons/src/test/java/org/apache/aurora/common/base/ClosuresTest.java @@ -15,17 +15,14 @@ package org.apache.aurora.common.base; import java.io.IOException; -import com.google.common.base.Function; import com.google.common.base.Predicate; - -import org.easymock.EasyMock; -import org.junit.Test; +import com.google.common.collect.ImmutableList; import org.apache.aurora.common.testing.easymock.EasyMockTest; +import org.junit.Test; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; -import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** @@ -37,64 +34,15 @@ public class ClosuresTest extends EasyMockTest { private static final Clazz<ExceptionalClosure<Integer, IOException>> EXC_INT_CLOSURE_CLZ = new Clazz<ExceptionalClosure<Integer, IOException>>() { }; - @Test(expected = NullPointerException.class) - public void testPreconditions() { - control.replay(); - - Closures.asFunction(null); - } - - @Test - public void testApply() throws IOException { - ExceptionalClosure<Integer, IOException> work = createMock(EXC_INT_CLOSURE_CLZ); - work.execute(1); - control.replay(); - - Function<Integer, Void> workFunction = Closures.asFunction(work); - workFunction.apply(1); - } - static class Thrown extends RuntimeException { } @Test - public void testApplyThrows() throws IOException { - ExceptionalClosure<Integer, IOException> work = createMock(EXC_INT_CLOSURE_CLZ); - work.execute(1); - RuntimeException runtimeException = new Thrown(); - EasyMock.expectLastCall().andThrow(runtimeException); - control.replay(); - - Function<Integer, Void> workFunction = Closures.asFunction(work); - try { - workFunction.apply(1); - } catch (Thrown e) { - assertSame(runtimeException, e); - } - } - - @Test - public void testApplyThrowsTransparent() throws IOException { - Closure<Integer> work = createMock(INT_CLOSURE_CLZ); - work.execute(1); - RuntimeException runtimeException = new Thrown(); - EasyMock.expectLastCall().andThrow(runtimeException); - control.replay(); - - Function<Integer, Void> workFunction = Closures.asFunction(work); - try { - workFunction.apply(1); - } catch (Thrown e) { - assertSame(runtimeException, e); - } - } - - @Test public void testCombine() { Closure<Integer> work1 = createMock(INT_CLOSURE_CLZ); Closure<Integer> work2 = createMock(INT_CLOSURE_CLZ); @SuppressWarnings("unchecked") // Needed because type information lost in vargs. - Closure<Integer> wrapper = Closures.combine(work1, work2); + Closure<Integer> wrapper = Closures.combine(ImmutableList.of(work1, work2)); work1.execute(1); work2.execute(1); @@ -115,7 +63,7 @@ public class ClosuresTest extends EasyMockTest { Closure<Integer> work3 = createMock(INT_CLOSURE_CLZ); @SuppressWarnings("unchecked") // Needed because type information lost in vargs. - Closure<Integer> wrapper = Closures.combine(work1, work2, work3); + Closure<Integer> wrapper = Closures.combine(ImmutableList.of(work1, work2, work3)); work1.execute(1); expectLastCall().andThrow(new Thrown()); http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/base/CommandsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/base/CommandsTest.java b/commons/src/test/java/org/apache/aurora/common/base/CommandsTest.java deleted file mode 100644 index 0a9bad9..0000000 --- a/commons/src/test/java/org/apache/aurora/common/base/CommandsTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Licensed 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.aurora.common.base; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; - -import org.apache.aurora.common.testing.easymock.EasyMockTest; - -import static org.easymock.EasyMock.expectLastCall; -import static org.junit.Assert.assertNull; - -public class CommandsTest extends EasyMockTest { - private Command c1; - private Command c2; - private Command c3; - - @Before - public void mySetup() { - c1 = createMock(new Clazz<Command>() { }); - c2 = createMock(new Clazz<Command>() { }); - c3 = createMock(new Clazz<Command>() { }); - } - - @Test - public void testAsSupplier() { - c1.execute(); - - control.replay(); - - assertNull(Commands.asSupplier(c1).get()); - } - - @Test(expected = NullPointerException.class) - public void testAsSupplierPreconditions() { - control.replay(); - - Commands.asSupplier(null); - } - - @Test - public void testCompoundCommand() { - c1.execute(); - c2.execute(); - c3.execute(); - - control.replay(); - - Commands.compound(Arrays.asList(c1, c2, c3)).execute(); - } - - @Test(expected = NullPointerException.class) - public void testCompoundCommandPreconditions() { - control.replay(); - - Commands.compound(Arrays.asList(c1, null, c2)); - } - - @Test(expected = RuntimeException.class) - public void testRuntimeException() { - Command badCommand = createMock(new Clazz<Command>() { }); - - c1.execute(); - badCommand.execute(); - expectLastCall().andThrow(new RuntimeException("Cannot Run")); - - control.replay(); - - Commands.compound(Arrays.asList(c1, badCommand, c2)).execute(); - } -} http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/collections/Iterables2Test.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/collections/Iterables2Test.java b/commons/src/test/java/org/apache/aurora/common/collections/Iterables2Test.java index e74038d..5b832cd 100644 --- a/commons/src/test/java/org/apache/aurora/common/collections/Iterables2Test.java +++ b/commons/src/test/java/org/apache/aurora/common/collections/Iterables2Test.java @@ -13,7 +13,6 @@ */ package org.apache.aurora.common.collections; -import java.util.Arrays; import java.util.List; import com.google.common.base.Predicate; @@ -65,17 +64,6 @@ public class Iterables2Test { @Test @SuppressWarnings("unchecked") // Needed because type information lost in vargs. - public void testZipEmptyIterable() { - assertValues(Iterables2.zip(10, list(1, 2, 3, 4), Arrays.<Integer>asList()), - list(1, 10), - list(2, 10), - list(3, 10), - list(4, 10) - ); - } - - @Test - @SuppressWarnings("unchecked") // Needed because type information lost in vargs. public void testZipRemove() { final int DEFAULT = 10; Iterable<List<Integer>> meta = Iterables2.zip(DEFAULT, http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/inject/BindingsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/inject/BindingsTest.java b/commons/src/test/java/org/apache/aurora/common/inject/BindingsTest.java index a84de3e..348d6f1 100644 --- a/commons/src/test/java/org/apache/aurora/common/inject/BindingsTest.java +++ b/commons/src/test/java/org/apache/aurora/common/inject/BindingsTest.java @@ -25,8 +25,6 @@ import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; -import com.google.inject.name.Named; -import com.google.inject.name.Names; import org.junit.Assert; import org.junit.Test; @@ -40,7 +38,6 @@ import static org.junit.Assert.fail; public class BindingsTest { - private static final Named NAME_KEY = Names.named("fred"); private static final TypeLiteral<List<String>> STRING_LIST = new TypeLiteral<List<String>>() { }; @Retention(RUNTIME) @@ -53,7 +50,6 @@ public class BindingsTest { @Test public void testCheckBindingAnnotation() { - Bindings.checkBindingAnnotation(NAME_KEY); Bindings.checkBindingAnnotation(BindKey.class); try { @@ -64,13 +60,6 @@ public class BindingsTest { } try { - Bindings.checkBindingAnnotation((Annotation) null); - fail(); - } catch (NullPointerException e) { - // expected - } - - try { Bindings.checkBindingAnnotation(BindingAnnotation.class); fail(); } catch (IllegalArgumentException e) { @@ -89,20 +78,6 @@ public class BindingsTest { } @Test - public void testAnnotationKeyFactory() { - Bindings.KeyFactory factory = Bindings.annotatedKeyFactory(NAME_KEY); - assertEquals(Key.get(String.class, NAME_KEY), factory.create(String.class)); - assertEquals(Key.get(STRING_LIST, NAME_KEY), factory.create(STRING_LIST)); - } - - @Test - public void testAnnotationKeyFactoryJsr330() { - Bindings.KeyFactory factory = Bindings.annotatedKeyFactory(NAME_KEY); - assertEquals(Key.get(String.class, NAME_KEY), factory.create(String.class)); - assertEquals(Key.get(STRING_LIST, NAME_KEY), factory.create(STRING_LIST)); - } - - @Test public void testAnnotationTypeKeyFactory() { Bindings.KeyFactory factory = Bindings.annotatedKeyFactory(QualifierKey.class); assertEquals(Key.get(String.class, QualifierKey.class), factory.create(String.class)); @@ -110,18 +85,6 @@ public class BindingsTest { } @Test - public void testRebinder() { - Injector injector = Guice.createInjector(new AbstractModule() { - @Override protected void configure() { - Key<Integer> fromKey = Key.get(Integer.class, NAME_KEY); - bind(fromKey).toInstance(42); - Bindings.rebinder(binder(), BindKey.class).rebind(fromKey); - } - }); - assertEquals(42, injector.getInstance(Key.get(Integer.class, BindKey.class)).intValue()); - } - - @Test public void testExposing() { Injector injector = Guice.createInjector(Bindings.exposing(Key.get(String.class), http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/io/CodecTestUtilities.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/io/CodecTestUtilities.java b/commons/src/test/java/org/apache/aurora/common/io/CodecTestUtilities.java deleted file mode 100644 index 4cfd4c9..0000000 --- a/commons/src/test/java/org/apache/aurora/common/io/CodecTestUtilities.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed 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.aurora.common.io; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -class CodecTestUtilities { - static <T> byte[] serialize(Codec<T> codec, T item) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - codec.serialize(item, out); - return out.toByteArray(); - } - - static <T> T deserialize(Codec<T> codec, byte[] serialized) throws IOException { - return codec.deserialize(new ByteArrayInputStream(serialized)); - } - - static <T> T roundTrip(Codec<T> codec, T item) throws IOException { - return deserialize(codec, serialize(codec, item)); - } -} http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/io/CompatibilityCodecTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/io/CompatibilityCodecTest.java b/commons/src/test/java/org/apache/aurora/common/io/CompatibilityCodecTest.java deleted file mode 100644 index 4c1b537..0000000 --- a/commons/src/test/java/org/apache/aurora/common/io/CompatibilityCodecTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Licensed 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.aurora.common.io; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; - -import com.google.common.base.Predicate; - -import org.junit.Test; - -import static org.apache.aurora.common.io.CodecTestUtilities.deserialize; -import static org.apache.aurora.common.io.CodecTestUtilities.serialize; -import static org.junit.Assert.assertEquals; - -public class CompatibilityCodecTest { - private final Codec<TestClass> primaryCodec = new SimpleCodec('x'); - private final Codec<TestClass> secondaryCodec = new SimpleCodec('y'); - private final Codec<TestClass> compatibilityCodec = CompatibilityCodec.create(primaryCodec, - secondaryCodec, 1, new Predicate<byte[]>() { - @Override - public boolean apply(byte[] input) { - return input.length > 0 && input[0] == 'x'; - } - }); - private final TestClass t = new TestClass(); - { - t.data = "foo"; - } - - @Test - public void testCompatibilityDeserializesSecondary() throws IOException { - assertCanDeserialize(compatibilityCodec, secondaryCodec); - } - - @Test - public void testCompatibilityDeserializesPrimary() throws IOException { - assertCanDeserialize(compatibilityCodec, primaryCodec); - } - - @Test - public void testCompatibilitySerializesPrimary() throws IOException { - assertCanDeserialize(primaryCodec, compatibilityCodec); - } - - @Test(expected = IOException.class) - public void testCompatibilityDoesNotSerializeSecondary() throws IOException { - assertCanDeserialize(secondaryCodec, compatibilityCodec); - } - - private void assertCanDeserialize(Codec<TestClass> reader, Codec<TestClass> writer) - throws IOException { - assertEquals("foo", deserialize(reader, serialize(writer, t)).data); - } - - public static class TestClass implements Serializable { - public String data; - } - - private static class SimpleCodec implements Codec<TestClass> { - - private final byte firstByte; - - SimpleCodec(char firstByte) { - this.firstByte = (byte) firstByte; - } - - @Override - public TestClass deserialize(InputStream source) throws IOException { - DataInputStream in = new DataInputStream(source); - if (in.readByte() != firstByte) { - throw new IOException("Corrupted stream"); - } - TestClass t = new TestClass(); - t.data = in.readUTF(); - return t; - } - - @Override - public void serialize(TestClass item, OutputStream sink) throws IOException { - DataOutputStream out = new DataOutputStream(sink); - out.writeByte(firstByte); - out.writeUTF(item.data); - } - } -} http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/io/ThriftCodecTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/io/ThriftCodecTest.java b/commons/src/test/java/org/apache/aurora/common/io/ThriftCodecTest.java deleted file mode 100644 index ce112dc..0000000 --- a/commons/src/test/java/org/apache/aurora/common/io/ThriftCodecTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Licensed 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.aurora.common.io; - -import static org.apache.aurora.common.io.CodecTestUtilities.roundTrip; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.TTransport; -import org.junit.Test; - -import com.google.common.base.Function; -import org.apache.aurora.common.thrift.testing.TestThriftTypes.Struct; - -/** - * @author John Sirois - */ -public class ThriftCodecTest { - - @Test - public void testRoundTripJSON() throws IOException { - testRoundTrip(ThriftCodec.JSON_PROTOCOL); - } - - @Test - public void testRoundTripBinary() throws IOException { - testRoundTrip(ThriftCodec.BINARY_PROTOCOL); - } - - @Test - public void testRoundTripCompact() throws IOException { - testRoundTrip(ThriftCodec.COMPACT_PROTOCOL); - } - - private void testRoundTrip(Function<TTransport, TProtocol> protocolFactory) throws IOException { - Codec<Struct> codec = ThriftCodec.create(Struct.class, protocolFactory); - Struct struct = roundTrip(codec, new Struct("jake", "jones")); - assertEquals("jake", struct.getName()); - assertEquals("jones", struct.getValue()); - } -} http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/stats/StatsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/stats/StatsTest.java b/commons/src/test/java/org/apache/aurora/common/stats/StatsTest.java index 7946a59..91bbc09 100644 --- a/commons/src/test/java/org/apache/aurora/common/stats/StatsTest.java +++ b/commons/src/test/java/org/apache/aurora/common/stats/StatsTest.java @@ -13,12 +13,10 @@ */ package org.apache.aurora.common.stats; -import org.junit.After; -import org.junit.Test; - import java.util.concurrent.atomic.AtomicLong; -import com.google.common.util.concurrent.AtomicDouble; +import org.junit.After; +import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; @@ -46,16 +44,6 @@ public class StatsTest { } @Test - public void testDoubleExport() { - AtomicDouble var = Stats.exportDouble("test_double"); - assertCounter("test_double", 0.0); - var.addAndGet(1.1); - assertCounter("test_double", 1.1); - var.addAndGet(5.55); - assertCounter("test_double", 6.65); - } - - @Test public void testNotSame() { AtomicLong firstExport = Stats.exportLong("somevar"); firstExport.incrementAndGet(); http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/util/BackoffDeciderTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/util/BackoffDeciderTest.java b/commons/src/test/java/org/apache/aurora/common/util/BackoffDeciderTest.java deleted file mode 100644 index 7831063..0000000 --- a/commons/src/test/java/org/apache/aurora/common/util/BackoffDeciderTest.java +++ /dev/null @@ -1,324 +0,0 @@ -/** - * Licensed 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.aurora.common.util; - -import com.google.common.collect.Sets; -import org.apache.aurora.common.quantity.Amount; -import org.apache.aurora.common.quantity.Time; -import org.apache.aurora.common.util.testing.FakeClock; -import org.easymock.IMocksControl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -import static org.easymock.EasyMock.createControl; -import static org.easymock.EasyMock.expect; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -/** - * @author William Farner - */ -public class BackoffDeciderTest { - private static final String NAME = "test_decider"; - - private IMocksControl control; - - private FakeClock clock; - private Random random; - - @Before - public void setUp() { - control = createControl(); - random = control.createMock(Random.class); - - clock = new FakeClock(); - } - - private BackoffDecider.Builder builder(String name) { - return new BackoffDecider.Builder(name) - .withSeedSize(1) - .withRequestWindow(Amount.of(10L, Time.SECONDS)) - .withBucketCount(100) - .withClock(clock) - .withRandom(random); - } - - @After - public void verify() { - control.verify(); - } - - @Test - public void testAllSuccess() { - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - run(decider, 10, Result.SUCCESS, State.NORMAL); - } - - @Test - public void testAllFailures() { - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - run(decider, 10, Result.FAILURE, State.BACKOFF); - } - - @Test - public void testSingleFailure() { - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - run(decider, 10, Result.SUCCESS, State.NORMAL); - run(decider, 1, Result.FAILURE, State.NORMAL); - } - - @Test - public void testBelowThreshold() { - control.replay(); - - BackoffDecider decider = builder(NAME).withTolerateFailureRate(0.5).build(); - run(decider, 5, Result.SUCCESS, State.NORMAL); - run(decider, 5, Result.FAILURE, State.NORMAL); - } - - @Test - public void testAtThreshold() { - control.replay(); - - BackoffDecider decider = builder(NAME).withTolerateFailureRate(0.49).build(); - run(decider, 51, Result.SUCCESS, State.NORMAL); - run(decider, 49, Result.FAILURE, State.NORMAL); - } - - @Test - public void testAboveThreshold() { - control.replay(); - - BackoffDecider decider = builder(NAME).withTolerateFailureRate(0.49).build(); - run(decider, 51, Result.SUCCESS, State.NORMAL); - run(decider, 49, Result.FAILURE, State.NORMAL); - run(decider, 1, Result.FAILURE, State.BACKOFF); - } - - @Test - public void testRecoversFromBackoff() { - // Backoff for the single request during the recovery period. - expect(random.nextDouble()).andReturn(1d); - - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - decider.addFailure(); - assertThat(decider.shouldBackOff(), is(true)); - - // Enter recovery period. - clock.waitFor(101); - assertThat(decider.shouldBackOff(), is(true)); - - // Enter normal period. - clock.waitFor(101); - assertThat(decider.shouldBackOff(), is(false)); - } - - @Test - public void testLinearRecovery() { - for (int i = 0; i < 10; i++) { - expect(random.nextDouble()).andReturn(0.1 * i + 0.01); // Above threshold - back off. - expect(random.nextDouble()).andReturn(0.1 * i - 0.01); // Below threshold - allow request. - } - - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - decider.addFailure(); // Moves into backoff state. - assertThat(decider.shouldBackOff(), is(true)); - - // Enter recovery period. - clock.waitFor(101); - - // Step linearly through recovery period (100 ms). - for (int i = 0; i < 10; i++) { - clock.waitFor(10); - assertThat(decider.shouldBackOff(), is(true)); - assertThat(decider.shouldBackOff(), is(false)); - } - } - - @Test - public void testExponentialBackoff() { - // Don't back off during recovery period. - expect(random.nextDouble()).andReturn(0d).atLeastOnce(); - - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - List<Integer> backoffDurationsMs = Arrays.asList( - 100, 200, 400, 800, 1600, 3200, 6400, 10000, 10000); - - assertThat(decider.shouldBackOff(), is(false)); - - // normal -> backoff - decider.addFailure(); - assertThat(decider.shouldBackOff(), is(true)); - - for (int backoffDurationMs : backoffDurationsMs) { - assertThat(decider.shouldBackOff(), is(true)); - - // backoff -> recovery - clock.waitFor(backoffDurationMs + 1); - assertThat(decider.shouldBackOff(), is(false)); - - // recovery -> backoff - decider.addFailure(); - } - } - - @Test - public void testRequestsExpire() { - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - run(decider, 10, Result.SUCCESS, State.NORMAL); - run(decider, 10, Result.FAILURE, State.NORMAL); - assertThat(decider.shouldBackOff(), is(false)); - - // Depends on request window of 10 seconds, with 100 buckets. - clock.waitFor(10000); - run(decider, 1, Result.SUCCESS, State.NORMAL); - assertThat(decider.shouldBackOff(), is(false)); - assertThat(decider.requests.totalRequests, is(21L)); - assertThat(decider.requests.totalFailures, is(10L)); - - // Requests should have decayed out of the window. - clock.waitFor(101); - run(decider, 1, Result.SUCCESS, State.NORMAL); - assertThat(decider.shouldBackOff(), is(false)); - assertThat(decider.requests.totalRequests, is(2L)); - assertThat(decider.requests.totalFailures, is(0L)); - } - - @Test - public void testAllBackendsDontBackoff() { - // Back off for all requests during recovery period. - expect(random.nextDouble()).andReturn(1d); // decider2 in recovery. - expect(random.nextDouble()).andReturn(0d); // decider3 in recovery. - - control.replay(); - - Set<BackoffDecider> group = Sets.newHashSet(); - BackoffDecider decider1 = builder(NAME + 1).groupWith(group).build(); - BackoffDecider decider2 = builder(NAME + 2).groupWith(group).build(); - BackoffDecider decider3 = builder(NAME + 3).groupWith(group).build(); - - // Two of three backends start backing off. - decider1.addFailure(); - assertThat(decider1.shouldBackOff(), is(true)); - - decider2.addFailure(); - assertThat(decider2.shouldBackOff(), is(true)); - - // Since all but 1 backend is backing off, we switch out of backoff mode. - assertThat(decider3.shouldBackOff(), is(false)); - decider3.addFailure(); - assertThat(decider1.shouldBackOff(), is(false)); - assertThat(decider2.shouldBackOff(), is(false)); - assertThat(decider3.shouldBackOff(), is(false)); - - // Begin recovering one backend, others will return to recovery. - decider1.addSuccess(); - assertThat(decider1.shouldBackOff(), is(false)); // Still thinks others are backing off. - assertThat(decider2.shouldBackOff(), is(false)); // Realizes decider1 is up, moves to recovery. - assertThat(decider2.shouldBackOff(), is(true)); // In recovery. - assertThat(decider3.shouldBackOff(), is(false)); // Realizes 1 & 2 are up, moves to recovery. - assertThat(decider3.shouldBackOff(), is(false)); // In recovery. - } - - @Test - public void testOneBackendDoesntAffectOthers() { - control.replay(); - - Set<BackoffDecider> group = Sets.newHashSet(); - BackoffDecider decider1 = builder(NAME + 1).groupWith(group).build(); - BackoffDecider decider2 = builder(NAME + 2).groupWith(group).build(); - BackoffDecider decider3 = builder(NAME + 3).groupWith(group).build(); - - // One backend starts failing. - run(decider1, 10, Result.SUCCESS, State.NORMAL); - run(decider2, 10, Result.SUCCESS, State.NORMAL); - run(decider3, 10, Result.FAILURE, State.BACKOFF); - - // Other backends should remain normal. - run(decider1, 10, Result.SUCCESS, State.NORMAL); - run(decider2, 10, Result.SUCCESS, State.NORMAL); - } - - @Test - public void testPreventsBackoffFlapping() { - // Permit requests during the backoff period. - expect(random.nextDouble()).andReturn(0d).atLeastOnce(); - - control.replay(); - - BackoffDecider decider = builder(NAME).build(); - - // Simulate 20 threads being permitted to send a request. - for (int i = 0; i < 20; i++) assertThat(decider.shouldBackOff(), is(false)); - - // The first 4 threads succeed. - for (int i = 0; i < 4; i++) decider.addSuccess(); - assertThat(decider.shouldBackOff(), is(false)); - - // The next 6 fail, triggering backoff mode. - for (int i = 0; i < 6; i++) decider.addFailure(); - assertThat(decider.shouldBackOff(), is(true)); - - // The next 10 succeed, but we are already backing off...so we should not move out of backoff. - for (int i = 0; i < 10; i++) decider.addSuccess(); - assertThat(decider.shouldBackOff(), is(true)); - - // Attempt to push the decider into a higher backoff period. - for (int i = 0; i < 10; i++) decider.addFailure(); - - // Verify that the initial backoff period is in effect. - clock.waitFor(101); - assertThat(decider.shouldBackOff(), is(false)); - } - - private enum Result { - SUCCESS, FAILURE - } - - private enum State { - BACKOFF, NORMAL - } - - private void run(BackoffDecider decider, int numRequests, Result result, State state) { - for (int i = 0; i < numRequests; i++) { - if (result == Result.SUCCESS) { - decider.addSuccess(); - } else { - decider.addFailure(); - } - - boolean backingOff = state == State.BACKOFF; - assertThat(decider.shouldBackOff(), is(backingOff)); - } - } -} http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/util/StateMachineTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/util/StateMachineTest.java b/commons/src/test/java/org/apache/aurora/common/util/StateMachineTest.java index e10e019..9591e82 100644 --- a/commons/src/test/java/org/apache/aurora/common/util/StateMachineTest.java +++ b/commons/src/test/java/org/apache/aurora/common/util/StateMachineTest.java @@ -13,27 +13,15 @@ */ package org.apache.aurora.common.util; -import com.google.common.collect.ImmutableSet; - import org.apache.aurora.common.base.Closure; import org.apache.aurora.common.base.Closures; -import org.apache.aurora.common.base.Command; -import org.apache.aurora.common.base.Commands; -import org.apache.aurora.common.base.ExceptionalSupplier; -import org.apache.aurora.common.base.Supplier; import org.apache.aurora.common.testing.easymock.EasyMockTest; -import org.apache.aurora.common.util.StateMachine.Transition; import org.apache.aurora.common.util.StateMachine.Rule; - +import org.apache.aurora.common.util.StateMachine.Transition; import org.junit.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.LinkedBlockingQueue; - import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** @@ -198,120 +186,6 @@ public class StateMachineTest extends EasyMockTest { } @Test - public void testDoInStateMatches() { - control.replay(); - - StateMachine<String> stateMachine = StateMachine.<String>builder(NAME) - .initialState(A) - .addState(Rule.from(A).to(B)) - .build(); - - int amount = stateMachine.doInState(A, new Supplier<Integer>() { - @Override public Integer get() { - return 42; - } - }); - assertThat(amount, is(42)); - - stateMachine.transition(B); - - String name = stateMachine.doInState(B, new Supplier<String>() { - @Override public String get() { - return "jake"; - } - }); - assertThat(name, is("jake")); - } - - @Test - public void testDoInStateConcurrently() throws InterruptedException { - control.replay(); - - final StateMachine<String> stateMachine = StateMachine.<String>builder(NAME) - .initialState(A) - .addState(A, B) - .build(); - - final BlockingQueue<Integer> results = new LinkedBlockingQueue<Integer>(); - - final CountDownLatch supplier1Proceed = new CountDownLatch(1); - final ExceptionalSupplier<Void, RuntimeException> supplier1 = - Commands.asSupplier(new Command() { - @Override public void execute() { - results.offer(1); - try { - supplier1Proceed.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - }); - - final CountDownLatch supplier2Proceed = new CountDownLatch(1); - final ExceptionalSupplier<Void, RuntimeException> supplier2 = - Commands.asSupplier(new Command() { - @Override public void execute() { - results.offer(2); - try { - supplier2Proceed.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - }); - - Thread thread1 = new Thread(new Runnable() { - @Override public void run() { - stateMachine.doInState(A, supplier1); - } - }); - - Thread thread2 = new Thread(new Runnable() { - @Override public void run() { - stateMachine.doInState(A, supplier2); - } - }); - - Thread thread3 = new Thread(new Runnable() { - @Override public void run() { - stateMachine.transition(B); - } - }); - - thread1.start(); - thread2.start(); - - Integer result1 = results.take(); - Integer result2 = results.take(); - // we know 1 and 2 have the read lock held - - thread3.start(); // should be blocked by read locks in place - - assertThat(ImmutableSet.of(result1, result2), is(ImmutableSet.of(1, 2))); - assertTrue(results.isEmpty()); - - supplier1Proceed.countDown(); - supplier2Proceed.countDown(); - - thread1.join(); - thread2.join(); - thread3.join(); - - assertThat(B, is(stateMachine.getState())); - } - - @Test(expected = IllegalStateException.class) - public void testDoInStateFails() { - control.replay(); - - StateMachine.<String>builder(NAME) - .initialState(A) - .addState(A, B) - .build() - .doInState(B, Commands.asSupplier(Commands.NOOP)); - } - - @Test public void testNoThrowOnInvalidTransition() { control.replay(); @@ -334,21 +208,21 @@ public class StateMachineTest extends EasyMockTest { Closure<Transition<String>> fromA = createMock(TRANSITION_CLOSURE_CLZ); Closure<Transition<String>> fromB = createMock(TRANSITION_CLOSURE_CLZ); - Transition<String> aToB = new Transition<String>(A, B, true); + Transition<String> aToB = new Transition<>(A, B, true); anyTransition.execute(aToB); fromA.execute(aToB); - Transition<String> bToB = new Transition<String>(B, B, false); + Transition<String> bToB = new Transition<>(B, B, false); anyTransition.execute(bToB); fromB.execute(bToB); - Transition<String> bToC = new Transition<String>(B, C, true); + Transition<String> bToC = new Transition<>(B, C, true); anyTransition.execute(bToC); fromB.execute(bToC); - anyTransition.execute(new Transition<String>(C, B, true)); + anyTransition.execute(new Transition<>(C, B, true)); - Transition<String> bToD = new Transition<String>(B, D, true); + Transition<String> bToD = new Transition<>(B, D, true); anyTransition.execute(bToD); fromB.execute(bToD); @@ -376,7 +250,7 @@ public class StateMachineTest extends EasyMockTest { Closure<Transition<String>> aToBHandler = createMock(TRANSITION_CLOSURE_CLZ); Closure<Transition<String>> impossibleHandler = createMock(TRANSITION_CLOSURE_CLZ); - aToBHandler.execute(new Transition<String>(A, B, true)); + aToBHandler.execute(new Transition<>(A, B, true)); control.replay(); http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/zookeeper/CandidateImplTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/zookeeper/CandidateImplTest.java b/commons/src/test/java/org/apache/aurora/common/zookeeper/CandidateImplTest.java index cf7e5a3..0763521 100644 --- a/commons/src/test/java/org/apache/aurora/common/zookeeper/CandidateImplTest.java +++ b/commons/src/test/java/org/apache/aurora/common/zookeeper/CandidateImplTest.java @@ -18,23 +18,18 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; -import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.Ordering; +import org.apache.aurora.common.base.ExceptionalCommand; +import org.apache.aurora.common.quantity.Amount; +import org.apache.aurora.common.quantity.Time; import org.apache.aurora.common.zookeeper.testing.BaseZooKeeperTest; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.junit.Before; import org.junit.Test; -import org.apache.aurora.common.base.ExceptionalCommand; -import org.apache.aurora.common.quantity.Amount; -import org.apache.aurora.common.quantity.Time; - -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -48,7 +43,7 @@ public class CandidateImplTest extends BaseZooKeeperTest { @Before public void mySetUp() throws IOException { - candidateBuffer = new LinkedBlockingDeque<CandidateImpl>(); + candidateBuffer = new LinkedBlockingDeque<>(); } private Group createGroup(ZooKeeperClient zkClient) throws IOException { @@ -157,62 +152,6 @@ public class CandidateImplTest extends BaseZooKeeperTest { } @Test - public void testCustomJudge() throws Exception { - Function<Iterable<String>, String> judge = new Function<Iterable<String>, String>() { - @Override public String apply(Iterable<String> input) { - return Ordering.natural().max(input); - } - }; - - ZooKeeperClient zkClient1 = createZkClient(TIMEOUT); - Group group1 = createGroup(zkClient1); - final CandidateImpl candidate1 = - new CandidateImpl(group1, judge, Suppliers.ofInstance("Leader1".getBytes())) { - @Override public String toString() { - return "Leader1"; - } - }; - ZooKeeperClient zkClient2 = createZkClient(TIMEOUT); - Group group2 = createGroup(zkClient2); - final CandidateImpl candidate2 = - new CandidateImpl(group2, judge, Suppliers.ofInstance("Leader2".getBytes())) { - @Override public String toString() { - return "Leader2"; - } - }; - - Reign candidate1Reign = new Reign("1", candidate1); - Reign candidate2Reign = new Reign("2", candidate2); - - candidate1.offerLeadership(candidate1Reign); - assertSame(candidate1, candidateBuffer.takeLast()); - - Supplier<Boolean> candidate2Leader = candidate2.offerLeadership(candidate2Reign); - assertSame(candidate2, candidateBuffer.takeLast()); - candidate1Reign.expectDefeated(); - assertTrue("Since the judge picks the newest member joining a group as leader candidate 1 " - + "should be defeated and candidate 2 leader", candidate2Leader.get()); - } - - @Test - public void testCustomDataSupplier() throws Exception { - byte[] DATA = "Leader1".getBytes(); - ZooKeeperClient zkClient1 = createZkClient(TIMEOUT); - Group group1 = createGroup(zkClient1); - CandidateImpl candidate1 = new CandidateImpl(group1, Suppliers.ofInstance(DATA)) { - @Override public String toString() { - return "Leader1"; - } - }; - Reign candidate1Reign = new Reign("1", candidate1); - - Supplier<Boolean> candidate1Leader = candidate1.offerLeadership(candidate1Reign); - assertSame(candidate1, candidateBuffer.takeLast()); - assertTrue(candidate1Leader.get()); - assertArrayEquals(DATA, candidate1.getLeaderData().get()); - } - - @Test public void testEmptyMembership() throws Exception { ZooKeeperClient zkClient1 = createZkClient(TIMEOUT); final CandidateImpl candidate1 = new CandidateImpl(createGroup(zkClient1)); http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetImplTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetImplTest.java b/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetImplTest.java index 4db578c..5eb18e3 100644 --- a/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetImplTest.java +++ b/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetImplTest.java @@ -211,7 +211,7 @@ public class ServerSetImplTest extends BaseZooKeeperTest { @Test public void testJsonCodecRoundtrip() throws Exception { - Codec<ServiceInstance> codec = ServerSetImpl.createJsonCodec(); + Codec<ServiceInstance> codec = ServerSetImpl.createCodec(); ServiceInstance instance1 = new ServiceInstance( new Endpoint("foo", 1000), ImmutableMap.of("http", new Endpoint("foo", 8080)), @@ -246,10 +246,7 @@ public class ServerSetImplTest extends BaseZooKeeperTest { Status.ALIVE).setShard(42); ByteArrayOutputStream results = new ByteArrayOutputStream(); - ServerSetImpl.createJsonCodec().serialize(instance, results); - - results = new ByteArrayOutputStream(); - ServerSetImpl.createJsonCodec().serialize(instance, results); + ServerSetImpl.createCodec().serialize(instance, results); assertEquals( "{\"serviceEndpoint\":{\"host\":\"foo\",\"port\":1000}," + "\"additionalEndpoints\":{\"http\":{\"host\":\"foo\",\"port\":8080}}," http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetsTest.java b/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetsTest.java index e13b688..d3cca3f 100644 --- a/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetsTest.java +++ b/commons/src/test/java/org/apache/aurora/common/zookeeper/ServerSetsTest.java @@ -34,7 +34,7 @@ public class ServerSetsTest { Map<String, Endpoint > additionalEndpoints = ImmutableMap.of(); Status status = Status.ALIVE; - Codec<ServiceInstance> codec = ServerSetImpl.createDefaultCodec(); + Codec<ServiceInstance> codec = ServerSetImpl.createCodec(); byte[] data = ServerSets.serializeServiceInstance( endpoint, additionalEndpoints, status, codec); http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/zookeeper/SingletonServiceTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/zookeeper/SingletonServiceTest.java b/commons/src/test/java/org/apache/aurora/common/zookeeper/SingletonServiceTest.java index 7f537ec..2e9e246 100644 --- a/commons/src/test/java/org/apache/aurora/common/zookeeper/SingletonServiceTest.java +++ b/commons/src/test/java/org/apache/aurora/common/zookeeper/SingletonServiceTest.java @@ -17,38 +17,27 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; -import java.util.concurrent.CountDownLatch; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.testing.TearDown; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.Watcher.Event.EventType; -import org.apache.zookeeper.Watcher.Event.KeeperState; -import org.easymock.Capture; -import org.easymock.EasyMock; -import org.easymock.IAnswer; -import org.easymock.IExpectationSetters; -import org.easymock.IMocksControl; -import org.junit.Before; -import org.junit.Test; - import org.apache.aurora.common.base.ExceptionalCommand; import org.apache.aurora.common.zookeeper.Candidate.Leader; import org.apache.aurora.common.zookeeper.Group.JoinException; -import org.apache.aurora.common.zookeeper.SingletonService.DefeatOnDisconnectLeader; import org.apache.aurora.common.zookeeper.SingletonService.LeaderControl; import org.apache.aurora.common.zookeeper.SingletonService.LeadershipListener; import org.apache.aurora.common.zookeeper.testing.BaseZooKeeperTest; +import org.easymock.Capture; +import org.easymock.IExpectationSetters; +import org.easymock.IMocksControl; +import org.junit.Before; +import org.junit.Test; import static org.apache.aurora.common.testing.easymock.EasyMockTest.createCapture; import static org.easymock.EasyMock.capture; import static org.easymock.EasyMock.createControl; import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.fail; public class SingletonServiceTest extends BaseZooKeeperTest { @@ -257,92 +246,4 @@ public class SingletonServiceTest extends BaseZooKeeperTest { control.replay(); shutdownNetwork(); } - - private static IAnswer<?> countDownAnswer(final CountDownLatch latch) { - return new IAnswer<Void>() { - @Override public Void answer() { - latch.countDown(); - return null; - } - }; - } - - @Test - public void testLeaderDisconnect() throws Exception { - Capture<LeaderControl> controlCapture = createCapture(); - - CountDownLatch leading = new CountDownLatch(1); - listener.onLeading(capture(controlCapture)); - expectLastCall().andAnswer(countDownAnswer(leading)); - - CountDownLatch defeated = new CountDownLatch(1); - listener.onDefeated(null); - expectLastCall().andAnswer(countDownAnswer(defeated)); - - control.replay(); - - ZooKeeperClient zkClient = createZkClient(); - serverSet = new ServerSetImpl(zkClient, "/fake/path"); - candidate = new CandidateImpl( - new Group(zkClient, ZooKeeperUtils.OPEN_ACL_UNSAFE, "/fake/path")); - DefeatOnDisconnectLeader leader = new DefeatOnDisconnectLeader(zkClient, listener); - service = new SingletonService(serverSet, candidate); - service.lead(InetSocketAddress.createUnresolved("foo", PORT_A), - ImmutableMap.of("http-admin", InetSocketAddress.createUnresolved("foo", PORT_B)), - leader); - - leading.await(); - - shutdownNetwork(); - defeated.await(); - } - - @Test - public void testNonLeaderDisconnect() throws Exception { - CountDownLatch elected = new CountDownLatch(1); - listener.onLeading(EasyMock.<LeaderControl>anyObject()); - expectLastCall().andAnswer(countDownAnswer(elected)); - listener.onDefeated(null); - expectLastCall().anyTimes(); - - control.replay(); - - ZooKeeperClient zkClient = createZkClient(); - String path = "/fake/path"; - // Create a fake leading candidate node to ensure that the leader in this test is never - // elected. - ZooKeeperUtils.ensurePath(zkClient, ZooKeeperUtils.OPEN_ACL_UNSAFE, path); - String leaderNode = zkClient.get().create( - path + "/" + SingletonService.LEADER_ELECT_NODE_PREFIX, - "fake_leader".getBytes(), - ZooKeeperUtils.OPEN_ACL_UNSAFE, - CreateMode.PERSISTENT_SEQUENTIAL); - - serverSet = new ServerSetImpl(zkClient, path); - candidate = - SingletonService.createSingletonCandidate(zkClient, path, ZooKeeperUtils.OPEN_ACL_UNSAFE); - DefeatOnDisconnectLeader leader = new DefeatOnDisconnectLeader(zkClient, listener); - service = new SingletonService(serverSet, candidate); - service.lead(InetSocketAddress.createUnresolved("foo", PORT_A), - ImmutableMap.of("http-admin", InetSocketAddress.createUnresolved("foo", PORT_B)), - leader); - - final CountDownLatch disconnected = new CountDownLatch(1); - zkClient.register(new Watcher() { - @Override public void process(WatchedEvent event) { - if ((event.getType() == EventType.None) - && (event.getState() == KeeperState.Disconnected)) { - disconnected.countDown(); - } - } - }); - - shutdownNetwork(); - disconnected.await(); - - restartNetwork(); - zkClient.get().delete(leaderNode, ZooKeeperUtils.ANY_VERSION); - // Upon deletion of the fake leader node, the candidate should become leader. - elected.await(); - } } http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/commons/src/test/java/org/apache/aurora/common/zookeeper/guice/ServerSetModuleTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/org/apache/aurora/common/zookeeper/guice/ServerSetModuleTest.java b/commons/src/test/java/org/apache/aurora/common/zookeeper/guice/ServerSetModuleTest.java deleted file mode 100644 index a397dd9..0000000 --- a/commons/src/test/java/org/apache/aurora/common/zookeeper/guice/ServerSetModuleTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Licensed 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.aurora.common.zookeeper.guice; - -import java.util.Set; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.util.Providers; - -import org.apache.aurora.common.zookeeper.ServerSet; -import org.easymock.EasyMock; -import org.easymock.IMocksControl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.apache.aurora.common.application.ShutdownRegistry; -import org.apache.aurora.common.application.ShutdownRegistry.ShutdownRegistryImpl; -import org.apache.aurora.common.application.modules.LifecycleModule.ServiceRunner; -import org.apache.aurora.common.application.modules.LocalServiceRegistry; -import org.apache.aurora.common.zookeeper.ZooKeeperClient; -import org.apache.aurora.common.zookeeper.testing.BaseZooKeeperTest; - -public class ServerSetModuleTest extends BaseZooKeeperTest { - - private IMocksControl control; - - private ServerSet serverSet; - private ShutdownRegistry shutdownRegistry; - private ZooKeeperClient zooKeeperClient; - private LocalServiceRegistry localServiceRegistry; - - @Before - public void mySetUp() { - control = EasyMock.createControl(); - serverSet = control.createMock(ServerSet.class); - - shutdownRegistry = new ShutdownRegistryImpl(); - zooKeeperClient = createZkClient(); - Set<ServiceRunner> localServices = ImmutableSet.of(); - localServiceRegistry = new LocalServiceRegistry(Providers.of(localServices), shutdownRegistry); - } - - @After - public void verify() { - control.verify(); - } - - @Test - public void testInjection() { - control.replay(); - - Guice.createInjector(ImmutableList.of(ServerSetModule.builder().build(), new AbstractModule() { - @Override protected void configure() { - bind(ServerSet.class).toInstance(serverSet); - bind(ZooKeeperClient.class).toInstance(zooKeeperClient); - bind(ShutdownRegistry.class).toInstance(shutdownRegistry); - bind(LocalServiceRegistry.class).toInstance(localServiceRegistry); - } - })); - } -} http://git-wip-us.apache.org/repos/asf/aurora/blob/85f99544/src/jmh/java/org/apache/aurora/benchmark/fakes/FakeStatsProvider.java ---------------------------------------------------------------------- diff --git a/src/jmh/java/org/apache/aurora/benchmark/fakes/FakeStatsProvider.java b/src/jmh/java/org/apache/aurora/benchmark/fakes/FakeStatsProvider.java index 722531c..b1dfc01 100644 --- a/src/jmh/java/org/apache/aurora/benchmark/fakes/FakeStatsProvider.java +++ b/src/jmh/java/org/apache/aurora/benchmark/fakes/FakeStatsProvider.java @@ -53,21 +53,6 @@ public class FakeStatsProvider implements StatsProvider { public void requestComplete(long latencyMicros) { // no-op } - - @Override - public void incErrors() { - // no-op - } - - @Override - public void incReconnects() { - // no-op - } - - @Override - public void incTimeouts() { - // no-op - } }; } }
