Search in sources :

Example 1 with Client

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

the class KVTest method testKVClientCanRetryPutOnEtcdRestart.

@Test
@SuppressWarnings("FutureReturnValueIgnored")
public void testKVClientCanRetryPutOnEtcdRestart() throws InterruptedException {
    try (Client customClient = TestUtil.client(cluster).retryMaxDuration(Duration.ofMinutes(5)).retryDelay(10).retryMaxDelay(30).retryChronoUnit(ChronoUnit.SECONDS).build()) {
        ByteSequence key = ByteSequence.from("retry_dummy_key", StandardCharsets.UTF_8);
        int putCount = 1000;
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
        // start putting values in a sequence, at least on of them has to be retried
        executor.submit(() -> {
            for (int i = 0; i < putCount; ++i) {
                ByteSequence value = ByteSequence.from(Integer.toString(i), StandardCharsets.UTF_8);
                customClient.getKVClient().put(key, value).join();
            }
        });
        // restart the cluster while uploading
        executor.schedule(() -> cluster.restart(), 100, TimeUnit.MILLISECONDS);
        executor.shutdown();
        assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
        GetResponse getResponse = kvClient.get(key).join();
        assertThat(getResponse.getKvs().size()).as("There should be exactly one KeyValue for the test key").isEqualTo(1);
        ByteSequence lastPutValue = ByteSequence.from(Integer.toString(putCount - 1), StandardCharsets.UTF_8);
        assertThat(getResponse.getKvs().get(0).getValue()).as("The sequence of put operations should finish successfully. " + "Last seen value should match the expected value.").isEqualTo(lastPutValue);
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Client(io.etcd.jetcd.Client) GetResponse(io.etcd.jetcd.kv.GetResponse) ByteSequence(io.etcd.jetcd.ByteSequence) Test(org.junit.jupiter.api.Test)

Example 2 with Client

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

the class AuthUnitTest method testHeaders.

@Test
public void testHeaders() throws Exception {
    MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry();
    serviceRegistry.addService(new AuthGrpc.AuthImplBase() {

        @Override
        public void authenticate(io.etcd.jetcd.api.AuthenticateRequest request, io.grpc.stub.StreamObserver<io.etcd.jetcd.api.AuthenticateResponse> responseObserver) {
            responseObserver.onNext(AuthenticateResponse.newBuilder().setToken("token").build());
        }
    });
    serviceRegistry.addService(new KVGrpc.KVImplBase() {

        @Override
        public void put(io.etcd.jetcd.api.PutRequest request, io.grpc.stub.StreamObserver<io.etcd.jetcd.api.PutResponse> responseObserver) {
            responseObserver.onNext(PutResponse.newBuilder().build());
        }
    });
    Server server = null;
    Client client = null;
    try {
        Metadata intercepted = new Metadata();
        server = NettyServerBuilder.forPort(0).fallbackHandlerRegistry(serviceRegistry).intercept(new ServerInterceptor() {

            @Override
            public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
                if (AUTHENTICATE_METHOD_NAME.equals(call.getMethodDescriptor().getFullMethodName())) {
                    intercepted.merge(headers);
                }
                return next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<>(call) {
                }, headers);
            }
        }).directExecutor().build().start();
        client = Client.builder().endpoints(new URI("http://127.0.0.1:" + server.getPort())).user(user).password(userPass).authHeader("foo-a", "foo-auth").header("bar-h", "bar").build();
        client.getKVClient().put(key, value).get(30, TimeUnit.SECONDS);
        assertThat(intercepted.keys()).contains("foo-a");
    } finally {
        if (client != null) {
            client.close();
        }
        if (server != null) {
            server.shutdownNow();
        }
    }
}
Also used : AuthenticateResponse(io.etcd.jetcd.api.AuthenticateResponse) Server(io.grpc.Server) Metadata(io.grpc.Metadata) PutResponse(io.etcd.jetcd.api.PutResponse) URI(java.net.URI) Client(io.etcd.jetcd.Client) MutableHandlerRegistry(io.grpc.util.MutableHandlerRegistry) KVGrpc(io.etcd.jetcd.api.KVGrpc) AuthGrpc(io.etcd.jetcd.api.AuthGrpc) ServerInterceptor(io.grpc.ServerInterceptor) Test(org.junit.jupiter.api.Test)

Example 3 with Client

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

the class ClientConnectionManagerTest method testHeaders.

@Test
public void testHeaders() throws InterruptedException, ExecutionException {
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientBuilder builder = TestUtil.client(cluster).header("MyHeader1", "MyHeaderVal1").header("MyHeader2", "MyHeaderVal2").interceptor(new ClientInterceptor() {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

                @Override
                public void start(Listener<RespT> responseListener, Metadata headers) {
                    super.start(responseListener, headers);
                    assertThat(headers.get(Metadata.Key.of("MyHeader1", Metadata.ASCII_STRING_MARSHALLER))).isEqualTo("MyHeaderVal1");
                    assertThat(headers.get(Metadata.Key.of("MyHeader2", Metadata.ASCII_STRING_MARSHALLER))).isEqualTo("MyHeaderVal2");
                    latch.countDown();
                }
            };
        }
    });
    try (Client client = builder.build()) {
        CompletableFuture<PutResponse> future = client.getKVClient().put(bytesOf("sample_key"), bytesOf("sample_key"));
        latch.await(1, TimeUnit.MINUTES);
        future.get();
    }
}
Also used : Channel(io.grpc.Channel) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) CountDownLatch(java.util.concurrent.CountDownLatch) PutResponse(io.etcd.jetcd.kv.PutResponse) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) Client(io.etcd.jetcd.Client) ClientBuilder(io.etcd.jetcd.ClientBuilder) Test(org.junit.jupiter.api.Test)

Example 4 with Client

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

the class ClientConnectionManagerTest method testAuthHeaders.

@Test
public void testAuthHeaders() throws InterruptedException, ExecutionException {
    final CountDownLatch latch = new CountDownLatch(1);
    Auth authClient = TestUtil.client(cluster).build().getAuthClient();
    authClient.userAdd(root, rootPass).get();
    ByteSequence role = TestUtil.bytesOf("root");
    authClient.userGrantRole(root, role).get();
    authClient.authEnable().get();
    final ClientBuilder builder = TestUtil.client(cluster).authHeader("MyAuthHeader", "MyAuthHeaderVal").header("MyHeader2", "MyHeaderVal2").user(root).password(rootPass);
    assertThat(builder.authHeaders().get(Metadata.Key.of("MyAuthHeader", Metadata.ASCII_STRING_MARSHALLER))).isEqualTo("MyAuthHeaderVal");
    try (Client client = builder.build()) {
        CompletableFuture<AuthDisableResponse> future = client.getAuthClient().authDisable();
        latch.await(10, TimeUnit.SECONDS);
        future.get();
    }
    authClient.userRevokeRole(root, role).get();
    authClient.userDelete(root).get();
}
Also used : Auth(io.etcd.jetcd.Auth) CountDownLatch(java.util.concurrent.CountDownLatch) Client(io.etcd.jetcd.Client) ByteSequence(io.etcd.jetcd.ByteSequence) ClientBuilder(io.etcd.jetcd.ClientBuilder) AuthDisableResponse(io.etcd.jetcd.auth.AuthDisableResponse) Test(org.junit.jupiter.api.Test)

Example 5 with Client

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

the class WatchErrorTest method testWatchOnError.

@ParameterizedTest
@ValueSource(strings = { "test-namespace/", "" })
public void testWatchOnError(String ns) {
    final Client client = ns != null && ns.length() == 0 ? TestUtil.client(cluster).namespace(bytesOf(ns)).build() : TestUtil.client(cluster).build();
    final ByteSequence key = randomByteSequence();
    final List<Throwable> events = Collections.synchronizedList(new ArrayList<>());
    try (Watcher watcher = client.getWatchClient().watch(key, TestUtil::noOpWatchResponseConsumer, events::add)) {
        cluster.cluster().stop();
        await().atMost(15, TimeUnit.SECONDS).untilAsserted(() -> assertThat(events).isNotEmpty());
    }
    assertThat(events).allMatch(EtcdException.class::isInstance);
}
Also used : Watcher(io.etcd.jetcd.Watch.Watcher) Client(io.etcd.jetcd.Client) EtcdException(io.etcd.jetcd.common.exception.EtcdException) TestUtil.randomByteSequence(io.etcd.jetcd.impl.TestUtil.randomByteSequence) ByteSequence(io.etcd.jetcd.ByteSequence) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

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