Search in sources :

Example 21 with Client

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

the class LockTest method initializeLockCLient.

private void initializeLockCLient(boolean useNamespace) {
    Client client = useNamespace ? TestUtil.client(cluster).namespace(namespace).build() : TestUtil.client(cluster).build();
    this.lockClient = client.getLockClient();
}
Also used : Client(io.etcd.jetcd.Client)

Example 22 with Client

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

the class LockTest method testLockSegregationByNamespaces.

@Test
public void testLockSegregationByNamespaces() throws Exception {
    initializeLockCLient(false);
    // prepare two LockClients with different namespaces, lock operations on one LockClient
    // should have no effect on the other client.
    Client clientWithNamespace = TestUtil.client(cluster).namespace(namespace).build();
    Lock lockClientWithNamespace = clientWithNamespace.getLockClient();
    long lease = grantLease(5);
    CompletableFuture<LockResponse> feature = lockClientWithNamespace.lock(SAMPLE_NAME, lease);
    LockResponse response = feature.get();
    assertThat(response.getKey().startsWith(SAMPLE_NAME)).isTrue();
    // Unlock by full key name using LockClient without namespace, thus it should not take
    // much time to lock the same key again.
    ByteSequence nsKey = ByteSequence.from(namespace.concat(response.getKey()).getBytes());
    lockClient.unlock(nsKey).get();
    lease = grantLease(30);
    CompletableFuture<LockResponse> feature2 = lockClientWithNamespace.lock(SAMPLE_NAME, lease);
    LockResponse response2 = feature2.get();
    long timestamp2 = System.currentTimeMillis();
    long startTime = System.currentTimeMillis();
    assertThat(response2.getKey().startsWith(SAMPLE_NAME)).isTrue();
    assertThat(response2.getKey()).isNotEqualTo(response.getKey());
    assertThat((timestamp2 - startTime) <= 1000).withFailMessage(String.format("Lease not unlocked, wait time was too long (%dms)", timestamp2 - startTime)).isTrue();
    locksToRelease.add(ByteSequence.from(namespace.concat(response2.getKey()).getBytes()));
    // Lock the same key using LockClient with another namespace, it also should not take much time.
    lease = grantLease(5);
    Client clientWithNamespace2 = TestUtil.client(cluster).namespace(namespace2).build();
    Lock lockClientWithNamespace2 = clientWithNamespace2.getLockClient();
    CompletableFuture<LockResponse> feature3 = lockClientWithNamespace2.lock(SAMPLE_NAME, lease);
    LockResponse response3 = feature3.get();
    long timestamp3 = System.currentTimeMillis();
    assertThat(response3.getKey().startsWith(SAMPLE_NAME)).isTrue();
    assertThat(response3.getKey()).isNotEqualTo(response2.getKey());
    assertThat((timestamp3 - timestamp2) <= 1000).withFailMessage(String.format("wait time for requiring the lock was too long (%dms)", timestamp3 - timestamp2)).isTrue();
    locksToRelease.add(ByteSequence.from(namespace2.concat(response3.getKey()).getBytes()));
}
Also used : LockResponse(io.etcd.jetcd.lock.LockResponse) Client(io.etcd.jetcd.Client) ByteSequence(io.etcd.jetcd.ByteSequence) Lock(io.etcd.jetcd.Lock) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 23 with Client

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

the class WatchTokenExpireTest method testRefreshExpiredToken.

@Test
public void testRefreshExpiredToken() throws Exception {
    setUpEnvironment();
    Client authClient = createAuthClient();
    Watch authWatchClient = authClient.getWatchClient();
    KV authKVClient = authClient.getKVClient();
    authKVClient.put(key, TestUtil.randomByteSequence()).get(1, TimeUnit.SECONDS);
    Thread.sleep(3000);
    AtomicInteger modifications = new AtomicInteger();
    // watch should handle token refresh automatically
    // token is already expired when we attempt to create a watch
    Watch.Watcher watcher = authWatchClient.watch(key, response -> {
        modifications.incrementAndGet();
    });
    // create single thread pool, so that tasks are executed one after another
    ExecutorService executor = Executors.newFixedThreadPool(1);
    List<Future<?>> futures = new ArrayList<>(2);
    Client anotherClient = createAuthClient();
    for (int i = 0; i < 2; ++i) {
        futures.add(executor.submit(() -> {
            try {
                // wait 3 seconds for token to expire. during the test token will be refreshed twice
                Thread.sleep(3000);
                anotherClient.getKVClient().put(key, TestUtil.randomByteSequence()).get(1, TimeUnit.SECONDS);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }));
    }
    await().atMost(15, TimeUnit.SECONDS).untilAsserted(() -> assertThat(modifications.get()).isEqualTo(2));
    executor.shutdownNow();
    futures.forEach(f -> assertThat(f).isDone());
    anotherClient.close();
    watcher.close();
    authWatchClient.close();
    authClient.close();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Watch(io.etcd.jetcd.Watch) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) KV(io.etcd.jetcd.KV) Client(io.etcd.jetcd.Client) Test(org.junit.jupiter.api.Test)

Example 24 with Client

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

the class AuthClientTest method setupEnv.

/**
 * Build etcd client to create role, permission.
 */
@BeforeAll
public static void setupEnv() {
    Client client = TestUtil.client(cluster).build();
    authDisabledKVClient = client.getKVClient();
    authDisabledAuthClient = client.getAuthClient();
}
Also used : Client(io.etcd.jetcd.Client) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 25 with Client

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

the class AuthClientTest method testAuth.

@Test
public void testAuth() throws Exception {
    authDisabledAuthClient.roleAdd(rootRole).get();
    authDisabledAuthClient.roleAdd(userRole).get();
    final AuthRoleListResponse response = authDisabledAuthClient.roleList().get();
    assertThat(response.getRoles()).containsOnly(rootRoleString, userRoleString);
    authDisabledAuthClient.roleGrantPermission(rootRole, rootRoleKeyRangeBegin, rootRoleKeyRangeEnd, Permission.Type.READWRITE).get();
    authDisabledAuthClient.roleGrantPermission(userRole, userRoleKeyRangeBegin, userRoleKeyRangeEnd, Permission.Type.READWRITE).get();
    authDisabledAuthClient.userAdd(root, rootPass).get();
    authDisabledAuthClient.userAdd(user, userPass).get();
    authDisabledAuthClient.userChangePassword(user, userNewPass).get();
    List<String> users = authDisabledAuthClient.userList().get().getUsers();
    assertThat(users).containsOnly(rootString, userString);
    authDisabledAuthClient.userGrantRole(root, rootRole).get();
    authDisabledAuthClient.userGrantRole(user, rootRole).get();
    authDisabledAuthClient.userGrantRole(user, userRole).get();
    assertThat(authDisabledAuthClient.userGet(root).get().getRoles()).containsOnly(rootRoleString);
    assertThat(authDisabledAuthClient.userGet(user).get().getRoles()).containsOnly(rootRoleString, userRoleString);
    authDisabledAuthClient.authEnable().get();
    final Client userClient = TestUtil.client(cluster).user(user).password(userNewPass).build();
    final Client rootClient = TestUtil.client(cluster).user(root).password(rootPass).build();
    userClient.getKVClient().put(rootRoleKey, rootRoleValue).get();
    userClient.getKVClient().put(userRoleKey, userRoleValue).get();
    userClient.getKVClient().get(rootRoleKey).get();
    userClient.getKVClient().get(userRoleKey).get();
    assertThatThrownBy(() -> authDisabledKVClient.put(rootRoleKey, rootRoleValue).get()).hasMessageContaining("etcdserver: user name is empty");
    assertThatThrownBy(() -> authDisabledKVClient.put(userRoleKey, rootRoleValue).get()).hasMessageContaining("etcdserver: user name is empty");
    assertThatThrownBy(() -> authDisabledKVClient.get(rootRoleKey).get()).hasMessageContaining("etcdserver: user name is empty");
    assertThatThrownBy(() -> authDisabledKVClient.get(userRoleKey).get()).hasMessageContaining("etcdserver: user name is empty");
    AuthRoleGetResponse roleGetResponse = userClient.getAuthClient().roleGet(rootRole).get();
    assertThat(roleGetResponse.getPermissions().size()).isNotEqualTo(0);
    roleGetResponse = userClient.getAuthClient().roleGet(userRole).get();
    assertThat(roleGetResponse.getPermissions().size()).isNotEqualTo(0);
    rootClient.getAuthClient().userRevokeRole(user, rootRole).get();
    final KV kvClient = userClient.getKVClient();
    // verify the access to root role is revoked for user.
    assertThatThrownBy(() -> kvClient.get(rootRoleKey).get()).isNotNull();
    // verify userRole is still valid.
    assertThat(kvClient.get(userRoleKey).get().getCount()).isNotEqualTo(0);
    rootClient.getAuthClient().roleRevokePermission(userRole, userRoleKeyRangeBegin, userRoleKeyRangeEnd).get();
    // verify the access to foo is revoked for user.
    assertThatThrownBy(() -> userClient.getKVClient().get(userRoleKey).get()).isNotNull();
    rootClient.getAuthClient().authDisable().get();
    authDisabledAuthClient.userDelete(root).get();
    authDisabledAuthClient.userDelete(user).get();
    authDisabledAuthClient.roleDelete(rootRole).get();
    authDisabledAuthClient.roleDelete(userRole).get();
}
Also used : AuthRoleListResponse(io.etcd.jetcd.auth.AuthRoleListResponse) KV(io.etcd.jetcd.KV) Client(io.etcd.jetcd.Client) AuthRoleGetResponse(io.etcd.jetcd.auth.AuthRoleGetResponse) Test(org.junit.jupiter.api.Test)

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