Examples of InMemoryZKServer


Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

  @ClassRule
  public static TemporaryFolder tmpFolder = new TemporaryFolder();

  @Test
  public void testChroot() throws Exception {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setTickTime(1000).build();
    zkServer.startAndWait();

    try {
      ZKClientService client = ZKClientService.Builder.of(zkServer.getConnectionStr() + "/chroot").build();
      client.startAndWait();
      try {
        List<OperationFuture<String>> futures = Lists.newArrayList();
        futures.add(client.create("/test1/test2", null, CreateMode.PERSISTENT));
        futures.add(client.create("/test1/test3", null, CreateMode.PERSISTENT));
        Futures.successfulAsList(futures).get();

        Assert.assertNotNull(client.exists("/test1/test2").get());
        Assert.assertNotNull(client.exists("/test1/test3").get());

      } finally {
        client.stopAndWait();
      }
    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

    }
  }

  @Test
  public void testCreateParent() throws ExecutionException, InterruptedException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setTickTime(1000).build();
    zkServer.startAndWait();

    try {
      ZKClientService client = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
      client.startAndWait();

      try {
        String path = client.create("/test1/test2/test3/test4/test5",
                                    "testing".getBytes(), CreateMode.PERSISTENT_SEQUENTIAL).get();
        Assert.assertTrue(path.startsWith("/test1/test2/test3/test4/test5"));

        String dataPath = "";
        for (int i = 1; i <= 4; i++) {
          dataPath = dataPath + "/test" + i;
          Assert.assertNull(client.getData(dataPath).get().getData());
        }
        Assert.assertTrue(Arrays.equals("testing".getBytes(), client.getData(path).get().getData()));
      } finally {
        client.stopAndWait();
      }
    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

    }
  }

  @Test
  public void testGetChildren() throws ExecutionException, InterruptedException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setTickTime(1000).build();
    zkServer.startAndWait();

    try {
      ZKClientService client = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
      client.startAndWait();

      try {
        client.create("/test", null, CreateMode.PERSISTENT).get();
        Assert.assertTrue(client.getChildren("/test").get().getChildren().isEmpty());

        Futures.allAsList(ImmutableList.of(client.create("/test/c1", null, CreateMode.EPHEMERAL),
                                           client.create("/test/c2", null, CreateMode.EPHEMERAL))).get();

        NodeChildren nodeChildren = client.getChildren("/test").get();
        Assert.assertEquals(2, nodeChildren.getChildren().size());

        Assert.assertEquals(ImmutableSet.of("c1", "c2"), ImmutableSet.copyOf(nodeChildren.getChildren()));

      } finally {
        client.stopAndWait();
      }
    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

    }
  }

  @Test
  public void testSetData() throws ExecutionException, InterruptedException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setTickTime(1000).build();
    zkServer.startAndWait();

    try {
      ZKClientService client = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
      client.startAndWait();

      client.create("/test", null, CreateMode.PERSISTENT).get();
      Assert.assertNull(client.getData("/test").get().getData());

      client.setData("/test", "testing".getBytes()).get();
      Assert.assertTrue(Arrays.equals("testing".getBytes(), client.getData("/test").get().getData()));

    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

    }
  }

  @Test
  public void testExpireRewatch() throws InterruptedException, IOException, ExecutionException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setTickTime(1000).build();
    zkServer.startAndWait();

    try {
      final CountDownLatch expireReconnectLatch = new CountDownLatch(1);
      final AtomicBoolean expired = new AtomicBoolean(false);
      final ZKClientService client = ZKClientServices.delegate(ZKClients.reWatchOnExpire(
                                        ZKClientService.Builder.of(zkServer.getConnectionStr())
                                                       .setSessionTimeout(2000)
                                                       .setConnectionWatcher(new Watcher() {
            @Override
            public void process(WatchedEvent event) {
              if (event.getState() == Event.KeeperState.Expired) {
                expired.set(true);
              } else if (event.getState() == Event.KeeperState.SyncConnected && expired.compareAndSet(true, true)) {
                expireReconnectLatch.countDown();
              }
            }
          }).build()));
      client.startAndWait();

      try {
        final BlockingQueue<Watcher.Event.EventType> events = new LinkedBlockingQueue<Watcher.Event.EventType>();
        client.exists("/expireRewatch", new Watcher() {
          @Override
          public void process(WatchedEvent event) {
            client.exists("/expireRewatch", this);
            events.add(event.getType());
          }
        });

        client.create("/expireRewatch", null, CreateMode.PERSISTENT);
        Assert.assertEquals(Watcher.Event.EventType.NodeCreated, events.poll(2, TimeUnit.SECONDS));

        KillZKSession.kill(client.getZooKeeperSupplier().get(), zkServer.getConnectionStr(), 1000);

        Assert.assertTrue(expireReconnectLatch.await(5, TimeUnit.SECONDS));

        client.delete("/expireRewatch");
        Assert.assertEquals(Watcher.Event.EventType.NodeDeleted, events.poll(4, TimeUnit.SECONDS));
      } finally {
        client.stopAndWait();
      }
    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

  }

  @Test
  public void testRetry() throws ExecutionException, InterruptedException, TimeoutException, IOException {
    File dataDir = tmpFolder.newFolder();
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setDataDir(dataDir).setTickTime(1000).build();
    zkServer.startAndWait();
    int port = zkServer.getLocalAddress().getPort();

    final CountDownLatch disconnectLatch = new CountDownLatch(1);
    ZKClientService client = ZKClientServices.delegate(ZKClients.retryOnFailure(
      ZKClientService.Builder.of(zkServer.getConnectionStr()).setConnectionWatcher(new Watcher() {
      @Override
      public void process(WatchedEvent event) {
        if (event.getState() == Event.KeeperState.Disconnected) {
          disconnectLatch.countDown();
        }
      }
    }).build(), RetryStrategies.fixDelay(0, TimeUnit.SECONDS)));
    client.startAndWait();

    zkServer.stopAndWait();

    Assert.assertTrue(disconnectLatch.await(1, TimeUnit.SECONDS));

    final CountDownLatch createLatch = new CountDownLatch(1);
    Futures.addCallback(client.create("/testretry/test", null, CreateMode.PERSISTENT), new FutureCallback<String>() {
      @Override
      public void onSuccess(String result) {
        createLatch.countDown();
      }

      @Override
      public void onFailure(Throwable t) {
        t.printStackTrace(System.out);
      }
    });

    TimeUnit.SECONDS.sleep(2);
    zkServer = InMemoryZKServer.builder()
                               .setDataDir(dataDir)
                               .setAutoCleanDataDir(true)
                               .setPort(port)
                               .setTickTime(1000)
                               .build();
    zkServer.startAndWait();

    try {
      Assert.assertTrue(createLatch.await(5, TimeUnit.SECONDS));
    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

    }
  }

  @Test
  public void testACL() throws IOException, ExecutionException, InterruptedException, NoSuchAlgorithmException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setDataDir(tmpFolder.newFolder()).setTickTime(1000).build();
    zkServer.startAndWait();

    try {
      String userPass = "user:pass";
      String digest = DigestAuthenticationProvider.generateDigest(userPass);

      // Creates two zkclients
      ZKClientService zkClient = ZKClientService.Builder
                                                .of(zkServer.getConnectionStr())
                                                .addAuthInfo("digest", userPass.getBytes())
                                                .build();
      zkClient.startAndWait();

      ZKClientService noAuthClient = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
      noAuthClient.startAndWait();


      // Create a node that is readable by all client, but admin for the creator
      String path = "/testacl";
      zkClient.create(path, "test".getBytes(), CreateMode.PERSISTENT,
                      ImmutableList.of(
                        new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE),
                        new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.AUTH_IDS)
                      )).get();

      // Verify the ACL
      ACLData aclData = zkClient.getACL(path).get();
      Assert.assertEquals(2, aclData.getACL().size());
      ACL acl = aclData.getACL().get(1);
      Assert.assertEquals(ZooDefs.Perms.ALL, acl.getPerms());
      Assert.assertEquals("digest", acl.getId().getScheme());
      Assert.assertEquals(digest, acl.getId().getId());

      Assert.assertEquals("test", new String(noAuthClient.getData(path).get().getData()));

      // When tries to write using the no-auth zk client, it should fail.
      try {
        noAuthClient.setData(path, "test2".getBytes()).get();
        Assert.fail();
      } catch (ExecutionException e) {
        Assert.assertTrue(e.getCause() instanceof KeeperException.NoAuthException);
      }

      // Change ACL to make it open for all
      zkClient.setACL(path, ImmutableList.of(new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.ANYONE_ID_UNSAFE))).get();

      // Write again with the non-auth client, now should succeed.
      noAuthClient.setData(path, "test2".getBytes()).get();

      noAuthClient.stopAndWait();
      zkClient.stopAndWait();

    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

  private static final Logger LOG = LoggerFactory.getLogger(ZKServiceDecoratorTest.class);

  @Test
  public void testStateTransition() throws InterruptedException, ExecutionException, TimeoutException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().build();
    zkServer.startAndWait();

    try {
      final String namespace = Joiner.on('/').join("/twill", RunIds.generate(), "runnables", "Runner1");

      final ZKClientService zkClient = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
      zkClient.startAndWait();
      zkClient.create(namespace, null, CreateMode.PERSISTENT).get();

      try {
        JsonObject content = new JsonObject();
        content.addProperty("containerId", "container-123");
        content.addProperty("host", "localhost");

        RunId runId = RunIds.generate();
        final Semaphore semaphore = new Semaphore(0);
        ZKServiceDecorator service = new ZKServiceDecorator(ZKClients.namespace(zkClient, namespace),
                                                            runId, Suppliers.ofInstance(content),
                                                            new AbstractIdleService() {
          @Override
          protected void startUp() throws Exception {
            Preconditions.checkArgument(semaphore.tryAcquire(5, TimeUnit.SECONDS), "Fail to start");
          }

          @Override
          protected void shutDown() throws Exception {
            Preconditions.checkArgument(semaphore.tryAcquire(5, TimeUnit.SECONDS), "Fail to stop");
          }
        });

        final String runnablePath = namespace + "/" + runId.getId();
        final AtomicReference<String> stateMatch = new AtomicReference<String>("STARTING");
        watchDataChange(zkClient, runnablePath + "/state", semaphore, stateMatch);
        Assert.assertEquals(Service.State.RUNNING, service.start().get(5, TimeUnit.SECONDS));

        stateMatch.set("STOPPING");
        Assert.assertEquals(Service.State.TERMINATED, service.stop().get(5, TimeUnit.SECONDS));

      } finally {
        zkClient.stopAndWait();
      }
    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

  private static final Logger LOG = LoggerFactory.getLogger(ControllerTest.class);

  @Test
  public void testController() throws ExecutionException, InterruptedException, TimeoutException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().build();
    zkServer.startAndWait();

    LOG.info("ZKServer: " + zkServer.getConnectionStr());

    try {
      RunId runId = RunIds.generate();
      ZKClientService zkClientService = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
      zkClientService.startAndWait();

      Service service = createService(zkClientService, runId);
      service.startAndWait();

      TwillController controller = getController(zkClientService, runId);
      controller.sendCommand(Command.Builder.of("test").build()).get(2, TimeUnit.SECONDS);
      controller.stop().get(2, TimeUnit.SECONDS);

      Assert.assertEquals(ServiceController.State.TERMINATED, controller.state());

      final CountDownLatch terminateLatch = new CountDownLatch(1);
      service.addListener(new ServiceListenerAdapter() {
        @Override
        public void terminated(Service.State from) {
          terminateLatch.countDown();
        }
      }, Threads.SAME_THREAD_EXECUTOR);

      Assert.assertTrue(service.state() == Service.State.TERMINATED || terminateLatch.await(2, TimeUnit.SECONDS));

      zkClientService.stopAndWait();

    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here

Examples of org.apache.twill.internal.zookeeper.InMemoryZKServer

  }

  // Test controller created before service starts.
  @Test
  public void testControllerBefore() throws InterruptedException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().build();
    zkServer.startAndWait();

    LOG.info("ZKServer: " + zkServer.getConnectionStr());
    try {
      RunId runId = RunIds.generate();
      ZKClientService zkClientService = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
      zkClientService.startAndWait();

      final CountDownLatch runLatch = new CountDownLatch(1);
      final CountDownLatch stopLatch = new CountDownLatch(1);
      TwillController controller = getController(zkClientService, runId);
      controller.addListener(new ServiceListenerAdapter() {
        @Override
        public void running() {
          runLatch.countDown();
        }

        @Override
        public void terminated(Service.State from) {
          stopLatch.countDown();
        }
      }, Threads.SAME_THREAD_EXECUTOR);

      Service service = createService(zkClientService, runId);
      service.start();

      Assert.assertTrue(runLatch.await(2, TimeUnit.SECONDS));
      Assert.assertFalse(stopLatch.await(2, TimeUnit.SECONDS));

      service.stop();

      Assert.assertTrue(stopLatch.await(2, TimeUnit.SECONDS));

    } finally {
      zkServer.stopAndWait();
    }
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.