org.I0Itec.zkclient.exception.ZkInterruptedException Java Examples

The following examples show how to use org.I0Itec.zkclient.exception.ZkInterruptedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public boolean waitUntilExists(String path, TimeUnit timeUnit, long time) throws ZkInterruptedException {
    Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time));
    LOG.debug("Waiting until znode '" + path + "' becomes available.");
    if (exists(path)) {
        return true;
    }
    acquireEventLock();
    try {
        while (!exists(path, true)) {
            boolean gotSignal = getEventLock().getZNodeEventCondition().awaitUntil(timeout);
            if (!gotSignal) {
                return false;
            }
        }
        return true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}
 
Example #2
Source File: ZkClientx.java    From canal with Apache License 2.0 6 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param data
 * @param createParents if true all parent dirs are created as well and no
 * {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException if operation was interrupted, or a
 * required reconnection got interrupted
 * @throws IllegalArgumentException if called from anything except the
 * ZooKeeper event thread
 * @throws ZkException if any ZooKeeper exception occurred
 * @throws RuntimeException if any other exception occurs
 */
public String createPersistentSequential(String path, Object data, boolean createParents)
                                                                                         throws ZkInterruptedException,
                                                                                         IllegalArgumentException,
                                                                                         ZkException,
                                                                                         RuntimeException {
    try {
        return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, data, createParents);
    }
}
 
Example #3
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public boolean waitUntilExists(String path, TimeUnit timeUnit, long time) throws ZkInterruptedException {
    Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time));
    LOG.debug("Waiting until znode '" + path + "' becomes available.");
    if (exists(path)) {
        return true;
    }
    acquireEventLock();
    try {
        while (!exists(path, true)) {
            boolean gotSignal = getEventLock().getZNodeEventCondition().awaitUntil(timeout);
            if (!gotSignal) {
                return false;
            }
        }
        return true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}
 
Example #4
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to ZooKeeper.
 *
 * @param maxMsToWaitUntilConnected
 * @param watcher
 * @throws ZkInterruptedException
 *             if the connection timed out due to thread interruption
 * @throws ZkTimeoutException
 *             if the connection timed out
 * @throws IllegalStateException
 *             if the connection timed out due to thread interruption
 */
public void connect(final long maxMsToWaitUntilConnected, Watcher watcher) throws ZkInterruptedException, ZkTimeoutException, IllegalStateException {
    boolean started = false;
    acquireEventLock();
    try {
        setShutdownTrigger(false);
        _eventThread = new ZkEventThread(_connection.getServers());
        _eventThread.start();
        _connection.connect(watcher);

        LOG.debug("Awaiting connection to Zookeeper server");
        boolean waitSuccessful = waitUntilConnected(maxMsToWaitUntilConnected, TimeUnit.MILLISECONDS);
        if (!waitSuccessful) {
            throw new ZkTimeoutException("Unable to connect to zookeeper server '" + _connection.getServers() + "' with timeout of " + maxMsToWaitUntilConnected + " ms");
        }
        started = true;
    } finally {
        getEventLock().unlock();

        // we should close the zookeeper instance, otherwise it would keep
        // on trying to connect
        if (!started) {
            close();
        }
    }
}
 
Example #5
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
/**
 * Close the client.
 *
 * @throws ZkInterruptedException
 */
public void close() throws ZkInterruptedException {
    if (_closed) {
        return;
    }
    LOG.debug("Closing ZkClient...");
    getEventLock().lock();
    try {
        setShutdownTrigger(true);
        _eventThread.interrupt();
        _eventThread.join(2000);
        _connection.close();
        _closed = true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
    LOG.debug("Closing ZkClient...done");
}
 
Example #6
Source File: ZkClientx.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param data
 * @param createParents if true all parent dirs are created as well and no
 * {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException if operation was interrupted, or a
 * required reconnection got interrupted
 * @throws IllegalArgumentException if called from anything except the
 * ZooKeeper event thread
 * @throws ZkException if any ZooKeeper exception occurred
 * @throws RuntimeException if any other exception occurs
 */
public String createPersistentSequential(String path, Object data, boolean createParents)
                                                                                         throws ZkInterruptedException,
                                                                                         IllegalArgumentException,
                                                                                         ZkException,
                                                                                         RuntimeException {
    try {
        return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, data, createParents);
    }
}
 
Example #7
Source File: ZkClientX.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param data
 * @param createParents if true all parent dirs are created as well and no
 *                      {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException   if operation was interrupted, or a
 *                                  required reconnection got interrupted
 * @throws IllegalArgumentException if called parseFrom anything except the
 *                                  ZooKeeper event thread
 * @throws ZkException              if any ZooKeeper errors occurred
 * @throws RuntimeException         if any other errors occurs
 */
public String createPersistentSequential(String path, Object data, boolean createParents)
        throws ZkInterruptedException,
        IllegalArgumentException,
        ZkException,
        RuntimeException {
    try {
        return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, data, createParents);
    }
}
 
Example #8
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
/**
 * Close the client.
 *
 * @throws ZkInterruptedException
 */
public void close() throws ZkInterruptedException {
    if (_closed) {
        return;
    }
    LOG.debug("Closing ZkClient...");
    getEventLock().lock();
    try {
        setShutdownTrigger(true);
        _eventThread.interrupt();
        _eventThread.join(2000);
        _connection.close();
        _closed = true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
    LOG.debug("Closing ZkClient...done");
}
 
Example #9
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to ZooKeeper.
 *
 * @param maxMsToWaitUntilConnected
 * @param watcher
 * @throws ZkInterruptedException
 *             if the connection timed out due to thread interruption
 * @throws ZkTimeoutException
 *             if the connection timed out
 * @throws IllegalStateException
 *             if the connection timed out due to thread interruption
 */
public void connect(final long maxMsToWaitUntilConnected, Watcher watcher) throws ZkInterruptedException, ZkTimeoutException, IllegalStateException {
    boolean started = false;
    acquireEventLock();
    try {
        setShutdownTrigger(false);
        _eventThread = new ZkEventThread(_connection.getServers());
        _eventThread.start();
        _connection.connect(watcher);

        LOG.debug("Awaiting connection to Zookeeper server");
        boolean waitSuccessful = waitUntilConnected(maxMsToWaitUntilConnected, TimeUnit.MILLISECONDS);
        if (!waitSuccessful) {
            throw new ZkTimeoutException("Unable to connect to zookeeper server '" + _connection.getServers() + "' with timeout of " + maxMsToWaitUntilConnected + " ms");
        }
        started = true;
    } finally {
        getEventLock().unlock();

        // we should close the zookeeper instance, otherwise it would keep
        // on trying to connect
        if (!started) {
            close();
        }
    }
}
 
Example #10
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void acquireEventLock() {
    try {
        getEventLock().lockInterruptibly();
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    }
}
 
Example #11
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public boolean waitUntilConnected(long time, TimeUnit timeUnit) throws ZkInterruptedException {
    if (_isZkSaslEnabled) {
        return waitForKeeperState(KeeperState.SaslAuthenticated, time, timeUnit);
    } else {
        return waitForKeeperState(KeeperState.SyncConnected, time, timeUnit);
    }
}
 
Example #12
Source File: KafkaMirrorMakerConnectorTask.java    From brooklin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void postShutdownHook() {
  if (_enablePartitionAssignment) {
    boolean resetInterrupted = false;
    try {
      for (int numAttempts = 1; numAttempts <= 3; ++numAttempts) {
        try {
          // The task lock should only be released when it is absolutely safe (we can guarantee that the task cannot
          // consume any further). The shutdown process must complete and the consumer must be closed.
          LOG.info("Releasing the lock on datastreamTask: {}, was thread interrupted: {}, attempt: {}",
              _datastreamTask, resetInterrupted, numAttempts);
          _datastreamTask.release();
          break;
        } catch (ZkInterruptedException e) {
          LOG.warn("Releasing the task lock failed for datastreamTask: {}, retrying", _datastreamTask);
          if (Thread.currentThread().isInterrupted()) {
            // The interrupted status of the current thread must be reset to allow the task lock to be released
            resetInterrupted = Thread.interrupted();
          }
        }
      }
    } finally {
      if (resetInterrupted) {
        // Setting the status of the thread back to interrupted
        Thread.currentThread().interrupt();
      }
    }
  }
}
 
Example #13
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException {
    if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
        throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
    }
    Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time));

    LOG.info("Waiting for keeper state " + keeperState);
    acquireEventLock();
    try {
        boolean stillWaiting = true;
        while (_currentState != keeperState) {
            if (!stillWaiting) {
                return false;
            }
            stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout);
            // Throw an exception in the case authorization fails
            if (_currentState == KeeperState.AuthFailed && _isZkSaslEnabled) {
                throw new ZkAuthFailedException("Authentication failure");
            }
        }
        LOG.debug("State is " + _currentState);
        return true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}
 
Example #14
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public boolean waitUntilConnected(long time, TimeUnit timeUnit) throws ZkInterruptedException {
    if (_isZkSaslEnabled) {
        return waitForKeeperState(KeeperState.SaslAuthenticated, time, timeUnit);
    } else {
        return waitForKeeperState(KeeperState.SyncConnected, time, timeUnit);
    }
}
 
Example #15
Source File: ZkClient.java    From brooklin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void close() throws ZkInterruptedException {
  if (LOG.isTraceEnabled()) {
    StackTraceElement[] calls = Thread.currentThread().getStackTrace();
    LOG.trace("closing zkclient. callStack: {}", Arrays.asList(calls));
  }
  getEventLock().lock();
  try {
    if (_connection == null) {
      return;
    }
    LOG.info("closing zkclient: {}", ((ZkConnection) _connection).getZookeeper());
    super.close();
  } catch (ZkInterruptedException e) {
    /*
     * Workaround for HELIX-264: calling ZkClient#disconnect() in its own eventThread context will
     * throw ZkInterruptedException and skip ZkConnection#disconnect()
     */
    try {
      /*
       * ZkInterruptedException#construct() honors InterruptedException by calling
       * Thread.currentThread().interrupt(); clear it first, so we can safely disconnect the
       * zk-connection
       */
      Thread.interrupted();
      _connection.close();
      /*
       * restore interrupted status of current thread
       */
      Thread.currentThread().interrupt();
    } catch (InterruptedException e1) {
      throw new ZkInterruptedException(e1);
    }
  } finally {
    getEventLock().unlock();
    LOG.info("closed zkclient");
  }
}
 
Example #16
Source File: ZkClientx.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
    * 创建一个持久的顺序节点
    */
public String createPersistentSequential(String path, boolean createParents)
		throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException {
       try {
           return create(path, null, CreateMode.PERSISTENT_SEQUENTIAL);
       } catch (ZkNoNodeException e) {
           if (!createParents) {
               throw e;
           }
           String parentDir = path.substring(0, path.lastIndexOf('/'));
           createPersistent(parentDir, createParents);
           return createPersistentSequential(path, createParents);
       }
   }
 
Example #17
Source File: ZkClientx.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String createPersistentSequential(String path, Object data, boolean createParents)
throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException {
     try {
         return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
     } catch (ZkNoNodeException e) {
         if (!createParents) {
             throw e;
         }
         String parentDir = path.substring(0, path.lastIndexOf('/'));
         createPersistent(parentDir, createParents);
         return createPersistentSequential(path, data, createParents);
     }
 }
 
Example #18
Source File: ZkUtils.java    From samza with Apache License 2.0 5 votes vote down vote up
public void connect() throws ZkInterruptedException {
  boolean isConnected = zkClient.waitUntilConnected(connectionTimeoutMs, TimeUnit.MILLISECONDS);
  if (!isConnected) {
    metrics.zkConnectionError.inc();
    throw new RuntimeException("Unable to connect to Zookeeper within connectionTimeout " + connectionTimeoutMs + "ms. Shutting down!");
  }
}
 
Example #19
Source File: ZkClientx.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param createParents if true all parent dirs are created as well and no
 * {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException if operation was interrupted, or a
 * required reconnection got interrupted
 * @throws IllegalArgumentException if called from anything except the
 * ZooKeeper event thread
 * @throws ZkException if any ZooKeeper exception occurred
 * @throws RuntimeException if any other exception occurs
 */
public String createPersistentSequential(String path, boolean createParents) throws ZkInterruptedException,
                                                                            IllegalArgumentException, ZkException,
                                                                            RuntimeException {
    try {
        return create(path, null, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, createParents);
    }
}
 
Example #20
Source File: ZkUtils.java    From samza with Apache License 2.0 5 votes vote down vote up
public void close() {
  try {
    zkClient.close();
  } catch (ZkInterruptedException e) {
    LOG.warn("Interrupted when closing zkClient. Clearing the interrupted status and retrying.", e);
    Thread.interrupted();
    zkClient.close();
    Thread.currentThread().interrupt();
  }
}
 
Example #21
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException {
    if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
        throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
    }
    Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time));

    LOG.info("Waiting for keeper state " + keeperState);
    acquireEventLock();
    try {
        boolean stillWaiting = true;
        while (_currentState != keeperState) {
            if (!stillWaiting) {
                return false;
            }
            stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout);
            // Throw an exception in the case authorization fails
            if (_currentState == KeeperState.AuthFailed && _isZkSaslEnabled) {
                throw new ZkAuthFailedException("Authentication failure");
            }
        }
        LOG.debug("State is " + _currentState);
        return true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}
 
Example #22
Source File: ZkClientX.java    From DataLink with Apache License 2.0 5 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param createParents if true all parent dirs are created as well and no
 *                      {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException   if operation was interrupted, or a
 *                                  required reconnection got interrupted
 * @throws IllegalArgumentException if called parseFrom anything except the
 *                                  ZooKeeper event thread
 * @throws ZkException              if any ZooKeeper errors occurred
 * @throws RuntimeException         if any other errors occurs
 */
public String createPersistentSequential(String path, boolean createParents) throws ZkInterruptedException,
        IllegalArgumentException, ZkException,
        RuntimeException {
    try {
        return create(path, null, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, createParents);
    }
}
 
Example #23
Source File: ZkCoordinationUtils.java    From samza with Apache License 2.0 5 votes vote down vote up
public void close() {
  try {
    if (zkUtils != null)
      zkUtils.close();
  } catch (ZkInterruptedException ex) {
    // Swallowing due to occurrence in the last stage of lifecycle(Not actionable).
    LOG.error("Exception in close(): ", ex);
  }
}
 
Example #24
Source File: ParameterDynamicZookeeper.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public void shutdown() {
    LOGGER.info("ParameterDynamicZookeeper Shutting Down");
    this.stopScheduled();
    try {
        this.zkClient.close();
    } catch (ZkInterruptedException e) {
        LOGGER.error("ParameterDynamicZookeeper Exception - Shutdown", e);
    }
    LOGGER.info("ParameterDynamicZookeeper Shutdown");
}
 
Example #25
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void acquireEventLock() {
    try {
        getEventLock().lockInterruptibly();
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    }
}
 
Example #26
Source File: ZkClientx.java    From canal with Apache License 2.0 5 votes vote down vote up
/**
 * Create a persistent Sequential node.
 *
 * @param path
 * @param createParents if true all parent dirs are created as well and no
 * {@link ZkNodeExistsException} is thrown in case the path already exists
 * @throws ZkInterruptedException if operation was interrupted, or a
 * required reconnection got interrupted
 * @throws IllegalArgumentException if called from anything except the
 * ZooKeeper event thread
 * @throws ZkException if any ZooKeeper exception occurred
 * @throws RuntimeException if any other exception occurs
 */
public String createPersistentSequential(String path, boolean createParents) throws ZkInterruptedException,
                                                                            IllegalArgumentException, ZkException,
                                                                            RuntimeException {
    try {
        return create(path, null, CreateMode.PERSISTENT_SEQUENTIAL);
    } catch (ZkNoNodeException e) {
        if (!createParents) {
            throw e;
        }
        String parentDir = path.substring(0, path.lastIndexOf('/'));
        createPersistent(parentDir, createParents);
        return createPersistentSequential(path, createParents);
    }
}
 
Example #27
Source File: TestZkUtils.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseShouldRetryOnceOnInterruptedException() {
  ZkClient zkClient = Mockito.mock(ZkClient.class);
  ZkUtils zkUtils = new ZkUtils(KEY_BUILDER, zkClient, CONNECTION_TIMEOUT_MS, SESSION_TIMEOUT_MS, new NoOpMetricsRegistry());

  Mockito.doThrow(new ZkInterruptedException(new InterruptedException()))
         .doAnswer(invocation -> null)
         .when(zkClient).close();

  zkUtils.close();

  Mockito.verify(zkClient, Mockito.times(2)).close();
}
 
Example #28
Source File: ParameterDynamicZookeeper.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public void shutdown() {
    LOGGER.info("ParameterDynamicZookeeper Shutting Down");
    this.stopScheduled();
    try {
        this.zkClient.close();
    } catch (ZkInterruptedException e) {
        LOGGER.error("ParameterDynamicZookeeper Exception - Shutdown", e);
    }
    LOGGER.info("ParameterDynamicZookeeper Shutdown");
}
 
Example #29
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void reconnect() {
    getEventLock().lock();
    try {
        _connection.close();
        _connection.connect(this);
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}
 
Example #30
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void reconnect() {
    getEventLock().lock();
    try {
        _connection.close();
        _connection.connect(this);
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}