Categorygo.etcd.io/etcd/client/v3
modulepackage
3.6.0-alpha.0
Repository: https://github.com/etcd-io/etcd.git
Documentation: pkg.go.dev

# README

etcd/client/v3

Docs Godoc

etcd/clientv3 is the official Go etcd client for v3.

Install

go get go.etcd.io/etcd/client/v3

Get started

Create client using clientv3.New:

import clientv3 "go.etcd.io/etcd/client/v3"

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379", "localhost:22379", "localhost:32379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		// handle error!
	}
	defer cli.Close()
}

etcd v3 uses gRPC for remote procedure calls. And clientv3 uses grpc-go to connect to etcd. Make sure to close the client after using it. If the client is not closed, the connection will have leaky goroutines. To specify client request timeout, pass context.WithTimeout to APIs:

ctx, cancel := context.WithTimeout(context.Background(), timeout)
resp, err := cli.Put(ctx, "sample_key", "sample_value")
cancel()
if err != nil {
    // handle error!
}
// use the response

For full compatibility, it is recommended to install released versions of clients using go modules.

Error Handling

etcd client returns 2 types of errors:

  1. context error: canceled or deadline exceeded.
  2. gRPC error: see api/v3rpc/rpctypes.

Here is the example code to handle client errors:

resp, err := cli.Put(ctx, "", "")
if err != nil {
	switch err {
	case context.Canceled:
		log.Fatalf("ctx is canceled by another routine: %v", err)
	case context.DeadlineExceeded:
		log.Fatalf("ctx is attached with a deadline is exceeded: %v", err)
	case rpctypes.ErrEmptyKey:
		log.Fatalf("client-side error: %v", err)
	default:
		log.Fatalf("bad cluster endpoints, which are not etcd servers: %v", err)
	}
}

Metrics

The etcd client optionally exposes RPC metrics through go-grpc-prometheus. See the examples.

Namespacing

The namespace package provides clientv3 interface wrappers to transparently isolate client requests to a user-defined prefix.

Request size limit

Client request size limit is configurable via clientv3.Config.MaxCallSendMsgSize and MaxCallRecvMsgSize in bytes. If none given, client request send limit defaults to 2 MiB including gRPC overhead bytes. And receive limit defaults to math.MaxInt32.

Examples

More code examples can be found at GoDoc.

# Packages

Package clientv3util contains utility functions derived from clientv3.
Package concurrency implements concurrency operations on top of etcd such as distributed locks, barriers, and elections.
Package credentials implements gRPC credential interface with etcd specific logic.
Package leasing serves linearizable reads from a local cache by acquiring exclusive write access to keys through a client-side leasing protocol.
Package mirror implements etcd mirroring operations.
Package namespace is a clientv3 wrapper that translates all keys to begin with a given prefix.
Package naming provides: - subpackage endpoints: an abstraction layer to store and read endpoints information from etcd.
Package ordering is a clientv3 wrapper that caches response header revisions to detect ordering violations from stale responses.
Package snapshot implements utilities around etcd snapshot.
Package yaml handles yaml-formatted clientv3 configuration data.

# Functions

CreateDefaultZapLogger creates a logger that is configurable using env variable: ETCD_CLIENT_DEBUG= debug|info|warn|error|dpanic|panic|fatal|true (true=info).
CreateDefaultZapLoggerConfig creates a logger config that is configurable using env variable: ETCD_CLIENT_DEBUG= debug|info|warn|error|dpanic|panic|fatal|true (true=info).
GetPrefixRangeEnd gets the range end of the prefix.
IsConnCanceled returns true, if error is from a closed gRPC connection.
IsOptsWithFromKey returns true if WithFromKey option is called in the given opts.
IsOptsWithPrefix returns true if WithPrefix option is called in the given opts.
LeaseValue compares a key's LeaseID to a value of your choosing.
New creates a new etcdv3 client from a given configuration.
NewCtxClient creates a client with a context but no underlying grpc connection.
NewFromURL creates a new etcdv3 client from a URL.
NewFromURLs creates a new etcdv3 client from URLs.
OpCompact wraps slice CompactOption to create a CompactOp.
OpDelete returns "delete" operation based on given key and operation options.
OpGet returns "get" operation based on given key and operation options.
OpPut returns "put" operation based on given key-value and operation options.
OpTxn returns "txn" operation based on given transaction conditions.
RetryAuthClient implements a AuthClient.
RetryClusterClient implements a ClusterClient.
RetryKVClient implements a KVClient.
RetryLeaseClient implements a LeaseClient.
RetryMaintenanceClient implements a Maintenance.
SetLogger sets grpc logger.
WithAttachedKeys makes TimeToLive list the keys attached to the given lease ID.
WithCompactPhysical makes Compact wait until all compacted entries are removed from the etcd server's storage.
WithCountOnly makes the 'Get' request return only the count of keys.
WithCreatedNotify makes watch server sends the created event.
WithFilterDelete discards DELETE events from the watcher.
WithFilterPut discards PUT events from the watcher.
WithFirstCreate gets the key with the oldest creation revision in the request range.
WithFirstKey gets the lexically first key in the request range.
WithFirstRev gets the key with the oldest modification revision in the request range.
WithFragment to receive raw watch response with fragmentation.
WithFromKey specifies the range of 'Get', 'Delete', 'Watch' requests to be equal or greater than the key in the argument.
WithIgnoreLease updates the key using its current lease.
WithIgnoreValue updates the key using its current value.
WithKeysOnly makes the 'Get' request return only the keys and the corresponding values will be omitted.
WithLastCreate gets the key with the latest creation revision in the request range.
WithLastKey gets the lexically last key in the request range.
WithLastRev gets the key with the latest modification revision in the request range.
WithLease attaches a lease ID to a key in 'Put' request.
WithLimit limits the number of results to return from 'Get' request.
WithMaxCreateRev filters out keys for Get with creation revisions greater than the given revision.
WithMaxModRev filters out keys for Get with modification revisions greater than the given revision.
WithMinCreateRev filters out keys for Get with creation revisions less than the given revision.
WithMinModRev filters out keys for Get with modification revisions less than the given revision.
WithPrefix enables 'Get', 'Delete', or 'Watch' requests to operate on the keys with matching prefix.
WithPrevKV gets the previous key-value pair before the event happens.
WithProgressNotify makes watch server send periodic progress updates every 10 minutes when there is no incoming events.
WithRange specifies the range of 'Get', 'Delete', 'Watch' requests.
WithRequireLeader requires client requests to only succeed when the cluster has a leader.
WithRev specifies the store revision for 'Get' request.
WithSerializable makes 'Get' request serializable.
WithSort specifies the ordering in 'Get' request.
WithZapLogger is a NewCtxClient option that overrides the logger.

# Constants

# Variables

LeaseResponseChSize is the size of buffer to store unsent lease responses.

# Structs

Client provides and manages an etcd v3 client session.
CompactOp represents a compact operation.
ErrKeepAliveHalted is returned if client keep alive loop halts with an unexpected error.
LeaseGrantResponse wraps the protobuf message LeaseGrantResponse.
LeaseKeepAliveResponse wraps the protobuf message LeaseKeepAliveResponse.
LeaseLeasesResponse wraps the protobuf message LeaseLeasesResponse.
LeaseOp represents an Operation that lease can execute.
LeaseStatus represents a lease status.
LeaseTimeToLiveResponse wraps the protobuf message LeaseTimeToLiveResponse.
Op represents an Operation that kv can execute.
SnapshotResponse is aggregated response from the snapshot stream.

# Interfaces

Txn is the interface that wraps mini-transactions.

# Type aliases