Search in sources :

Example 1 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project coprhd-controller by CoprHD.

the class ZkConnection method build.

/**
 * Builds zk connector. Note that this method does not initiate a connection. {@link ZkConnection#connect()} must be called to connect
 * to cluster.
 * <p/>
 * This separation is provided so that callbacks can be setup separately prior to connection to cluster.
 */
public void build() {
    try {
        _zkConnection = CuratorFrameworkFactory.builder().connectString(_connectString).connectionTimeoutMs(DEFAULT_CONN_TIMEOUT).canBeReadOnly(true).sessionTimeoutMs(_timeoutMs).retryPolicy(new RetryUntilElapsed(_timeoutMs, RETRY_INTERVAL_MS)).build();
        _zkConnection.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() {

            @Override
            public void unhandledError(String message, Throwable e) {
                _logger.warn("Unknown exception in curator stack", e);
            }
        });
        _zkConnection.getConnectionStateListenable().addListener(new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                _logger.info("Current connection state {}", newState);
            }
        });
        if (FileUtils.exists(siteIdFile)) {
            siteId = new String(FileUtils.readDataFromFile(siteIdFile));
            siteId = siteId.trim();
            _logger.info("Current site id is {}", siteId);
        }
    } catch (Exception e) {
        throw CoordinatorException.fatals.failedToBuildZKConnector(e);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryUntilElapsed(org.apache.curator.retry.RetryUntilElapsed) UnhandledErrorListener(org.apache.curator.framework.api.UnhandledErrorListener) ConnectionState(org.apache.curator.framework.state.ConnectionState) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) IOException(java.io.IOException) CoordinatorException(com.emc.storageos.coordinator.exceptions.CoordinatorException)

Example 2 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project Saturn by vipshop.

the class ShardingListenerManager method start.

@Override
public void start() {
    if (necessaryWatcher != null) {
        executorService = Executors.newSingleThreadExecutor(new SaturnThreadFactory(executorName + "-" + jobName + "-registerNecessaryWatcher", false));
        shardingService.registerNecessaryWatcher(necessaryWatcher);
        connectionStateListener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED)) {
                    // maybe node data have changed, so doBusiness whatever, it's okay for MSG job
                    LOGGER.info("state change to {}, trigger doBusiness and register necessary watcher.", newState);
                    doBusiness();
                    registerNecessaryWatcher();
                }
            }
        };
        addConnectionStateListener(connectionStateListener);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ConnectionState(org.apache.curator.framework.state.ConnectionState) SaturnThreadFactory(com.vip.saturn.job.threads.SaturnThreadFactory) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener)

Example 3 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project incubator-gobblin by apache.

the class ZookeeperBasedJobLock method initializeCuratorFramework.

private static synchronized void initializeCuratorFramework(Properties properties) {
    if (curatorFrameworkShutdownHook == null) {
        curatorFrameworkShutdownHook = new CuratorFrameworkShutdownHook();
        Runtime.getRuntime().addShutdownHook(curatorFrameworkShutdownHook);
    }
    if (curatorFramework == null) {
        CuratorFramework newCuratorFramework = CuratorFrameworkFactory.builder().connectString(properties.getProperty(CONNECTION_STRING, CONNECTION_STRING_DEFAULT)).connectionTimeoutMs(getMilliseconds(properties, CONNECTION_TIMEOUT_SECONDS, CONNECTION_TIMEOUT_SECONDS_DEFAULT)).sessionTimeoutMs(getMilliseconds(properties, SESSION_TIMEOUT_SECONDS, SESSION_TIMEOUT_SECONDS_DEFAULT)).retryPolicy(new ExponentialBackoffRetry(getMilliseconds(properties, RETRY_BACKOFF_SECONDS, RETRY_BACKOFF_SECONDS_DEFAULT), getInt(properties, MAX_RETRY_COUNT, MAX_RETRY_COUNT_DEFAULT))).build();
        newCuratorFramework.getConnectionStateListenable().addListener(new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
                switch(connectionState) {
                    case LOST:
                        log.warn("Lost connection with zookeeper");
                        for (Map.Entry<String, JobLockEventListener> lockEventListener : lockEventListeners.entrySet()) {
                            log.warn("Informing job {} that lock was lost", lockEventListener.getKey());
                            lockEventListener.getValue().onLost();
                        }
                        break;
                    case SUSPENDED:
                        log.warn("Suspended connection with zookeeper");
                        for (Map.Entry<String, JobLockEventListener> lockEventListener : lockEventListeners.entrySet()) {
                            log.warn("Informing job {} that lock was suspended", lockEventListener.getKey());
                            lockEventListener.getValue().onLost();
                        }
                        break;
                    case CONNECTED:
                        log.info("Connected with zookeeper");
                        break;
                    case RECONNECTED:
                        log.warn("Regained connection with zookeeper");
                        break;
                    case READ_ONLY:
                        log.warn("Zookeeper connection went into read-only mode");
                        break;
                }
            }
        });
        newCuratorFramework.start();
        try {
            if (!newCuratorFramework.blockUntilConnected(getInt(properties, CONNECTION_TIMEOUT_SECONDS, CONNECTION_TIMEOUT_SECONDS_DEFAULT), TimeUnit.SECONDS)) {
                throw new RuntimeException("Time out while waiting to connect to zookeeper");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while waiting to connect to zookeeper");
        }
        curatorFramework = newCuratorFramework;
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) ConnectionState(org.apache.curator.framework.state.ConnectionState) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener)

Example 4 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project xian by happyyangyuan.

the class TestFramework method testConnectionState.

@Test
public void testConnectionState() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        final BlockingQueue<ConnectionState> queue = new LinkedBlockingQueue<ConnectionState>();
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                queue.add(newState);
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        client.start();
        Assert.assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.CONNECTED);
        server.stop();
        Assert.assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.SUSPENDED);
        Assert.assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.LOST);
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryOneTime(org.apache.curator.retry.RetryOneTime) Timing(org.apache.curator.test.Timing) ConnectionState(org.apache.curator.framework.state.ConnectionState) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) Test(org.testng.annotations.Test)

Example 5 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project xian by happyyangyuan.

the class TestFramework method testCreateACLWithReset.

@Test
public void testCreateACLWithReset() throws Exception {
    Timing timing = new Timing();
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).authorization("digest", "me:pass".getBytes()).retryPolicy(new RetryOneTime(1)).build();
    client.start();
    try {
        final CountDownLatch lostLatch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    lostLatch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS);
        List<ACL> aclList = Lists.newArrayList(acl);
        client.create().withACL(aclList).forPath("/test", "test".getBytes());
        server.stop();
        Assert.assertTrue(timing.awaitLatch(lostLatch));
        try {
            client.checkExists().forPath("/");
            Assert.fail("Connection should be down");
        } catch (KeeperException.ConnectionLossException e) {
        // expected
        }
        server.restart();
        try {
            client.setData().forPath("/test", "test".getBytes());
        } catch (KeeperException.NoAuthException e) {
            Assert.fail("Auth failed");
        }
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : RetryOneTime(org.apache.curator.retry.RetryOneTime) CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) ACL(org.apache.zookeeper.data.ACL) CountDownLatch(java.util.concurrent.CountDownLatch) CuratorFramework(org.apache.curator.framework.CuratorFramework) Timing(org.apache.curator.test.Timing) ConnectionState(org.apache.curator.framework.state.ConnectionState) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) KeeperException(org.apache.zookeeper.KeeperException) Test(org.testng.annotations.Test)

Aggregations

CuratorFramework (org.apache.curator.framework.CuratorFramework)37 ConnectionStateListener (org.apache.curator.framework.state.ConnectionStateListener)37 ConnectionState (org.apache.curator.framework.state.ConnectionState)36 Test (org.testng.annotations.Test)29 Timing (org.apache.curator.test.Timing)24 CountDownLatch (java.util.concurrent.CountDownLatch)23 RetryOneTime (org.apache.curator.retry.RetryOneTime)20 ExponentialBackoffRetry (org.apache.curator.retry.ExponentialBackoffRetry)9 KeeperException (org.apache.zookeeper.KeeperException)9 TestingCluster (org.apache.curator.test.TestingCluster)5 TestingServer (org.apache.curator.test.TestingServer)5 IOException (java.io.IOException)4 Semaphore (java.util.concurrent.Semaphore)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 InstanceSpec (org.apache.curator.test.InstanceSpec)4 ExecutorCompletionService (java.util.concurrent.ExecutorCompletionService)3 ExecutorService (java.util.concurrent.ExecutorService)3 RetryNTimes (org.apache.curator.retry.RetryNTimes)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2