Documentation ¶
Index ¶
- Constants
- Variables
- func IsServerError(err error) bool
- func SetupTLSConfig(tlsConfig *TLSConfig) (*tls.Config, error)
- type ACL
- func (a *ACL) Clone(id string, q *WriteOptions) (string, *WriteMeta, error)
- func (a *ACL) Create(acl *ACLEntry, q *WriteOptions) (string, *WriteMeta, error)
- func (a *ACL) Destroy(id string, q *WriteOptions) (*WriteMeta, error)
- func (a *ACL) Info(id string, q *QueryOptions) (*ACLEntry, *QueryMeta, error)
- func (a *ACL) List(q *QueryOptions) ([]*ACLEntry, *QueryMeta, error)
- func (a *ACL) Update(acl *ACLEntry, q *WriteOptions) (*WriteMeta, error)
- type ACLEntry
- type Agent
- func (a *Agent) CheckDeregister(checkID string) error
- func (a *Agent) CheckRegister(check *AgentCheckRegistration) error
- func (a *Agent) Checks() (map[string]*AgentCheck, error)
- func (a *Agent) DisableNodeMaintenance() error
- func (a *Agent) DisableServiceMaintenance(serviceID string) error
- func (a *Agent) EnableNodeMaintenance(reason string) error
- func (a *Agent) EnableServiceMaintenance(serviceID, reason string) error
- func (a *Agent) FailTTL(checkID, note string) error
- func (a *Agent) ForceLeave(node string) error
- func (a *Agent) Join(addr string, wan bool) error
- func (a *Agent) Leave() error
- func (a *Agent) Members(wan bool) ([]*AgentMember, error)
- func (a *Agent) Monitor(loglevel string, stopCh chan struct{}, q *QueryOptions) (chan string, error)
- func (a *Agent) NodeName() (string, error)
- func (a *Agent) PassTTL(checkID, note string) error
- func (a *Agent) Reload() error
- func (a *Agent) Self() (map[string]map[string]interface{}, error)
- func (a *Agent) ServiceDeregister(serviceID string) error
- func (a *Agent) ServiceRegister(service *AgentServiceRegistration) error
- func (a *Agent) Services() (map[string]*AgentService, error)
- func (a *Agent) UpdateTTL(checkID, output, status string) error
- func (a *Agent) WarnTTL(checkID, note string) error
- type AgentCheck
- type AgentCheckRegistration
- type AgentMember
- type AgentService
- type AgentServiceCheck
- type AgentServiceChecks
- type AgentServiceRegistration
- type Catalog
- func (c *Catalog) Datacenters() ([]string, error)
- func (c *Catalog) Deregister(dereg *CatalogDeregistration, q *WriteOptions) (*WriteMeta, error)
- func (c *Catalog) Node(node string, q *QueryOptions) (*CatalogNode, *QueryMeta, error)
- func (c *Catalog) Nodes(q *QueryOptions) ([]*Node, *QueryMeta, error)
- func (c *Catalog) Register(reg *CatalogRegistration, q *WriteOptions) (*WriteMeta, error)
- func (c *Catalog) Service(service, tag string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error)
- func (c *Catalog) Services(q *QueryOptions) (map[string][]string, *QueryMeta, error)
- type CatalogDeregistration
- type CatalogNode
- type CatalogRegistration
- type CatalogService
- type Client
- func (c *Client) ACL() *ACL
- func (c *Client) Agent() *Agent
- func (c *Client) Catalog() *Catalog
- func (c *Client) Coordinate() *Coordinate
- func (c *Client) Event() *Event
- func (c *Client) Health() *Health
- func (c *Client) KV() *KV
- func (c *Client) LockKey(key string) (*Lock, error)
- func (c *Client) LockOpts(opts *LockOptions) (*Lock, error)
- func (c *Client) Operator() *Operator
- func (c *Client) PreparedQuery() *PreparedQuery
- func (c *Client) Raw() *Raw
- func (c *Client) SemaphoreOpts(opts *SemaphoreOptions) (*Semaphore, error)
- func (c *Client) SemaphorePrefix(prefix string, limit int) (*Semaphore, error)
- func (c *Client) Session() *Session
- func (c *Client) Snapshot() *Snapshot
- func (c *Client) Status() *Status
- type Config
- type Coordinate
- type CoordinateDatacenterMap
- type CoordinateEntry
- type Event
- type Health
- func (h *Health) Checks(service string, q *QueryOptions) (HealthChecks, *QueryMeta, error)
- func (h *Health) Node(node string, q *QueryOptions) (HealthChecks, *QueryMeta, error)
- func (h *Health) Service(service, tag string, passingOnly bool, q *QueryOptions) ([]*ServiceEntry, *QueryMeta, error)
- func (h *Health) State(state string, q *QueryOptions) (HealthChecks, *QueryMeta, error)
- type HealthCheck
- type HealthChecks
- type HttpBasicAuth
- type KV
- func (k *KV) Acquire(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)
- func (k *KV) CAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)
- func (k *KV) Delete(key string, w *WriteOptions) (*WriteMeta, error)
- func (k *KV) DeleteCAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)
- func (k *KV) DeleteTree(prefix string, w *WriteOptions) (*WriteMeta, error)
- func (k *KV) Get(key string, q *QueryOptions) (*KVPair, *QueryMeta, error)
- func (k *KV) Keys(prefix, separator string, q *QueryOptions) ([]string, *QueryMeta, error)
- func (k *KV) List(prefix string, q *QueryOptions) (KVPairs, *QueryMeta, error)
- func (k *KV) Put(p *KVPair, q *WriteOptions) (*WriteMeta, error)
- func (k *KV) Release(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)
- func (k *KV) Txn(txn KVTxnOps, q *QueryOptions) (bool, *KVTxnResponse, *QueryMeta, error)
- type KVOp
- type KVPair
- type KVPairs
- type KVTxnOp
- type KVTxnOps
- type KVTxnResponse
- type KeyringResponse
- type Lock
- type LockOptions
- type Node
- type Operator
- func (op *Operator) KeyringInstall(key string, q *WriteOptions) error
- func (op *Operator) KeyringList(q *QueryOptions) ([]*KeyringResponse, error)
- func (op *Operator) KeyringRemove(key string, q *WriteOptions) error
- func (op *Operator) KeyringUse(key string, q *WriteOptions) error
- func (op *Operator) RaftGetConfiguration(q *QueryOptions) (*RaftConfiguration, error)
- func (op *Operator) RaftRemovePeerByAddress(address string, q *WriteOptions) error
- type PreparedQuery
- func (c *PreparedQuery) Create(query *PreparedQueryDefinition, q *WriteOptions) (string, *WriteMeta, error)
- func (c *PreparedQuery) Delete(queryID string, q *WriteOptions) (*WriteMeta, error)
- func (c *PreparedQuery) Execute(queryIDOrName string, q *QueryOptions) (*PreparedQueryExecuteResponse, *QueryMeta, error)
- func (c *PreparedQuery) Get(queryID string, q *QueryOptions) ([]*PreparedQueryDefinition, *QueryMeta, error)
- func (c *PreparedQuery) List(q *QueryOptions) ([]*PreparedQueryDefinition, *QueryMeta, error)
- func (c *PreparedQuery) Update(query *PreparedQueryDefinition, q *WriteOptions) (*WriteMeta, error)
- type PreparedQueryDefinition
- type PreparedQueryExecuteResponse
- type QueryDNSOptions
- type QueryDatacenterOptions
- type QueryMeta
- type QueryOptions
- type QueryTemplate
- type RaftConfiguration
- type RaftServer
- type Raw
- type Semaphore
- type SemaphoreOptions
- type ServiceEntry
- type ServiceQuery
- type Session
- func (s *Session) Create(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error)
- func (s *Session) CreateNoChecks(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error)
- func (s *Session) Destroy(id string, q *WriteOptions) (*WriteMeta, error)
- func (s *Session) Info(id string, q *QueryOptions) (*SessionEntry, *QueryMeta, error)
- func (s *Session) List(q *QueryOptions) ([]*SessionEntry, *QueryMeta, error)
- func (s *Session) Node(node string, q *QueryOptions) ([]*SessionEntry, *QueryMeta, error)
- func (s *Session) Renew(id string, q *WriteOptions) (*SessionEntry, *WriteMeta, error)
- func (s *Session) RenewPeriodic(initialTTL string, id string, q *WriteOptions, doneCh chan struct{}) error
- type SessionEntry
- type Snapshot
- type Status
- type TLSConfig
- type TxnError
- type TxnErrors
- type TxnOp
- type TxnOps
- type TxnResponse
- type TxnResult
- type TxnResults
- type UserEvent
- type WriteMeta
- type WriteOptions
Constants ¶
const ( // ACLCLientType is the client type token ACLClientType = "client" // ACLManagementType is the management type token ACLManagementType = "management" )
const ( // HTTPAddrEnvName defines an environment variable name which sets // the HTTP address if there is no -http-addr specified. HTTPAddrEnvName = "CONSUL_HTTP_ADDR" // HTTPTokenEnvName defines an environment variable name which sets // the HTTP token. HTTPTokenEnvName = "CONSUL_HTTP_TOKEN" // HTTPAuthEnvName defines an environment variable name which sets // the HTTP authentication header. HTTPAuthEnvName = "CONSUL_HTTP_AUTH" // HTTPSSLEnvName defines an environment variable name which sets // whether or not to use HTTPS. HTTPSSLEnvName = "CONSUL_HTTP_SSL" // HTTPSSLVerifyEnvName defines an environment variable name which sets // whether or not to disable certificate checking. HTTPSSLVerifyEnvName = "CONSUL_HTTP_SSL_VERIFY" )
const ( // HealthAny is special, and is used as a wild card, // not as a specific state. HealthAny = "any" HealthPassing = "passing" HealthWarning = "warning" HealthCritical = "critical" HealthMaint = "maintenance" )
const ( // NodeMaint is the special key set by a node in maintenance mode. NodeMaint = "_node_maintenance" // ServiceMaintPrefix is the prefix for a service in maintenance mode. ServiceMaintPrefix = "_service_maintenance:" )
const ( // DefaultLockSessionName is the Session Name we assign if none is provided DefaultLockSessionName = "Consul API Lock" // DefaultLockSessionTTL is the default session TTL if no Session is provided // when creating a new Lock. This is used because we do not have another // other check to depend upon. DefaultLockSessionTTL = "15s" // DefaultLockWaitTime is how long we block for at a time to check if lock // acquisition is possible. This affects the minimum time it takes to cancel // a Lock acquisition. DefaultLockWaitTime = 15 * time.Second // DefaultLockRetryTime is how long we wait after a failed lock acquisition // before attempting to do the lock again. This is so that once a lock-delay // is in effect, we do not hot loop retrying the acquisition. DefaultLockRetryTime = 5 * time.Second // DefaultMonitorRetryTime is how long we wait after a failed monitor check // of a lock (500 response code). This allows the monitor to ride out brief // periods of unavailability, subject to the MonitorRetries setting in the // lock options which is by default set to 0, disabling this feature. This // affects locks and semaphores. DefaultMonitorRetryTime = 2 * time.Second // LockFlagValue is a magic flag we set to indicate a key // is being used for a lock. It is used to detect a potential // conflict with a semaphore. LockFlagValue = 0x2ddccbc058a50c18 )
const ( // DefaultSemaphoreSessionName is the Session Name we assign if none is provided DefaultSemaphoreSessionName = "Consul API Semaphore" // DefaultSemaphoreSessionTTL is the default session TTL if no Session is provided // when creating a new Semaphore. This is used because we do not have another // other check to depend upon. DefaultSemaphoreSessionTTL = "15s" // DefaultSemaphoreWaitTime is how long we block for at a time to check if semaphore // acquisition is possible. This affects the minimum time it takes to cancel // a Semaphore acquisition. DefaultSemaphoreWaitTime = 15 * time.Second // DefaultSemaphoreKey is the key used within the prefix to // use for coordination between all the contenders. DefaultSemaphoreKey = ".lock" // SemaphoreFlagValue is a magic flag we set to indicate a key // is being used for a semaphore. It is used to detect a potential // conflict with a lock. SemaphoreFlagValue = 0xe0f69a2baa414de0 )
const ( // SessionBehaviorRelease is the default behavior and causes // all associated locks to be released on session invalidation. SessionBehaviorRelease = "release" // SessionBehaviorDelete is new in Consul 0.5 and changes the // behavior to delete all associated locks on session invalidation. // It can be used in a way similar to Ephemeral Nodes in ZooKeeper. SessionBehaviorDelete = "delete" )
Variables ¶
var ( // ErrLockHeld is returned if we attempt to double lock ErrLockHeld = fmt.Errorf("Lock already held") // ErrLockNotHeld is returned if we attempt to unlock a lock // that we do not hold. ErrLockNotHeld = fmt.Errorf("Lock not held") // ErrLockInUse is returned if we attempt to destroy a lock // that is in use. ErrLockInUse = fmt.Errorf("Lock in use") // ErrLockConflict is returned if the flags on a key // used for a lock do not match expectation ErrLockConflict = fmt.Errorf("Existing key does not match lock use") )
var ( // ErrSemaphoreHeld is returned if we attempt to double lock ErrSemaphoreHeld = fmt.Errorf("Semaphore already held") // ErrSemaphoreNotHeld is returned if we attempt to unlock a semaphore // that we do not hold. ErrSemaphoreNotHeld = fmt.Errorf("Semaphore not held") // ErrSemaphoreInUse is returned if we attempt to destroy a semaphore // that is in use. ErrSemaphoreInUse = fmt.Errorf("Semaphore in use") // ErrSemaphoreConflict is returned if the flags on a key // used for a semaphore do not match expectation ErrSemaphoreConflict = fmt.Errorf("Existing key does not match semaphore use") )
var ErrSessionExpired = errors.New("session expired")
Functions ¶
func IsServerError ¶ added in v0.6.1
IsServerError returns true for 500 errors from the Consul servers, these are usually retryable at a later time.
Types ¶
type ACL ¶
type ACL struct {
// contains filtered or unexported fields
}
ACL can be used to query the ACL endpoints
func (*ACL) Destroy ¶
func (a *ACL) Destroy(id string, q *WriteOptions) (*WriteMeta, error)
Destroy is used to destroy a given ACL token ID
type ACLEntry ¶
type ACLEntry struct { CreateIndex uint64 ModifyIndex uint64 ID string Name string Type string Rules string }
ACLEntry is used to represent an ACL entry
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent can be used to query the Agent endpoints
func (*Agent) CheckDeregister ¶
CheckDeregister is used to deregister a check with the local agent
func (*Agent) CheckRegister ¶
func (a *Agent) CheckRegister(check *AgentCheckRegistration) error
CheckRegister is used to register a new check with the local agent
func (*Agent) Checks ¶
func (a *Agent) Checks() (map[string]*AgentCheck, error)
Checks returns the locally registered checks
func (*Agent) DisableNodeMaintenance ¶
DisableNodeMaintenance toggles node maintenance mode off for the agent we are connected to.
func (*Agent) DisableServiceMaintenance ¶
DisableServiceMaintenance toggles service maintenance mode off for the given service ID.
func (*Agent) EnableNodeMaintenance ¶
EnableNodeMaintenance toggles node maintenance mode on for the agent we are connected to.
func (*Agent) EnableServiceMaintenance ¶
EnableServiceMaintenance toggles service maintenance mode on for the given service ID.
func (*Agent) FailTTL ¶
FailTTL is used to set a TTL check to the failing state.
DEPRECATION NOTICE: This interface is deprecated in favor of UpdateTTL(). The client interface will be removed in 0.8 or changed to use UpdateTTL()'s endpoint and the server endpoints will be removed in 0.9.
func (*Agent) ForceLeave ¶
ForceLeave is used to have the agent eject a failed node
func (*Agent) Leave ¶ added in v0.7.2
Leave is used to have the agent gracefully leave the cluster and shutdown
func (*Agent) Members ¶
func (a *Agent) Members(wan bool) ([]*AgentMember, error)
Members returns the known gossip members. The WAN flag can be used to query a server for WAN members.
func (*Agent) Monitor ¶ added in v0.7.2
func (a *Agent) Monitor(loglevel string, stopCh chan struct{}, q *QueryOptions) (chan string, error)
Monitor returns a channel which will receive streaming logs from the agent Providing a non-nil stopCh can be used to close the connection and stop the log stream
func (*Agent) PassTTL ¶
PassTTL is used to set a TTL check to the passing state.
DEPRECATION NOTICE: This interface is deprecated in favor of UpdateTTL(). The client interface will be removed in 0.8 or changed to use UpdateTTL()'s endpoint and the server endpoints will be removed in 0.9.
func (*Agent) Reload ¶ added in v0.7.2
Reload triggers a configuration reload for the agent we are connected to.
func (*Agent) Self ¶
Self is used to query the agent we are speaking to for information about itself
func (*Agent) ServiceDeregister ¶
ServiceDeregister is used to deregister a service with the local agent
func (*Agent) ServiceRegister ¶
func (a *Agent) ServiceRegister(service *AgentServiceRegistration) error
ServiceRegister is used to register a new service with the local agent
func (*Agent) Services ¶
func (a *Agent) Services() (map[string]*AgentService, error)
Services returns the locally registered services
func (*Agent) UpdateTTL ¶
UpdateTTL is used to update the TTL of a check. This uses the newer API that was introduced in Consul 0.6.4 and later. We translate the old status strings for compatibility (though a newer version of Consul will still be required to use this API).
type AgentCheck ¶
type AgentCheck struct { Node string CheckID string Name string Status string Notes string Output string ServiceID string ServiceName string }
AgentCheck represents a check known to the agent
type AgentCheckRegistration ¶
type AgentCheckRegistration struct { ID string `json:",omitempty"` Name string `json:",omitempty"` Notes string `json:",omitempty"` ServiceID string `json:",omitempty"` AgentServiceCheck }
AgentCheckRegistration is used to register a new check
type AgentMember ¶
type AgentMember struct { Name string Addr string Port uint16 Tags map[string]string Status int ProtocolMin uint8 ProtocolMax uint8 ProtocolCur uint8 DelegateMin uint8 DelegateMax uint8 DelegateCur uint8 }
AgentMember represents a cluster member known to the agent
type AgentService ¶
type AgentService struct { ID string Service string Tags []string Port int Address string EnableTagOverride bool }
AgentService represents a service known to the agent
type AgentServiceCheck ¶
type AgentServiceCheck struct { Script string `json:",omitempty"` DockerContainerID string `json:",omitempty"` Shell string `json:",omitempty"` // Only supported for Docker. Interval string `json:",omitempty"` Timeout string `json:",omitempty"` TTL string `json:",omitempty"` HTTP string `json:",omitempty"` TCP string `json:",omitempty"` Status string `json:",omitempty"` Notes string `json:",omitempty"` TLSSkipVerify bool `json:",omitempty"` // In Consul 0.7 and later, checks that are associated with a service // may also contain this optional DeregisterCriticalServiceAfter field, // which is a timeout in the same Go time format as Interval and TTL. If // a check is in the critical state for more than this configured value, // then its associated service (and all of its associated checks) will // automatically be deregistered. DeregisterCriticalServiceAfter string `json:",omitempty"` }
AgentServiceCheck is used to define a node or service level check
type AgentServiceChecks ¶
type AgentServiceChecks []*AgentServiceCheck
type AgentServiceRegistration ¶
type AgentServiceRegistration struct { ID string `json:",omitempty"` Name string `json:",omitempty"` Tags []string `json:",omitempty"` Port int `json:",omitempty"` Address string `json:",omitempty"` EnableTagOverride bool `json:",omitempty"` Check *AgentServiceCheck Checks AgentServiceChecks }
AgentServiceRegistration is used to register a new service
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog can be used to query the Catalog endpoints
func (*Catalog) Datacenters ¶
Datacenters is used to query for all the known datacenters
func (*Catalog) Deregister ¶
func (c *Catalog) Deregister(dereg *CatalogDeregistration, q *WriteOptions) (*WriteMeta, error)
func (*Catalog) Node ¶
func (c *Catalog) Node(node string, q *QueryOptions) (*CatalogNode, *QueryMeta, error)
Node is used to query for service information about a single node
func (*Catalog) Nodes ¶
func (c *Catalog) Nodes(q *QueryOptions) ([]*Node, *QueryMeta, error)
Nodes is used to query all the known nodes
func (*Catalog) Register ¶
func (c *Catalog) Register(reg *CatalogRegistration, q *WriteOptions) (*WriteMeta, error)
func (*Catalog) Service ¶
func (c *Catalog) Service(service, tag string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error)
Service is used to query catalog entries for a given service
type CatalogDeregistration ¶
type CatalogNode ¶
type CatalogNode struct { Node *Node Services map[string]*AgentService }
type CatalogRegistration ¶
type CatalogRegistration struct { Node string Address string TaggedAddresses map[string]string Datacenter string Service *AgentService Check *AgentCheck }
type CatalogService ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client provides a client to the Consul API
func (*Client) Coordinate ¶ added in v0.6.0
func (c *Client) Coordinate() *Coordinate
Coordinate returns a handle to the coordinate endpoints
func (*Client) LockKey ¶
LockKey returns a handle to a lock struct which can be used to acquire and release the mutex. The key used must have write permissions.
func (*Client) LockOpts ¶
func (c *Client) LockOpts(opts *LockOptions) (*Lock, error)
LockOpts returns a handle to a lock struct which can be used to acquire and release the mutex. The key used must have write permissions.
func (*Client) PreparedQuery ¶ added in v0.6.0
func (c *Client) PreparedQuery() *PreparedQuery
PreparedQuery returns a handle to the prepared query endpoints.
func (*Client) SemaphoreOpts ¶
func (c *Client) SemaphoreOpts(opts *SemaphoreOptions) (*Semaphore, error)
SemaphoreOpts is used to create a Semaphore with the given options. The prefix must have write privileges, and the limit must be agreed upon by all contenders. If a Session is not provided, one will be created.
func (*Client) SemaphorePrefix ¶
SemaphorePrefix is used to created a Semaphore which will operate at the given KV prefix and uses the given limit for the semaphore. The prefix must have write privileges, and the limit must be agreed upon by all contenders.
type Config ¶
type Config struct { // Address is the address of the Consul server Address string // Scheme is the URI scheme for the Consul server Scheme string // Datacenter to use. If not provided, the default agent datacenter is used. Datacenter string // HttpClient is the client to use. Default will be // used if not provided. HttpClient *http.Client // HttpAuth is the auth info to use for http access. HttpAuth *HttpBasicAuth // WaitTime limits how long a Watch will block. If not provided, // the agent default values will be used. WaitTime time.Duration // Token is used to provide a per-request ACL token // which overrides the agent's default token. Token string }
Config is used to configure the creation of a client
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a default configuration for the client. By default this will pool and reuse idle connections to Consul. If you have a long-lived client object, this is the desired behavior and should make the most efficient use of the connections to Consul. If you don't reuse a client object , which is not recommended, then you may notice idle connections building up over time. To avoid this, use the DefaultNonPooledConfig() instead.
func DefaultNonPooledConfig ¶ added in v0.6.4
func DefaultNonPooledConfig() *Config
DefaultNonPooledConfig returns a default configuration for the client which does not pool connections. This isn't a recommended configuration because it will reconnect to Consul on every request, but this is useful to avoid the accumulation of idle connections if you make many client objects during the lifetime of your application.
type Coordinate ¶ added in v0.6.0
type Coordinate struct {
// contains filtered or unexported fields
}
Coordinate can be used to query the coordinate endpoints
func (*Coordinate) Datacenters ¶ added in v0.6.0
func (c *Coordinate) Datacenters() ([]*CoordinateDatacenterMap, error)
Datacenters is used to return the coordinates of all the servers in the WAN pool.
func (*Coordinate) Nodes ¶ added in v0.6.0
func (c *Coordinate) Nodes(q *QueryOptions) ([]*CoordinateEntry, *QueryMeta, error)
Nodes is used to return the coordinates of all the nodes in the LAN pool.
type CoordinateDatacenterMap ¶ added in v0.6.0
type CoordinateDatacenterMap struct { Datacenter string Coordinates []CoordinateEntry }
CoordinateDatacenterMap represents a datacenter and its associated WAN nodes and their associates coordinates.
type CoordinateEntry ¶ added in v0.6.0
type CoordinateEntry struct { Node string Coord *coordinate.Coordinate }
CoordinateEntry represents a node and its associated network coordinate.
type Event ¶
type Event struct {
// contains filtered or unexported fields
}
Event can be used to query the Event endpoints
func (*Event) Fire ¶
Fire is used to fire a new user event. Only the Name, Payload and Filters are respected. This returns the ID or an associated error. Cross DC requests are supported.
func (*Event) IDToIndex ¶
IDToIndex is a bit of a hack. This simulates the index generation to convert an event ID into a WaitIndex.
type Health ¶
type Health struct {
// contains filtered or unexported fields
}
Health can be used to query the Health endpoints
func (*Health) Checks ¶
func (h *Health) Checks(service string, q *QueryOptions) (HealthChecks, *QueryMeta, error)
Checks is used to return the checks associated with a service
func (*Health) Node ¶
func (h *Health) Node(node string, q *QueryOptions) (HealthChecks, *QueryMeta, error)
Node is used to query for checks belonging to a given node
func (*Health) Service ¶
func (h *Health) Service(service, tag string, passingOnly bool, q *QueryOptions) ([]*ServiceEntry, *QueryMeta, error)
Service is used to query health information along with service info for a given service. It can optionally do server-side filtering on a tag or nodes with passing health checks only.
func (*Health) State ¶
func (h *Health) State(state string, q *QueryOptions) (HealthChecks, *QueryMeta, error)
State is used to retrieve all the checks in a given state. The wildcard "any" state can also be used for all checks.
type HealthCheck ¶
type HealthCheck struct { Node string CheckID string Name string Status string Notes string Output string ServiceID string ServiceName string }
HealthCheck is used to represent a single check
type HealthChecks ¶ added in v0.7.2
type HealthChecks []*HealthCheck
HealthChecks is a collection of HealthCheck structs.
func (HealthChecks) AggregatedStatus ¶ added in v0.7.2
func (c HealthChecks) AggregatedStatus() string
AggregatedStatus returns the "best" status for the list of health checks. Because a given entry may have many service and node-level health checks attached, this function determines the best representative of the status as as single string using the following heuristic:
maintenance > critical > warning > passing
type HttpBasicAuth ¶
type HttpBasicAuth struct { // Username to use for HTTP Basic Authentication Username string // Password to use for HTTP Basic Authentication Password string }
HttpBasicAuth is used to authenticate http client with HTTP Basic Authentication
type KV ¶
type KV struct {
// contains filtered or unexported fields
}
KV is used to manipulate the K/V API
func (*KV) Acquire ¶
Acquire is used for a lock acquisition operation. The Key, Flags, Value and Session are respected. Returns true on success or false on failures.
func (*KV) CAS ¶
CAS is used for a Check-And-Set operation. The Key, ModifyIndex, Flags and Value are respected. Returns true on success or false on failures.
func (*KV) Delete ¶
func (k *KV) Delete(key string, w *WriteOptions) (*WriteMeta, error)
Delete is used to delete a single key
func (*KV) DeleteCAS ¶
DeleteCAS is used for a Delete Check-And-Set operation. The Key and ModifyIndex are respected. Returns true on success or false on failures.
func (*KV) DeleteTree ¶
func (k *KV) DeleteTree(prefix string, w *WriteOptions) (*WriteMeta, error)
DeleteTree is used to delete all keys under a prefix
func (*KV) Get ¶
Get is used to lookup a single key. The returned pointer to the KVPair will be nil if the key does not exist.
func (*KV) Keys ¶
Keys is used to list all the keys under a prefix. Optionally, a separator can be used to limit the responses.
func (*KV) Put ¶
func (k *KV) Put(p *KVPair, q *WriteOptions) (*WriteMeta, error)
Put is used to write a new value. Only the Key, Flags and Value is respected.
func (*KV) Release ¶
Release is used for a lock release operation. The Key, Flags, Value and Session are respected. Returns true on success or false on failures.
func (*KV) Txn ¶ added in v0.7.0
func (k *KV) Txn(txn KVTxnOps, q *QueryOptions) (bool, *KVTxnResponse, *QueryMeta, error)
Txn is used to apply multiple KV operations in a single, atomic transaction.
Note that Go will perform the required base64 encoding on the values automatically because the type is a byte slice. Transactions are defined as a list of operations to perform, using the KVOp constants and KVTxnOp structure to define operations. If any operation fails, none of the changes are applied to the state store. Note that this hides the internal raw transaction interface and munges the input and output types into KV-specific ones for ease of use. If there are more non-KV operations in the future we may break out a new transaction API client, but it will be easy to keep this KV-specific variant supported.
Even though this is generally a write operation, we take a QueryOptions input and return a QueryMeta output. If the transaction contains only read ops, then Consul will fast-path it to a different endpoint internally which supports consistency controls, but not blocking. If there are write operations then the request will always be routed through raft and any consistency settings will be ignored.
Here's an example:
ops := KVTxnOps{ &KVTxnOp{ Verb: KVLock, Key: "test/lock", Session: "adf4238a-882b-9ddc-4a9d-5b6758e4159e", Value: []byte("hello"), }, &KVTxnOp{ Verb: KVGet, Key: "another/key", }, }
ok, response, _, err := kv.Txn(&ops, nil)
If there is a problem making the transaction request then an error will be returned. Otherwise, the ok value will be true if the transaction succeeded or false if it was rolled back. The response is a structured return value which will have the outcome of the transaction. Its Results member will have entries for each operation. Deleted keys will have a nil entry in the, and to save space, the Value of each key in the Results will be nil unless the operation is a KVGet. If the transaction was rolled back, the Errors member will have entries referencing the index of the operation that failed along with an error message.
type KVOp ¶ added in v0.7.0
type KVOp string
KVOp constants give possible operations available in a KVTxn.
const ( KVSet KVOp = "set" KVDelete KVOp = "delete" KVDeleteCAS KVOp = "delete-cas" KVDeleteTree KVOp = "delete-tree" KVCAS KVOp = "cas" KVLock KVOp = "lock" KVUnlock KVOp = "unlock" KVGet KVOp = "get" KVGetTree KVOp = "get-tree" KVCheckSession KVOp = "check-session" KVCheckIndex KVOp = "check-index" )
type KVPair ¶
type KVPair struct { // Key is the name of the key. It is also part of the URL path when accessed // via the API. Key string // CreateIndex holds the index corresponding the creation of this KVPair. This // is a read-only field. CreateIndex uint64 // ModifyIndex is used for the Check-And-Set operations and can also be fed // back into the WaitIndex of the QueryOptions in order to perform blocking // queries. ModifyIndex uint64 // LockIndex holds the index corresponding to a lock on this key, if any. This // is a read-only field. LockIndex uint64 // Flags are any user-defined flags on the key. It is up to the implementer // to check these values, since Consul does not treat them specially. Flags uint64 // Value is the value for the key. This can be any value, but it will be // base64 encoded upon transport. Value []byte // Session is a string representing the ID of the session. Any other // interactions with this key over the same session must specify the same // session ID. Session string }
KVPair is used to represent a single K/V entry
type KVTxnOps ¶ added in v0.7.0
type KVTxnOps []*KVTxnOp
KVTxnOps defines a set of operations to be performed inside a single transaction.
type KVTxnResponse ¶ added in v0.7.0
KVTxnResponse has the outcome of a transaction.
type KeyringResponse ¶ added in v0.7.2
type KeyringResponse struct { // Whether this response is for a WAN ring WAN bool // The datacenter name this request corresponds to Datacenter string // A map of the encryption keys to the number of nodes they're installed on Keys map[string]int // The total number of nodes in this ring NumNodes int }
KeyringResponse is returned when listing the gossip encryption keys
type Lock ¶
type Lock struct {
// contains filtered or unexported fields
}
Lock is used to implement client-side leader election. It is follows the algorithm as described here: https://www.consul.io/docs/guides/leader-election.html.
func (*Lock) Destroy ¶
Destroy is used to cleanup the lock entry. It is not necessary to invoke. It will fail if the lock is in use.
func (*Lock) Lock ¶
Lock attempts to acquire the lock and blocks while doing so. Providing a non-nil stopCh can be used to abort the lock attempt. Returns a channel that is closed if our lock is lost or an error. This channel could be closed at any time due to session invalidation, communication errors, operator intervention, etc. It is NOT safe to assume that the lock is held until Unlock() unless the Session is specifically created without any associated health checks. By default Consul sessions prefer liveness over safety and an application must be able to handle the lock being lost.
type LockOptions ¶
type LockOptions struct { Key string // Must be set and have write permissions Value []byte // Optional, value to associate with the lock Session string // Optional, created if not specified SessionOpts *SessionEntry // Optional, options to use when creating a session SessionName string // Optional, defaults to DefaultLockSessionName (ignored if SessionOpts is given) SessionTTL string // Optional, defaults to DefaultLockSessionTTL (ignored if SessionOpts is given) MonitorRetries int // Optional, defaults to 0 which means no retries MonitorRetryTime time.Duration // Optional, defaults to DefaultMonitorRetryTime LockWaitTime time.Duration // Optional, defaults to DefaultLockWaitTime LockTryOnce bool // Optional, defaults to false which means try forever }
LockOptions is used to parameterize the Lock behavior.
type Operator ¶ added in v0.7.0
type Operator struct {
// contains filtered or unexported fields
}
Operator can be used to perform low-level operator tasks for Consul.
func (*Operator) KeyringInstall ¶ added in v0.7.2
func (op *Operator) KeyringInstall(key string, q *WriteOptions) error
KeyringInstall is used to install a new gossip encryption key into the cluster
func (*Operator) KeyringList ¶ added in v0.7.2
func (op *Operator) KeyringList(q *QueryOptions) ([]*KeyringResponse, error)
KeyringList is used to list the gossip keys installed in the cluster
func (*Operator) KeyringRemove ¶ added in v0.7.2
func (op *Operator) KeyringRemove(key string, q *WriteOptions) error
KeyringRemove is used to remove a gossip encryption key from the cluster
func (*Operator) KeyringUse ¶ added in v0.7.2
func (op *Operator) KeyringUse(key string, q *WriteOptions) error
KeyringUse is used to change the active gossip encryption key
func (*Operator) RaftGetConfiguration ¶ added in v0.7.0
func (op *Operator) RaftGetConfiguration(q *QueryOptions) (*RaftConfiguration, error)
RaftGetConfiguration is used to query the current Raft peer set.
func (*Operator) RaftRemovePeerByAddress ¶ added in v0.7.0
func (op *Operator) RaftRemovePeerByAddress(address string, q *WriteOptions) error
RaftRemovePeerByAddress is used to kick a stale peer (one that it in the Raft quorum but no longer known to Serf or the catalog) by address in the form of "IP:port".
type PreparedQuery ¶ added in v0.6.0
type PreparedQuery struct {
// contains filtered or unexported fields
}
PreparedQuery can be used to query the prepared query endpoints.
func (*PreparedQuery) Create ¶ added in v0.6.0
func (c *PreparedQuery) Create(query *PreparedQueryDefinition, q *WriteOptions) (string, *WriteMeta, error)
Create makes a new prepared query. The ID of the new query is returned.
func (*PreparedQuery) Delete ¶ added in v0.6.0
func (c *PreparedQuery) Delete(queryID string, q *WriteOptions) (*WriteMeta, error)
Delete is used to delete a specific prepared query.
func (*PreparedQuery) Execute ¶ added in v0.6.0
func (c *PreparedQuery) Execute(queryIDOrName string, q *QueryOptions) (*PreparedQueryExecuteResponse, *QueryMeta, error)
Execute is used to execute a specific prepared query. You can execute using a query ID or name.
func (*PreparedQuery) Get ¶ added in v0.6.0
func (c *PreparedQuery) Get(queryID string, q *QueryOptions) ([]*PreparedQueryDefinition, *QueryMeta, error)
Get is used to fetch a specific prepared query.
func (*PreparedQuery) List ¶ added in v0.6.0
func (c *PreparedQuery) List(q *QueryOptions) ([]*PreparedQueryDefinition, *QueryMeta, error)
List is used to fetch all the prepared queries (always requires a management token).
func (*PreparedQuery) Update ¶ added in v0.6.0
func (c *PreparedQuery) Update(query *PreparedQueryDefinition, q *WriteOptions) (*WriteMeta, error)
Update makes updates to an existing prepared query.
type PreparedQueryDefinition ¶ added in v0.6.0
type PreparedQueryDefinition struct { // ID is this UUID-based ID for the query, always generated by Consul. ID string // Name is an optional friendly name for the query supplied by the // user. NOTE - if this feature is used then it will reduce the security // of any read ACL associated with this query/service since this name // can be used to locate nodes with supplying any ACL. Name string // Session is an optional session to tie this query's lifetime to. If // this is omitted then the query will not expire. Session string // Token is the ACL token used when the query was created, and it is // used when a query is subsequently executed. This token, or a token // with management privileges, must be used to change the query later. Token string // Service defines a service query (leaving things open for other types // later). Service ServiceQuery // DNS has options that control how the results of this query are // served over DNS. DNS QueryDNSOptions // Template is used to pass through the arguments for creating a // prepared query with an attached template. If a template is given, // interpolations are possible in other struct fields. Template QueryTemplate }
PrepatedQueryDefinition defines a complete prepared query.
type PreparedQueryExecuteResponse ¶ added in v0.6.0
type PreparedQueryExecuteResponse struct { // Service is the service that was queried. Service string // Nodes has the nodes that were output by the query. Nodes []ServiceEntry // DNS has the options for serving these results over DNS. DNS QueryDNSOptions // Datacenter is the datacenter that these results came from. Datacenter string // Failovers is a count of how many times we had to query a remote // datacenter. Failovers int }
PreparedQueryExecuteResponse has the results of executing a query.
type QueryDNSOptions ¶ added in v0.6.0
type QueryDNSOptions struct { // TTL is the time to live for the served DNS results. TTL string }
QueryDNSOptions controls settings when query results are served over DNS.
type QueryDatacenterOptions ¶ added in v0.6.0
type QueryDatacenterOptions struct { // NearestN is set to the number of remote datacenters to try, based on // network coordinates. NearestN int // Datacenters is a fixed list of datacenters to try after NearestN. We // never try a datacenter multiple times, so those are subtracted from // this list before proceeding. Datacenters []string }
QueryDatacenterOptions sets options about how we fail over if there are no healthy nodes in the local datacenter.
type QueryMeta ¶
type QueryMeta struct { // LastIndex. This can be used as a WaitIndex to perform // a blocking query LastIndex uint64 // Time of last contact from the leader for the // server servicing the request LastContact time.Duration // Is there a known leader KnownLeader bool // How long did the request take RequestTime time.Duration // Is address translation enabled for HTTP responses on this agent AddressTranslationEnabled bool }
QueryMeta is used to return meta data about a query
type QueryOptions ¶
type QueryOptions struct { // Providing a datacenter overwrites the DC provided // by the Config Datacenter string // AllowStale allows any Consul server (non-leader) to service // a read. This allows for lower latency and higher throughput AllowStale bool // RequireConsistent forces the read to be fully consistent. // This is more expensive but prevents ever performing a stale // read. RequireConsistent bool // WaitIndex is used to enable a blocking query. Waits // until the timeout or the next index is reached WaitIndex uint64 // WaitTime is used to bound the duration of a wait. // Defaults to that of the Config, but can be overridden. WaitTime time.Duration // Token is used to provide a per-request ACL token // which overrides the agent's default token. Token string // Near is used to provide a node name that will sort the results // in ascending order based on the estimated round trip time from // that node. Setting this to "_agent" will use the agent's node // for the sort. Near string }
QueryOptions are used to parameterize a query
type QueryTemplate ¶ added in v0.7.0
type QueryTemplate struct { // Type specifies the type of the query template. Currently only // "name_prefix_match" is supported. This field is required. Type string // Regexp allows specifying a regex pattern to match against the name // of the query being executed. Regexp string }
QueryTemplate carries the arguments for creating a templated query.
type RaftConfiguration ¶ added in v0.7.0
type RaftConfiguration struct { // Servers has the list of servers in the Raft configuration. Servers []*RaftServer // Index has the Raft index of this configuration. Index uint64 }
RaftConfigration is returned when querying for the current Raft configuration.
type RaftServer ¶ added in v0.7.0
type RaftServer struct { // ID is the unique ID for the server. These are currently the same // as the address, but they will be changed to a real GUID in a future // release of Consul. ID string // Node is the node name of the server, as known by Consul, or this // will be set to "(unknown)" otherwise. Node string // Address is the IP:port of the server, used for Raft communications. Address string // Leader is true if this server is the current cluster leader. Leader bool // Voter is true if this server has a vote in the cluster. This might // be false if the server is staging and still coming online, or if // it's a non-voting server, which will be added in a future release of // Consul. Voter bool }
RaftServer has information about a server in the Raft configuration.
type Raw ¶
type Raw struct {
// contains filtered or unexported fields
}
Raw can be used to do raw queries against custom endpoints
type Semaphore ¶
type Semaphore struct {
// contains filtered or unexported fields
}
Semaphore is used to implement a distributed semaphore using the Consul KV primitives.
func (*Semaphore) Acquire ¶
Acquire attempts to reserve a slot in the semaphore, blocking until success, interrupted via the stopCh or an error is encountered. Providing a non-nil stopCh can be used to abort the attempt. On success, a channel is returned that represents our slot. This channel could be closed at any time due to session invalidation, communication errors, operator intervention, etc. It is NOT safe to assume that the slot is held until Release() unless the Session is specifically created without any associated health checks. By default Consul sessions prefer liveness over safety and an application must be able to handle the session being lost.
type SemaphoreOptions ¶
type SemaphoreOptions struct { Prefix string // Must be set and have write permissions Limit int // Must be set, and be positive Value []byte // Optional, value to associate with the contender entry Session string // Optional, created if not specified SessionName string // Optional, defaults to DefaultLockSessionName SessionTTL string // Optional, defaults to DefaultLockSessionTTL MonitorRetries int // Optional, defaults to 0 which means no retries MonitorRetryTime time.Duration // Optional, defaults to DefaultMonitorRetryTime SemaphoreWaitTime time.Duration // Optional, defaults to DefaultSemaphoreWaitTime SemaphoreTryOnce bool // Optional, defaults to false which means try forever }
SemaphoreOptions is used to parameterize the Semaphore
type ServiceEntry ¶
type ServiceEntry struct { Node *Node Service *AgentService Checks HealthChecks }
ServiceEntry is used for the health service endpoint
type ServiceQuery ¶ added in v0.6.0
type ServiceQuery struct { // Service is the service to query. Service string // Near allows baking in the name of a node to automatically distance- // sort from. The magic "_agent" value is supported, which sorts near // the agent which initiated the request by default. Near string // Failover controls what we do if there are no healthy nodes in the // local datacenter. Failover QueryDatacenterOptions // If OnlyPassing is true then we will only include nodes with passing // health checks (critical AND warning checks will cause a node to be // discarded) OnlyPassing bool // Tags are a set of required and/or disallowed tags. If a tag is in // this list it must be present. If the tag is preceded with "!" then // it is disallowed. Tags []string }
ServiceQuery is used to query for a set of healthy nodes offering a specific service.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session can be used to query the Session endpoints
func (*Session) Create ¶
func (s *Session) Create(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error)
Create makes a new session. Providing a session entry can customize the session. It can also be nil to use defaults.
func (*Session) CreateNoChecks ¶
func (s *Session) CreateNoChecks(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error)
CreateNoChecks is like Create but is used specifically to create a session with no associated health checks.
func (*Session) Destroy ¶
func (s *Session) Destroy(id string, q *WriteOptions) (*WriteMeta, error)
Destroy invalidates a given session
func (*Session) Info ¶
func (s *Session) Info(id string, q *QueryOptions) (*SessionEntry, *QueryMeta, error)
Info looks up a single session
func (*Session) List ¶
func (s *Session) List(q *QueryOptions) ([]*SessionEntry, *QueryMeta, error)
List gets all active sessions
func (*Session) Node ¶
func (s *Session) Node(node string, q *QueryOptions) ([]*SessionEntry, *QueryMeta, error)
List gets sessions for a node
func (*Session) Renew ¶
func (s *Session) Renew(id string, q *WriteOptions) (*SessionEntry, *WriteMeta, error)
Renew renews the TTL on a given session
func (*Session) RenewPeriodic ¶
func (s *Session) RenewPeriodic(initialTTL string, id string, q *WriteOptions, doneCh chan struct{}) error
RenewPeriodic is used to periodically invoke Session.Renew on a session until a doneCh is closed. This is meant to be used in a long running goroutine to ensure a session stays valid.
type SessionEntry ¶
type SessionEntry struct { CreateIndex uint64 ID string Name string Node string Checks []string LockDelay time.Duration Behavior string TTL string }
SessionEntry represents a session in consul
type Snapshot ¶ added in v0.7.1
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot can be used to query the /v1/snapshot endpoint to take snapshots of Consul's internal state and restore snapshots for disaster recovery.
func (*Snapshot) Restore ¶ added in v0.7.1
func (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error
Restore streams in an existing snapshot and attempts to restore it.
func (*Snapshot) Save ¶ added in v0.7.1
func (s *Snapshot) Save(q *QueryOptions) (io.ReadCloser, *QueryMeta, error)
Save requests a new snapshot and provides an io.ReadCloser with the snapshot data to save. If this doesn't return an error, then it's the responsibility of the caller to close it. Only a subset of the QueryOptions are supported: Datacenter, AllowStale, and Token.
type Status ¶
type Status struct {
// contains filtered or unexported fields
}
Status can be used to query the Status endpoints
type TLSConfig ¶ added in v0.7.0
type TLSConfig struct { // Address is the optional address of the Consul server. The port, if any // will be removed from here and this will be set to the ServerName of the // resulting config. Address string // CAFile is the optional path to the CA certificate used for Consul // communication, defaults to the system bundle if not specified. CAFile string // CertFile is the optional path to the certificate for Consul // communication. If this is set then you need to also set KeyFile. CertFile string // KeyFile is the optional path to the private key for Consul communication. // If this is set then you need to also set CertFile. KeyFile string // InsecureSkipVerify if set to true will disable TLS host verification. InsecureSkipVerify bool }
TLSConfig is used to generate a TLSClientConfig that's useful for talking to Consul using TLS.
type TxnError ¶ added in v0.7.0
TxnError is used to return information about an operation in a transaction.
type TxnErrors ¶ added in v0.7.0
type TxnErrors []*TxnError
TxnErrors is a list of TxnError objects.
type TxnOp ¶ added in v0.7.0
type TxnOp struct {
KV *KVTxnOp
}
TxnOp is the internal format we send to Consul. It's not specific to KV, though currently only KV operations are supported.
type TxnResponse ¶ added in v0.7.0
type TxnResponse struct { Results TxnResults Errors TxnErrors }
TxnResponse is the internal format we receive from Consul.
type TxnResult ¶ added in v0.7.0
type TxnResult struct {
KV *KVPair
}
TxnResult is the internal format we receive from Consul.
type TxnResults ¶ added in v0.7.0
type TxnResults []*TxnResult
TxnResults is a list of TxnResult objects.
type UserEvent ¶
type UserEvent struct { ID string Name string Payload []byte NodeFilter string ServiceFilter string TagFilter string Version int LTime uint64 }
UserEvent represents an event that was fired by the user
type WriteOptions ¶
type WriteOptions struct { // Providing a datacenter overwrites the DC provided // by the Config Datacenter string // Token is used to provide a per-request ACL token // which overrides the agent's default token. Token string }
WriteOptions are used to parameterize a write