Search in sources :

Example 11 with Code

use of org.apache.zookeeper.KeeperException.Code in project zookeeper by apache.

the class ZooKeeperServer method processPacket.

public void processPacket(ServerCnxn cnxn, ByteBuffer incomingBuffer) throws IOException {
    // We have the request, now process and setup for next
    InputStream bais = new ByteBufferInputStream(incomingBuffer);
    BinaryInputArchive bia = BinaryInputArchive.getArchive(bais);
    RequestHeader h = new RequestHeader();
    h.deserialize(bia, "header");
    // Need to increase the outstanding request count first, otherwise
    // there might be a race condition that it enabled recv after
    // processing request and then disabled when check throttling.
    // 
    // Be aware that we're actually checking the global outstanding
    // request before this request.
    // 
    // It's fine if the IOException thrown before we decrease the count
    // in cnxn, since it will close the cnxn anyway.
    cnxn.incrOutstandingAndCheckThrottle(h);
    // Through the magic of byte buffers, txn will not be
    // pointing
    // to the start of the txn
    incomingBuffer = incomingBuffer.slice();
    if (h.getType() == OpCode.auth) {
        LOG.info("got auth packet {}", cnxn.getRemoteSocketAddress());
        AuthPacket authPacket = new AuthPacket();
        ByteBufferInputStream.byteBuffer2Record(incomingBuffer, authPacket);
        String scheme = authPacket.getScheme();
        ServerAuthenticationProvider ap = ProviderRegistry.getServerProvider(scheme);
        Code authReturn = KeeperException.Code.AUTHFAILED;
        if (ap != null) {
            try {
                // handleAuthentication may close the connection, to allow the client to choose
                // a different server to connect to.
                authReturn = ap.handleAuthentication(new ServerAuthenticationProvider.ServerObjs(this, cnxn), authPacket.getAuth());
            } catch (RuntimeException e) {
                LOG.warn("Caught runtime exception from AuthenticationProvider: {}", scheme, e);
                authReturn = KeeperException.Code.AUTHFAILED;
            }
        }
        if (authReturn == KeeperException.Code.OK) {
            LOG.info("Session 0x{}: auth success for scheme {} and address {}", Long.toHexString(cnxn.getSessionId()), scheme, cnxn.getRemoteSocketAddress());
            ReplyHeader rh = new ReplyHeader(h.getXid(), 0, KeeperException.Code.OK.intValue());
            cnxn.sendResponse(rh, null, null);
        } else {
            if (ap == null) {
                LOG.warn("No authentication provider for scheme: {} has {}", scheme, ProviderRegistry.listProviders());
            } else {
                LOG.warn("Authentication failed for scheme: {}", scheme);
            }
            // send a response...
            ReplyHeader rh = new ReplyHeader(h.getXid(), 0, KeeperException.Code.AUTHFAILED.intValue());
            cnxn.sendResponse(rh, null, null);
            // ... and close connection
            cnxn.sendBuffer(ServerCnxnFactory.closeConn);
            cnxn.disableRecv();
        }
        return;
    } else if (h.getType() == OpCode.sasl) {
        processSasl(incomingBuffer, cnxn, h);
    } else {
        if (!authHelper.enforceAuthentication(cnxn, h.getXid())) {
            // Already sent response to user about failure and closed the session, lets return
            return;
        } else {
            Request si = new Request(cnxn, cnxn.getSessionId(), h.getXid(), h.getType(), incomingBuffer, cnxn.getAuthInfo());
            int length = incomingBuffer.limit();
            if (isLargeRequest(length)) {
                // checkRequestSize will throw IOException if request is rejected
                checkRequestSizeWhenMessageReceived(length);
                si.setLargeRequestSize(length);
            }
            si.setOwner(ServerCnxn.me);
            submitRequest(si);
        }
    }
}
Also used : BinaryInputArchive(org.apache.jute.BinaryInputArchive) ReplyHeader(org.apache.zookeeper.proto.ReplyHeader) InputStream(java.io.InputStream) AuthPacket(org.apache.zookeeper.proto.AuthPacket) ConnectRequest(org.apache.zookeeper.proto.ConnectRequest) DeleteRequest(org.apache.zookeeper.proto.DeleteRequest) CreateRequest(org.apache.zookeeper.proto.CreateRequest) SetACLRequest(org.apache.zookeeper.proto.SetACLRequest) GetSASLRequest(org.apache.zookeeper.proto.GetSASLRequest) SetDataRequest(org.apache.zookeeper.proto.SetDataRequest) RequestHeader(org.apache.zookeeper.proto.RequestHeader) ServerAuthenticationProvider(org.apache.zookeeper.server.auth.ServerAuthenticationProvider) Code(org.apache.zookeeper.KeeperException.Code) OpCode(org.apache.zookeeper.ZooDefs.OpCode)

Example 12 with Code

use of org.apache.zookeeper.KeeperException.Code in project accumulo by apache.

the class ZooReader method sync.

public void sync(final String path) throws KeeperException, InterruptedException {
    final AtomicInteger rc = new AtomicInteger();
    final CountDownLatch waiter = new CountDownLatch(1);
    getZooKeeper().sync(path, (code, arg1, arg2) -> {
        rc.set(code);
        waiter.countDown();
    }, null);
    waiter.await();
    Code code = Code.get(rc.get());
    if (code != Code.OK) {
        throw KeeperException.create(code);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CountDownLatch(java.util.concurrent.CountDownLatch) Code(org.apache.zookeeper.KeeperException.Code)

Example 13 with Code

use of org.apache.zookeeper.KeeperException.Code in project hadoop by apache.

the class ActiveStandbyElector method processResult.

/**
   * interface implementation of Zookeeper callback for create
   */
@Override
public synchronized void processResult(int rc, String path, Object ctx, String name) {
    if (isStaleClient(ctx))
        return;
    if (LOG.isDebugEnabled()) {
        LOG.debug("CreateNode result: " + rc + " for path: " + path + " connectionState: " + zkConnectionState + "  for " + this);
    }
    Code code = Code.get(rc);
    if (isSuccess(code)) {
        // we successfully created the znode. we are the leader. start monitoring
        if (becomeActive()) {
            monitorActiveStatus();
        } else {
            reJoinElectionAfterFailureToBecomeActive();
        }
        return;
    }
    if (isNodeExists(code)) {
        if (createRetryCount == 0) {
            // znode exists and we did not retry the operation. so a different
            // instance has created it. become standby and monitor lock.
            becomeStandby();
        }
        // if we had retried then the znode could have been created by our first
        // attempt to the server (that we lost) and this node exists response is
        // for the second attempt. verify this case via ephemeral node owner. this
        // will happen on the callback for monitoring the lock.
        monitorActiveStatus();
        return;
    }
    String errorMessage = "Received create error from Zookeeper. code:" + code.toString() + " for path " + path;
    LOG.debug(errorMessage);
    if (shouldRetry(code)) {
        if (createRetryCount < maxRetryNum) {
            LOG.debug("Retrying createNode createRetryCount: " + createRetryCount);
            ++createRetryCount;
            createLockNodeAsync();
            return;
        }
        errorMessage = errorMessage + ". Not retrying further znode create connection errors.";
    } else if (isSessionExpired(code)) {
        // This isn't fatal - the client Watcher will re-join the election
        LOG.warn("Lock acquisition failed because session was lost");
        return;
    }
    fatalError(errorMessage);
}
Also used : Code(org.apache.zookeeper.KeeperException.Code)

Example 14 with Code

use of org.apache.zookeeper.KeeperException.Code in project accumulo by apache.

the class ZooUtil method isLockHeld.

public static boolean isLockHeld(ZooKeeperConnectionInfo info, LockID lid) throws KeeperException, InterruptedException {
    final Retry retry = RETRY_FACTORY.createRetry();
    while (true) {
        try {
            List<String> children = getZooKeeper(info).getChildren(lid.path, false);
            if (children.size() == 0) {
                return false;
            }
            Collections.sort(children);
            String lockNode = children.get(0);
            if (!lid.node.equals(lockNode))
                return false;
            Stat stat = getZooKeeper(info).exists(lid.path + "/" + lid.node, false);
            return stat != null && stat.getEphemeralOwner() == lid.eid;
        } catch (KeeperException ex) {
            final Code c = ex.code();
            if (c == Code.CONNECTIONLOSS || c == Code.OPERATIONTIMEOUT || c == Code.SESSIONEXPIRED) {
                retryOrThrow(retry, ex);
            }
        }
        retry.waitForNextAttempt();
    }
}
Also used : Stat(org.apache.zookeeper.data.Stat) Retry(org.apache.accumulo.fate.util.Retry) Code(org.apache.zookeeper.KeeperException.Code) KeeperException(org.apache.zookeeper.KeeperException)

Example 15 with Code

use of org.apache.zookeeper.KeeperException.Code in project accumulo by apache.

the class ZooUtil method recursiveCopyPersistent.

public static void recursiveCopyPersistent(ZooKeeperConnectionInfo info, String source, String destination, NodeExistsPolicy policy) throws KeeperException, InterruptedException {
    Stat stat = null;
    if (!exists(info, source))
        throw KeeperException.create(Code.NONODE, source);
    if (exists(info, destination)) {
        switch(policy) {
            case OVERWRITE:
                break;
            case SKIP:
                return;
            case FAIL:
            default:
                throw KeeperException.create(Code.NODEEXISTS, source);
        }
    }
    stat = new Stat();
    byte[] data = getData(info, source, stat);
    if (stat.getEphemeralOwner() == 0) {
        if (data == null)
            throw KeeperException.create(Code.NONODE, source);
        putPersistentData(info, destination, data, policy);
        if (stat.getNumChildren() > 0) {
            List<String> children;
            final Retry retry = RETRY_FACTORY.createRetry();
            while (true) {
                try {
                    children = getZooKeeper(info).getChildren(source, false);
                    break;
                } catch (KeeperException e) {
                    final Code c = e.code();
                    if (c == Code.CONNECTIONLOSS || c == Code.OPERATIONTIMEOUT || c == Code.SESSIONEXPIRED) {
                        retryOrThrow(retry, e);
                    } else {
                        throw e;
                    }
                }
                retry.waitForNextAttempt();
            }
            for (String child : children) {
                recursiveCopyPersistent(info, source + "/" + child, destination + "/" + child, policy);
            }
        }
    }
}
Also used : Stat(org.apache.zookeeper.data.Stat) Retry(org.apache.accumulo.fate.util.Retry) Code(org.apache.zookeeper.KeeperException.Code) KeeperException(org.apache.zookeeper.KeeperException)

Aggregations

Code (org.apache.zookeeper.KeeperException.Code)19 KeeperException (org.apache.zookeeper.KeeperException)10 Stat (org.apache.zookeeper.data.Stat)10 ArrayList (java.util.ArrayList)4 Retry (org.apache.accumulo.fate.util.Retry)4 IOException (java.io.IOException)3 ZooKeeper (org.apache.zookeeper.ZooKeeper)3 CompletableFuture (java.util.concurrent.CompletableFuture)2 NotNull (javax.validation.constraints.NotNull)2 CreateCallbackHandler (org.apache.helix.manager.zk.ZkAsyncCallbacks.CreateCallbackHandler)2 CreateMode (org.apache.zookeeper.CreateMode)2 Op (org.apache.zookeeper.Op)2 OpCode (org.apache.zookeeper.ZooDefs.OpCode)2 InputStream (java.io.InputStream)1 ByteBuffer (java.nio.ByteBuffer)1 List (java.util.List)1 Set (java.util.Set)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 SetDataCallbackHandler (org.apache.helix.manager.zk.ZkAsyncCallbacks.SetDataCallbackHandler)1