Module etcd-client
etcd storage client.
Instance methods
Module functions
| new (opts) | Create a new etcd client instance. |
Module and instance constants
| NEXT | Fetch all values prefixed via range request. |
| ALL | Fetch values without upper boundary. |
| NEW_LEASE_ID | A lease will be created with a generated ID value. |
| EXPIRED_TTL | TTL value of an expired lease. |
| _VERSION | Current module version in format MAJOR.MINOR.PATCH. |
| ClosedErrorMessage | Error message if trying to call methods for closed client instance. |
General API notes
| ResponseHeader | ResponseHeader |
| KeyValue | KeyValue |
| Member | Member |
| LeaseStatus | LeaseStatus |
Instance methods
- instance.close (self[, timeout])
-
Close a client instance.
Close call waits until all watcher requests are finished.
Parameters:
- self
etcd client instance.
- timeout
(number,
optional)
Maximum waiting time for all in progress watcher requests. Passing 0 as a timeout allows to skip waiting. Default value is 60 seconds.
Returns:
-
nil
- self
- instance.authenticate (self, name, password)
-
Authenticate in the storage.
Authenticates in the storage by user name and password.
Parameters:
- self
etcd client instance.
- name
(string)
User name.
- password
(string)
User password.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, token = string, }Raises:
See 'General API notes'.See also:
- self
- instance.put (self, key[, value[, opts]])
-
Put the given key into the key-value storage.
Creates a key if it does not exist. Increments a revision of the key-value store. Generates one event in the event history.
Parameters:
- self
etcd client instance.
- key
(string)
Key to put.
- value
(string,
optional)
Value to associate with the key.
Use opts.ignore_value to leave the existing value unchanged.
Technically it is possible to omit the value without the opts.ignore_value option, however the result may be misleading. The default string value (an empty string) will be associated with the key.
TODO: Consider dropping the ignore_value option from the API and provide this behavious, when value == nil is given. In Lua, unlike protobuf v3, we able to distinguish nil and an empty string.
- opts
(table,
optional)
Put request options.
- lease
(integer,
optional)
Lease ID to associate with the key. Zero indicates no lease. You could create a lease with instance.leasegrant. When omitted it drops a previous lease on the key.
Note: Use 'ignore_lease' to reuse currently existing lease.
- prev_kv
(boolean,
optional)
Whether to return the previous key-value pair in the response.
- ignore_value
(boolean,
optional)
Update the key using the **existing** value: so 'value' remains the same, but 'mod_revision' and 'version' are updated.
Returns the INVALID_ARGUMENT error if the key does not exist.
- ignore_lease
(boolean,
optional)
Update the key using the **existing** lease.
Returns the INVALID_ARGUMENT error if the key does not exist.
- lease
(integer,
optional)
Returns:
-
Response of the following structure:
{ header = ResponseHeader, prev_kv = KeyValue (if prev_kv is set), }Raises:
See 'General API notes'.See also:
- self
- instance.range (self, key[, range_end], opts)
-
Fetch a range of keys and its values.
This methods allows to fetch key-value pairs by a key, a prefix of a key, a range of keys.
The following table summarizes different ways to indicate a range of keys.
key range_end effect 'foo' nil keys exactly matched 'foo' 'foo' 'zoo' keys in ['foo', 'zoo') 'foo' NEXT keys prefixed with 'foo' 'foo' ALL keys >= 'foo' ALL 'foo' keys < 'foo' ALL ALL all keys Parameters:
- self
etcd client instance.
- key
(string)
A key, a key prefix or a range start (depending of 'range_end' value).
The special value
etcd-client.ALLmeans no lower boundary. - range_end
(string,
optional)
Upper boundary of the range (exclusive).
The special value
etcd-client.NEXTmeans to fetch all values prefixed with 'key'.The special value
etcd-client.ALLmeans no upper boundary.A function (key -> range_end) may be passed here.
- opts
(string)
Range request options.
- limit
(integer)
Limit number of returned keys. Zero means no limit.
- revision
(integer)
Revision (a kind of point-in-time) to use for the request. Negative or zero value means using of the newest revision.
Note: The response header always contains the newest revision. The option affects returned key-values.
Returns the OUT_OF_RANGE error if the revision is compacted.
- sort_order
(string)
Order for returned result:
- 'NONE' (default, no sorting),
- 'ASCEND' (lowest target value first),
- 'DESCEND' (highest target value first).
- sort_target
(string)
KeyValue field to use for sorting: 'KEY' (default), 'VERSION', 'CREATE', 'MOD', 'VALUE'.
- serializable
(boolean)
Use serializable member-local reads.
Range requests are linearizable by default; linearizable requests have higher latency and lower throughput than serializable requests but reflect the current consensus of the cluster.
For better performance, in exchange for possible stale reads, a serializable range request is served locally without needing to reach consensus with other nodes in the cluster.
- keys_only
(boolean)
Return only keys, not values.
Since all omitted fields are set to default values (which are defined by protobuf v3), all fetched values will appear as empty strings in the response.
- count_only
(boolean)
Return only the keys count in the range, but not key-values itself (so,
response.kvswill be an empty table).response.countis set always, disregarding of theopts.count_onlyvalue in the request. - min_mod_revision
(integer)
Filter out keys with
mod_revisionlesser than given revision. - max_mod_revision
(integer)
Filter out keys with
mod_revisiongreater than given revision. - min_create_revision
(integer)
Filter out keys with
create_revisionlesser than given revision. - max_create_resivion
(integer)
Filter out keys with
create_revisiongreater than given revision.
- limit
(integer)
Returns:
-
Response of the following structure:
{ header = ResponseHeader, kvs = array of KeyValue (empty table when opts.count_only is true), more = boolean (if there are more keys to return in the requested range), count = integer, }Raises:
See 'General API notes'.See also:
- self
- instance.deleterange (self, key[, range_end[, opts]])
-
Delete the given range from the key-value storage.
Increments the revision of the key-value store. Generates a delete event in the event history for every deleted key.
The meaning of
keyandrange_endarguments is exactly same as for corresponding instance.range arguments.Parameters:
- self
etcd client instance.
- key
(string)
The first key of the range to delete.
A string or
etcd-client.ALL. - range_end
(string,
optional)
Upper boundary of the range to delete (exclusive).
A string,
etcd-client.NEXT,etcd-client.ALLor a function (key -> range_end). - opts
(table,
optional)
Delete range request options.
- prev_kv
(boolean,
optional)
Whether to return deleted key-value pairs in the response.
- prev_kv
(boolean,
optional)
Returns:
-
Response of the following structure:
{ header = ResponseHeader, deleted = integer (number of deleted keys), prev_kvs = array of KeyValue (empty table when opts.prev_kv is false or omitted), }Raises:
See 'General API notes'.See also:
- self
- instance.compact (self, revision, physical)
-
Compact the key-value store up to a given revision.
All superseded keys with a revision less than the compaction revision will be removed.
Parameters:
- self
etcd client instance.
- revision
(integer)
The key-value store revision for the compaction operation.
- physical
(boolean)
Physical is set so the RPC will wait until the compaction is physically applied to the local database such that compacted entries are totally removed from the backend database.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, }Raises:
See 'General API notes'.See also:
- self
- instance.addmember (self[, peerURLs[, isLearner]])
-
Adds a member to the cluster.
Parameters:
- self
etcd client instance.
- peerURLs
(table,
optional)
List of URLs the added member will use to communicate with the cluster.
- isLearner
(boolean,
optional)
Indicates if the added member is raft learner.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, member = Member, members = array of Member }Raises:
See 'General API notes'.See also:
- self
- instance.removemember (self[, ID])
-
Remove a member from the cluster.
Parameters:
- self
etcd client instance.
- ID
(integer,
optional)
ID of the member to remove.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, members = array of Member }Raises:
See 'General API notes'.See also:
- self
- instance.members (self[, linearizable])
-
Lists all members in the cluster.
Parameters:
- self
etcd client instance.
- linearizable
(boolean,
optional)
Shows if the request is linearizable.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, members = array of Member }Raises:
See 'General API notes'.See also:
- self
- instance.leases (self)
-
Lists all existing leases.
Parameters:
- self
etcd client instance.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, leases = array of LeaseStatus }Raises:
See 'General API notes'.See also:
- self
- instance.leasegrant (self, TTL[, opts])
-
Creates a lease.
The lease expires if the server does not receive a keepAlive within a given time to live period. All keys attached to the lease will be expired and deleted if the lease expires. Each expired key generates a delete event in the event history.
Parameters:
- self
etcd client instance.
- TTL
(integer)
TTL is the advisory time-to-live in seconds.
- opts
(table,
optional)
Lease grant request options.
- ID
(integer,
optional)
ID is the requested ID for the lease. NEW_LEASE_ID is a default value.
If ID is NEW_LEASE_ID, the etcd chooses an ID.
- ID
(integer,
optional)
Returns:
-
Response of the following structure:
{ header = ResponseHeader, ID = integer, TTL = integer (expired lease has EXPIRED_TTL), }Raises:
See 'General API notes'.See also:
- self
- instance.leaserevoke (self, ID)
-
Revokes a lease.
All keys attached to the lease will expire and be deleted.
Parameters:
- self
etcd client instance.
- ID
(integer)
ID is the lease ID to revoke. When the ID is revoked, all associated keys will be deleted.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, }Raises:
See 'General API notes'.See also:
- self
- instance.leasekeepalive (self, ID)
-
Keeps the lease alive.
Parameters:
- self
etcd client instance.
- ID
(integer)
ID is the lease ID for the lease to keep alive.
Returns:
-
Response of the following structure:
{ header = ResponseHeader, ID = integer, TTL = integer (new time-to-live for the lease), }Raises:
See 'General API notes'.See also:
- self
- instance.leasetimetolive (self, ID[, opts])
-
Retrieves lease information.
Parameters:
- self
etcd client instance.
- ID
(integer)
ID is the lease ID for the lease.
- opts
(table,
optional)
Lease time to live request options.
- keys
(boolean,
optional)
keys is true to query all the keys attached to this lease.
- keys
(boolean,
optional)
Returns:
-
Response of the following structure:
{ header = ResponseHeader, ID = integer, TTL = integer (remaining TTL), grantedTTL = integer (original TTL), keys = array of strings (the list of keys attached to this lease), }Raises:
See 'General API notes'.See also:
- self
- instance.txn (self, transaction)
-
Txn processes multiple requests in a single transaction.
A txn request increments the revision of the key-value store and generates events with the same revision for every completed request. It is not allowed to modify the same key several times within one txn.
Parameters:
- self
etcd client instance.
- transaction
(table)
A transaction etcd-client.txn instance.
Returns:
-
Response of the following structure, depending on the requests made:
{ header = ResponseHeader, succeeded = bool (whether txn comparisons evaluated to true or false), responses = array of { response_put = PutResponse (same as returns instance.put) or response_range = RangeResponse (same as returns instance.range) or response_delete_range = DeleteRangeResponse (same as returns instance.deleterange) or response_txn = TxnResponse (same as returns instance.txn) } }Raises:
See 'General API notes'.See also:
- self
- instance.watchcreate (self, key[, opts])
-
Create a watcher for the given keys.
You need to pick up events as they arrive. So you should avoid to create watchers without using them because it can lead to locks. See
opts.watchers.recv_queue_size.This methods allows to create a watcher for key-value pairs by a key, a prefix of a key, a range of keys.
The following table summarizes different ways to indicate a range of keys.
key opts.range_end effect 'foo' nil keys exactly matched 'foo' 'foo' 'zoo' keys in ['foo', 'zoo') 'foo' NEXT keys prefixed with 'foo' 'foo' ALL keys >= 'foo' ALL 'foo' keys < 'foo' ALL ALL all keys Parameters:
- self
etcd client instance.
- key
(string)
Key to watch.
- opts
(table,
optional)
Create watch request options.
- filters
(table,
optional)
A list of event types to filter away at server side ('NOPUT' or 'NODELETE' values)
- prev_kv
(boolean,
optional)
When set, the watch receives the key-value data from before the event happens. This is useful for knowing what data has been overwritten.
- progress_notify
(boolean,
optional)
When set, the watch will periodically receive a WatchResponse with no events, if there are no recent events. It is useful when clients wish to recover a disconnected watcher starting from a recent known revision. The etcd server decides how often to send notifications based on current server load.
- range_end
(string,
optional)
The end key of range to watch.
- start_revision
(number,
optional)
An optional revision for where to inclusively begin watching. If not given, it will stream events following the revision of the watch creation response header revision. The entire available event history can be watched starting from the last compaction revision.
- filters
(table,
optional)
Returns:
-
Response of the following structure:
{ header = ResponseHeader, cancel_reason = string, canceled = bool, compact_revision = number, created = bool, fragment = bool, watch_id = number, }Note that etcd uses the same structure as a response for
:watchcreate()and:watchwait(). In response to:watchcreate(), events field is always nil. This also means that all events starting from the given or latest revision will arrive as a response from:watchwait().Raises:
An error if unable to encode the params.etcd-client.error.etcd.EtcdError with DEADLINE_EXCEEDED code if failed to connect to any etcd instance.
etcd-client.error.etcd.EtcdError with INVALID_ARGUMENT code if arguments are invalid (as example, `opts.range_end` is less than `key`). For more info about the cause of the error, check `details` field.
See also:
- self
- instance.watchwait (self, watch_id[, timeout])
-
Wait for a next event.
Parameters:
- self
etcd client instance.
- watch_id
(number)
The watch id value from the instance.watchcreate response.
- timeout
(number,
optional)
Maximum waiting time for an event per a single request. Total time is depends on opts.watchers.reconnect_timeout and opts.watchers.reconnect_max_attempts,
Returns:
- nil if timeout exceeded
-
Response of the following structure:
{ header = ResponseHeader, cancel_reason = string, canceled = bool, compact_revision = number, created = bool, events = list of Event { kv = KeyValue pair, prev_kv = KeyValue pair, type = 'PUT' or 'DELETE', }, fragment = bool, watch_id = number, }Note that if
compact_revisionfield is non-zero, the watcher is already cancelled by the etcd-client. Thecanceledfield is also true in this case andcancel_reasonholdsrequired revision has been compactedmessage.eventsfield is also empty.
Raises:
An error if `watch_id` is invalid. The message is `autosubscriber: watcher not found`.An error if `timeout` is negative. The message is `subscriber: timeout must be >= 0`.
etcd-client.error.etcd.EtcdError with DEADLINE_EXCEEDED code if failed to connect to any etcd instance.
etcd-client.error.etcd.EtcdError with CANCELLED code if waiting is interrupted by watcher cancellation.
See also:
- self
- instance.watchcancel (self, watch_id)
-
Cancel a watcher.
To completely clean up resources, you need to cancel all watchers.
Parameters:
- self
etcd client instance.
- watch_id
(number)
The watch id value from the instance.watchcreate response.
Returns:
-
nil
Raises:
An error if `watch_id` is invalid. The message is `autosubscriber: watcher not found`.etcd-client.error.etcd.EtcdError with DEADLINE_EXCEEDED code if failed to connect to any etcd instance.
etcd-client.error.etcd.EtcdError with CANCELLED code if cancellation is interrupted by another cancellation of the same watcher.
- self
Module functions
- new (opts)
-
Create a new etcd client instance.
If etcd is started with
--auto-tls(or there is other reason to don't verify server's identity on the client), set theopts.ssl.verify_peeroption tofalse. It corresponds to the--insecure(-k) curl option.If the etcd server is secured by enforcement of clients to use a client certificate, use
opts.ssl.ssl_keyandopts.ssl.ssl_certoptions. They correspond to the--keyand--certcurl options.Please, note that this etcd client cannot use TLS Common Name to authenticate with the server, because the gRPC to JSON gateway does not support it.
If the authentication is enabled on the etcd server, provide
opts.nameandopts.passwordoptions.etcd may be configured to don't require neither client side key & certificate, nor user ID & password.
Parameters:
- opts
(table)
etcd client options.
- endpoints
({string, ...})
Endpoint URLs.
- name
(string,
optional)
A user ID to authenticate with the server.
- password
(string,
optional)
A password to authenticate with given User ID.
- http_client
(table,
optional)
HTTP client options.
- http_client.new
(table,
optional)
- http_client.request
(table,
optional)
- watchers
(table,
optional)
Options for watcher requests: watchcreate, watchwait and watchcancel.
- watchers.reconnect_timeout
(number,
optional)
A time to wait between reconnects. A default value is 1 second.
- watchers.reconnect_max_attempts
(number,
optional)
Max attempts number per request for reconnect. A default value is 10.
- watchers.recv_queue_size
(number,
optional)
A size of recv queue per watcher. When the queue is full, new events are blocked. A default value is 128.
- ssl
(table,
optional)
TLS options.
- ssl.ssl_key
(string,
optional)
Path to a client's TLS key.
- ssl.ssl_cert
(string,
optional)
Path to a client's TLS certificate.
- ssl.ca_path
(string,
optional)
Path to CA certificates to validate server's certificate.
- ssl.ca_file
(string,
optional)
File with CA certificates to validate server's certificate.
- ssl.verify_peer
(boolean,
optional)
Whether to verify the peer's SSL certificate.
- ssl.verify_host
(boolean,
optional)
Whether to verify the certificate's name (CN) against host.
- auto_sync_interval
(integer,
optional)
Interval in seconds for auto-sync of the etcd nodes. The recommended sync interval is 10 seconds to 1 minute, which does not bring too much overhead to server and makes client catch up the cluster change in time.
- streams_check_timeout
(integer,
optional)
Interval in seconds for alive check for created streams. A default value is 1. This field is used only with Tarantool < 2.10.8 and < 2.11.2.
- endpoints
({string, ...})
Returns:
-
etcd client instance.
Raises:
See 'General API notes'. - opts
(table)
Module and instance constants
- NEXT
-
Fetch all values prefixed via range request.
See also:
- ALL
-
Fetch values without upper boundary.
See also:
- NEW_LEASE_ID
-
A lease will be created with a generated ID value.
See also:
- EXPIRED_TTL
-
TTL value of an expired lease.
See also:
- _VERSION
-
Current module version in format
MAJOR.MINOR.PATCH. - ClosedErrorMessage
-
Error message if trying to call methods for closed client instance.
General API notes
Integers.
Whenever a request or response field is marked as integer,
the API accepts and may return two types: number or so
called number64 (e.g. 1LL or 1ULL). Signed and unsigned
integers are not marked explicitly. One may find precise types
in the protocol description: here and here.
The subsections below describe responses parts, which are common for different responses.
Errors.
Functions of the module may raise different kinds of errors:
1. Arguments validation error (Lua string).
2. Attempt to call methods of closed client instance (Lua string). ClosedErrorMessage
3. etcd-client.error.etcd.EtcdError.
4. etcd-client.error.http.HttpError.
5. Internal HTTP client error: say, out-of-memory during the
request (box.error instance).
The subsections below describe content of those errors.