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:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

/**
 * checks if the path in zk exist or not. If it doesn't exist, will create the node.
 *
 * @param path/*from w ww.  j  a v  a  2 s. com*/
 * @param callback
 */
public void ensurePersistentNodeExists(String path, final Callback<None> callback) {
    final ZooKeeper zk = zk();
    // Remove any trailing slash except for when we just want the root
    while (path.endsWith("/") && path.length() > 1) {
        path = path.substring(0, path.length() - 1);
    }
    final String normalizedPath = path;
    AsyncCallback.StringCallback createCallback = new AsyncCallback.StringCallback() {
        @Override
        public void processResult(int rc, String unused, Object ctx, String name) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
            case NODEEXISTS:
                callback.onSuccess(None.none());
                break;
            case NONODE:
                // create parent and retry
                String parent = normalizedPath.substring(0, normalizedPath.lastIndexOf('/'));
                ensurePersistentNodeExists(parent, new Callback<None>() {
                    @Override
                    public void onSuccess(None none) {
                        ensurePersistentNodeExists(normalizedPath, callback);
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onError(e);
                    }
                });
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };
    try {
        zk.create(normalizedPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, createCallback,
                null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

private void setDataUnsafe(final String path, final byte[] data, final Callback<None> callback,
        final int count) {
    final ZooKeeper zk = zk();
    final AsyncCallback.StatCallback dataCallback = new AsyncCallback.StatCallback() {
        @Override/*from  www.j  a v a  2s  .  c o  m*/
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                callback.onSuccess(None.none());
                break;
            case BADVERSION:
                if (count < MAX_RETRIES) {
                    LOG.info("setDataUnsafe: ignored BADVERSION for {}", path);
                    setDataUnsafe(path, data, callback, count + 1);
                } else {
                    callback.onError(KeeperException.create(code));
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };
    final AsyncCallback.StatCallback statCallback = new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                zk.setData(path, data, stat.getVersion(), dataCallback, null);
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };
    try {
        zk.exists(path, false, statCallback, null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

private void removeNodeUnsafe(final String path, final Callback<None> callback, final int count) {
    final ZooKeeper zk = zk();

    final AsyncCallback.VoidCallback deleteCallback = new AsyncCallback.VoidCallback() {
        @Override//from   www  .  ja  v a2  s.  co  m
        public void processResult(int rc, String path, Object ctx) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                callback.onSuccess(None.none());
                break;
            case BADVERSION:
                // Need to retry
                if (count < MAX_RETRIES) {
                    LOG.info("removeNodeUnsafe: retrying after ignoring BADVERSION for {}", path);
                    removeNodeUnsafe(path, callback, count + 1);
                } else {
                    callback.onError(KeeperException.create(code));
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };

    final AsyncCallback.StatCallback existsCallback = new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                zk.delete(path, stat.getVersion(), deleteCallback, null);
                break;
            case NONODE:
                callback.onSuccess(None.none());
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };

    try {
        zk.exists(path, false, existsCallback, null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

/**
 * see {@link #removeNodeUnsafe} but remove recursively
 *
 * @param path//from  w ww.  jav  a 2 s . com
 * @param callback
 */
public void removeNodeUnsafeRecursive(final String path, final Callback<None> callback) {
    final ZooKeeper zk = zk();

    final Callback<None> deleteThisNodeCallback = new Callback<None>() {
        @Override
        public void onSuccess(None none) {
            removeNodeUnsafe(path, callback);
        }

        @Override
        public void onError(Throwable e) {
            callback.onError(e);
        }
    };

    // Note ChildrenCallback is compatible with a ZK 3.2 server; Children2Callback is
    // compatible only with ZK 3.3+ server.
    final AsyncCallback.ChildrenCallback childCallback = new AsyncCallback.ChildrenCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                Callback<None> multiCallback = Callbacks.countDown(deleteThisNodeCallback, children.size());
                for (String child : children) {
                    removeNodeUnsafeRecursive(path + "/" + child, multiCallback);
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }

        }
    };

    try {
        zk.getChildren(path, false, childCallback, null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.linkedin.d2.discovery.stores.zk.ZkUtil.java

License:Apache License

public static <T> AsyncCallback.DataCallback zkDataCallback(final Callback<T> callback,
        final PropertySerializer<T> serializer) {
    return new AsyncCallback.DataCallback() {
        @Override/*from   w  ww . j a v  a 2  s .  co  m*/
        public void processResult(int rc, String path, Object context, byte[] bytes, Stat stat) {
            LOG.trace("Data callback got rc {} for path {}", rc, path);
            KeeperException.Code result = KeeperException.Code.get(rc);
            switch (result) {
            case OK:
                try {
                    callback.onSuccess(serializer.fromBytes(bytes));
                } catch (PropertySerializationException e) {
                    callback.onError(e);
                }
                break;
            case NONODE:
                callback.onSuccess(null);
                break;
            default:
                callback.onError(KeeperException.create(result));
                break;
            }
        }
    };
}

From source file:com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore.java

License:Apache License

@Override
public void put(final String prop, final T value, final Callback<None> callback) {
    _putStats.inc();//from ww  w.  j  a v  a2  s .  c o m

    trace(_log, "put ", prop, ": ", value);

    final String path = getPath(prop);
    _zkConn.ensurePersistentNodeExists(path, new Callback<None>() {
        @Override
        public void onSuccess(None none) {
            final String ephemeralPath = path + "/ephemoral-";

            AsyncCallback.StringCallback stringCallback = new AsyncCallback.StringCallback() {
                @Override
                public void processResult(int rc, String path, Object ctx, String name) {
                    KeeperException.Code code = KeeperException.Code.get(rc);
                    switch (code) {
                    case OK:
                        callback.onSuccess(None.none());
                        break;
                    default:
                        callback.onError(KeeperException.create(code));
                        break;
                    }
                }
            };

            if (_zk instanceof RetryZooKeeper) {
                ((RetryZooKeeper) _zk).createUniqueSequential(ephemeralPath, _serializer.toBytes(value),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, stringCallback, null);
            } else {
                _zk.create(ephemeralPath, _serializer.toBytes(value), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL_SEQUENTIAL, stringCallback, null);
            }
        }

        @Override
        public void onError(Throwable e) {
            callback.onError(e);
        }
    });
}

From source file:com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore.java

License:Apache License

public void removePartial(final String prop, final T value, final Callback<None> callback) {
    final String path = getPath(prop);

    trace(_log, "remove partial ", prop, ": ", value);

    final Callback<Map<String, T>> childrenCallback = new Callback<Map<String, T>>() {
        @Override//from w  w w  .j ava2s . co  m
        public void onSuccess(Map<String, T> children) {
            String delete = _merger.unmerge(prop, value, children);
            _zkConn.removeNodeUnsafe(path + "/" + delete.toString(), callback);

        }

        @Override
        public void onError(Throwable e) {
            callback.onError(e);
        }
    };

    _zk.getChildren(path, false, new AsyncCallback.ChildrenCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                if (children.size() > 0) {
                    ChildCollector collector = new ChildCollector(children.size(), childrenCallback);
                    for (String child : children) {
                        _zk.getData(path + "/" + child, false, collector, null);
                    }
                } else {
                    _log.warn("Ignoring request to removePartial with no children: {}", path);
                    callback.onSuccess(None.none());
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }

        }
    }, null);
}

From source file:com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore.java

License:Apache License

@Override
public void get(final String listenTo, final Callback<T> callback) {
    String path = getPath(listenTo);
    // Note ChildrenCallback is compatible with a ZK 3.2 server; Children2Callback is
    // compatible only with ZK 3.3+ server.
    AsyncCallback.ChildrenCallback zkCallback = new AsyncCallback.ChildrenCallback() {
        @Override//from   w  w w  . j ava  2 s  .  c o m
        public void processResult(int rc, String path, Object context, List<String> children) {
            KeeperException.Code result = KeeperException.Code.get(rc);
            switch (result) {
            case NONODE:
                callback.onSuccess(null);
                break;

            case OK:
                getMergedChildren(path, children, null, callback);
                break;

            default:
                callback.onError(KeeperException.create(result));
                break;
            }
        }
    };
    _zk.getChildren(path, null, zkCallback, null);
}

From source file:com.linkedin.d2.discovery.util.TestD2Config.java

License:Apache License

@Test
public static void testWriteConfigDelta() throws Exception {
    // Upload config for the first time.
    @SuppressWarnings("serial")
    Map<String, List<String>> clustersData = new HashMap<String, List<String>>() {
        {/* w  w  w.j a va 2  s.c o m*/
            put("cluster-a", Arrays.asList(new String[] { "service-1_a", "service-1_b" }));
            put("cluster-b", Arrays.asList(new String[] { "service-2_a", "service-2_b" }));
        }
    };
    D2ConfigTestUtil d2Conf = new D2ConfigTestUtil(clustersData);
    d2Conf.setUseDeltaWrite(true);
    assertEquals(d2Conf.runDiscovery(_zkHosts), 0);

    // Upload the same config with service-1_1 replaced with service-1_3.
    //  - Duplicate services will not be rewritten.
    //  - New service (service-1_3) will be added.
    //  - Deleted service (service-1_1) will NOT be deleted.
    // Therefore all clusters & services should be uploaded once after this step (aka all have version 1).
    clustersData.put("cluster-a", Arrays.asList(new String[] { "service-1_b", "service-1_c" }));
    d2Conf = new D2ConfigTestUtil(clustersData);
    d2Conf.setUseDeltaWrite(true);
    assertEquals(d2Conf.runDiscovery(_zkHosts), 0);

    // Upload cluster-1 and service-1_1 again with new properties.
    // They should both change to version 2 while others remain version 1.
    //  - Rest of cluster-a's fields deleted.
    //  - cluster-b deleted
    //  - cluster-c added
    @SuppressWarnings("serial")
    Map<String, List<String>> modifiedClustersData = new HashMap<String, List<String>>() {
        {
            put("cluster-a", Arrays.asList(new String[] { "service-1_a" }));
            put("cluster-c", Arrays.asList(new String[] { "service-3_a" }));
        }
    };
    d2Conf = new D2ConfigTestUtil(modifiedClustersData);
    d2Conf.setUseDeltaWrite(true);
    d2Conf.setServiceDefaults(Arrays.asList(new String[] { "degrader-new" }));
    d2Conf.setClusterProperties(1001, 1002);
    assertEquals(d2Conf.runDiscovery(_zkHosts), 0);

    // Build map of path to expected version.
    final HashMap<String, Integer> expectedVersionMap = new HashMap<String, Integer>();
    expectedVersionMap.put("/d2/services/service-1_a", 2);
    expectedVersionMap.put("/d2/services/service-1_b", 1);
    expectedVersionMap.put("/d2/services/service-1_c", 1);
    expectedVersionMap.put("/d2/services/service-2_a", 1);
    expectedVersionMap.put("/d2/services/service-2_b", 1);
    expectedVersionMap.put("/d2/services/service-3_a", 1);
    expectedVersionMap.put("/d2/clusters/cluster-a", 2);
    expectedVersionMap.put("/d2/clusters/cluster-b", 1);
    expectedVersionMap.put("/d2/clusters/cluster-c", 1);

    // Get actual version number for each path.
    final HashMap<String, Integer> actualVersionMap = new HashMap<String, Integer>();
    final CountDownLatch latch = new CountDownLatch(expectedVersionMap.size());
    final AsyncCallback.StatCallback statCallback = new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            if (code == KeeperException.Code.OK) {
                actualVersionMap.put(path, stat.getVersion());
                latch.countDown();
            }
        }
    };

    ZooKeeper zk = _zkclient.getZooKeeper();
    for (String path : expectedVersionMap.keySet()) {
        zk.exists(path, false, statCallback, null);
    }

    // Wait for expectedVersionMap to be populated.
    if (!latch.await(5, TimeUnit.SECONDS)) {
        fail("Unable to get stat for all paths.");
    }

    for (String path : expectedVersionMap.keySet()) {
        assertEquals(actualVersionMap.get(path).intValue(), expectedVersionMap.get(path).intValue());
    }
}

From source file:com.linkedin.parseq.zk.client.TestReaper.java

License:Apache License

@Test
public void testReaperRetry() throws InterruptedException {
    final int MAX_RETRY = 3;
    final CountDownLatch failure = new CountDownLatch(MAX_RETRY);
    final CountDownLatch success = new CountDownLatch(1);

    Reaper.Zombie zombie = new Reaper.Zombie() {
        private int count = 0;

        @Override/*from  w  w w. ja v a2s.c o  m*/
        public Task<Void> reap() {
            if (count++ < MAX_RETRY) {
                return Task.action(() -> failure.countDown())
                        .andThen(Task.failure(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)));
            } else {
                return Task.action(() -> success.countDown());
            }
        }
    };
    _reaper.submit(zombie);

    Assert.assertTrue(failure.await(10, TimeUnit.SECONDS));
    Assert.assertTrue(success.await(10, TimeUnit.SECONDS));
}