jetcd Documentation

repository·main·Indexed 22 days ago

https://github.com/etcd-io/jetcd

The official Java client for etcd v3, providing a high-level API to interact with the etcd key-value store. It includes support for KV operations, lease management, watch mechanisms, and TLS security. The library also provides jetcd-ctl for command-line interaction and EtcdClusterExtension for JUnit 5 integration testing via Testcontainers.

Tokens
4K
Snippets
13
Records
21
Agent score
78%

What's inside jetcd

  1. Maintain lease vitality with KeepAlive services

    main

    To prevent leases from expiring, jetcd provides background services to automatically send keep-alive requests to etcd.

    KeepAlive Lifecycle

    • Starting the Service: Calling startKeepAliveService initializes a background scheduler (keepAliveSchedule) and a ScheduledExecutorService. This service manages two primary tasks:
      • keepAliveExecutor: Periodically scans registered leases and sends keep-alive requests via a StreamObserver when the nextKeepAliveTime is reached.
      • deadLineExecutor: Periodically scans leases and removes them from the internal map once their DeadLine is reached, triggering expiration logic.
    • Using keepAlive: The keepAlive function creates a keepAlive object, adds it to the internal tracking map, and schedules it for automatic renewal.
    • Stopping the Service: Use closeKeepAliveService to terminate the background scheduler and close the StreamObserver connection to etcd.
  2. Manage etcd leases using the Lease interface

    main

    The Lease interface allows you to manage the lifecycle of etcd leases, including granting new leases, revoking existing ones, and maintaining them via keep-alive mechanisms.

    Core Lease Operations

    • Granting a Lease: Use the grant function by building a leaseGrantRequest with a specified ttl (Time To Live) in seconds. This creates a new lease in etcd.
    • Revoking a Lease: Use the revoke function by building a leaseRevokeRequest with a specific lease id to manually terminate a lease.
  3. Understand Watcher behavior in multi-member clusters

    main

    When using jetcd in a multi-member etcd cluster (e.g., via cluster:// targets), be aware of how gRPC load balancing affects watch streams:

    • Independent Streams: Each Watch.watch(...) call creates its own independent bidirectional gRPC Watch stream. They are not multiplexed into a single stream.
    • Member IDs: The ResponseHeader.member_id identifies the specific etcd member that generated the RPC response. Because gRPC load balances requests, two parallel watchers observing the same logical update may return different member_id values if they are served by different cluster members.
    • Flaky Assertions: Do not rely on the equality of the full ResponseHeader (including member_id) to determine if two watchers saw the same event.

    Recommendation: When verifying that multiple watchers see the same event, compare the actual events and relevant revision fields rather than the raw header metadata.

  4. Use jetcd-ctl to interact with etcd

    main

    The jetcd-ctl tool allows you to interact with an etcd cluster via the command line. It can be used to perform basic operations such as putting keys, getting values, and watching for changes. Note that you must have an etcd node running before using these commands. You can download and start an etcd node from the official etcd releases.

    To run these commands using Gradle, use the gradle run --args="<command>" pattern.

    # Example: Put a key-value pair
    $ gradle run --args="put foo bar"
    
    # Example: Get a value
    $ gradle run --args="get foo"
  5. Watch keys and handle events

    main

    Use the watch method to monitor a key or a key range for changes. The watch client handles the creation of the request, registration of callbacks, and automatic resumption if the connection to the etcd server is lost.

    When a watch is successfully created, the onCreate callback is triggered. If the watch fails (e.g., due to a slow connection or if the requested revision has been compacted), onCreateFailed is called.

    To ensure continuity during disconnections, the client automatically resumes watches by requesting the next revision (last received revision + 1).

    // Conceptual usage based on documentation
    Watch watch = client.getWatchClient();
    Watch.Watcher watcher = watch.watch(ByteSequence.from("key".getBytes()), options, response -> {
        // Handle events here
    });
  6. Use the EtcdClusterExtension for integration testing

    main

    The io.etcd:jetcd-test artifact provides EtcdClusterExtension, which uses Testcontainers to programmatically start and stop isolated etcd servers. This is ideal for JUnit 5 integration tests.

    import io.etcd.jetcd.Client;
    import io.etcd.jetcd.test.EtcdClusterExtension;
    import org.junit.jupiter.api.extension.RegisterExtension;
    
    @RegisterExtension
    public static final EtcdClusterExtension cluster = EtcdClusterExtension.builder()
            .withNodes(1)
            .build();
    
    Client client = Client.builder().endpoints(cluster.clientEndpoints()).build();
  7. Install jetcd via Maven

    main

    Add the jetcd-core dependency to your pom.xml. Ensure you replace ${jetcd-version} with the desired version number. Java 11 or above is required.

    <dependency>
      <groupId>io.etcd</groupId>
      <artifactId>jetcd-core</artifactId>
      <version>${jetcd-version}</version>
    </dependency>
  8. Cancel a watch request

    main
    To stop monitoring a key, use the cancelWatch function. This removes the watcher from the active watchers map and sends a cancellation request to the etcd server. Once the cancellation is successfully processed by the server, the onCanceled callback is triggered.
  9. Prepare certificate files for TLS secured etcd

    main

    To connect to a TLS-secured etcd cluster, you need the CA certificate, the client certificate, and the client private key.

    Depending on your installation method, these files are typically located at:

    • etcdadm: /etc/etcd/pki/ (files: ca.crt, etcdctl-etcd-client.key, etcdctl-etcd-client.crt)
    • kubeadm (builtin etcd): /etc/kubernetes/pki/etcd/ (files: ca.crt, healthcheck-client.crt, healthcheck-client.key)

    Important: The SslContextBuilder requires the private key to be in PKCS#8 PEM format. If your key is not in this format (e.g., a standard etcdctl-etcd-client.key), you must convert it to a PEM file before use.

  10. Watch a key using jetcd-ctl

    main

    Use the watch command to monitor changes to a specific key. You can also specify a starting revision to watch changes that occurred from that point forward.

    Syntax: gradle run --args="watch <key> --rev=<revision_number>"

    $ gradle run --args="watch foo --rev=2"
    21:35:09.162|INFO |CommandWatch - type=PUT, key=foo, value=bar
    21:35:09.164|INFO |CommandWatch - type=PUT, key=foo, value=bar2