Search in sources :

Example 11 with Client

use of io.etcd.jetcd.Client in project dubbo by alibaba.

the class JEtcdClientTest method testWatchWithGrpc.

@Test
public void testWatchWithGrpc() {
    String path = "/dubbo/config/test_watch_with_grpc/configurators";
    String endpoint = "http://127.0.0.1:2379";
    CountDownLatch latch = new CountDownLatch(1);
    try (Client client = Client.builder().endpoints(endpoint).build()) {
        ManagedChannel channel = getChannel(client);
        StreamObserver<WatchRequest> observer = WatchGrpc.newStub(channel).watch(new StreamObserver<WatchResponse>() {

            @Override
            public void onNext(WatchResponse response) {
                for (Event event : response.getEventsList()) {
                    Assertions.assertEquals("PUT", event.getType().toString());
                    Assertions.assertEquals(path, event.getKv().getKey().toString(UTF_8));
                    Assertions.assertEquals("Hello", event.getKv().getValue().toString(UTF_8));
                    latch.countDown();
                }
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onCompleted() {
            }
        });
        WatchCreateRequest.Builder builder = WatchCreateRequest.newBuilder().setKey(ByteString.copyFrom(path, UTF_8));
        observer.onNext(WatchRequest.newBuilder().setCreateRequest(builder).build());
        // try to modify the key
        client.getKVClient().put(ByteSequence.from(path, UTF_8), ByteSequence.from("Hello", UTF_8));
        latch.await(5, TimeUnit.SECONDS);
    } catch (Exception e) {
        Assertions.fail(e.getMessage());
    }
}
Also used : WatchRequest(io.etcd.jetcd.api.WatchRequest) ByteString(com.google.protobuf.ByteString) CountDownLatch(java.util.concurrent.CountDownLatch) WatchResponse(io.etcd.jetcd.api.WatchResponse) ClosedClientException(io.etcd.jetcd.common.exception.ClosedClientException) WatchCreateRequest(io.etcd.jetcd.api.WatchCreateRequest) ManagedChannel(io.grpc.ManagedChannel) WatchEvent(io.etcd.jetcd.watch.WatchEvent) Event(io.etcd.jetcd.api.Event) Client(io.etcd.jetcd.Client) Test(org.junit.jupiter.api.Test)

Example 12 with Client

use of io.etcd.jetcd.Client in project jetcd by coreos.

the class ElectionTest method testSynchronizationBarrier.

@Test
public void testSynchronizationBarrier() throws Exception {
    final int threadCount = 5;
    final Random random = new Random();
    ByteSequence electionName = ByteSequence.from(randomString(), StandardCharsets.UTF_8);
    final AtomicInteger sharedVariable = new AtomicInteger(0);
    // create separate clients so they will compete for access to shared resource
    List<Client> clients = new ArrayList<>(threadCount);
    List<Long> leases = new ArrayList<>(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Client client = TestUtil.client(cluster).build();
        long leaseId = client.getLeaseClient().grant(100).get().getID();
        clients.add(client);
        leases.add(leaseId);
    }
    ExecutorService executor = Executors.newFixedThreadPool(threadCount);
    List<Future<?>> futures = new ArrayList<>(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        final int id = i;
        final ByteSequence proposal = ByteSequence.from(Integer.toString(id), StandardCharsets.UTF_8);
        futures.add(executor.submit(() -> {
            try {
                Election electionClient = clients.get(id).getElectionClient();
                CampaignResponse campaignResponse = electionClient.campaign(electionName, leases.get(id), proposal).get(OPERATION_TIMEOUT, TimeUnit.SECONDS);
                int localCopy = sharedVariable.get();
                Thread.sleep(200 + random.nextInt(300));
                sharedVariable.set(localCopy + 1);
                electionClient.resign(campaignResponse.getLeader()).get(OPERATION_TIMEOUT, TimeUnit.SECONDS);
            } catch (Exception e) {
                fail("Unexpected error in thread {}: {}", id, e);
            }
        }));
    }
    executor.shutdown();
    executor.awaitTermination(threadCount * OPERATION_TIMEOUT, TimeUnit.SECONDS);
    futures.forEach(f -> assertThat(f).isDone());
    assertThat(sharedVariable.get()).isEqualTo(threadCount);
    GetOption getOption = GetOption.newBuilder().isPrefix(true).build();
    assertThat(kvClient.get(electionName, getOption).get().getCount()).isEqualTo(0L);
    for (int i = 0; i < threadCount; ++i) {
        clients.get(i).getLeaseClient().revoke(leases.get(i)).get();
        clients.get(i).close();
    }
}
Also used : CampaignResponse(io.etcd.jetcd.election.CampaignResponse) ArrayList(java.util.ArrayList) Election(io.etcd.jetcd.Election) NoLeaderException(io.etcd.jetcd.election.NoLeaderException) NotLeaderException(io.etcd.jetcd.election.NotLeaderException) ExecutionException(java.util.concurrent.ExecutionException) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) GetOption(io.etcd.jetcd.options.GetOption) Future(java.util.concurrent.Future) Client(io.etcd.jetcd.Client) ByteSequence(io.etcd.jetcd.ByteSequence) TestUtil.randomByteSequence(io.etcd.jetcd.impl.TestUtil.randomByteSequence) Test(org.junit.jupiter.api.Test)

Example 13 with Client

use of io.etcd.jetcd.Client in project jetcd by coreos.

the class ElectionTest method setUp.

@BeforeAll
public static void setUp() {
    Client client = TestUtil.client(cluster).build();
    electionClient = client.getElectionClient();
    leaseClient = client.getLeaseClient();
    kvClient = client.getKVClient();
}
Also used : Client(io.etcd.jetcd.Client) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 14 with Client

use of io.etcd.jetcd.Client in project jetcd by coreos.

the class KVTest method waitForReadySemantics.

@Test()
public void waitForReadySemantics() throws ExecutionException, InterruptedException, TimeoutException {
    String nonExistingServer = "http://127.0.0.1:9999";
    try (Client customClient = Client.builder().endpoints(nonExistingServer).waitForReady(false).retryMaxDuration(Duration.ofSeconds(3)).retryDelay(1).retryMaxDelay(2).retryChronoUnit(ChronoUnit.SECONDS).connectTimeout(Duration.ofSeconds(1)).build()) {
        KV kvClient = customClient.getKVClient();
        CompletableFuture<String> future = kvClient.get(ByteSequence.from("/x", StandardCharsets.UTF_8)).thenApply(response -> "we got a response").exceptionally(throwable -> "completed exceptionally");
        assertThat(future.get(5, TimeUnit.SECONDS)).isEqualTo("completed exceptionally");
    }
}
Also used : DeleteOption(io.etcd.jetcd.options.DeleteOption) AssertionsForClassTypes.assertThatExceptionOfType(org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType) Cmp(io.etcd.jetcd.op.Cmp) Client(io.etcd.jetcd.Client) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) EtcdClusterExtension(io.etcd.jetcd.test.EtcdClusterExtension) UTF_8(com.google.common.base.Charsets.UTF_8) TxnResponse(io.etcd.jetcd.kv.TxnResponse) DeleteResponse(io.etcd.jetcd.kv.DeleteResponse) BeforeAll(org.junit.jupiter.api.BeforeAll) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) ByteSequence(io.etcd.jetcd.ByteSequence) Duration(java.time.Duration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) GetResponse(io.etcd.jetcd.kv.GetResponse) GetOption(io.etcd.jetcd.options.GetOption) KV(io.etcd.jetcd.KV) Op(io.etcd.jetcd.op.Op) PutOption(io.etcd.jetcd.options.PutOption) SortOrder(io.etcd.jetcd.options.GetOption.SortOrder) CmpTarget(io.etcd.jetcd.op.CmpTarget) TestUtil.randomString(io.etcd.jetcd.impl.TestUtil.randomString) SortTarget(io.etcd.jetcd.options.GetOption.SortTarget) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) TestUtil.bytesOf(io.etcd.jetcd.impl.TestUtil.bytesOf) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) Txn(io.etcd.jetcd.Txn) Timeout(org.junit.jupiter.api.Timeout) PutResponse(io.etcd.jetcd.kv.PutResponse) TestUtil.randomString(io.etcd.jetcd.impl.TestUtil.randomString) KV(io.etcd.jetcd.KV) Client(io.etcd.jetcd.Client) Test(org.junit.jupiter.api.Test)

Example 15 with Client

use of io.etcd.jetcd.Client in project jetcd by coreos.

the class CommandWatch method accept.

@Override
public void accept(Client client) throws Exception {
    CountDownLatch latch = new CountDownLatch(maxEvents);
    Watcher watcher = null;
    try {
        ByteSequence watchKey = ByteSequence.from(key, Charsets.UTF_8);
        WatchOption watchOpts = WatchOption.newBuilder().withRevision(rev).build();
        watcher = client.getWatchClient().watch(watchKey, watchOpts, response -> {
            for (WatchEvent event : response.getEvents()) {
                LOGGER.info("type={}, key={}, value={}", event.getEventType().toString(), Optional.ofNullable(event.getKeyValue().getKey()).map(bs -> bs.toString(Charsets.UTF_8)).orElse(""), Optional.ofNullable(event.getKeyValue().getValue()).map(bs -> bs.toString(Charsets.UTF_8)).orElse(""));
            }
            latch.countDown();
        });
        latch.await();
    } catch (Exception e) {
        if (watcher != null) {
            watcher.close();
        }
        throw e;
    }
}
Also used : Charsets(com.google.common.base.Charsets) Parameters(com.beust.jcommander.Parameters) Logger(org.slf4j.Logger) Client(io.etcd.jetcd.Client) WatchEvent(io.etcd.jetcd.watch.WatchEvent) Parameter(com.beust.jcommander.Parameter) LoggerFactory(org.slf4j.LoggerFactory) CountDownLatch(java.util.concurrent.CountDownLatch) ByteSequence(io.etcd.jetcd.ByteSequence) Optional(java.util.Optional) CheckedConsumer(org.jooq.lambda.fi.util.function.CheckedConsumer) WatchOption(io.etcd.jetcd.options.WatchOption) Watcher(io.etcd.jetcd.Watch.Watcher) Watcher(io.etcd.jetcd.Watch.Watcher) WatchEvent(io.etcd.jetcd.watch.WatchEvent) CountDownLatch(java.util.concurrent.CountDownLatch) ByteSequence(io.etcd.jetcd.ByteSequence) WatchOption(io.etcd.jetcd.options.WatchOption)

Aggregations

Client (io.etcd.jetcd.Client)28 Test (org.junit.jupiter.api.Test)20 ByteSequence (io.etcd.jetcd.ByteSequence)13 KV (io.etcd.jetcd.KV)8 CountDownLatch (java.util.concurrent.CountDownLatch)7 Watch (io.etcd.jetcd.Watch)5 WatchEvent (io.etcd.jetcd.watch.WatchEvent)5 ByteString (com.google.protobuf.ByteString)4 ClientBuilder (io.etcd.jetcd.ClientBuilder)4 Watcher (io.etcd.jetcd.Watch.Watcher)4 ClosedClientException (io.etcd.jetcd.common.exception.ClosedClientException)4 PutResponse (io.etcd.jetcd.kv.PutResponse)4 URI (java.net.URI)4 TimeUnit (java.util.concurrent.TimeUnit)4 Event (io.etcd.jetcd.api.Event)3 WatchCreateRequest (io.etcd.jetcd.api.WatchCreateRequest)3 EtcdClusterExtension (io.etcd.jetcd.test.EtcdClusterExtension)3 ArrayList (java.util.ArrayList)3 BeforeAll (org.junit.jupiter.api.BeforeAll)3 WatchCancelRequest (io.etcd.jetcd.api.WatchCancelRequest)2