Example usage for org.apache.zookeeper KeeperException code

List of usage examples for org.apache.zookeeper KeeperException code

Introduction

In this page you can find the example usage for org.apache.zookeeper KeeperException code.

Prototype

Code code

To view the source code for org.apache.zookeeper KeeperException code.

Click Source Link

Usage

From source file:org.apache.accumulo.server.security.handler.ZKPermHandler.java

License:Apache License

@Override
public boolean hasSystemPermission(String user, SystemPermission permission) throws AccumuloSecurityException {
    byte[] perms;
    try {/*from w w  w. j  a  va  2  s. c om*/
        String path = ZKUserPath + "/" + user + ZKUserSysPerms;
        ZooReaderWriter.getInstance().sync(path);
        perms = ZooReaderWriter.getInstance().getData(path, null);
    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            return false;
        }
        log.warn("Unhandled KeeperException, failing closed for table permission check", e);
        return false;
    } catch (InterruptedException e) {
        log.warn("Unhandled InterruptedException, failing closed for table permission check", e);
        return false;
    }

    if (perms == null)
        return false;
    return ZKSecurityTool.convertSystemPermissions(perms).contains(permission);
}

From source file:org.apache.accumulo.server.security.handler.ZKPermHandler.java

License:Apache License

@Override
public void cleanUser(String user) throws AccumuloSecurityException {
    try {// w w w .j  a  v a  2 s.  c om
        synchronized (zooCache) {
            IZooReaderWriter zoo = ZooReaderWriter.getInstance();
            zoo.recursiveDelete(ZKUserPath + "/" + user + ZKUserSysPerms, NodeMissingPolicy.SKIP);
            zoo.recursiveDelete(ZKUserPath + "/" + user + ZKUserTablePerms, NodeMissingPolicy.SKIP);
            zoo.recursiveDelete(ZKUserPath + "/" + user + ZKUserNamespacePerms, NodeMissingPolicy.SKIP);
            zooCache.clear(ZKUserPath + "/" + user);
        }
    } catch (InterruptedException e) {
        log.error("{}", e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (KeeperException e) {
        log.error("{}", e.getMessage(), e);
        if (e.code().equals(KeeperException.Code.NONODE))
            throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST, e);
        throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e);

    }
}

From source file:org.apache.accumulo.server.security.ZKAuthenticator.java

License:Apache License

/**
 * Creates a user with no permissions whatsoever
 *///from   w  w  w  . ja v a2  s . c o m
public void createUser(AuthInfo credentials, String user, byte[] pass, Authorizations authorizations)
        throws AccumuloSecurityException {
    if (!hasSystemPermission(credentials, credentials.user, SystemPermission.CREATE_USER))
        throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);

    if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER)) {
        Authorizations creatorAuths = getUserAuthorizations(credentials, credentials.user);
        for (byte[] auth : authorizations.getAuthorizations())
            if (!creatorAuths.contains(auth)) {
                log.info("User " + credentials.user + " attempted to create a user " + user
                        + " with authorization " + new String(auth) + " they did not have");
                throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_AUTHORIZATIONS);
            }
    }

    // don't allow creating a user with the same name as system user
    if (user.equals(SecurityConstants.SYSTEM_USERNAME))
        throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED);

    try {
        constructUser(user, Tool.createPass(pass), new TreeSet<SystemPermission>(),
                new HashMap<String, Set<TablePermission>>(), authorizations);
        log.info("Created user " + user + " at the request of user " + credentials.user);
    } catch (KeeperException e) {
        log.error(e, e);
        if (e.code().equals(KeeperException.Code.NODEEXISTS))
            throw new AccumuloSecurityException(user, SecurityErrorCode.USER_EXISTS, e);
        throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e);
    } catch (InterruptedException e) {
        log.error(e, e);
        throw new RuntimeException(e);
    } catch (AccumuloException e) {
        log.error(e, e);
        throw new AccumuloSecurityException(user, SecurityErrorCode.DEFAULT_SECURITY_ERROR, e);
    }
}

From source file:org.apache.accumulo.server.security.ZKAuthenticator.java

License:Apache License

public void dropUser(AuthInfo credentials, String user) throws AccumuloSecurityException {
    if (!hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_USER))
        throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);

    // can't delete root or system users
    if (user.equals(getRootUsername()) || user.equals(SecurityConstants.SYSTEM_USERNAME))
        throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED);

    try {//from ww  w . j a  va 2 s .c o m
        synchronized (zooCache) {
            zooCache.clear();
            ZooReaderWriter.getRetryingInstance().recursiveDelete(ZKUserPath + "/" + user,
                    NodeMissingPolicy.FAIL);
        }
        log.info("Deleted user " + user + " at the request of user " + credentials.user);
    } catch (InterruptedException e) {
        log.error(e, e);
        throw new RuntimeException(e);
    } catch (KeeperException e) {
        log.error(e, e);
        if (e.code().equals(KeeperException.Code.NONODE))
            throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST, e);
        throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e);
    }
}

From source file:org.apache.accumulo.tserver.TabletServer.java

License:Apache License

private void announceExistence() {
    IZooReaderWriter zoo = ZooReaderWriter.getInstance();
    try {//from w ww  .  j  a  v  a 2  s .c o  m
        String zPath = ZooUtil.getRoot(getInstance()) + Constants.ZTSERVERS + "/" + getClientAddressString();

        try {
            zoo.putPersistentData(zPath, new byte[] {}, NodeExistsPolicy.SKIP);
        } catch (KeeperException e) {
            if (KeeperException.Code.NOAUTH == e.code()) {
                log.error(
                        "Failed to write to ZooKeeper. Ensure that accumulo-site.xml, specifically instance.secret, is consistent.");
            }
            throw e;
        }

        tabletServerLock = new ZooLock(zPath);

        LockWatcher lw = new LockWatcher() {

            @Override
            public void lostLock(final LockLossReason reason) {
                Halt.halt(serverStopRequested ? 0 : 1, new Runnable() {
                    @Override
                    public void run() {
                        if (!serverStopRequested)
                            log.error("Lost tablet server lock (reason = " + reason + "), exiting.");
                        gcLogger.logGCInfo(getConfiguration());
                    }
                });
            }

            @Override
            public void unableToMonitorLockNode(final Throwable e) {
                Halt.halt(1, new Runnable() {
                    @Override
                    public void run() {
                        log.error("Lost ability to monitor tablet server lock, exiting.", e);
                    }
                });

            }
        };

        byte[] lockContent = new ServerServices(getClientAddressString(), Service.TSERV_CLIENT).toString()
                .getBytes(UTF_8);
        for (int i = 0; i < 120 / 5; i++) {
            zoo.putPersistentData(zPath, new byte[0], NodeExistsPolicy.SKIP);

            if (tabletServerLock.tryLock(lw, lockContent)) {
                log.debug("Obtained tablet server lock " + tabletServerLock.getLockPath());
                lockID = tabletServerLock.getLockID()
                        .serialize(ZooUtil.getRoot(getInstance()) + Constants.ZTSERVERS + "/");
                return;
            }
            log.info("Waiting for tablet server lock");
            sleepUninterruptibly(5, TimeUnit.SECONDS);
        }
        String msg = "Too many retries, exiting.";
        log.info(msg);
        throw new RuntimeException(msg);
    } catch (Exception e) {
        log.info("Could not obtain tablet server lock, exiting.", e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.blur.zookeeper.WatchChildren.java

License:Apache License

public WatchChildren watch(final OnChange onChange, long fireAnywayTime, TimeUnit timeUnit) {
    if (_debug) {
        StringWriter writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        new Throwable().printStackTrace(printWriter);
        printWriter.close();/* w w  w  . jav a 2s . c o m*/
        _debugStackTrace = writer.toString();
    }
    final long timeToFireAnywayTime = TimeUnit.MILLISECONDS.convert(fireAnywayTime, timeUnit);
    _watchThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Watcher watcher = new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    synchronized (_lock) {
                        _lock.notify();
                    }
                }
            };
            startDoubleCheckThread();
            while (_running.get()) {
                synchronized (_lock) {
                    try {
                        List<String> children = _zooKeeper.getChildren(_path, watcher);
                        try {
                            onChange.action(children);
                            _children = children;
                        } catch (Throwable t) {
                            LOG.error("Unknown error during onchange action [" + this + "].", t);
                        }
                        _lock.wait(timeToFireAnywayTime);
                    } catch (KeeperException e) {
                        if (!_running.get()) {
                            LOG.info("Error [{0}]", e.getMessage());
                            return;
                        }
                        if (e.code() == Code.NONODE) {
                            if (_debug) {
                                LOG.debug("Path for watching not found [{0}], no longer watching, debug [{1}].",
                                        _path, _debugStackTrace);
                            } else {
                                LOG.debug("Path for watching not found [{0}], no longer watching.", _path);
                            }
                            close();
                            return;
                        }
                        if (_debug) {
                            LOG.error("Unknown error [{0}]", e, _debugStackTrace);
                        } else {
                            LOG.error("Unknown error", e);
                        }
                        throw new RuntimeException(e);
                    } catch (InterruptedException e) {
                        return;
                    }
                }
            }
            _running.set(false);
        }
    });
    _watchThread.setName("Watch Children [" + _path + "][" + instance + "]");
    _watchThread.setDaemon(true);
    _watchThread.start();
    return this;
}

From source file:org.apache.blur.zookeeper.WatchChildren.java

License:Apache License

private void startDoubleCheckThread() {
    _doubleCheckThread = new Thread(new Runnable() {
        @Override//from www  .  j  ava  2  s  .  co m
        public void run() {
            while (_running.get()) {
                try {
                    synchronized (_running) {
                        _running.wait(_delay);
                    }
                    if (!_running.get()) {
                        return;
                    }
                    if (_zooKeeper.exists(_path, false) == null) {
                        LOG.debug("Path for watching not found [{0}], no longer double checking.", _path);
                        return;
                    }
                    List<String> children = _zooKeeper.getChildren(_path, false);
                    if (!isCorrect(children)) {
                        LOG.error("Double check triggered for [" + _path + "] [" + instance + "]");
                        synchronized (_lock) {
                            _lock.notify();
                        }
                    }
                } catch (KeeperException e) {
                    if (!_running.get()) {
                        LOG.info("Error [{0}]", e.getMessage());
                        return;
                    }
                    if (e.code() == Code.SESSIONEXPIRED) {
                        LOG.warn("Session expired for [" + _path + "] [" + instance + "]");
                        return;
                    }
                    LOG.error("Unknown error", e);
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    });
    _doubleCheckThread.setName("Poll Watch Children [" + _path + "][" + instance + "]");
    _doubleCheckThread.setDaemon(true);
    _doubleCheckThread.start();
}

From source file:org.apache.blur.zookeeper.WatchNodeData.java

License:Apache License

private void startDoubleCheckThread() {
    _doubleCheckThread = new Thread(new Runnable() {

        @Override/*w  w w.jav  a  2s  . c o  m*/
        public void run() {
            while (_running.get()) {
                try {
                    synchronized (_running) {
                        _running.wait(_delay);
                    }
                    if (!_running.get()) {
                        return;
                    }
                    Stat stat = _zooKeeper.exists(_path, false);
                    if (stat == null) {
                        LOG.debug("Path [{0}] not found.", _path);
                        synchronized (_lock) {
                            _lock.notify();
                        }
                        return;
                    }

                    byte[] data = _zooKeeper.getData(_path, false, stat);
                    if (!isCorrect(data)) {
                        LOG.debug("Double check triggered for [" + _path + "]");
                        synchronized (_lock) {
                            _lock.notify();
                        }
                    }
                } catch (KeeperException e) {
                    if (!_running.get()) {
                        LOG.info("Error [{0}]", e.getMessage());
                        return;
                    }
                    if (e.code() == Code.SESSIONEXPIRED) {
                        LOG.warn("Session expired for [" + _path + "] [" + instance + "]");
                        return;
                    }
                    LOG.error("Unknown error", e);
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    });
    _doubleCheckThread.setName("Poll Watch Data [" + _path + "][" + instance + "]");
    _doubleCheckThread.setDaemon(true);
    _doubleCheckThread.start();
}

From source file:org.apache.blur.zookeeper.WatchNodeExistance.java

License:Apache License

private void startDoubleCheckThread() {
    _doubleCheckThread = new Thread(new Runnable() {
        @Override/*from   w  w w .  j av a2 s.  c o  m*/
        public void run() {
            while (_running.get()) {
                try {
                    synchronized (_running) {
                        _running.wait(_delay);
                    }
                    if (!_running.get()) {
                        return;
                    }
                    Stat stat = _zooKeeper.exists(_path, false);
                    if (!isCorrect(stat)) {
                        LOG.debug("Double check triggered for [" + _path + "]");
                        synchronized (_lock) {
                            _lock.notify();
                        }
                    }
                } catch (KeeperException e) {
                    if (!_running.get()) {
                        LOG.info("Error [{0}]", e.getMessage());
                        return;
                    }
                    if (e.code() == Code.SESSIONEXPIRED) {
                        LOG.warn("Session expired for [" + _path + "] [" + instance + "]");
                        return;
                    }
                    LOG.error("Unknown error", e);
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    });
    _doubleCheckThread.setName("Poll Watch Existance [" + _path + "][" + instance + "]");
    _doubleCheckThread.setDaemon(true);
    _doubleCheckThread.start();
}

From source file:org.apache.blur.zookeeper.ZooKeeperClient.java

License:Apache License

public <T> T execute(ZKExecutor<T> executor) throws KeeperException, InterruptedException {
    final long timestmap = System.currentTimeMillis();
    int sessionTimeout = getSessionTimeout();
    if (sessionTimeout == 0) {
        sessionTimeout = internalSessionTimeout;
    }//w  w  w.  j av  a 2s.  co  m
    while (true) {
        Tracer trace = Trace.trace("remote call - zookeeper", Trace.param("method", executor._name),
                Trace.param("toString", executor.toString()));
        try {
            return executor.execute();
        } catch (KeeperException e) {
            if (e.code() == Code.CONNECTIONLOSS && timestmap + sessionTimeout >= System.currentTimeMillis()) {
                LOG.warn("Connection loss");
                ZkUtils.pause(this);
                continue;
            }
            throw e;
        } finally {
            trace.done();
        }
    }
}