Documentation
¶
Overview ¶
Package consul provides the implementation of a consul client.
Index ¶
- Constants
- Variables
- func Dial(network string, address string) (net.Conn, error)
- func DialContext(ctx context.Context, network string, address string) (net.Conn, error)
- func Distance(a Coordinates, b Coordinates) time.Duration
- func ListServices(ctx context.Context) (map[string][]string, error)
- func Listen(network string, address string) (net.Listener, error)
- func ListenContext(ctx context.Context, network string, address string) (net.Listener, error)
- func Lock(ctx context.Context, keys ...string) (context.Context, context.CancelFunc)
- func LookupHost(ctx context.Context, name string) ([]string, error)
- func Shuffle(list []Endpoint)
- func TryLockOne(ctx context.Context, keys ...string) (context.Context, context.CancelFunc)
- func Watch(ctx context.Context, key string, handler WatcherFunc)
- func WatchPrefix(ctx context.Context, prefix string, handler WatcherFunc)
- func WeightRTT(endpoint Endpoint) float64
- func WeightedShuffle(list []Endpoint, weightOf func(Endpoint) float64)
- func WeightedShuffleOnRTT(list []Endpoint)
- func WithSession(ctx context.Context, session Session) (context.Context, context.CancelFunc)
- type Agent
- type Balancer
- type BalancerFunc
- type Catalog
- type Client
- func (c *Client) Delete(ctx context.Context, path string, query Query, recv interface{}) error
- func (c *Client) Do(ctx context.Context, method string, path string, query Query, send interface{}, ...) (err error)
- func (c *Client) Get(ctx context.Context, path string, query Query, recv interface{}) error
- func (c *Client) Put(ctx context.Context, path string, query Query, send interface{}, ...) error
- type Coordinates
- type Dialer
- type Endpoint
- type KeyData
- type Listener
- type LoadBalancer
- type Locker
- type LookupServiceFunc
- type NodeCoordinates
- type NullBalancer
- type Param
- type PreferTags
- type Query
- type Resolver
- type ResolverBlacklist
- type ResolverCache
- type Rotator
- type RoundRobin
- type Session
- type SessionBehavior
- type SessionID
- type Shuffler
- type Store
- func (store *Store) Delete(ctx context.Context, prefix string, index int64) (ok bool, err error)
- func (store *Store) Read(ctx context.Context, key string) (value io.ReadCloser, index int64, err error)
- func (store *Store) ReadValue(ctx context.Context, key string, ptr interface{}) (index int64, err error)
- func (store *Store) Session(ctx context.Context, key string) (session Session, err error)
- func (store *Store) Tree(ctx context.Context, prefix string) (keys []string, err error)
- func (store *Store) Walk(ctx context.Context, prefix string, walk func(key string) error) (err error)
- func (store *Store) WalkData(ctx context.Context, prefix string, walk func(data KeyData) error) (err error)
- func (store *Store) Write(ctx context.Context, key string, value io.ReadCloser, index int64) (ok bool, err error)
- func (store *Store) WriteValue(ctx context.Context, key string, value interface{}, index int64) (ok bool, err error)
- type Tomography
- type Watcher
- type WatcherFunc
- type WeightedShuffler
Constants ¶
const ( // DefaultAddress is the default consul agent address used when creating a // consul client. DefaultAddress = "localhost:8500" ConsulEnvironment = "CONSUL_HTTP_ADDR" )
Variables ¶
var ( // DefaultTransport is the default HTTP transport used by consul clients. // It differs from the default transport in net/http because we don't want // to enable compression, or allow requests to be proxied. The sizes of the // connection pool is also tuned to lower numbers since clients usually // communicate with their local agent only. Finally the timeouts are set to // lower values because the client and agent most likely communicate over // the loopback interface. DefaultTransport http.RoundTripper = &http.Transport{ DialContext: (&net.Dialer{ Timeout: 5 * time.Second, }).DialContext, DisableCompression: true, MaxIdleConns: 5, MaxIdleConnsPerHost: 2, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 5 * time.Second, ExpectContinueTimeout: 5 * time.Second, } // DefaultClient is the default client used when none is specified. DefaultClient = &Client{ Address: getConsulAddress(), } // DefaultUserAgent is the default user agent used by consul clients when // none has been set. DefaultUserAgent string )
var ( // DefaultLocker is the default Locker used by the package-level lock // management functions. DefaultLocker = &Locker{} // LocksKey is used to lookup the keys held by a lock from its associated // context. LocksKey = &contextKey{"consul-locks-key"} // Unlocked is the error returned by contexts when the lock they were // associated with has been lost. Unlocked = errors.New("unlocked") )
var ( DefaultWatcher = &Watcher{ MaxAttempts: defMaxAttempts, InitialBackoff: defInitialBackoff, MaxBackoff: defMaxBackoff, } // WatchTransport is the same as DefaultTransport with a longer // ResponseHeaderTimeout. This is copied from DefaultTransport. We don't // do an actual copy because the Transport uses mutexes. copied mutexes // are ineffective. You will panic on concurrent map access if running // with other clients without instantiating a new transport for watch. WatchTransport http.RoundTripper = &http.Transport{ DialContext: (&net.Dialer{ Timeout: 5 * time.Second, }).DialContext, DisableCompression: true, MaxIdleConns: 5, MaxIdleConnsPerHost: 2, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 1 * time.Minute, ExpectContinueTimeout: 5 * time.Second, } )
var DefaultAgent = &Agent{}
DefaultAgent is an agent configured to expose the agent information of the consul agent that the default client connects to.
var DefaultCatalog = &Catalog{}
DefaultCatalog is a catalog configured to use the default client.
var DefaultResolver = &Resolver{ OnlyPassing: true, Cache: &ResolverCache{Balancer: MultiBalancer(defaultCacheBalancer(), &Shuffler{})}, Blacklist: &ResolverBlacklist{}, Balancer: &LoadBalancer{New: func() Balancer { return &RoundRobin{} }}, Sort: WeightedShuffleOnRTT, }
DefaultResolver is the Resolver used by a Dialer when non has been specified.
var DefaultTomography = &Tomography{}
DefaultTomography is used as the default Tomography instance when
var (
// SessionKey is the key at which the Session value is stored in a context.
SessionKey = &contextKey{"consul-session"}
)
Functions ¶
func DialContext ¶
DialContext is a wrapper for calling (*Dialer).DialContext on a default dialer.
func Distance ¶
func Distance(a Coordinates, b Coordinates) time.Duration
Distance computes the approximate RTT between two Consul coordinates.
The algorithm was taken from: https://www.consul.io/docs/internals/coordinates.html#working-with-coordinates
func ListServices ¶
ListServices is a helper function that delegates to the default catalog.
func Listen ¶
Listen creates a listener that accept connections on the given network and address, and registers to consul using the default client.
func ListenContext ¶
ListenContext creates a listener that accept connections on the given network and address, and registers to consul use the default client.
The context may be used to asynchronously cancel the consul registration.
func LookupHost ¶
LookupHost is a wrapper around the default resolver's LookupHost method.
func Shuffle ¶
func Shuffle(list []Endpoint)
Shuffle is a sorting function that randomly rearranges the list of endpoints.
func TryLockOne ¶
TryLockOne calls DefaultLocker.TryLockOne.
func Watch ¶
func Watch(ctx context.Context, key string, handler WatcherFunc)
Watch is the package-level Watch definition which is called on DefaultWatcher.
func WatchPrefix ¶
func WatchPrefix(ctx context.Context, prefix string, handler WatcherFunc)
WatchPrefix is the package-level WatchPrefix definition which is called on DefaultWatcher.
func WeightedShuffle ¶
WeightedShuffle is a sorting function that randomly rearranges the list of endpoints, using the weightOf function to obtain the weight of each endpoint of the list.
func WeightedShuffleOnRTT ¶
func WeightedShuffleOnRTT(list []Endpoint)
WeightedShuffleOnRTT is a sorting function that randomly rearranges the list of endpoints, using the RTT as a weight to increase the chance of endpoints with low RTT to be placed at the front of the list.
func WithSession ¶
WithSession constructs a copy of the context which is attached to a newly created session.
Types ¶
type Agent ¶
type Agent struct { // Client Client *Client // Configures how often the state is updated. If zero, the state is updated // every second. CacheTimeout time.Duration // contains filtered or unexported fields }
Agent exposes methods to get information about the agent that a client is configured to connect to.
type Balancer ¶
type Balancer interface { // Balance is called with a service name and a list of endpoints that this // name resolved to, and returns the potentially modified list of endpoints // sorted by preference. // // The returned slice of endpoints may or may not be the same slice than the // one that was passed to the method, the balancer implementation is allowed // to perform in-place modifications of the endpoints slice, applications // must take into consideration that the balancer ownes the slice for the // duration of the method call. // // Balance must not retain the slice of endpoints it received, nor the one // it returned. Balance(name string, endpoints []Endpoint) []Endpoint }
Balancer is the interface implemented by types that provides load balancing algorithms for a Resolver.
Balancers must be safe to use concurrently from multiple goroutines.
func MultiBalancer ¶
MultiBalancer composes a new Balancer from a list of multiple balancers, each of them being called for each Balance call in the order that they were given to the function.
func PreferEC2AvailabilityZone ¶
PreferEC2AvailabilityZone is a constructor for a balancer which prefers routing traffic to services registered in the same EC2 availability zone than the caller.
If the metadata aren't available the function returns the NullBalancer balancer which doesn't modify the list of endpoints.
type BalancerFunc ¶
BalancerFunc allows regular functions to be used as balancers.
type Catalog ¶
type Catalog struct { // The client used by the catalog, which may be nil to indicate that a // default client should be used. Client *Client }
Catalog exposes methods to interract with the consul catalog.
type Client ¶
type Client struct { // Address of the consul agent this client sends requests to. // DefaultAddress is used if this field is empty. Address string // UserAgent may be set to any string which identify who the client is. UserAgent string // Datacenter may be set to configure which consul datacenter the client // sends requests for. // If Datacenter is an empty string the agent's default is used. Datacenter string // Transport is the HTTP transport used by the client to send requests to // its agent. // If Transport is nil then DefaultTransport is used instead. Transport http.RoundTripper }
A Client exposes an API for communicating with a consul agent.
The properties of a client are only read by its method, it is therefore safe to use a client concurrently from multiple goroutines.
Clients are safe to used concurrently from multiple goroutines after they were first constructed.
func (*Client) Delete ¶
Delete sends a DELETE request to the consul agent.
See (*Client).Do for the full documentation.
func (*Client) Do ¶
func (c *Client) Do(ctx context.Context, method string, path string, query Query, send interface{}, recv interface{}) (err error)
Do sends a request to the consul agent. The method, path, and query arguments represent the API call being made. The send argument is the value sent in the body of the request, which is usually of struct type, or nil if the request has an empty body. The recv argument should be a pointer to a type which matches the format of the response, or nil if no response is expected.
type Coordinates ¶
The Coordinates type represents network coordinates of nodes in a consul system.
More information can be found at: https://www.consul.io/docs/internals/coordinates.html
type Dialer ¶
type Dialer struct { Timeout time.Duration Deadline time.Time LocalAddr net.Addr DualStack bool FallbackDelay time.Duration KeepAlive time.Duration BlacklistTTL time.Duration Resolver *Resolver }
The Dialer type mirrors the net.Dialer API but uses consul to resolve service names to network addresses instead of DNS.
The Dialer always ignores ports specified in the addreses that it's trying to connect to and uses the ports looked up from consul instead, unless it was given and address which is a valid IP representation in which case it does not resolve the service name and directly establish the connection.
For a full description of each of the fields please refer to the net.Dialer documentation at https://golang.org/pkg/net/#Dialer.
func (*Dialer) Dial ¶
Dial establishes a network connection to address, using consul to resolve the address if necessary.
For a full description of the method's behavior please refer to the (*net.Dialer).Dial documentation at https://golang.org/pkg/net/#Dialer.Dial.
func (*Dialer) DialContext ¶
DialContext establishes a network connection to address, using consul to resolve the address if necessary.
For a full description of the method's behavior please refer to the (*net.Dialer).Dialcontext documentation at https://golang.org/pkg/net/#Dialer.DialContext.
type Endpoint ¶
type Endpoint struct { // The ID under which the service was registered. ID string // The node name that the endpoint belongs to. Node string // The network address at which the service can be reached. Addr net.Addr // The list of tags associated with the service. Tags []string // The set of metadata associated with the node on which the service is // running. Meta map[string]string // RTT is an estimation of the round-trip-time between the node specified by // Resolver.Agent and the endpoint (may be zero if the information wasn't yet // available). RTT time.Duration // contains filtered or unexported fields }
An Endpoint represents the address at which a service is available, coupled with the metadata associated with the service registration.
type KeyData ¶
type KeyData struct { CreateIndex int64 ModifyIndex int64 Key string Flags int64 Value []byte Session SessionID }
KeyData is a representation of a key in Consul, which follows the structure documented at https://www.consul.io/api/kv.html#read-key
type Listener ¶
type Listener struct { // The Client used to register the listener to a consul agent. If nil, the // default client is used instead. Client *Client // A unique identifier for the service registered to consul. This only needs // to be unique within the agent that the service registers to, and may be // omitted. In that case, ServiceName is used instead. // This value is appended to ServiceName using ':' as separator to create a // unique ID for the listener within a set of services with the same name. ServiceID string // The logical name of the service registered to consul. If none is set, the // program name is used instead. ServiceName string // A list of tags to set on the service registered to consul. ServiceTags []string // If non-nil, specifies the address under which the service will be // registered to consul. This is useful when running within a container for // example, where the program may not have access to the external address to // which clients should connect to in order to reach the service. // By default, the address that new listeners accept connections on is used. ServiceAddress net.Addr // Configures whether registering the service with specific tags should // overwrite existing values. ServiceEnableTagOverride bool // If the listener is intended to be used to serve HTTP connection this // field may be set to the path that consul should query to health check // the service. CheckHTTP string // CheckInterval is the time interval set on the TCP check that is // registered to consul along with the service. Defaults to 10 seconds. CheckInterval time.Duration // Amount of time after which a service that is reported critical should be // automatically deregistered. Defaults to never. CheckDeregisterCriticalServiceAfter time.Duration }
The Listener type contains options to create listeners that automatically register to consul.
func (*Listener) Listen ¶
Listen creates a new listener that accepts network connections on the given address, and automatically registers to consul.
func (*Listener) ListenContext ¶
func (l *Listener) ListenContext(ctx context.Context, network string, address string) (net.Listener, error)
ListenContext creates a new listener that accepts network connections on the given address, and automatically registers to consul.
The context may be used to asynchronously cancel the consul registration.
type LoadBalancer ¶
type LoadBalancer struct { // Constructs the balancing algorithm used by this load balancer. // // The function cannot be nil or calling the LoadBalancer's Balance method // will panic. New func() Balancer // contains filtered or unexported fields }
A LoadBalancer is an implementation of Balancer which maintains a set of balancers that are local to each service name that Balance has been called for. It enables using simple load balancing algorithms that are designed to work on a set of endpoints belonging to a single service (like RoundRobin) in the context of the Resolver which may be used to
type Locker ¶
type Locker struct { // The client used to send requests to the consul agent. If nil, the default // client is used instead. Client *Client // A key prefix to apply to all operations made on this locker. Keyspace string // LockDelay is the amount of time that a lock will stay held if it hasn't // been released and the session that was attached to it expired. LockDelay time.Duration // The behavior to used when releasing a lock (default to Release). UnlockBehavior SessionBehavior }
A Locker exposes methods for acquiring locks on keys of the consul key/value store.
func (*Locker) Lock ¶
Lock acquires locks on the given keys. The method blocks until the locks were acquired, or the context was canceled. The returned context will be canceled when the locks are released (by calling the cancellation function), or if the ownership was lost, in this case the contexts' Err method returns Unlocked.
func (*Locker) TryLockOne ¶
func (l *Locker) TryLockOne(ctx context.Context, keys ...string) (context.Context, context.CancelFunc)
TryLockOne attempts to acquire a lock on one of the given keys. The returned context will be canceled when the lock is released (by calling the cancellation function), or if the ownership was lost, in this case the context's Err method returns Unlocked. The method never blocks, if it fails to acquire any of the locks it returns a canceled context.
type LookupServiceFunc ¶
LookupServiceFunc is the signature of functions that can be used to lookup service names.
type NodeCoordinates ¶
type NodeCoordinates map[string]Coordinates
NodeCoordinates is a mapping of node names to their consul coordinates.
type NullBalancer ¶
type NullBalancer struct{}
NullBalancer is a balancer which doesn't modify the list of endpoints.
type PreferTags ¶
type PreferTags []string
PreferTags is a balancer which groups endpoints that match certain tags. The tags are ordered by preference, so endpoints matching the tag at index zero will be placed at the head of the result list.
The result slice is also truncated to return only endpoints that matched at least one tag, unless this would end up returning an empty slice, in which case the balancer simply returns the full endpoints list.
type Query ¶
type Query []Param
Query is a representation of a URL query string as a list of parameters.
type Resolver ¶
type Resolver struct { // The client used by the resolver, which may be nil to indicate that a // default client should be used. Client *Client // A list of service tags used to filter the result set. Only addresses of // services that match those tags will be returned by LookupService. ServiceTags []string // A set of key/value pairs used to filter the result set. Only addresses of // nodes that have matching metadata will be returned by LookupService. NodeMeta map[string]string // If set to true, the resolver only returns services that are passing their // health checks. OnlyPassing bool // If set to true, allow any server to serve the requests (not only the // leader). AllowStale bool // If set to true, allow the agent to serve the requests from its local // cache instead of forwarding the requests to the servers. AllowCached bool // If set to true, disable fetching the node coordinates when looking up // service endpoints. DisableCoordinates bool // Cache used by the resolver to reduce the number of round-trips to consul. // If set to nil then no cache is used. // // ResolverCache instances should not be shared by multiple resolvers // because the cache uses the service name as a lookup key, but the resolver // may apply filters based on the values of the ServiceTags, NodeMeta, and // OnlyPassing fields. Cache *ResolverCache // This field may be set to allow the resolver to support temporarily // blacklisting addresses that are known to be unreachable. Blacklist *ResolverBlacklist // Agent is used to set the origin from which the distance to each endpoints // are computed. If nil, DefaultAgent is used instead. Agent *Agent // Tomography is used when Agent is set to compute the distance from the // agnet to the endpoints. If nil, DefaultTomography is used instead. Tomography *Tomography // The balancer is used to reorder the list of endpoints returned by the // resolver when looking up services. // // This field takes precedence over Sort, to use a simple sorting function, // set the value to nil. Balancer Balancer // Sort is called to order the list of endpoints returned by the resolver. // Setting this field to nil means no ordering of the endpoints is done. // // If the resolver is intended to be used to distribute load across a pool // of services it is important to set a Sort function that shuffles the list // of endpoints, otherwise consecutive calls would likely return the list in // the same order, and picking the first item would result in routing all // traffic to a single instance of the service. // // DEPRECATED: use Balancer instead. Sort func([]Endpoint) }
A Resolver is a high-level abstraction on top of the consul service discovery API.
The zero-value is a valid Resolver that uses DefaultClient to query the consul agent.
func (*Resolver) LookupHost ¶
LookupHost resolves a service name to a list of network addresses.
The method name is a bit misleading because it uses the term Host but accepts a service name as argument, this is done to match the signature of the net.(*Resolver).LookupHost method so the types can satisfy the same interface.
func (*Resolver) LookupService ¶
LookupService resolves a service name to a list of endpoints using the resolver's configuration to narrow and sort the result set.
func (*Resolver) LookupServiceInto ¶
func (rslv *Resolver) LookupServiceInto(ctx context.Context, name string, list []Endpoint) ([]Endpoint, error)
LookupServiceInto resolves a service name to a list of endpoints using the resolver's configuration to narrow and sort the result set. It uses the provided slice to store the results, if it has a large enough capacity.
type ResolverBlacklist ¶
type ResolverBlacklist struct {
// contains filtered or unexported fields
}
ResolverBlacklist implements a negative caching for Resolver instances. It works by registering addresses that should be filtered out of a service name resolution result, with a deadline at which the address blacklist will expire.
type ResolverCache ¶
type ResolverCache struct { // The maximum age of cache entries. If zero, a default value of 1 second is // used. CacheTimeout time.Duration // A balancer used by the cache to potentially filter or reorder endpoints // from the resolved names before caching them. Balancer Balancer // contains filtered or unexported fields }
The ResolverCache type provides the implementation of a caching layer for service name resolutions.
Instances of ResolverCache are save to use concurrently from multiple goroutines.
func (*ResolverCache) LookupService ¶
func (cache *ResolverCache) LookupService(ctx context.Context, name string, lookup LookupServiceFunc) ([]Endpoint, error)
LookupService resolves a service name by fetching the address list from the cache, or calling lookup if the name did not exist.
func (*ResolverCache) LookupServiceInto ¶
func (cache *ResolverCache) LookupServiceInto(ctx context.Context, name string, list []Endpoint, lookup LookupServiceFunc) ([]Endpoint, error)
LookupServiceInto resolves a service name by fetching the address list from the cache, or calling lookup if the name did not exist. The results are stored in the provided list value, if it has a large enough capacity.
type Rotator ¶
type Rotator struct {
// contains filtered or unexported fields
}
Rotator is the implementation of a load balancing algorithms similar to RoundRobin but which returns the full list of endpoints instead of a single one.
Using this balancer is useful to take advantage of the automatic retry logic implemented in the dialer or http transport.
type RoundRobin ¶
type RoundRobin struct {
// contains filtered or unexported fields
}
RoundRobin is the implementation of a simple load balancing algorithms which chooses and returns a single endpoint of the input list in a round robin fashion.
type Session ¶
type Session struct { // The client used to create the session. Client *Client // A human-readable name for the session (optional). Name string // The session ID, this should not be set when creating the session but it // may be read from the context associated with the session. ID SessionID // The behavior to apply to keys associated with the session when the // session expires. // // If unset, uses Release. Behavior SessionBehavior // LockDelay is the amount of time that a lock will stay held if it hasn't // been released and the session that was attached to it expired. // // If zero, 15 seconds is used. LockDelay time.Duration // The time-to-live of the session, a session automatically expires if it // hasn't been renewed for longer than its TTL. // // If zero, uses 2 x LockDelay. TTL time.Duration }
Session carries a session configuration, it is used in the WithSession function to customize the session properties.
type SessionBehavior ¶
type SessionBehavior string
SessionBehavior is an enumeration repesenting the behaviors of session expirations.
const ( // Release describes the release behavior, locks are released on keys // associated with an expired session. Release SessionBehavior = "release" // Delete describes the delete behavior, keys are deleted when the session // that hold a lock on them expires. Delete SessionBehavior = "delete" )
type Shuffler ¶
type Shuffler struct{}
Shuffler is a Balancer implementation which returns a randomly shuffled list of endpoints.
type Store ¶
type Store struct { // The client used to send requests to the consul agent. Client *Client // A key prefix to apply to all operations made on this store. Keyspace string // Allow read operations to hit any consul servers, not just the leader. AllowStale bool }
A Store exposes an API to interract with the consul key/value store.
func (*Store) Delete ¶
Delete deletes the keys stored under the given prefix. If index is set to a positive value, it is used to turn the delete call into a compare-and-swap operation where the keys are only deleted if the last index that modified them matches the given index.
The method returns a boolean to indicate whether the keys could be deleted.
func (*Store) Read ¶
func (store *Store) Read(ctx context.Context, key string) (value io.ReadCloser, index int64, err error)
Read reads the value of the given key, returning it as a pair of an io.ReadCloser and value of the last index that modified the key.
The program must close the value when it's done reading from it to prevent any leak of internal resources.
func (*Store) ReadValue ¶
func (store *Store) ReadValue(ctx context.Context, key string, ptr interface{}) (index int64, err error)
ReadValue reads the JSON-encoded value at the given key into ptr. The usual unmarshaling rules apply.
See Read for more details on the method.
func (*Store) Session ¶
Session return the session used to lock the given key. It returns an error if the key is not locked or does not exist.
func (*Store) Tree ¶
Tree recursively scans the given key prefix in the consul key/value store, returning the list of keys as a slice of strings.
If the consul key/value store contains a large number of keys under the given prefix, one may prefer to use the Walk method to iterate through the keys without loading them all in memory.
func (*Store) Walk ¶
func (store *Store) Walk(ctx context.Context, prefix string, walk func(key string) error) (err error)
Walk traverses the keyspace under the given prefix, calling the walk function and passing each key.
If the walk function returns an error the iteration is stopped and the error is returned by Walk.
func (*Store) WalkData ¶
func (store *Store) WalkData(ctx context.Context, prefix string, walk func(data KeyData) error) (err error)
WalkData traverses the keyspace under the given prefix, calling the walk function and passing each key's data
If the walk function returns an error the iteration is stopped and the error is returned by WalkData
func (*Store) Write ¶
func (store *Store) Write(ctx context.Context, key string, value io.ReadCloser, index int64) (ok bool, err error)
Write writes bytes from value at the given key in the consul key/value store.
If index is set to a positive value, it is used to turn the write call into a compare-and-swap operation. The value will only be updated if the last index that modified the key matches the given index.
If the given context inherits from a lock, the associated session is used to allow the write operation to succeed.
The method returns a boolean that indicates whether the write operation succeeded, it would return false if the key was locked by another session or if index was specified but was different in consul.
The value is always closed by a call to Write, even if the method returns an error.
type Tomography ¶
type Tomography struct { // The Client used to send requests to a consul agent. Client *Client // Configures how often the state is updated. If zero, the state is updated // every second. CacheTimeout time.Duration // contains filtered or unexported fields }
Tomography exposes methods to fetch network coordinates information from consul.
The Tomography implementation uses an internal cache of node coordinates that is updated asynchronously and fully non-blocking (except for the very first call which has to initialize the cache).
Methods of Tomography are safe to use concurrently from multiple goroutines, assuming the fields aren't being modified after the value was constructed.
func (*Tomography) NodeCoordinates ¶
func (t *Tomography) NodeCoordinates(ctx context.Context) (NodeCoordinates, error)
NodeCoordinates returns the current coordinates of all nodes in the consul datacenter.
type Watcher ¶
type Watcher struct { Client *Client // MaxAttempts limits the number of subsequent failed API calls before // bailing out of the watch. Defaults to 10. MaxAttempts int // InitialBackoff is the amount of time to wait on the initial backoff when // an error occurs. Backoff durations are subsequently increased exponentially // while less than MaxBackoff. Defaults to 1s. InitialBackoff time.Duration // MaxBackoff limits the maximum time to wait when doing exponential backoff // after encountering errors. Defaults to 30s. MaxBackoff time.Duration }
Watcher is the struct upon which Watch and WatchPrefix are built.
func (*Watcher) Watch ¶
func (w *Watcher) Watch(ctx context.Context, key string, handler WatcherFunc)
Watch executes a long poll for changes to the given key. handler will be called immediately upon registration to initialize the watch and returns the initial value (as a list, this is what Consul API returns). In cases where the key is being rapidly updated, there is a chance that Watch can miss intermediate updates due to the way the API is implemented. However, Watch will always converge on the most recent value. See https://github.com/hashicorp/consul/issues/1761 for details.
func (*Watcher) WatchPrefix ¶
func (w *Watcher) WatchPrefix(ctx context.Context, prefix string, handler WatcherFunc)
WatchPrefix executes a long poll for changes to anything under the given prefix. handler will be called immediately upon registration to initialize the watch and returns the initial value (as a list, this is what Consul API returns). In cases where children of prefix are being rapidly updated, there is a chance that WatchPrefix can miss intermediate updates due to the way the API is implemented. However, WatchPrefix will always converge on the most recent values. See https://github.com/hashicorp/consul/issues/1761 for details.
type WatcherFunc ¶
WatcherFunc is the function signature for the callback from watch. It passes a list of KeyData representing the most recent value or values stored at the key or everything below the prefix. It can be nil. error is passed through to the handler if it is not Temporary. Caller is responsible for stopping the watch via canceling the context and implementing back off logic. If the error is temporary, it will not pass it through to the WatcherFunc unless MaxAttempts was hit.
type WeightedShuffler ¶
type WeightedShuffler struct { // WeightOf returns the weight of an endpoint. WeightOf func(Endpoint) float64 }
WeightedShuffler is a Balancer implementation which shuffles the list of endpoints using a different weight for each endpoint.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package httpconsul provides extensions to integrate the standard net/http package with consul.
|
Package httpconsul provides extensions to integrate the standard net/http package with consul. |