Search in sources :

Example 6 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class ZooKeeperNode method init.

/**
   * Initialize zookeeper tracking for this {@link Supplier}.  Once this call returns, this object
   * will be tracking data in zookeeper.
   *
   * @throws InterruptedException if the underlying zookeeper server transaction is interrupted
   * @throws KeeperException if the server signals an error
   * @throws ZooKeeperConnectionException if there was a problem connecting to the zookeeper
   *     cluster
   */
@VisibleForTesting
void init() throws InterruptedException, KeeperException, ZooKeeperConnectionException {
    Watcher watcher = zkClient.registerExpirationHandler(new Command() {

        @Override
        public void execute() {
            try {
                synchronized (safeToRewatchLock) {
                    if (safeToRewatch) {
                        tryWatchDataNode();
                    }
                }
            } catch (InterruptedException e) {
                LOG.log(Level.WARNING, "Interrupted while trying to re-establish watch.", e);
                Thread.currentThread().interrupt();
            }
        }
    });
    try {
        /*
       * Synchronize to prevent the race of watchDataNode completing and then the session expiring
       * before we update safeToRewatch.
       */
        synchronized (safeToRewatchLock) {
            watchDataNode();
            safeToRewatch = true;
        }
    } catch (InterruptedException e) {
        zkClient.unregister(watcher);
        throw e;
    } catch (KeeperException e) {
        zkClient.unregister(watcher);
        throw e;
    } catch (ZooKeeperConnectionException e) {
        zkClient.unregister(watcher);
        throw e;
    }
}
Also used : Command(com.twitter.common.base.Command) Watcher(org.apache.zookeeper.Watcher) ZooKeeperConnectionException(com.twitter.common.zookeeper.ZooKeeperClient.ZooKeeperConnectionException) KeeperException(org.apache.zookeeper.KeeperException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 7 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class CandidateImpl method offerLeadership.

@Override
public Supplier<Boolean> offerLeadership(final Leader leader) throws JoinException, WatchException, InterruptedException {
    final Membership membership = group.join(dataSupplier, new Command() {

        @Override
        public void execute() {
            leader.onDefeated();
        }
    });
    final AtomicBoolean elected = new AtomicBoolean(false);
    final AtomicBoolean abdicated = new AtomicBoolean(false);
    group.watch(new GroupChangeListener() {

        @Override
        public void onGroupChange(Iterable<String> memberIds) {
            boolean noCandidates = Iterables.isEmpty(memberIds);
            String memberId = membership.getMemberId();
            if (noCandidates) {
                LOG.warning("All candidates have temporarily left the group: " + group);
            } else if (!Iterables.contains(memberIds, memberId)) {
                LOG.severe(String.format("Current member ID %s is not a candidate for leader, current voting: %s", memberId, memberIds));
            } else {
                boolean electedLeader = memberId.equals(getLeader(memberIds));
                boolean previouslyElected = elected.getAndSet(electedLeader);
                if (!previouslyElected && electedLeader) {
                    LOG.info(String.format("Candidate %s is now leader of group: %s", membership.getMemberPath(), memberIds));
                    leader.onElected(new ExceptionalCommand<JoinException>() {

                        @Override
                        public void execute() throws JoinException {
                            membership.cancel();
                            abdicated.set(true);
                        }
                    });
                } else if (!electedLeader) {
                    if (previouslyElected) {
                        leader.onDefeated();
                    }
                    LOG.info(String.format("Candidate %s waiting for the next leader election, current voting: %s", membership.getMemberPath(), memberIds));
                }
            }
        }
    });
    return new Supplier<Boolean>() {

        @Override
        public Boolean get() {
            return !abdicated.get() && elected.get();
        }
    };
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) JoinException(com.twitter.common.zookeeper.Group.JoinException) ExceptionalCommand(com.twitter.common.base.ExceptionalCommand) Command(com.twitter.common.base.Command) GroupChangeListener(com.twitter.common.zookeeper.Group.GroupChangeListener) Membership(com.twitter.common.zookeeper.Group.Membership) Supplier(com.google.common.base.Supplier)

Example 8 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class LifecycleModuleTest method testOrdering.

@Test
public void testOrdering() throws Exception {
    final ServiceRunner runner = createMock(ServiceRunner.class);
    Command shutdown = createMock(Command.class);
    expect(runner.launch()).andReturn(LocalService.primaryService(100, shutdown));
    shutdown.execute();
    Module testModule = new AbstractModule() {

        @Override
        protected void configure() {
            LifecycleModule.runnerBinder(binder()).addBinding().toInstance(runner);
        }
    };
    Injector injector = Guice.createInjector(new SystemModule(), testModule);
    LocalServiceRegistry registry = injector.getInstance(LocalServiceRegistry.class);
    control.replay();
    assertEquals(Optional.of(getLocalAddress(100)), registry.getPrimarySocket());
    injector.getInstance(ShutdownRegistryImpl.class).execute();
}
Also used : ServiceRunner(com.twitter.common.application.modules.LifecycleModule.ServiceRunner) Command(com.twitter.common.base.Command) ShutdownRegistryImpl(com.twitter.common.application.ShutdownRegistry.ShutdownRegistryImpl) Injector(com.google.inject.Injector) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule) EasyMockTest(com.twitter.common.testing.easymock.EasyMockTest) Test(org.junit.Test)

Example 9 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class ArgScannerTest method testEnforcesConstraints.

@Test
public void testEnforcesConstraints() {
    test(VerifyArgs.class, new Command() {

        @Override
        public void execute() {
            assertThat(VerifyArgs.STRING_VAL.get(), is("newstring"));
            assertThat(VerifyArgs.OPTIONAL_STRING_VAL.get(), nullValue(String.class));
        }
    }, "string", "newstring");
    testFails(VerifyArgs.class, "custom", "jane");
    testFails(VerifyArgs.class, "string", "");
    testFails(VerifyArgs.class, "optional_string", "");
    testFails(VerifyArgs.class, "int", "0");
    testFails(VerifyArgs.class, "long", "-1");
    test(VerifyArgs.class, new Command() {

        @Override
        public void execute() {
            assertThat(VerifyArgs.FLOAT_VAL.get(), is(10.5f));
        }
    }, "float", "10.5");
    testFails(VerifyArgs.class, "float", "9");
}
Also used : Command(com.twitter.common.base.Command) Test(org.junit.Test)

Example 10 with Command

use of com.twitter.common.base.Command in project commons by twitter.

the class ZooKeeperMapTest method testReadOnly.

@Test
public void testReadOnly() throws Exception {
    String parentPath = "/twitter/path";
    final String node = "node";
    String nodePath = parentPath + "/" + node;
    String data = "DaTa";
    ZooKeeperUtils.ensurePath(zkClient, ACL, parentPath);
    zkClient.get().create(nodePath, data.getBytes(), ACL, CreateMode.PERSISTENT);
    final Map<String, String> zkMap = ZooKeeperMap.create(zkClient, parentPath, BYTES_TO_STRING);
    checkUnsupported(new Command() {

        @Override
        public void execute() {
            zkMap.clear();
        }
    });
    checkUnsupported(new Command() {

        @Override
        public void execute() {
            zkMap.remove(node);
        }
    });
    checkUnsupported(new Command() {

        @Override
        public void execute() {
            zkMap.put("othernode", "othervalue");
        }
    });
    checkUnsupported(new Command() {

        @Override
        public void execute() {
            zkMap.putAll(ImmutableMap.of("othernode", "othervalue"));
        }
    });
    checkUnsupported(new Command() {

        @Override
        public void execute() {
            zkMap.keySet().iterator().remove();
        }
    });
    checkUnsupported(new Command() {

        @Override
        public void execute() {
            zkMap.values().iterator().remove();
        }
    });
    checkUnsupported(new Command() {

        @Override
        public void execute() {
            zkMap.entrySet().iterator().remove();
        }
    });
    // Ensure contents didn't change
    assertEquals(1, zkMap.size());
    assertEquals(data, zkMap.get(node));
}
Also used : Command(com.twitter.common.base.Command) Test(org.junit.Test) BaseZooKeeperTest(com.twitter.common.zookeeper.testing.BaseZooKeeperTest)

Aggregations

Command (com.twitter.common.base.Command)23 Test (org.junit.Test)15 EasyMockTest (com.twitter.common.testing.easymock.EasyMockTest)6 BaseZooKeeperTest (com.twitter.common.zookeeper.testing.BaseZooKeeperTest)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 Membership (com.twitter.common.zookeeper.Group.Membership)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)2 AbstractModule (com.google.inject.AbstractModule)2 Injector (com.google.inject.Injector)2 Module (com.google.inject.Module)2 ShutdownRegistryImpl (com.twitter.common.application.ShutdownRegistry.ShutdownRegistryImpl)2 ExceptionalCommand (com.twitter.common.base.ExceptionalCommand)2 ZooKeeperConnectionException (com.twitter.common.zookeeper.ZooKeeperClient.ZooKeeperConnectionException)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 KeeperException (org.apache.zookeeper.KeeperException)2 Watcher (org.apache.zookeeper.Watcher)2 Supplier (com.google.common.base.Supplier)1