api

package
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 30, 2018 License: MPL-2.0 Imports: 23 Imported by: 0

README

Consul API client

This package provides the api package which attempts to provide programmatic access to the full Consul API.

Currently, all of the Consul APIs included in version 0.6.0 are supported.

Documentation

The full documentation is available on Godoc

Usage

Below is an example of using the Consul client:

package main

import "github.com/hashicorp/consul/api"
import "fmt"

func main() {
	// Get a new client
	client, err := api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err)
	}

	// Get a handle to the KV API
	kv := client.KV()

	// PUT a new KV pair
	p := &api.KVPair{Key: "REDIS_MAXCLIENTS", Value: []byte("1000")}
	_, err = kv.Put(p, nil)
	if err != nil {
		panic(err)
	}

	// Lookup the pair
	pair, _, err := kv.Get("REDIS_MAXCLIENTS", nil)
	if err != nil {
		panic(err)
	}
	fmt.Printf("KV: %v %s\n", pair.Key, pair.Value)
}

To run this example, start a Consul server:

consul agent -dev

Copy the code above into a file such as main.go.

Install and run. You'll see a key (REDIS_MAXCLIENTS) and value (1000) printed.

$ go get
$ go run main.go
KV: REDIS_MAXCLIENTS 1000

After running the code, you can also view the values in the Consul UI on your local machine at http://localhost:8500/ui/dc1/kv

Documentation

Overview

The /v1/operator/area endpoints are available only in Consul Enterprise and interact with its network area subsystem. Network areas are used to link together Consul servers in different Consul datacenters. With network areas, Consul datacenters can be linked together in ways other than a fully-connected mesh, as is required for Consul's WAN.

Index

Constants

View Source
const (
	// ACLClientType is the client type token
	ACLClientType = "client"

	// ACLManagementType is the management type token
	ACLManagementType = "management"
)
View Source
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"

	// HTTPCAFile defines an environment variable name which sets the
	// CA file to use for talking to Consul over TLS.
	HTTPCAFile = "CONSUL_CACERT"

	// HTTPCAPath defines an environment variable name which sets the
	// path to a directory of CA certs to use for talking to Consul over TLS.
	HTTPCAPath = "CONSUL_CAPATH"

	// HTTPClientCert defines an environment variable name which sets the
	// client cert file to use for talking to Consul over TLS.
	HTTPClientCert = "CONSUL_CLIENT_CERT"

	// HTTPClientKey defines an environment variable name which sets the
	// client key file to use for talking to Consul over TLS.
	HTTPClientKey = "CONSUL_CLIENT_KEY"

	// HTTPTLSServerName defines an environment variable name which sets the
	// server name to use as the SNI host when connecting via TLS
	HTTPTLSServerName = "CONSUL_TLS_SERVER_NAME"

	// HTTPSSLVerifyEnvName defines an environment variable name which sets
	// whether or not to disable certificate checking.
	HTTPSSLVerifyEnvName = "CONSUL_HTTP_SSL_VERIFY"
)
View Source
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"
)
View Source
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:"
)
View Source
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
)
View Source
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
)
View Source
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"
)
View Source
const AllSegments = "_all"

AllSegments is used to select for all segments in MembersOpts.

View Source
const IntentionDefaultNamespace = "default"

IntentionDefaultNamespace is the default namespace value.

Variables

View Source
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")
)
View Source
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")
)
View Source
var ErrSessionExpired = errors.New("session expired")

Functions

func IsRetryableError added in v1.0.0

func IsRetryableError(err error) bool

IsRetryableError returns true for 500 errors from the Consul servers, and network connection errors. These are usually retryable at a later time. This applies to reads but NOT to writes. This may return true for errors on writes that may have still gone through, so do not use this to retry any write operations.

func NewHttpClient added in v0.8.2

func NewHttpClient(transport *http.Transport, tlsConf TLSConfig) (*http.Client, error)

NewHttpClient returns an http client configured with the given Transport and TLS config.

func SetupTLSConfig added in v0.7.0

func SetupTLSConfig(tlsConfig *TLSConfig) (*tls.Config, error)

TLSConfig is used to generate a TLSClientConfig that's useful for talking to Consul using TLS.

Types

type ACL

type ACL struct {
	// contains filtered or unexported fields
}

ACL can be used to query the ACL endpoints

func (*ACL) Bootstrap added in v0.9.1

func (a *ACL) Bootstrap() (string, *WriteMeta, error)

Bootstrap is used to perform a one-time ACL bootstrap operation on a cluster to get the first management token.

func (*ACL) Clone

func (a *ACL) Clone(id string, q *WriteOptions) (string, *WriteMeta, error)

Clone is used to return a new token cloned from an existing one

func (*ACL) Create

func (a *ACL) Create(acl *ACLEntry, q *WriteOptions) (string, *WriteMeta, error)

Create is used to generate a new token with the given parameters

func (*ACL) Destroy

func (a *ACL) Destroy(id string, q *WriteOptions) (*WriteMeta, error)

Destroy is used to destroy a given ACL token ID

func (*ACL) Info

func (a *ACL) Info(id string, q *QueryOptions) (*ACLEntry, *QueryMeta, error)

Info is used to query for information about an ACL token

func (*ACL) List

func (a *ACL) List(q *QueryOptions) ([]*ACLEntry, *QueryMeta, error)

List is used to get all the ACL tokens

func (*ACL) Replication added in v0.8.2

func (a *ACL) Replication(q *QueryOptions) (*ACLReplicationStatus, *QueryMeta, error)

Replication returns the status of the ACL replication process in the datacenter

func (*ACL) Update

func (a *ACL) Update(acl *ACLEntry, q *WriteOptions) (*WriteMeta, error)

Update is used to update the rules of an existing token

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 ACLReplicationStatus added in v0.8.2

type ACLReplicationStatus struct {
	Enabled          bool
	Running          bool
	SourceDatacenter string
	ReplicatedIndex  uint64
	LastSuccess      time.Time
	LastError        time.Time
}

ACLReplicationStatus is used to represent the status of ACL replication.

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent can be used to query the Agent endpoints

func (*Agent) CheckDeregister

func (a *Agent) CheckDeregister(checkID string) error

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) ConnectAuthorize added in v1.2.0

func (a *Agent) ConnectAuthorize(auth *AgentAuthorizeParams) (*AgentAuthorize, error)

ConnectAuthorize is used to authorize an incoming connection to a natively integrated Connect service.

func (*Agent) ConnectCALeaf added in v1.2.0

func (a *Agent) ConnectCALeaf(serviceID string, q *QueryOptions) (*LeafCert, *QueryMeta, error)

ConnectCALeaf gets the leaf certificate for the given service ID.

func (*Agent) ConnectCARoots added in v1.2.0

func (a *Agent) ConnectCARoots(q *QueryOptions) (*CARootList, *QueryMeta, error)

ConnectCARoots returns the list of roots.

func (*Agent) ConnectProxyConfig added in v1.2.0

func (a *Agent) ConnectProxyConfig(proxyServiceID string, q *QueryOptions) (*ConnectProxyConfig, *QueryMeta, error)

ConnectProxyConfig gets the configuration for a local managed proxy instance.

Note that this uses an unconventional blocking mechanism since it's agent-local state. That means there is no persistent raft index so we block based on object hash instead.

func (*Agent) DisableNodeMaintenance

func (a *Agent) DisableNodeMaintenance() error

DisableNodeMaintenance toggles node maintenance mode off for the agent we are connected to.

func (*Agent) DisableServiceMaintenance

func (a *Agent) DisableServiceMaintenance(serviceID string) error

DisableServiceMaintenance toggles service maintenance mode off for the given service ID.

func (*Agent) EnableNodeMaintenance

func (a *Agent) EnableNodeMaintenance(reason string) error

EnableNodeMaintenance toggles node maintenance mode on for the agent we are connected to.

func (*Agent) EnableServiceMaintenance

func (a *Agent) EnableServiceMaintenance(serviceID, reason string) error

EnableServiceMaintenance toggles service maintenance mode on for the given service ID.

func (*Agent) FailTTL

func (a *Agent) FailTTL(checkID, note string) error

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

func (a *Agent) ForceLeave(node string) error

ForceLeave is used to have the agent eject a failed node

func (*Agent) Join

func (a *Agent) Join(addr string, wan bool) error

Join is used to instruct the agent to attempt a join to another cluster member

func (*Agent) Leave added in v0.7.2

func (a *Agent) Leave() error

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) MembersOpts added in v0.9.3

func (a *Agent) MembersOpts(opts MembersOpts) ([]*AgentMember, error)

MembersOpts returns the known gossip members and can be passed additional options for WAN/segment filtering.

func (*Agent) Metrics added in v0.9.1

func (a *Agent) Metrics() (*MetricsInfo, error)

Metrics is used to query the agent we are speaking to for its current internal metric data

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. An empty string will be sent down the given channel when there's nothing left to stream, after which the caller should close the stopCh.

func (*Agent) NodeName

func (a *Agent) NodeName() (string, error)

NodeName is used to get the node name of the agent

func (*Agent) PassTTL

func (a *Agent) PassTTL(checkID, note string) error

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

func (a *Agent) Reload() error

Reload triggers a configuration reload for the agent we are connected to.

func (*Agent) Self

func (a *Agent) Self() (map[string]map[string]interface{}, error)

Self is used to query the agent we are speaking to for information about itself

func (*Agent) ServiceDeregister

func (a *Agent) ServiceDeregister(serviceID string) error

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) UpdateACLAgentMasterToken added in v0.9.1

func (a *Agent) UpdateACLAgentMasterToken(token string, q *WriteOptions) (*WriteMeta, error)

UpdateACLAgentMasterToken updates the agent's "acl_agent_master_token". See updateToken for more details.

func (*Agent) UpdateACLAgentToken added in v0.9.1

func (a *Agent) UpdateACLAgentToken(token string, q *WriteOptions) (*WriteMeta, error)

UpdateACLAgentToken updates the agent's "acl_agent_token". See updateToken for more details.

func (*Agent) UpdateACLReplicationToken added in v0.9.1

func (a *Agent) UpdateACLReplicationToken(token string, q *WriteOptions) (*WriteMeta, error)

UpdateACLReplicationToken updates the agent's "acl_replication_token". See updateToken for more details.

func (*Agent) UpdateACLToken added in v0.9.1

func (a *Agent) UpdateACLToken(token string, q *WriteOptions) (*WriteMeta, error)

UpdateACLToken updates the agent's "acl_token". See updateToken for more details.

func (*Agent) UpdateTTL

func (a *Agent) UpdateTTL(checkID, output, status string) error

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).

func (*Agent) WarnTTL

func (a *Agent) WarnTTL(checkID, note string) error

WarnTTL is used to set a TTL check to the warning 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.

type AgentAuthorize added in v1.2.0

type AgentAuthorize struct {
	Authorized bool
	Reason     string
}

AgentAuthorize is the response structure for Connect authorization.

type AgentAuthorizeParams added in v1.2.0

type AgentAuthorizeParams struct {
	Target           string
	ClientCertURI    string
	ClientCertSerial string
}

AgentAuthorizeParams are the request parameters for authorizing a request.

type AgentCheck

type AgentCheck struct {
	Node        string
	CheckID     string
	Name        string
	Status      string
	Notes       string
	Output      string
	ServiceID   string
	ServiceName string
	Definition  HealthCheckDefinition
}

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 {
	Kind              ServiceKind
	ID                string
	Service           string
	Tags              []string
	Meta              map[string]string
	Port              int
	Address           string
	EnableTagOverride bool
	CreateIndex       uint64
	ModifyIndex       uint64
	ProxyDestination  string
	Connect           *AgentServiceConnect
}

AgentService represents a service known to the agent

type AgentServiceCheck

type AgentServiceCheck struct {
	CheckID           string              `json:",omitempty"`
	Name              string              `json:",omitempty"`
	Args              []string            `json:"ScriptArgs,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"`
	Header            map[string][]string `json:",omitempty"`
	Method            string              `json:",omitempty"`
	TCP               string              `json:",omitempty"`
	Status            string              `json:",omitempty"`
	Notes             string              `json:",omitempty"`
	TLSSkipVerify     bool                `json:",omitempty"`
	GRPC              string              `json:",omitempty"`
	GRPCUseTLS        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 AgentServiceConnect added in v1.2.0

type AgentServiceConnect struct {
	Native bool
	Proxy  *AgentServiceConnectProxy
}

AgentServiceConnect represents the Connect configuration of a service.

type AgentServiceConnectProxy added in v1.2.0

type AgentServiceConnectProxy struct {
	ExecMode ProxyExecMode
	Command  []string
	Config   map[string]interface{}
}

AgentServiceConnectProxy represents the Connect Proxy configuration of a service.

type AgentServiceRegistration

type AgentServiceRegistration struct {
	Kind              ServiceKind       `json:",omitempty"`
	ID                string            `json:",omitempty"`
	Name              string            `json:",omitempty"`
	Tags              []string          `json:",omitempty"`
	Port              int               `json:",omitempty"`
	Address           string            `json:",omitempty"`
	EnableTagOverride bool              `json:",omitempty"`
	Meta              map[string]string `json:",omitempty"`
	Check             *AgentServiceCheck
	Checks            AgentServiceChecks
	ProxyDestination  string               `json:",omitempty"`
	Connect           *AgentServiceConnect `json:",omitempty"`
}

AgentServiceRegistration is used to register a new service

type AgentToken added in v0.9.1

type AgentToken struct {
	Token string
}

AgentToken is used when updating ACL tokens for an agent.

type Area added in v0.8.0

type Area struct {
	// ID is this identifier for an area (a UUID). This must be left empty
	// when creating a new area.
	ID string

	// PeerDatacenter is the peer Consul datacenter that will make up the
	// other side of this network area. Network areas always involve a pair
	// of datacenters: the datacenter where the area was created, and the
	// peer datacenter. This is required.
	PeerDatacenter string

	// RetryJoin specifies the address of Consul servers to join to, such as
	// an IPs or hostnames with an optional port number. This is optional.
	RetryJoin []string

	// UseTLS specifies whether gossip over this area should be encrypted with TLS
	// if possible.
	UseTLS bool
}

Area defines a network area.

type AreaJoinResponse added in v0.8.0

type AreaJoinResponse struct {
	// The address that was joined.
	Address string

	// Whether or not the join was a success.
	Joined bool

	// If we couldn't join, this is the message with information.
	Error string
}

AreaJoinResponse is returned when a join occurs and gives the result for each address.

type AutopilotConfiguration added in v0.8.0

type AutopilotConfiguration struct {
	// CleanupDeadServers controls whether to remove dead servers from the Raft
	// peer list when a new server joins
	CleanupDeadServers bool

	// LastContactThreshold is the limit on the amount of time a server can go
	// without leader contact before being considered unhealthy.
	LastContactThreshold *ReadableDuration

	// MaxTrailingLogs is the amount of entries in the Raft Log that a server can
	// be behind before being considered unhealthy.
	MaxTrailingLogs uint64

	// ServerStabilizationTime is the minimum amount of time a server must be
	// in a stable, healthy state before it can be added to the cluster. Only
	// applicable with Raft protocol version 3 or higher.
	ServerStabilizationTime *ReadableDuration

	// (Enterprise-only) RedundancyZoneTag is the node tag to use for separating
	// servers into zones for redundancy. If left blank, this feature will be disabled.
	RedundancyZoneTag string

	// (Enterprise-only) DisableUpgradeMigration will disable Autopilot's upgrade migration
	// strategy of waiting until enough newer-versioned servers have been added to the
	// cluster before promoting them to voters.
	DisableUpgradeMigration bool

	// (Enterprise-only) UpgradeVersionTag is the node tag to use for version info when
	// performing upgrade migrations. If left blank, the Consul version will be used.
	UpgradeVersionTag string

	// CreateIndex holds the index corresponding the creation of this configuration.
	// This is a read-only field.
	CreateIndex uint64

	// ModifyIndex will be set to the index of the last update when retrieving the
	// Autopilot configuration. Resubmitting a configuration with
	// AutopilotCASConfiguration will perform a check-and-set operation which ensures
	// there hasn't been a subsequent update since the configuration was retrieved.
	ModifyIndex uint64
}

AutopilotConfiguration is used for querying/setting the Autopilot configuration. Autopilot helps manage operator tasks related to Consul servers like removing failed servers from the Raft quorum.

type CAConfig added in v1.2.0

type CAConfig struct {
	// Provider is the CA provider implementation to use.
	Provider string

	// Configuration is arbitrary configuration for the provider. This
	// should only contain primitive values and containers (such as lists
	// and maps).
	Config map[string]interface{}

	CreateIndex uint64
	ModifyIndex uint64
}

CAConfig is the structure for the Connect CA configuration.

type CARoot added in v1.2.0

type CARoot struct {
	// ID is a globally unique ID (UUID) representing this CA root.
	ID string

	// Name is a human-friendly name for this CA root. This value is
	// opaque to Consul and is not used for anything internally.
	Name string

	// RootCertPEM is the PEM-encoded public certificate.
	RootCertPEM string `json:"RootCert"`

	// Active is true if this is the current active CA. This must only
	// be true for exactly one CA. For any method that modifies roots in the
	// state store, tests should be written to verify that multiple roots
	// cannot be active.
	Active bool

	CreateIndex uint64
	ModifyIndex uint64
}

CARoot represents a root CA certificate that is trusted.

type CARootList added in v1.2.0

type CARootList struct {
	ActiveRootID string
	TrustDomain  string
	Roots        []*CARoot
}

CARootList is the structure for the results of listing roots.

type Catalog

type Catalog struct {
	// contains filtered or unexported fields
}

Catalog can be used to query the Catalog endpoints

func (*Catalog) Connect added in v1.2.0

func (c *Catalog) Connect(service, tag string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error)

Connect is used to query catalog entries for a given Connect-enabled service

func (*Catalog) Datacenters

func (c *Catalog) Datacenters() ([]string, error)

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

func (*Catalog) Services

func (c *Catalog) Services(q *QueryOptions) (map[string][]string, *QueryMeta, error)

Services is used to query for all known services

type CatalogDeregistration

type CatalogDeregistration struct {
	Node       string
	Address    string // Obsolete.
	Datacenter string
	ServiceID  string
	CheckID    string
}

type CatalogNode

type CatalogNode struct {
	Node     *Node
	Services map[string]*AgentService
}

type CatalogRegistration

type CatalogRegistration struct {
	ID              string
	Node            string
	Address         string
	TaggedAddresses map[string]string
	NodeMeta        map[string]string
	Datacenter      string
	Service         *AgentService
	Check           *AgentCheck
	SkipNodeUpdate  bool
}

type CatalogService

type CatalogService struct {
	ID                       string
	Node                     string
	Address                  string
	Datacenter               string
	TaggedAddresses          map[string]string
	NodeMeta                 map[string]string
	ServiceID                string
	ServiceName              string
	ServiceAddress           string
	ServiceTags              []string
	ServiceMeta              map[string]string
	ServicePort              int
	ServiceEnableTagOverride bool
	CreateIndex              uint64
	ModifyIndex              uint64
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides a client to the Consul API

func NewClient

func NewClient(config *Config) (*Client, error)

NewClient returns a new client

func (*Client) ACL

func (c *Client) ACL() *ACL

ACL returns a handle to the ACL endpoints

func (*Client) Agent

func (c *Client) Agent() *Agent

Agent returns a handle to the agent endpoints

func (*Client) Catalog

func (c *Client) Catalog() *Catalog

Catalog returns a handle to the catalog endpoints

func (*Client) Connect added in v1.2.0

func (c *Client) Connect() *Connect

Connect returns a handle to the connect-related endpoints

func (*Client) Coordinate added in v0.6.0

func (c *Client) Coordinate() *Coordinate

Coordinate returns a handle to the coordinate endpoints

func (*Client) Event

func (c *Client) Event() *Event

Event returns a handle to the event endpoints

func (*Client) Health

func (c *Client) Health() *Health

Health returns a handle to the health endpoints

func (*Client) KV

func (c *Client) KV() *KV

KV is used to return a handle to the K/V apis

func (*Client) LockKey

func (c *Client) LockKey(key string) (*Lock, error)

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) Operator added in v0.7.0

func (c *Client) Operator() *Operator

Operator returns a handle to the operator endpoints.

func (*Client) PreparedQuery added in v0.6.0

func (c *Client) PreparedQuery() *PreparedQuery

PreparedQuery returns a handle to the prepared query endpoints.

func (*Client) Raw

func (c *Client) Raw() *Raw

Raw returns a handle to 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

func (c *Client) SemaphorePrefix(prefix string, limit int) (*Semaphore, error)

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.

func (*Client) Session

func (c *Client) Session() *Session

Session returns a handle to the session endpoints

func (*Client) Snapshot added in v0.7.1

func (c *Client) Snapshot() *Snapshot

Snapshot returns a handle that exposes the snapshot endpoints.

func (*Client) Status

func (c *Client) Status() *Status

Status returns a handle to the status endpoints

type CommonCAProviderConfig added in v1.2.2

type CommonCAProviderConfig struct {
	LeafCertTTL time.Duration
}

CommonCAProviderConfig is the common options available to all CA providers.

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

	// Transport is the Transport to use for the http client.
	Transport *http.Transport

	// 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

	TLSConfig TLSConfig
}

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.

func (*Config) GenerateEnv added in v1.2.1

func (c *Config) GenerateEnv() []string

type Connect added in v1.2.0

type Connect struct {
	// contains filtered or unexported fields
}

Connect can be used to work with endpoints related to Connect, the feature for securely connecting services within Consul.

func (*Connect) CAGetConfig added in v1.2.0

func (h *Connect) CAGetConfig(q *QueryOptions) (*CAConfig, *QueryMeta, error)

CAGetConfig returns the current CA configuration.

func (*Connect) CARoots added in v1.2.0

func (h *Connect) CARoots(q *QueryOptions) (*CARootList, *QueryMeta, error)

CARoots queries the list of available roots.

func (*Connect) CASetConfig added in v1.2.0

func (h *Connect) CASetConfig(conf *CAConfig, q *WriteOptions) (*WriteMeta, error)

CASetConfig sets the current CA configuration.

func (*Connect) IntentionCheck added in v1.2.0

func (h *Connect) IntentionCheck(args *IntentionCheck, q *QueryOptions) (bool, *QueryMeta, error)

IntentionCheck returns whether a given source/destination would be allowed or not given the current set of intentions and the configuration of Consul.

func (*Connect) IntentionCreate added in v1.2.0

func (c *Connect) IntentionCreate(ixn *Intention, q *WriteOptions) (string, *WriteMeta, error)

IntentionCreate will create a new intention. The ID in the given structure must be empty and a generate ID will be returned on success.

func (*Connect) IntentionDelete added in v1.2.0

func (h *Connect) IntentionDelete(id string, q *WriteOptions) (*WriteMeta, error)

IntentionDelete deletes a single intention.

func (*Connect) IntentionGet added in v1.2.0

func (h *Connect) IntentionGet(id string, q *QueryOptions) (*Intention, *QueryMeta, error)

IntentionGet retrieves a single intention.

func (*Connect) IntentionMatch added in v1.2.0

func (h *Connect) IntentionMatch(args *IntentionMatch, q *QueryOptions) (map[string][]*Intention, *QueryMeta, error)

IntentionMatch returns the list of intentions that match a given source or destination. The returned intentions are ordered by precedence where result[0] is the highest precedence (if that matches, then that rule overrides all other rules).

Matching can be done for multiple names at the same time. The resulting map is keyed by the given names. Casing is preserved.

func (*Connect) IntentionUpdate added in v1.2.0

func (c *Connect) IntentionUpdate(ixn *Intention, q *WriteOptions) (*WriteMeta, error)

IntentionUpdate will update an existing intention. The ID in the given structure must be non-empty.

func (*Connect) Intentions added in v1.2.0

func (h *Connect) Intentions(q *QueryOptions) ([]*Intention, *QueryMeta, error)

Intentions returns the list of intentions.

type ConnectProxyConfig added in v1.2.0

type ConnectProxyConfig struct {
	ProxyServiceID    string
	TargetServiceID   string
	TargetServiceName string
	ContentHash       string
	ExecMode          ProxyExecMode
	Command           []string
	Config            map[string]interface{}
}

ConnectProxyConfig is the response structure for agent-local proxy configuration.

type ConsulCAProviderConfig added in v1.2.0

type ConsulCAProviderConfig struct {
	CommonCAProviderConfig `mapstructure:",squash"`

	PrivateKey     string
	RootCert       string
	RotationPeriod time.Duration
}

ConsulCAProviderConfig is the config for the built-in Consul CA provider.

func ParseConsulCAConfig added in v1.2.0

func ParseConsulCAConfig(raw map[string]interface{}) (*ConsulCAProviderConfig, error)

ParseConsulCAConfig takes a raw config map and returns a parsed ConsulCAProviderConfig.

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) Node added in v1.0.1

func (c *Coordinate) Node(node string, q *QueryOptions) ([]*CoordinateEntry, *QueryMeta, error)

Node is used to return the coordinates of a single in the LAN 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.

func (*Coordinate) Update added in v1.0.1

func (c *Coordinate) Update(coord *CoordinateEntry, q *WriteOptions) (*WriteMeta, error)

Update inserts or updates the LAN coordinate of a node.

type CoordinateDatacenterMap added in v0.6.0

type CoordinateDatacenterMap struct {
	Datacenter  string
	AreaID      string
	Coordinates []CoordinateEntry
}

CoordinateDatacenterMap has the coordinates for servers in a given datacenter and area. Network coordinates are only compatible within the same area.

type CoordinateEntry added in v0.6.0

type CoordinateEntry struct {
	Node    string
	Segment 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

func (e *Event) Fire(params *UserEvent, q *WriteOptions) (string, *WriteMeta, error)

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

func (e *Event) IDToIndex(uuid string) uint64

IDToIndex is a bit of a hack. This simulates the index generation to convert an event ID into a WaitIndex.

func (*Event) List

func (e *Event) List(name string, q *QueryOptions) ([]*UserEvent, *QueryMeta, error)

List is used to get the most recent events an agent has received. This list can be optionally filtered by the name. This endpoint supports quasi-blocking queries. The index is not monotonic, nor does it provide provide LastContact or KnownLeader.

type GaugeValue added in v0.9.1

type GaugeValue struct {
	Name   string
	Value  float32
	Labels map[string]string
}

GaugeValue stores one value that is updated as time goes on, such as the amount of memory allocated.

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) Connect added in v1.2.0

func (h *Health) Connect(service, tag string, passingOnly bool, q *QueryOptions) ([]*ServiceEntry, *QueryMeta, error)

Connect is equivalent to Service except that it will only return services which are Connect-enabled and will returns the connection address for Connect client's to use which may be a proxy in front of the named service. If passingOnly is true only instances where both the service and any proxy are healthy will be returned.

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
	ServiceTags []string

	Definition HealthCheckDefinition
}

HealthCheck is used to represent a single check

type HealthCheckDefinition added in v1.0.1

type HealthCheckDefinition struct {
	HTTP                           string
	Header                         map[string][]string
	Method                         string
	TLSSkipVerify                  bool
	TCP                            string
	Interval                       ReadableDuration
	Timeout                        ReadableDuration
	DeregisterCriticalServiceAfter ReadableDuration
}

HealthCheckDefinition is used to store the details about a health check's execution.

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 Intention added in v1.2.0

type Intention struct {
	// ID is the UUID-based ID for the intention, always generated by Consul.
	ID string

	// Description is a human-friendly description of this intention.
	// It is opaque to Consul and is only stored and transferred in API
	// requests.
	Description string

	// SourceNS, SourceName are the namespace and name, respectively, of
	// the source service. Either of these may be the wildcard "*", but only
	// the full value can be a wildcard. Partial wildcards are not allowed.
	// The source may also be a non-Consul service, as specified by SourceType.
	//
	// DestinationNS, DestinationName is the same, but for the destination
	// service. The same rules apply. The destination is always a Consul
	// service.
	SourceNS, SourceName           string
	DestinationNS, DestinationName string

	// SourceType is the type of the value for the source.
	SourceType IntentionSourceType

	// Action is whether this is a whitelist or blacklist intention.
	Action IntentionAction

	// DefaultAddr, DefaultPort of the local listening proxy (if any) to
	// make this connection.
	DefaultAddr string
	DefaultPort int

	// Meta is arbitrary metadata associated with the intention. This is
	// opaque to Consul but is served in API responses.
	Meta map[string]string

	// Precedence is the order that the intention will be applied, with
	// larger numbers being applied first. This is a read-only field, on
	// any intention update it is updated.
	Precedence int

	// CreatedAt and UpdatedAt keep track of when this record was created
	// or modified.
	CreatedAt, UpdatedAt time.Time

	CreateIndex uint64
	ModifyIndex uint64
}

Intention defines an intention for the Connect Service Graph. This defines the allowed or denied behavior of a connection between two services using Connect.

func (*Intention) DestinationString added in v1.2.0

func (i *Intention) DestinationString() string

DestinationString returns the namespace/name format for the source, or just "name" if the namespace is the default namespace.

func (*Intention) SourceString added in v1.2.0

func (i *Intention) SourceString() string

SourceString returns the namespace/name format for the source, or just "name" if the namespace is the default namespace.

func (*Intention) String added in v1.2.0

func (i *Intention) String() string

String returns human-friendly output describing ths intention.

type IntentionAction added in v1.2.0

type IntentionAction string

IntentionAction is the action that the intention represents. This can be "allow" or "deny" to whitelist or blacklist intentions.

const (
	IntentionActionAllow IntentionAction = "allow"
	IntentionActionDeny  IntentionAction = "deny"
)

type IntentionCheck added in v1.2.0

type IntentionCheck struct {
	// Source and Destination are the source and destination values to
	// check. The destination is always a Consul service, but the source
	// may be other values as defined by the SourceType.
	Source, Destination string

	// SourceType is the type of the value for the source.
	SourceType IntentionSourceType
}

IntentionCheck are the arguments for the intention check API. For more documentation see the IntentionCheck function.

type IntentionMatch added in v1.2.0

type IntentionMatch struct {
	By    IntentionMatchType
	Names []string
}

IntentionMatch are the arguments for the intention match API.

type IntentionMatchType added in v1.2.0

type IntentionMatchType string

IntentionMatchType is the target for a match request. For example, matching by source will look for all intentions that match the given source value.

const (
	IntentionMatchSource      IntentionMatchType = "source"
	IntentionMatchDestination IntentionMatchType = "destination"
)

type IntentionSourceType added in v1.2.0

type IntentionSourceType string

IntentionSourceType is the type of the source within an intention.

const (
	// IntentionSourceConsul is a service within the Consul catalog.
	IntentionSourceConsul IntentionSourceType = "consul"
)

type KV

type KV struct {
	// contains filtered or unexported fields
}

KV is used to manipulate the K/V API

func (*KV) Acquire

func (k *KV) Acquire(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)

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

func (k *KV) CAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)

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

func (k *KV) DeleteCAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)

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

func (k *KV) Get(key string, q *QueryOptions) (*KVPair, *QueryMeta, error)

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

func (k *KV) Keys(prefix, separator string, q *QueryOptions) ([]string, *QueryMeta, error)

Keys is used to list all the keys under a prefix. Optionally, a separator can be used to limit the responses.

func (*KV) List

func (k *KV) List(prefix string, q *QueryOptions) (KVPairs, *QueryMeta, error)

List is used to lookup all keys under a prefix

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

func (k *KV) Release(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error)

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"
	KVCheckNotExists KVOp = "check-not-exists"
)

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 KVPairs

type KVPairs []*KVPair

KVPairs is a list of KVPair objects

type KVTxnOp added in v0.7.0

type KVTxnOp struct {
	Verb    KVOp
	Key     string
	Value   []byte
	Flags   uint64
	Index   uint64
	Session string
}

KVTxnOp defines a single operation inside a transaction.

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

type KVTxnResponse struct {
	Results []*KVPair
	Errors  TxnErrors
}

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

	// Segment has the network segment this request corresponds to.
	Segment 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 LeafCert added in v1.2.0

type LeafCert struct {
	// SerialNumber is the unique serial number for this certificate.
	// This is encoded in standard hex separated by :.
	SerialNumber string

	// CertPEM and PrivateKeyPEM are the PEM-encoded certificate and private
	// key for that cert, respectively. This should not be stored in the
	// state store, but is present in the sign API response.
	CertPEM       string `json:",omitempty"`
	PrivateKeyPEM string `json:",omitempty"`

	// Service is the name of the service for which the cert was issued.
	// ServiceURI is the cert URI value.
	Service    string
	ServiceURI string

	// ValidAfter and ValidBefore are the validity periods for the
	// certificate.
	ValidAfter  time.Time
	ValidBefore time.Time

	CreateIndex uint64
	ModifyIndex uint64
}

LeafCert is a certificate that has been issued by a Connect CA.

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

func (l *Lock) Destroy() error

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

func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error)

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.

func (*Lock) Unlock

func (l *Lock) Unlock() error

Unlock released the lock. It is an error to call this if the lock is not currently held.

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 MembersOpts added in v0.9.3

type MembersOpts struct {
	// WAN is whether to show members from the WAN.
	WAN bool

	// Segment is the LAN segment to show members for. Setting this to the
	// AllSegments value above will show members in all segments.
	Segment string
}

MembersOpts is used for querying member information.

type MetricsInfo added in v0.9.1

type MetricsInfo struct {
	Timestamp string
	Gauges    []GaugeValue
	Points    []PointValue
	Counters  []SampledValue
	Samples   []SampledValue
}

Metrics info is used to store different types of metric values from the agent.

type Node

type Node struct {
	ID              string
	Node            string
	Address         string
	Datacenter      string
	TaggedAddresses map[string]string
	Meta            map[string]string
	CreateIndex     uint64
	ModifyIndex     uint64
}

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) AreaCreate added in v0.8.0

func (op *Operator) AreaCreate(area *Area, q *WriteOptions) (string, *WriteMeta, error)

AreaCreate will create a new network area. The ID in the given structure must be empty and a generated ID will be returned on success.

func (*Operator) AreaDelete added in v0.8.0

func (op *Operator) AreaDelete(areaID string, q *WriteOptions) (*WriteMeta, error)

AreaDelete deletes the given network area.

func (*Operator) AreaGet added in v0.8.0

func (op *Operator) AreaGet(areaID string, q *QueryOptions) ([]*Area, *QueryMeta, error)

AreaGet returns a single network area.

func (*Operator) AreaJoin added in v0.8.0

func (op *Operator) AreaJoin(areaID string, addresses []string, q *WriteOptions) ([]*AreaJoinResponse, *WriteMeta, error)

AreaJoin attempts to join the given set of join addresses to the given network area. See the Area structure for details about join addresses.

func (*Operator) AreaList added in v0.8.0

func (op *Operator) AreaList(q *QueryOptions) ([]*Area, *QueryMeta, error)

AreaList returns all the available network areas.

func (*Operator) AreaMembers added in v0.8.0

func (op *Operator) AreaMembers(areaID string, q *QueryOptions) ([]*SerfMember, *QueryMeta, error)

AreaMembers lists the Serf information about the members in the given area.

func (*Operator) AreaUpdate added in v1.0.0

func (op *Operator) AreaUpdate(areaID string, area *Area, q *WriteOptions) (string, *WriteMeta, error)

AreaUpdate will update the configuration of the network area with the given ID.

func (*Operator) AutopilotCASConfiguration added in v0.8.0

func (op *Operator) AutopilotCASConfiguration(conf *AutopilotConfiguration, q *WriteOptions) (bool, error)

AutopilotCASConfiguration is used to perform a Check-And-Set update on the Autopilot configuration. The ModifyIndex value will be respected. Returns true on success or false on failures.

func (*Operator) AutopilotGetConfiguration added in v0.8.0

func (op *Operator) AutopilotGetConfiguration(q *QueryOptions) (*AutopilotConfiguration, error)

AutopilotGetConfiguration is used to query the current Autopilot configuration.

func (*Operator) AutopilotServerHealth added in v0.8.0

func (op *Operator) AutopilotServerHealth(q *QueryOptions) (*OperatorHealthReply, error)

AutopilotServerHealth

func (*Operator) AutopilotSetConfiguration added in v0.8.0

func (op *Operator) AutopilotSetConfiguration(conf *AutopilotConfiguration, q *WriteOptions) error

AutopilotSetConfiguration is used to set the current Autopilot configuration.

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".

func (*Operator) RaftRemovePeerByID added in v0.8.0

func (op *Operator) RaftRemovePeerByID(id string, q *WriteOptions) error

RaftRemovePeerByID is used to kick a stale peer (one that it in the Raft quorum but no longer known to Serf or the catalog) by ID.

func (*Operator) SegmentList added in v0.9.3

func (op *Operator) SegmentList(q *QueryOptions) ([]string, *QueryMeta, error)

SegmentList returns all the available LAN segments.

type OperatorHealthReply added in v0.8.0

type OperatorHealthReply struct {
	// Healthy is true if all the servers in the cluster are healthy.
	Healthy bool

	// FailureTolerance is the number of healthy servers that could be lost without
	// an outage occurring.
	FailureTolerance int

	// Servers holds the health of each server.
	Servers []ServerHealth
}

OperatorHealthReply is a representation of the overall health of the cluster

type PointValue added in v0.9.1

type PointValue struct {
	Name   string
	Points []float32
}

PointValue holds a series of points for a metric.

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

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

Get is used to fetch a specific prepared query.

func (*PreparedQuery) List added in v0.6.0

List is used to fetch all the prepared queries (always requires a management token).

func (*PreparedQuery) Update added in v0.6.0

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
}

PreparedQueryDefinition 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 ProxyExecMode added in v1.2.0

type ProxyExecMode string

ProxyExecMode is the execution mode for a managed Connect proxy.

const (
	// ProxyExecModeDaemon indicates that the proxy command should be long-running
	// and should be started and supervised by the agent until it's target service
	// is deregistered.
	ProxyExecModeDaemon ProxyExecMode = "daemon"

	// ProxyExecModeScript indicates that the proxy command should be invoke to
	// completion on each change to the configuration of lifecycle event. The
	// script typically fetches the config and certificates from the agent API and
	// then configures an externally managed daemon, perhaps starting and stopping
	// it if necessary.
	ProxyExecModeScript ProxyExecMode = "script"
)

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

	// LastContentHash. This can be used as a WaitHash to perform a blocking query
	// for endpoints that support hash-based blocking. Endpoints that do not
	// support it will return an empty hash.
	LastContentHash string

	// 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

	// WaitHash is used by some endpoints instead of WaitIndex to perform blocking
	// on state based on a hash of the response rather than a monotonic index.
	// This is required when the state being blocked on is not stored in Raft, for
	// example agent-local proxy configuration.
	WaitHash string

	// 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

	// NodeMeta is used to filter results by nodes with the given
	// metadata key/value pairs. Currently, only one key/value pair can
	// be provided for filtering.
	NodeMeta map[string]string

	// RelayFactor is used in keyring operations to cause responses to be
	// relayed back to the sender through N other random nodes. Must be
	// a value from 0 to 5 (inclusive).
	RelayFactor uint8

	// Connect filters prepared query execution to only include Connect-capable
	// services. This currently affects prepared query execution.
	Connect bool
	// contains filtered or unexported fields
}

QueryOptions are used to parameterize a query

func (*QueryOptions) Context added in v0.9.0

func (o *QueryOptions) Context() context.Context

func (*QueryOptions) WithContext added in v0.9.0

func (o *QueryOptions) WithContext(ctx context.Context) *QueryOptions

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
}

RaftConfiguration 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

	// Protocol version is the raft protocol version used by the server
	ProtocolVersion string

	// 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

func (*Raw) Query

func (raw *Raw) Query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error)

Query is used to do a GET request against an endpoint and deserialize the response into an interface using standard Consul conventions.

func (*Raw) Write

func (raw *Raw) Write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error)

Write is used to do a PUT request against an endpoint and serialize/deserialized using the standard Consul conventions.

type ReadableDuration added in v0.8.0

type ReadableDuration time.Duration

ReadableDuration is a duration type that is serialized to JSON in human readable format.

func NewReadableDuration added in v0.8.0

func NewReadableDuration(dur time.Duration) *ReadableDuration

func (*ReadableDuration) Duration added in v0.8.0

func (d *ReadableDuration) Duration() time.Duration

func (*ReadableDuration) MarshalJSON added in v0.8.0

func (d *ReadableDuration) MarshalJSON() ([]byte, error)

func (*ReadableDuration) String added in v0.8.0

func (d *ReadableDuration) String() string

func (*ReadableDuration) UnmarshalJSON added in v0.8.0

func (d *ReadableDuration) UnmarshalJSON(raw []byte) error

type SampledValue added in v0.9.1

type SampledValue struct {
	Name   string
	Count  int
	Sum    float64
	Min    float64
	Max    float64
	Mean   float64
	Stddev float64
	Labels map[string]string
}

SampledValue stores info about a metric that is incremented over time, such as the number of requests to an HTTP endpoint.

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

func (s *Semaphore) Acquire(stopCh <-chan struct{}) (<-chan struct{}, error)

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.

func (*Semaphore) Destroy

func (s *Semaphore) Destroy() error

Destroy is used to cleanup the semaphore entry. It is not necessary to invoke. It will fail if the semaphore is in use.

func (*Semaphore) Release

func (s *Semaphore) Release() error

Release is used to voluntarily give up our semaphore slot. It is an error to call this if the semaphore has not been acquired.

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 SerfMember added in v0.8.0

type SerfMember struct {
	// ID is the node identifier (a UUID).
	ID string

	// Name is the node name.
	Name string

	// Addr has the IP address.
	Addr net.IP

	// Port is the RPC port.
	Port uint16

	// Datacenter is the DC name.
	Datacenter string

	// Role is "client", "server", or "unknown".
	Role string

	// Build has the version of the Consul agent.
	Build string

	// Protocol is the protocol of the Consul agent.
	Protocol int

	// Status is the Serf health status "none", "alive", "leaving", "left",
	// or "failed".
	Status string

	// RTT is the estimated round trip time from the server handling the
	// request to the this member. This will be negative if no RTT estimate
	// is available.
	RTT time.Duration
}

SerfMember is a generic structure for reporting information about members in a Serf cluster. This is only used by the area endpoints right now, but this could be expanded to other endpoints in the future.

type ServerHealth added in v0.8.0

type ServerHealth struct {
	// ID is the raft ID of the server.
	ID string

	// Name is the node name of the server.
	Name string

	// Address is the address of the server.
	Address string

	// The status of the SerfHealth check for the server.
	SerfStatus string

	// Version is the Consul version of the server.
	Version string

	// Leader is whether this server is currently the leader.
	Leader bool

	// LastContact is the time since this node's last contact with the leader.
	LastContact *ReadableDuration

	// LastTerm is the highest leader term this server has a record of in its Raft log.
	LastTerm uint64

	// LastIndex is the last log index this server has a record of in its Raft log.
	LastIndex uint64

	// Healthy is whether or not the server is healthy according to the current
	// Autopilot config.
	Healthy bool

	// Voter is whether this is a voting server.
	Voter bool

	// StableSince is the last time this server's Healthy value changed.
	StableSince time.Time
}

ServerHealth is the health (from the leader's point of view) of a server.

type ServiceEntry

type ServiceEntry struct {
	Node    *Node
	Service *AgentService
	Checks  HealthChecks
}

ServiceEntry is used for the health service endpoint

type ServiceKind added in v1.2.0

type ServiceKind string

ServiceKind is the kind of service being registered.

const (
	// ServiceKindTypical is a typical, classic Consul service. This is
	// represented by the absence of a value. This was chosen for ease of
	// backwards compatibility: existing services in the catalog would
	// default to the typical service.
	ServiceKindTypical ServiceKind = ""

	// ServiceKindConnectProxy is a proxy for the Connect feature. This
	// service proxies another service within Consul and speaks the connect
	// protocol.
	ServiceKindConnectProxy ServiceKind = "connect-proxy"
)

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

	// IgnoreCheckIDs is an optional list of health check IDs to ignore when
	// considering which nodes are healthy. It is useful as an emergency measure
	// to temporarily override some health check that is producing false negatives
	// for example.
	IgnoreCheckIDs []string

	// 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

	// NodeMeta is a map of required node metadata fields. If a key/value
	// pair is in this map it must be present on the node in order for the
	// service entry to be returned.
	NodeMeta map[string]string

	// Connect if true will filter the prepared query results to only
	// include Connect-capable services. These include both native services
	// and proxies for matching services. Note that if a proxy matches,
	// the constraints in the query above (Near, OnlyPassing, etc.) apply
	// to the _proxy_ and not the service being proxied. In practice, proxies
	// should be directly next to their services so this isn't an issue.
	Connect bool
}

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

func (*Status) Leader

func (s *Status) Leader() (string, error)

Leader is used to query for a known leader

func (*Status) Peers

func (s *Status) Peers() ([]string, error)

Peers is used to query for a known raft peers

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

	// CAPath is the optional path to a directory of CA certificates to use for
	// Consul communication, defaults to the system bundle if not specified.
	CAPath 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

type TxnError struct {
	OpIndex int
	What    string
}

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 TxnOps added in v0.7.0

type TxnOps []*TxnOp

TxnOps is a list of transaction operations.

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 WriteMeta

type WriteMeta struct {
	// How long did the request take
	RequestTime time.Duration
}

WriteMeta is used to return meta data about a write

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

	// RelayFactor is used in keyring operations to cause responses to be
	// relayed back to the sender through N other random nodes. Must be
	// a value from 0 to 5 (inclusive).
	RelayFactor uint8
	// contains filtered or unexported fields
}

WriteOptions are used to parameterize a write

func (*WriteOptions) Context added in v0.9.0

func (o *WriteOptions) Context() context.Context

func (*WriteOptions) WithContext added in v0.9.0

func (o *WriteOptions) WithContext(ctx context.Context) *WriteOptions

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL