const ( PermRead = authpb.READ PermWrite = authpb.WRITE PermReadWrite = authpb.READWRITE )
const ( EventTypeDelete = mvccpb.DELETE EventTypePut = mvccpb.PUT // AutoWatchID is the watcher ID passed in WatchStream.Watch when no // user-provided ID is available. If pass, an ID will automatically be assigned. AutoWatchID = 0 // InvalidWatchID represents an invalid watch ID and prevents duplication with an existing watch. InvalidWatchID = -1 )
MaxLeaseTTL is the maximum lease TTL value
const MaxLeaseTTL = 9000000000
var ( ErrNoAvailableEndpoints = errors.New("etcdclient: no available endpoints") ErrOldCluster = errors.New("etcdclient: old cluster version") )
LeaseResponseChSize is the size of buffer to store unsent lease responses. WARNING: DO NOT UPDATE. Only for testing purposes.
var LeaseResponseChSize = 16
func GetPrefixRangeEnd(prefix string) string
GetPrefixRangeEnd gets the range end of the prefix. 'Get(foo, WithPrefix())' is equal to 'Get(foo, WithRange(GetPrefixRangeEnd(foo))'.
func IsConnCanceled(err error) bool
IsConnCanceled returns true, if error is from a closed gRPC connection. ref. https://github.com/grpc/grpc-go/pull/1854
func IsOptsWithFromKey(opts []OpOption) bool
IsOptsWithFromKey returns true if WithFromKey option is called in the given opts.
func IsOptsWithPrefix(opts []OpOption) bool
IsOptsWithPrefix returns true if WithPrefix option is called in the given opts.
func RetryAuthClient(c *Client) pb.AuthClient
RetryAuthClient implements a AuthClient.
func RetryClusterClient(c *Client) pb.ClusterClient
RetryClusterClient implements a ClusterClient.
func RetryKVClient(c *Client) pb.KVClient
RetryKVClient implements a KVClient.
func RetryLeaseClient(c *Client) pb.LeaseClient
RetryLeaseClient implements a LeaseClient.
func RetryMaintenanceClient(c *Client, conn *grpc.ClientConn) pb.MaintenanceClient
RetryMaintenanceClient implements a Maintenance.
func SetLogger(l grpclog.LoggerV2)
SetLogger sets grpc logger.
Deprecated: use grpclog.SetLoggerV2 directly or grpc_zap.ReplaceGrpcLoggerV2.
func WithRequireLeader(ctx context.Context) context.Context
WithRequireLeader requires client requests to only succeed when the cluster has a leader.
type AlarmMember pb.AlarmMember
type AlarmResponse pb.AlarmResponse
type Auth interface { // Authenticate login and get token Authenticate(ctx context.Context, name string, password string) (*AuthenticateResponse, error) // AuthEnable enables auth of an etcd cluster. AuthEnable(ctx context.Context) (*AuthEnableResponse, error) // AuthDisable disables auth of an etcd cluster. AuthDisable(ctx context.Context) (*AuthDisableResponse, error) // AuthStatus returns the status of auth of an etcd cluster. AuthStatus(ctx context.Context) (*AuthStatusResponse, error) // UserAdd adds a new user to an etcd cluster. UserAdd(ctx context.Context, name string, password string) (*AuthUserAddResponse, error) // UserAddWithOptions adds a new user to an etcd cluster with some options. UserAddWithOptions(ctx context.Context, name string, password string, opt *UserAddOptions) (*AuthUserAddResponse, error) // UserDelete deletes a user from an etcd cluster. UserDelete(ctx context.Context, name string) (*AuthUserDeleteResponse, error) // UserChangePassword changes a password of a user. UserChangePassword(ctx context.Context, name string, password string) (*AuthUserChangePasswordResponse, error) // UserGrantRole grants a role to a user. UserGrantRole(ctx context.Context, user string, role string) (*AuthUserGrantRoleResponse, error) // UserGet gets a detailed information of a user. UserGet(ctx context.Context, name string) (*AuthUserGetResponse, error) // UserList gets a list of all users. UserList(ctx context.Context) (*AuthUserListResponse, error) // UserRevokeRole revokes a role of a user. UserRevokeRole(ctx context.Context, name string, role string) (*AuthUserRevokeRoleResponse, error) // RoleAdd adds a new role to an etcd cluster. RoleAdd(ctx context.Context, name string) (*AuthRoleAddResponse, error) // RoleGrantPermission grants a permission to a role. RoleGrantPermission(ctx context.Context, name string, key, rangeEnd string, permType PermissionType) (*AuthRoleGrantPermissionResponse, error) // RoleGet gets a detailed information of a role. RoleGet(ctx context.Context, role string) (*AuthRoleGetResponse, error) // RoleList gets a list of all roles. RoleList(ctx context.Context) (*AuthRoleListResponse, error) // RoleRevokePermission revokes a permission from a role. RoleRevokePermission(ctx context.Context, role string, key, rangeEnd string) (*AuthRoleRevokePermissionResponse, error) // RoleDelete deletes a role. RoleDelete(ctx context.Context, role string) (*AuthRoleDeleteResponse, error) }
func NewAuth(c *Client) Auth
func NewAuthFromAuthClient(remote pb.AuthClient, c *Client) Auth
type AuthDisableResponse pb.AuthDisableResponse
type AuthEnableResponse pb.AuthEnableResponse
type AuthRoleAddResponse pb.AuthRoleAddResponse
type AuthRoleDeleteResponse pb.AuthRoleDeleteResponse
type AuthRoleGetResponse pb.AuthRoleGetResponse
type AuthRoleGrantPermissionResponse pb.AuthRoleGrantPermissionResponse
type AuthRoleListResponse pb.AuthRoleListResponse
type AuthRoleRevokePermissionResponse pb.AuthRoleRevokePermissionResponse
type AuthStatusResponse pb.AuthStatusResponse
type AuthUserAddResponse pb.AuthUserAddResponse
type AuthUserChangePasswordResponse pb.AuthUserChangePasswordResponse
type AuthUserDeleteResponse pb.AuthUserDeleteResponse
type AuthUserGetResponse pb.AuthUserGetResponse
type AuthUserGrantRoleResponse pb.AuthUserGrantRoleResponse
type AuthUserListResponse pb.AuthUserListResponse
type AuthUserRevokeRoleResponse pb.AuthUserRevokeRoleResponse
type AuthenticateResponse pb.AuthenticateResponse
Client provides and manages an etcd v3 client session.
type Client struct { Cluster KV Lease Watcher Auth Maintenance // Username is a user name for authentication. Username string // Password is a password for authentication. Password string // contains filtered or unexported fields }
func New(cfg Config) (*Client, error)
New creates a new etcdv3 client from a given configuration.
func NewCtxClient(ctx context.Context, opts ...Option) *Client
NewCtxClient creates a client with a context but no underlying grpc connection. This is useful for embedded cases that override the service interface implementations and do not need connection management.
func NewFromURL(url string) (*Client, error)
NewFromURL creates a new etcdv3 client from a URL.
func NewFromURLs(urls []string) (*Client, error)
NewFromURLs creates a new etcdv3 client from URLs.
func (c *Client) ActiveConnection() *grpc.ClientConn
ActiveConnection returns the current in-use connection
func (c *Client) Close() error
Close shuts down the client's etcd connections.
func (c *Client) Ctx() context.Context
Ctx is a context for "out of band" messages (e.g., for sending "clean up" message when another context is canceled). It is canceled on client Close().
func (c *Client) Dial(ep string) (*grpc.ClientConn, error)
Dial connects to a single endpoint using the client's config.
func (c *Client) Endpoints() []string
Endpoints lists the registered endpoints for the client.
func (c *Client) GetLogger() *zap.Logger
GetLogger gets the logger. NOTE: This method is for internal use of etcd-client library and should not be used as general-purpose logger.
func (c *Client) SetEndpoints(eps ...string)
SetEndpoints updates client's endpoints.
func (c *Client) Sync(ctx context.Context) error
Sync synchronizes client's endpoints with the known endpoints from the etcd membership.
func (c *Client) WithLogger(lg *zap.Logger) *Client
WithLogger overrides the logger.
Deprecated: Please use WithZapLogger or Logger field in clientv3.Config
Does not changes grpcLogger, that can be explicitly configured using grpc_zap.ReplaceGrpcLoggerV2(..) method.
type Cluster interface { // MemberList lists the current cluster membership. MemberList(ctx context.Context) (*MemberListResponse, error) // MemberAdd adds a new member into the cluster. MemberAdd(ctx context.Context, peerAddrs []string) (*MemberAddResponse, error) // MemberAddAsLearner adds a new learner member into the cluster. MemberAddAsLearner(ctx context.Context, peerAddrs []string) (*MemberAddResponse, error) // MemberRemove removes an existing member from the cluster. MemberRemove(ctx context.Context, id uint64) (*MemberRemoveResponse, error) // MemberUpdate updates the peer addresses of the member. MemberUpdate(ctx context.Context, id uint64, peerAddrs []string) (*MemberUpdateResponse, error) // MemberPromote promotes a member from raft learner (non-voting) to raft voting member. MemberPromote(ctx context.Context, id uint64) (*MemberPromoteResponse, error) }
func NewCluster(c *Client) Cluster
func NewClusterFromClusterClient(remote pb.ClusterClient, c *Client) Cluster
type Cmp pb.Compare
func Compare(cmp Cmp, result string, v interface{}) Cmp
func CreateRevision(key string) Cmp
func LeaseValue(key string) Cmp
LeaseValue compares a key's LeaseID to a value of your choosing. The empty LeaseID is 0, otherwise known as `NoLease`.
func ModRevision(key string) Cmp
func Value(key string) Cmp
func Version(key string) Cmp
func (cmp *Cmp) KeyBytes() []byte
KeyBytes returns the byte slice holding with the comparison key.
func (cmp *Cmp) ValueBytes() []byte
ValueBytes returns the byte slice holding the comparison value, if any.
func (cmp *Cmp) WithKeyBytes(key []byte)
WithKeyBytes sets the byte slice for the comparison key.
func (cmp Cmp) WithPrefix() Cmp
WithPrefix sets the comparison to scan all keys prefixed by the key.
func (cmp Cmp) WithRange(end string) Cmp
WithRange sets the comparison to scan the range [key, end).
func (cmp *Cmp) WithValueBytes(v []byte)
WithValueBytes sets the byte slice for the comparison's value.
CompactOp represents a compact operation.
type CompactOp struct {
// contains filtered or unexported fields
}
func OpCompact(rev int64, opts ...CompactOption) CompactOp
OpCompact wraps slice CompactOption to create a CompactOp.
CompactOption configures compact operation.
type CompactOption func(*CompactOp)
func WithCompactPhysical() CompactOption
WithCompactPhysical makes Compact wait until all compacted entries are removed from the etcd server's storage.
type CompactResponse pb.CompactionResponse
type CompareResult int
type CompareTarget int
const ( CompareVersion CompareTarget = iota CompareCreated CompareModified CompareValue )
type Config struct { // Endpoints is a list of URLs. Endpoints []string `json:"endpoints"` // AutoSyncInterval is the interval to update endpoints with its latest members. // 0 disables auto-sync. By default auto-sync is disabled. AutoSyncInterval time.Duration `json:"auto-sync-interval"` // DialTimeout is the timeout for failing to establish a connection. DialTimeout time.Duration `json:"dial-timeout"` // DialKeepAliveTime is the time after which client pings the server to see if // transport is alive. DialKeepAliveTime time.Duration `json:"dial-keep-alive-time"` // DialKeepAliveTimeout is the time that the client waits for a response for the // keep-alive probe. If the response is not received in this time, the connection is closed. DialKeepAliveTimeout time.Duration `json:"dial-keep-alive-timeout"` // MaxCallSendMsgSize is the client-side request send limit in bytes. // If 0, it defaults to 2.0 MiB (2 * 1024 * 1024). // Make sure that "MaxCallSendMsgSize" < server-side default send/recv limit. // ("--max-request-bytes" flag to etcd or "embed.Config.MaxRequestBytes"). MaxCallSendMsgSize int // MaxCallRecvMsgSize is the client-side response receive limit. // If 0, it defaults to "math.MaxInt32", because range response can // easily exceed request send limits. // Make sure that "MaxCallRecvMsgSize" >= server-side default send/recv limit. // ("--max-request-bytes" flag to etcd or "embed.Config.MaxRequestBytes"). MaxCallRecvMsgSize int // TLS holds the client secure credentials, if any. TLS *tls.Config // Username is a user name for authentication. Username string `json:"username"` // Password is a password for authentication. Password string `json:"password"` // RejectOldCluster when set will refuse to create a client against an outdated cluster. RejectOldCluster bool `json:"reject-old-cluster"` // DialOptions is a list of dial options for the grpc client (e.g., for interceptors). // For example, pass "grpc.WithBlock()" to block until the underlying connection is up. // Without this, Dial returns immediately and connecting the server happens in background. DialOptions []grpc.DialOption // Context is the default client context; it can be used to cancel grpc dial out and // other operations that do not have an explicit context. Context context.Context // Logger sets client-side logger. // If nil, fallback to building LogConfig. Logger *zap.Logger // LogConfig configures client-side logger. // If nil, use the default logger. // TODO: configure gRPC logger LogConfig *zap.Config // PermitWithoutStream when set will allow client to send keepalive pings to server without any active streams(RPCs). PermitWithoutStream bool `json:"permit-without-stream"` // MaxUnaryRetries is the maximum number of retries for unary RPCs. MaxUnaryRetries uint `json:"max-unary-retries"` // BackoffWaitBetween is the wait time before retrying an RPC. BackoffWaitBetween time.Duration `json:"backoff-wait-between"` // BackoffJitterFraction is the jitter fraction to randomize backoff wait time. BackoffJitterFraction float64 `json:"backoff-jitter-fraction"` }
type DefragmentResponse pb.DefragmentResponse
type DeleteResponse pb.DeleteRangeResponse
func (resp *DeleteResponse) OpResponse() OpResponse
ErrKeepAliveHalted is returned if client keep alive loop halts with an unexpected error.
This usually means that automatic lease renewal via KeepAlive is broken, but KeepAliveOnce will still work as expected.
type ErrKeepAliveHalted struct { Reason error }
func (e ErrKeepAliveHalted) Error() string
type Event mvccpb.Event
func (e *Event) IsCreate() bool
IsCreate returns true if the event tells that the key is newly created.
func (e *Event) IsModify() bool
IsModify returns true if the event tells that a new value is put on existing key.
type GetResponse pb.RangeResponse
func (resp *GetResponse) OpResponse() OpResponse
type HashKVResponse pb.HashKVResponse
type KV interface { // Put puts a key-value pair into etcd. // Note that key,value can be plain bytes array and string is // an immutable representation of that bytes array. // To get a string of bytes, do string([]byte{0x10, 0x20}). Put(ctx context.Context, key, val string, opts ...OpOption) (*PutResponse, error) // Get retrieves keys. // By default, Get will return the value for "key", if any. // When passed WithRange(end), Get will return the keys in the range [key, end). // When passed WithFromKey(), Get returns keys greater than or equal to key. // When passed WithRev(rev) with rev > 0, Get retrieves keys at the given revision; // if the required revision is compacted, the request will fail with ErrCompacted . // When passed WithLimit(limit), the number of returned keys is bounded by limit. // When passed WithSort(), the keys will be sorted. Get(ctx context.Context, key string, opts ...OpOption) (*GetResponse, error) // Delete deletes a key, or optionally using WithRange(end), [key, end). Delete(ctx context.Context, key string, opts ...OpOption) (*DeleteResponse, error) // Compact compacts etcd KV history before the given rev. Compact(ctx context.Context, rev int64, opts ...CompactOption) (*CompactResponse, error) // Do applies a single Op on KV without a transaction. // Do is useful when creating arbitrary operations to be issued at a // later time; the user can range over the operations, calling Do to // execute them. Get/Put/Delete, on the other hand, are best suited // for when the operation should be issued at the time of declaration. Do(ctx context.Context, op Op) (OpResponse, error) // Txn creates a transaction. Txn(ctx context.Context) Txn }
func NewKV(c *Client) KV
func NewKVFromKVClient(remote pb.KVClient, c *Client) KV
type Lease interface { // Grant creates a new lease. Grant(ctx context.Context, ttl int64) (*LeaseGrantResponse, error) // Revoke revokes the given lease. Revoke(ctx context.Context, id LeaseID) (*LeaseRevokeResponse, error) // TimeToLive retrieves the lease information of the given lease ID. TimeToLive(ctx context.Context, id LeaseID, opts ...LeaseOption) (*LeaseTimeToLiveResponse, error) // Leases retrieves all leases. Leases(ctx context.Context) (*LeaseLeasesResponse, error) // KeepAlive attempts to keep the given lease alive forever. If the keepalive responses posted // to the channel are not consumed promptly the channel may become full. When full, the lease // client will continue sending keep alive requests to the etcd server, but will drop responses // until there is capacity on the channel to send more responses. // // If client keep alive loop halts with an unexpected error (e.g. "etcdserver: no leader") or // canceled by the caller (e.g. context.Canceled), KeepAlive returns a ErrKeepAliveHalted error // containing the error reason. // // The returned "LeaseKeepAliveResponse" channel closes if underlying keep // alive stream is interrupted in some way the client cannot handle itself; // given context "ctx" is canceled or timed out. // // TODO(v4.0): post errors to last keep alive message before closing // (see https://github.com/etcd-io/etcd/pull/7866) KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error) // KeepAliveOnce renews the lease once. The response corresponds to the // first message from calling KeepAlive. If the response has a recoverable // error, KeepAliveOnce will retry the RPC with a new keep alive message. // // In most of the cases, Keepalive should be used instead of KeepAliveOnce. KeepAliveOnce(ctx context.Context, id LeaseID) (*LeaseKeepAliveResponse, error) // Close releases all resources Lease keeps for efficient communication // with the etcd server. Close() error }
func NewLease(c *Client) Lease
func NewLeaseFromLeaseClient(remote pb.LeaseClient, c *Client, keepAliveTimeout time.Duration) Lease
LeaseGrantResponse wraps the protobuf message LeaseGrantResponse.
type LeaseGrantResponse struct { *pb.ResponseHeader ID LeaseID TTL int64 Error string }
type LeaseID int64
const ( // NoLease is a lease ID for the absence of a lease. NoLease LeaseID = 0 )
LeaseKeepAliveResponse wraps the protobuf message LeaseKeepAliveResponse.
type LeaseKeepAliveResponse struct { *pb.ResponseHeader ID LeaseID TTL int64 }
LeaseLeasesResponse wraps the protobuf message LeaseLeasesResponse.
type LeaseLeasesResponse struct { *pb.ResponseHeader Leases []LeaseStatus `json:"leases"` }
LeaseOp represents an Operation that lease can execute.
type LeaseOp struct {
// contains filtered or unexported fields
}
LeaseOption configures lease operations.
type LeaseOption func(*LeaseOp)
func WithAttachedKeys() LeaseOption
WithAttachedKeys makes TimeToLive list the keys attached to the given lease ID.
type LeaseRevokeResponse pb.LeaseRevokeResponse
LeaseStatus represents a lease status.
type LeaseStatus struct { ID LeaseID `json:"id"` }
LeaseTimeToLiveResponse wraps the protobuf message LeaseTimeToLiveResponse.
type LeaseTimeToLiveResponse struct { *pb.ResponseHeader ID LeaseID `json:"id"` // TTL is the remaining TTL in seconds for the lease; the lease will expire in under TTL+1 seconds. Expired lease will return -1. TTL int64 `json:"ttl"` // GrantedTTL is the initial granted time in seconds upon lease creation/renewal. GrantedTTL int64 `json:"granted-ttl"` // Keys is the list of keys attached to this lease. Keys [][]byte `json:"keys"` }
type Maintenance interface { // AlarmList gets all active alarms. AlarmList(ctx context.Context) (*AlarmResponse, error) // AlarmDisarm disarms a given alarm. AlarmDisarm(ctx context.Context, m *AlarmMember) (*AlarmResponse, error) // Defragment releases wasted space from internal fragmentation on a given etcd member. // Defragment is only needed when deleting a large number of keys and want to reclaim // the resources. // Defragment is an expensive operation. User should avoid defragmenting multiple members // at the same time. // To defragment multiple members in the cluster, user need to call defragment multiple // times with different endpoints. Defragment(ctx context.Context, endpoint string) (*DefragmentResponse, error) // Status gets the status of the endpoint. Status(ctx context.Context, endpoint string) (*StatusResponse, error) // HashKV returns a hash of the KV state at the time of the RPC. // If revision is zero, the hash is computed on all keys. If the revision // is non-zero, the hash is computed on all keys at or below the given revision. HashKV(ctx context.Context, endpoint string, rev int64) (*HashKVResponse, error) // Snapshot provides a reader for a point-in-time snapshot of etcd. // If the context "ctx" is canceled or timed out, reading from returned // "io.ReadCloser" would error out (e.g. context.Canceled, context.DeadlineExceeded). Snapshot(ctx context.Context) (io.ReadCloser, error) // MoveLeader requests current leader to transfer its leadership to the transferee. // Request must be made to the leader. MoveLeader(ctx context.Context, transfereeID uint64) (*MoveLeaderResponse, error) }
func NewMaintenance(c *Client) Maintenance
func NewMaintenanceFromMaintenanceClient(remote pb.MaintenanceClient, c *Client) Maintenance
type Member pb.Member
type MemberAddResponse pb.MemberAddResponse
type MemberListResponse pb.MemberListResponse
type MemberPromoteResponse pb.MemberPromoteResponse
type MemberRemoveResponse pb.MemberRemoveResponse
type MemberUpdateResponse pb.MemberUpdateResponse
type MoveLeaderResponse pb.MoveLeaderResponse
Op represents an Operation that kv can execute.
type Op struct {
// contains filtered or unexported fields
}
func NewOp() *Op
func OpDelete(key string, opts ...OpOption) Op
OpDelete returns "delete" operation based on given key and operation options.
func OpGet(key string, opts ...OpOption) Op
OpGet returns "get" operation based on given key and operation options.
func OpPut(key, val string, opts ...OpOption) Op
OpPut returns "put" operation based on given key-value and operation options.
func OpTxn(cmps []Cmp, thenOps []Op, elseOps []Op) Op
OpTxn returns "txn" operation based on given transaction conditions.
func (op Op) IsCountOnly() bool
IsCountOnly returns whether countOnly is set.
func (op Op) IsDelete() bool
IsDelete returns true iff the operation is a Delete.
func (op Op) IsGet() bool
IsGet returns true iff the operation is a Get.
func (op Op) IsKeysOnly() bool
IsKeysOnly returns whether keysOnly is set.
func (op Op) IsPut() bool
IsPut returns true iff the operation is a Put.
func (op Op) IsSerializable() bool
IsSerializable returns true if the serializable field is true.
func (op Op) IsTxn() bool
IsTxn returns true if the "Op" type is transaction.
func (op Op) KeyBytes() []byte
KeyBytes returns the byte slice holding the Op's key.
func (op Op) MaxCreateRev() int64
MaxCreateRev returns the operation's maximum create revision.
func (op Op) MaxModRev() int64
MaxModRev returns the operation's maximum modify revision.
func (op Op) MinCreateRev() int64
MinCreateRev returns the operation's minimum create revision.
func (op Op) MinModRev() int64
MinModRev returns the operation's minimum modify revision.
func (op Op) RangeBytes() []byte
RangeBytes returns the byte slice holding with the Op's range end, if any.
func (op Op) Rev() int64
Rev returns the requested revision, if any.
func (op Op) Txn() ([]Cmp, []Op, []Op)
Txn returns the comparison(if) operations, "then" operations, and "else" operations.
func (op Op) ValueBytes() []byte
ValueBytes returns the byte slice holding the Op's value, if any.
func (op *Op) WithKeyBytes(key []byte)
WithKeyBytes sets the byte slice for the Op's key.
func (op *Op) WithRangeBytes(end []byte)
WithRangeBytes sets the byte slice for the Op's range end.
func (op *Op) WithValueBytes(v []byte)
WithValueBytes sets the byte slice for the Op's value.
OpOption configures Operations like Get, Put, Delete.
type OpOption func(*Op)
func WithCountOnly() OpOption
WithCountOnly makes the 'Get' request return only the count of keys.
func WithCreatedNotify() OpOption
WithCreatedNotify makes watch server sends the created event.
func WithFilterDelete() OpOption
WithFilterDelete discards DELETE events from the watcher.
func WithFilterPut() OpOption
WithFilterPut discards PUT events from the watcher.
func WithFirstCreate() []OpOption
WithFirstCreate gets the key with the oldest creation revision in the request range.
func WithFirstKey() []OpOption
WithFirstKey gets the lexically first key in the request range.
func WithFirstRev() []OpOption
WithFirstRev gets the key with the oldest modification revision in the request range.
func WithFragment() OpOption
WithFragment to receive raw watch response with fragmentation. Fragmentation is disabled by default. If fragmentation is enabled, etcd watch server will split watch response before sending to clients when the total size of watch events exceed server-side request limit. The default server-side request limit is 1.5 MiB, which can be configured as "--max-request-bytes" flag value + gRPC-overhead 512 bytes. See "etcdserver/api/v3rpc/watch.go" for more details.
func WithFromKey() OpOption
WithFromKey specifies the range of 'Get', 'Delete', 'Watch' requests to be equal or greater than the key in the argument.
func WithIgnoreLease() OpOption
WithIgnoreLease updates the key using its current lease. This option can not be combined with WithLease. Returns an error if the key does not exist.
func WithIgnoreValue() OpOption
WithIgnoreValue updates the key using its current value. This option can not be combined with non-empty values. Returns an error if the key does not exist.
func WithKeysOnly() OpOption
WithKeysOnly makes the 'Get' request return only the keys and the corresponding values will be omitted.
func WithLastCreate() []OpOption
WithLastCreate gets the key with the latest creation revision in the request range.
func WithLastKey() []OpOption
WithLastKey gets the lexically last key in the request range.
func WithLastRev() []OpOption
WithLastRev gets the key with the latest modification revision in the request range.
func WithLease(leaseID LeaseID) OpOption
WithLease attaches a lease ID to a key in 'Put' request.
func WithLimit(n int64) OpOption
WithLimit limits the number of results to return from 'Get' request. If WithLimit is given a 0 limit, it is treated as no limit.
func WithMaxCreateRev(rev int64) OpOption
WithMaxCreateRev filters out keys for Get with creation revisions greater than the given revision.
func WithMaxModRev(rev int64) OpOption
WithMaxModRev filters out keys for Get with modification revisions greater than the given revision.
func WithMinCreateRev(rev int64) OpOption
WithMinCreateRev filters out keys for Get with creation revisions less than the given revision.
func WithMinModRev(rev int64) OpOption
WithMinModRev filters out keys for Get with modification revisions less than the given revision.
func WithPrefix() OpOption
WithPrefix enables 'Get', 'Delete', or 'Watch' requests to operate on the keys with matching prefix. For example, 'Get(foo, WithPrefix())' can return 'foo1', 'foo2', and so on.
func WithPrevKV() OpOption
WithPrevKV gets the previous key-value pair before the event happens. If the previous KV is already compacted, nothing will be returned.
func WithProgressNotify() OpOption
WithProgressNotify makes watch server send periodic progress updates every 10 minutes when there is no incoming events. Progress updates have zero events in WatchResponse.
func WithRange(endKey string) OpOption
WithRange specifies the range of 'Get', 'Delete', 'Watch' requests. For example, 'Get' requests with 'WithRange(end)' returns the keys in the range [key, end). endKey must be lexicographically greater than start key.
func WithRev(rev int64) OpOption
WithRev specifies the store revision for 'Get' request. Or the start revision of 'Watch' request.
func WithSerializable() OpOption
WithSerializable makes 'Get' request serializable. By default, it's linearizable. Serializable requests are better for lower latency requirement.
func WithSort(target SortTarget, order SortOrder) OpOption
WithSort specifies the ordering in 'Get' request. It requires 'WithRange' and/or 'WithPrefix' to be specified too. 'target' specifies the target to sort by: key, version, revisions, value. 'order' can be either 'SortNone', 'SortAscend', 'SortDescend'.
type OpResponse struct {
// contains filtered or unexported fields
}
func (op OpResponse) Del() *DeleteResponse
func (op OpResponse) Get() *GetResponse
func (op OpResponse) Put() *PutResponse
func (op OpResponse) Txn() *TxnResponse
Option is a function type that can be passed as argument to NewCtxClient to configure client
type Option func(*Client)
func WithZapLogger(lg *zap.Logger) Option
WithZapLogger is a NewCtxClient option that overrides the logger
type Permission authpb.Permission
type PermissionType authpb.Permission_Type
func StrToPermissionType(s string) (PermissionType, error)
type PutResponse pb.PutResponse
func (resp *PutResponse) OpResponse() OpResponse
type SortOption struct { Target SortTarget Order SortOrder }
type SortOrder int
const ( SortNone SortOrder = iota SortAscend SortDescend )
type SortTarget int
const ( SortByKey SortTarget = iota SortByVersion SortByCreateRevision SortByModRevision SortByValue )
type StatusResponse pb.StatusResponse
Txn is the interface that wraps mini-transactions.
Txn(context.TODO()).If( Compare(Value(k1), ">", v1), Compare(Version(k1), "=", 2) ).Then( OpPut(k2,v2), OpPut(k3,v3) ).Else( OpPut(k4,v4), OpPut(k5,v5) ).Commit()
type Txn interface { // If takes a list of comparison. If all comparisons passed in succeed, // the operations passed into Then() will be executed. Or the operations // passed into Else() will be executed. If(cs ...Cmp) Txn // Then takes a list of operations. The Ops list will be executed, if the // comparisons passed in If() succeed. Then(ops ...Op) Txn // Else takes a list of operations. The Ops list will be executed, if the // comparisons passed in If() fail. Else(ops ...Op) Txn // Commit tries to commit the transaction. Commit() (*TxnResponse, error) }
type TxnResponse pb.TxnResponse
func (resp *TxnResponse) OpResponse() OpResponse
type UserAddOptions authpb.UserAddOptions
type WatchChan <-chan WatchResponse
type WatchResponse struct { Header pb.ResponseHeader Events []*Event // CompactRevision is the minimum revision the watcher may receive. CompactRevision int64 // Canceled is used to indicate watch failure. // If the watch failed and the stream was about to close, before the channel is closed, // the channel sends a final response that has Canceled set to true with a non-nil Err(). Canceled bool // Created is used to indicate the creation of the watcher. Created bool // contains filtered or unexported fields }
func (wr *WatchResponse) Err() error
Err is the error value if this WatchResponse holds an error.
func (wr *WatchResponse) IsProgressNotify() bool
IsProgressNotify returns true if the WatchResponse is progress notification.
type Watcher interface { // Watch watches on a key or prefix. The watched events will be returned // through the returned channel. If revisions waiting to be sent over the // watch are compacted, then the watch will be canceled by the server, the // client will post a compacted error watch response, and the channel will close. // If the requested revision is 0 or unspecified, the returned channel will // return watch events that happen after the server receives the watch request. // If the context "ctx" is canceled or timed out, returned "WatchChan" is closed, // and "WatchResponse" from this closed channel has zero events and nil "Err()". // The context "ctx" MUST be canceled, as soon as watcher is no longer being used, // to release the associated resources. // // If the context is "context.Background/TODO", returned "WatchChan" will // not be closed and block until event is triggered, except when server // returns a non-recoverable error (e.g. ErrCompacted). // For example, when context passed with "WithRequireLeader" and the // connected server has no leader (e.g. due to network partition), // error "etcdserver: no leader" (ErrNoLeader) will be returned, // and then "WatchChan" is closed with non-nil "Err()". // In order to prevent a watch stream being stuck in a partitioned node, // make sure to wrap context with "WithRequireLeader". // // Otherwise, as long as the context has not been canceled or timed out, // watch will retry on other recoverable errors forever until reconnected. // // TODO: explicitly set context error in the last "WatchResponse" message and close channel? // Currently, client contexts are overwritten with "valCtx" that never closes. // TODO(v3.4): configure watch retry policy, limit maximum retry number // (see https://github.com/etcd-io/etcd/issues/8980) Watch(ctx context.Context, key string, opts ...OpOption) WatchChan // RequestProgress requests a progress notify response be sent in all watch channels. RequestProgress(ctx context.Context) error // Close closes the watcher and cancels all watch requests. Close() error }
func NewWatchFromWatchClient(wc pb.WatchClient, c *Client) Watcher
func NewWatcher(c *Client) Watcher
Name | Synopsis |
---|---|
.. | |
clientv3util | Package clientv3util contains utility functions derived from clientv3. |
concurrency | Package concurrency implements concurrency operations on top of etcd such as distributed locks, barriers, and elections. |
credentials | Package credentials implements gRPC credential interface with etcd specific logic. |
experimental | |
recipes | Package recipe contains experimental client-side distributed synchronization primitives. |
leasing | Package leasing serves linearizable reads from a local cache by acquiring exclusive write access to keys through a client-side leasing protocol. |
mirror | Package mirror implements etcd mirroring operations. |
mock | |
mockserver | Package mockserver provides mock implementations for etcdserver's server interface. |
namespace | Package namespace is a clientv3 wrapper that translates all keys to begin with a given prefix. |
naming | Package naming provides: |
endpoints | |
resolver | |
ordering | Package ordering is a clientv3 wrapper that caches response header revisions to detect ordering violations from stale responses. |
snapshot | Package snapshot implements utilities around etcd snapshot. |
yaml | Package yaml handles yaml-formatted clientv3 configuration data. |