org.apache.zookeeper.ZooDefs Java Examples

The following examples show how to use org.apache.zookeeper.ZooDefs. 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: BasicTests.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void     testSimple() throws Exception
{
    CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
    client.start();
    try
    {
        client.blockUntilConnectedOrTimedOut();
        String              path = client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        Assert.assertEquals(path, "/test");
    }
    finally
    {
        client.close();
    }
}
 
Example #2
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrowSetupExceptionAndNotDoSetupIfSetupInProgressNodeExists() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    setupServerIdSelectionMocks();
    setupSetupInProgressPathMocks(ZooDefs.Ids.OPEN_ACL_UNSAFE, mock(Stat.class));

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);

    try {
        setupSteps.runSetup();
    } catch (Exception e) {
        assertTrue(e instanceof SetupException);
    }

    verifyZeroInteractions(setupStep1);
}
 
Example #3
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteSetupInProgressNodeAfterCompletion() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    DeleteBuilder deleteBuilder = setupSetupInProgressPathMocks(aclList).getRight();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(deleteBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE);
}
 
Example #4
Source File: ZookeeperCompensationServiceImpl.java    From hmily with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean updateRetry(final String id, final Integer retry, final String appName) {
    if (StringUtils.isBlank(id) || StringUtils.isBlank(appName) || Objects.isNull(retry)) {
        return Boolean.FALSE;
    }
    final String rootPathPrefix = RepositoryPathUtils.buildZookeeperPathPrefix(appName);
    final String path = RepositoryPathUtils.buildZookeeperRootPath(rootPathPrefix, id);
    try {
        byte[] content = zooKeeper.getData(path,
                false, new Stat());
        final CoordinatorRepositoryAdapter adapter =
                objectSerializer.deSerialize(content, CoordinatorRepositoryAdapter.class);
        adapter.setLastTime(DateUtils.getDateYYYY());
        adapter.setRetriedCount(retry);
        zooKeeper.create(path,
                objectSerializer.serialize(adapter),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        return Boolean.TRUE;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Boolean.FALSE;
}
 
Example #5
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRunRegisteredSetupSteps() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    SetupStep setupStep2 = mock(SetupStep.class);
    steps.add(setupStep1);
    steps.add(setupStep2);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    setupServerIdSelectionMocks();
    setupSetupInProgressPathMocks(ZooDefs.Ids.OPEN_ACL_UNSAFE);

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(setupStep1).run();
    verify(setupStep2).run();
}
 
Example #6
Source File: ZookeeperCoordinatorRepository.java    From myth with Apache License 2.0 6 votes vote down vote up
private void connect(final MythZookeeperConfig config) {
    try {
        zooKeeper = new ZooKeeper(config.getHost(), config.getSessionTimeOut(), watchedEvent -> {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                // 放开闸门, wait在connect方法上的线程将被唤醒
                LATCH.countDown();
            }
        });
        LATCH.await();
        Stat stat = zooKeeper.exists(rootPathPrefix, false);
        if (stat == null) {
            zooKeeper.create(rootPathPrefix, rootPathPrefix.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    } catch (Exception e) {
        LogUtil.error(LOGGER, "zookeeper init error please check you config!:{}", e::getMessage);
        throw new MythRuntimeException(e);
    }

}
 
Example #7
Source File: ZkDistributeLock.java    From azeroth with Apache License 2.0 6 votes vote down vote up
/**
 * @param zkServers
 * @param lockName
 * @param sessionTimeout
 */
public ZkDistributeLock(String zkServers, String lockName, int sessionTimeout) {
    if (lockName.contains(LOCK_KEY_SUFFIX)) {
        throw new LockException("lockName 不能包含[" + LOCK_KEY_SUFFIX + "]");
    }
    this.lockName = lockName;
    this.sessionTimeout = sessionTimeout;
    try {
        zk = new ZooKeeper(zkServers, sessionTimeout, this);
        Stat stat = zk.exists(ROOT_PATH, false);
        if (stat == null) {
            // 创建根节点
            zk.create(ROOT_PATH, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    } catch (Exception e) {
        throw new LockException(e);
    }
}
 
Example #8
Source File: ZKManager.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
	zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
			.toString()), Integer.parseInt(this.properties
			.getProperty(keys.zkSessionTimeout.toString())),
			new Watcher() {
				public void process(WatchedEvent event) {
					sessionEvent(connectionLatch, event);
				}
			});
	String authString = this.properties.getProperty(keys.userName.toString())
			+ ":"+ this.properties.getProperty(keys.password.toString());
	this.isCheckParentPath = Boolean.parseBoolean(this.properties.getProperty(keys.isCheckParentPath.toString(),"true"));
	zk.addAuthInfo("digest", authString.getBytes());
	acl.clear();
	acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
			DigestAuthenticationProvider.generateDigest(authString))));
	acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #9
Source File: ZookeeperRecoverTransactionServiceImpl.java    From Raincat with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Boolean updateRetry(final String id, final Integer retry, final String applicationName) {
    if (StringUtils.isBlank(id) || StringUtils.isBlank(applicationName) || Objects.isNull(retry)) {
        return Boolean.FALSE;
    }
    final String rootPath = RepositoryPathUtils.buildZookeeperPath(applicationName);
    final String path = buildRootPath(rootPath, id);
    try {
        byte[] content = zooKeeper.getData(path,
                false, new Stat());
        final TransactionRecoverAdapter adapter =
                objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
        adapter.setLastTime(DateUtils.getDateYYYY());
        adapter.setRetriedCount(retry);
        zooKeeper.create(path,
                objectSerializer.serialize(adapter),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        return Boolean.TRUE;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Boolean.FALSE;
}
 
Example #10
Source File: ZookeeperClient.java    From doctorkafka with Apache License 2.0 6 votes vote down vote up
public boolean createIfNotExists(String path) {
  int numRetries = 0;
  while (numRetries < MAX_RETRIES) {
    try {
      Stat stat = curator.checkExists().forPath(path);
      if (stat == null) {
        curator.create()
            .creatingParentsIfNeeded()
            .withMode(CreateMode.PERSISTENT)
            .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
            .forPath(path);
      }
      return true;
    } catch (Exception e) {
      LOG.error("Failed to create zk path {}", path, e);
      numRetries++;
      waitBetweenRetries(numRetries);
    }
  }
  return false;
}
 
Example #11
Source File: ZookeeperTransactionRecoverRepository.java    From Raincat with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void connect(final TxZookeeperConfig config) {
    try {
        zooKeeper = new ZooKeeper(config.getHost(), config.getSessionTimeOut(), watchedEvent -> {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                COUNT_DOWN_LATCH.countDown();
            }
        });
        COUNT_DOWN_LATCH.await();
        Stat stat = zooKeeper.exists(rootPath, false);
        if (stat == null) {
            zooKeeper.create(rootPath, rootPath.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    } catch (Exception e) {
        throw new TransactionIoException(e);
    }
}
 
Example #12
Source File: ZKManager.java    From tbschedule with Apache License 2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
    zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString.toString()),
        Integer.parseInt(this.properties.getProperty(keys.zkSessionTimeout.toString())),
        new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                sessionEvent(connectionLatch, event);
            }
        });
    String authString = this.properties.getProperty(keys.userName.toString()) + ":" + this.properties
        .getProperty(keys.password.toString());
    this.isCheckParentPath = Boolean
        .parseBoolean(this.properties.getProperty(keys.isCheckParentPath.toString(), "true"));
    zk.addAuthInfo("digest", authString.getBytes());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #13
Source File: ZkInstance.java    From libevent with Apache License 2.0 6 votes vote down vote up
private boolean tryLockWhenConnectionLoss(String clientId, String resource)
        throws KeeperException, InterruptedException {

    try{
        zk.create(resource, clientId.getBytes(Charset.forName("utf-8")),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        return true;
    } catch(KeeperException e) {
        if (e.code().equals(KeeperException.Code.NODEEXISTS)) {
            return this.checkNode(clientId, resource);
        } else if (e.code().equals(KeeperException.Code.CONNECTIONLOSS)) {
            return this.tryLockWhenConnectionLoss(clientId, resource);
        } else {
            throw e;
        }
    }
}
 
Example #14
Source File: TestLockACLs.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testLockACLs() throws Exception
{
    CuratorFramework client = createClient(new TestLockACLsProvider());
    try
    {
        client.create().forPath("/foo");
        Assert.assertNotNull(client.checkExists().forPath("/foo"));
        Assert.assertEquals(ZooDefs.Perms.ALL, client.getACL().forPath("/foo").get(0).getPerms());
        Assert.assertEquals("ip", client.getACL().forPath("/foo").get(0).getId().getScheme());
        Assert.assertEquals("127.0.0.1", client.getACL().forPath("/foo").get(0).getId().getId());

        InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/bar");
        InterProcessMutex writeLock = lock.writeLock();
        writeLock.acquire();
        Assert.assertNotNull(client.checkExists().forPath("/bar"));
        Assert.assertEquals(ZooDefs.Perms.ALL, client.getACL().forPath("/bar").get(0).getPerms());
        Assert.assertEquals("ip", client.getACL().forPath("/bar").get(0).getId().getScheme());
        Assert.assertEquals("127.0.0.1", client.getACL().forPath("/bar").get(0).getId().getId());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #15
Source File: ZookeeperCoordinatorRepository.java    From hmily with Apache License 2.0 6 votes vote down vote up
private void connect(final HmilyZookeeperConfig config) {
    try {
        zooKeeper = new ZooKeeper(config.getHost(), config.getSessionTimeOut(), watchedEvent -> {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                LATCH.countDown();
            }
        });
        LATCH.await();
        Stat stat = zooKeeper.exists(rootPathPrefix, false);
        if (stat == null) {
            zooKeeper.create(rootPathPrefix, rootPathPrefix.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    } catch (Exception e) {
        throw new HmilyRuntimeException(e);
    }
}
 
Example #16
Source File: ZookeeperLogServiceImpl.java    From myth with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean updateRetry(final String id, final Integer retry, final String appName) {
    if (StringUtils.isBlank(id) || StringUtils.isBlank(appName)
            || Objects.isNull(retry)) {
        return Boolean.FALSE;
    }
    final String rootPathPrefix = RepositoryPathUtils.buildZookeeperPathPrefix(appName);
    final String path = RepositoryPathUtils.buildZookeeperRootPath(rootPathPrefix, id);
    try {
        byte[] content = zooKeeper.getData(path,
                false, new Stat());
        final CoordinatorRepositoryAdapter adapter =
                objectSerializer.deSerialize(content, CoordinatorRepositoryAdapter.class);
        adapter.setLastTime(DateUtils.getDateYYYY());
        adapter.setRetriedCount(retry);
        zooKeeper.create(path,
                objectSerializer.serialize(adapter),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        return Boolean.TRUE;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Boolean.FALSE;
}
 
Example #17
Source File: BasicTests.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void     testReconnect() throws Exception
{
    CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
    client.start();
    try
    {
        client.blockUntilConnectedOrTimedOut();

        byte[]      writtenData = {1, 2, 3};
        client.getZooKeeper().create("/test", writtenData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        Thread.sleep(1000);
        server.stop();
        Thread.sleep(1000);

        server.restart();
        Assert.assertTrue(client.blockUntilConnectedOrTimedOut());
        byte[]      readData = client.getZooKeeper().getData("/test", false, null);
        Assert.assertEquals(readData, writtenData);
    }
    finally
    {
        client.close();
    }
}
 
Example #18
Source File: LogSearchConfigZKHelper.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Pares ZK ACL permission string and transform it to an integer
 * @param permission string input (permission) that will be transformed to an integer
 * @return Integer code of a zookeeper ACL
 */
public static Integer parsePermission(String permission) {
  int permissionCode = 0;
  for (char each : permission.toLowerCase().toCharArray()) {
    switch (each) {
      case 'r':
        permissionCode |= ZooDefs.Perms.READ;
        break;
      case 'w':
        permissionCode |= ZooDefs.Perms.WRITE;
        break;
      case 'c':
        permissionCode |= ZooDefs.Perms.CREATE;
        break;
      case 'd':
        permissionCode |= ZooDefs.Perms.DELETE;
        break;
      case 'a':
        permissionCode |= ZooDefs.Perms.ADMIN;
        break;
      default:
        throw new IllegalArgumentException("Unsupported permission: " + permission);
    }
  }
  return permissionCode;
}
 
Example #19
Source File: ZooLog.java    From zooadmin with MIT License 5 votes vote down vote up
public static String op2String(int op) {
    switch (op) {
        case ZooDefs.OpCode.notification:
            return "notification";
        case ZooDefs.OpCode.create:
            return "create";
        case ZooDefs.OpCode.delete:
            return "delete";
        case ZooDefs.OpCode.exists:
            return "exists";
        case ZooDefs.OpCode.getData:
            return "getDate";
        case ZooDefs.OpCode.setData:
            return "setData";
        case ZooDefs.OpCode.multi:
            return "multi";
        case ZooDefs.OpCode.getACL:
            return "getACL";
        case ZooDefs.OpCode.setACL:
            return "setACL";
        case ZooDefs.OpCode.getChildren:
            return "getChildren";
        case ZooDefs.OpCode.getChildren2:
            return "getChildren2";
        case ZooDefs.OpCode.ping:
            return "ping";
        case ZooDefs.OpCode.createSession:
            return "createSession";
        case ZooDefs.OpCode.closeSession:
            return "closeSession";
        case ZooDefs.OpCode.error:
            return "error";
        default:
            return "unknown " + op;
    }
}
 
Example #20
Source File: TestRegistrySecurityHelper.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testBuildAclsNullRealm() throws Throwable {
  registrySecurity.buildACLs(
      SASL_YARN_SHORT +
      ", " +
      SASL_MAPRED_SHORT,
      "", ZooDefs.Perms.ALL);
  fail("");

}
 
Example #21
Source File: ZookeeperAuthBoltServerTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 获取默认的AclProvider
 *
 * @return
 */
private static ACLProvider getDefaultAclProvider() {
    return new ACLProvider() {
        @Override
        public List<ACL> getDefaultAcl() {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }

        @Override
        public List<ACL> getAclForPath(String path) {
            return ZooDefs.Ids.CREATOR_ALL_ACL;
        }
    };
}
 
Example #22
Source File: AtlasZookeeperSecurityPropertiesTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetAcl() {
    ACL acl = AtlasZookeeperSecurityProperties.parseAcl("sasl:[email protected]");
    assertEquals(acl.getId().getScheme(), "sasl");
    assertEquals(acl.getId().getId(), "[email protected]");
    assertEquals(acl.getPerms(), ZooDefs.Perms.ALL);
}
 
Example #23
Source File: ServiceRegistry.java    From lionrpc with Apache License 2.0 5 votes vote down vote up
private void createNode(ZooKeeper zk, String data) {
    try {
        byte[] bytes = data.getBytes();
        String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        LOGGER.debug("create zookeeper node ({} => {})", path, data);
    } catch (KeeperException e) {
        LOGGER.error("", e);
    }
    catch (InterruptedException ex){
        LOGGER.error("", ex);
    }
}
 
Example #24
Source File: ActiveInstanceStateTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedPathIsCreatedIfNotExists() throws Exception {

    when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT);
    when(configuration.getString(
            HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);

    when(curatorFactory.clientInstance()).thenReturn(curatorFramework);

    ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
    when(curatorFramework.checkExists()).thenReturn(existsBuilder);
    when(existsBuilder.forPath(getPath())).thenReturn(null);

    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(curatorFramework.create()).thenReturn(createBuilder);
    when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder);
    when(createBuilder.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)).thenReturn(createBuilder);

    SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
    when(curatorFramework.setData()).thenReturn(setDataBuilder);

    ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory);
    activeInstanceState.update("id1");

    verify(createBuilder).forPath(getPath());
}
 
Example #25
Source File: CuratorService.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Add a new write access entry for all future write operations.
 * @param id ID to use
 * @param pass password
 * @throws IOException on any failure to build the digest
 */
public boolean addWriteAccessor(String id, String pass) throws IOException {
  RegistrySecurity security = getRegistrySecurity();
  ACL digestACL = new ACL(ZooDefs.Perms.ALL,
      security.toDigestId(security.digest(id, pass)));
  return security.addDigestACL(digestACL);
}
 
Example #26
Source File: ZkService.java    From DBus with Apache License 2.0 5 votes vote down vote up
/**
 * createNodeWithACL
 * Create a node under ACL mode
 *
 * @param path
 * @param payload
 * @throws Exception
 */
public void createNodeWithACL(String path, byte[] payload) throws Exception {
    ACL acl = new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.AUTH_IDS);
    List<ACL> aclList = Lists.newArrayList(acl);
    try {
        client.create().withACL(aclList).forPath(path, payload);
    } catch (Exception e) {
        logger.error("Create security file failed.");
        e.printStackTrace();
    }
}
 
Example #27
Source File: TestNamespaceFacade.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Test that ACLs work on a NamespaceFacade. See CURATOR-132
 * @throws Exception
 */
@Test
public void testACL() throws Exception
{
    CuratorFramework    client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    client.getZookeeperClient().blockUntilConnectedOrTimedOut();

    client.create().creatingParentsIfNeeded().forPath("/parent/child", "A string".getBytes());
    CuratorFramework client2 = client.usingNamespace("parent");

    Assert.assertNotNull(client2.getData().forPath("/child"));  
    client.setACL().withACL(Collections.singletonList(
        new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.ANYONE_ID_UNSAFE))).
            forPath("/parent/child");
    // This will attempt to setACL on /parent/child, Previously this failed because /child
    // isn't present. Using "child" would case a failure because the path didn't start with
    // a slash
    try
    {
        List<ACL> acls = client2.getACL().forPath("/child");
        Assert.assertNotNull(acls);
        Assert.assertEquals(acls.size(), 1);
        Assert.assertEquals(acls.get(0).getId(), ZooDefs.Ids.ANYONE_ID_UNSAFE);
        Assert.assertEquals(acls.get(0).getPerms(), ZooDefs.Perms.WRITE);
        client2.setACL().withACL(Collections.singletonList(
            new ACL(ZooDefs.Perms.DELETE, ZooDefs.Ids.ANYONE_ID_UNSAFE))).
                forPath("/child");
        Assert.fail("Expected auth exception was not thrown");
    }
    catch(NoAuthException e)
    {
        //Expected
    }
}
 
Example #28
Source File: ZookeeperCoordinatorRepository.java    From myth with Apache License 2.0 5 votes vote down vote up
@Override
public int create(final MythTransaction mythTransaction) {
    try {
        zooKeeper.create(buildRootPath(mythTransaction.getTransId()),
                RepositoryConvertUtils.convert(mythTransaction, objectSerializer),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        return CommonConstant.SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();
        return CommonConstant.ERROR;
    }
}
 
Example #29
Source File: CuratorTransactionImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
private CuratorTransactionResult makeCuratorResult(OpResult opResult, CuratorMultiTransactionRecord.TypeAndPath metadata)
{
    String                                      resultPath = null;
    Stat resultStat = null;
    switch ( opResult.getType() )
    {
        default:
        {
            // NOP
            break;
        }

        case ZooDefs.OpCode.create:
        {
            OpResult.CreateResult       createResult = (OpResult.CreateResult)opResult;
            resultPath = client.unfixForNamespace(createResult.getPath());
            break;
        }

        case ZooDefs.OpCode.setData:
        {
            OpResult.SetDataResult      setDataResult = (OpResult.SetDataResult)opResult;
            resultStat = setDataResult.getStat();
            break;
        }
    }

    return new CuratorTransactionResult(metadata.type, metadata.forPath, resultPath, resultStat);
}
 
Example #30
Source File: ZookeeperTransactionRecoverRepository.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int create(final TransactionRecover transactionRecover) {
    try {
        zooKeeper.create(getRootPath(transactionRecover.getId()),
                TransactionRecoverUtils.convert(transactionRecover, objectSerializer),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        return ROWS;
    } catch (Exception e) {
        throw new TransactionIoException(e);
    }
}