Back to godoc.org
github.com/hashicorp/consul/api

package api

v1.5.0
Latest Go to latest
Published: Jun 18, 2020 | License: MPL-2.0 | Module: github.com/hashicorp/consul/api

Index

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"

	// HTTPTokenFileEnvName defines an environment variable name which sets
	// the HTTP token file.
	HTTPTokenFileEnvName = "CONSUL_HTTP_TOKEN_FILE"

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

	// GRPCAddrEnvName defines an environment variable name which sets the gRPC
	// address for consul connect envoy. Note this isn't actually used by the api
	// client in this package but is defined here for consistency with all the
	// other ENV names we use.
	GRPCAddrEnvName = "CONSUL_GRPC_ADDR"

	// HTTPNamespaceEnvVar defines an environment variable name which sets
	// the HTTP Namespace to be used by default. This can still be overridden.
	HTTPNamespaceEnvName = "CONSUL_NAMESPACE"
)
const (
	ServiceDefaults    string = "service-defaults"
	ProxyDefaults      string = "proxy-defaults"
	ServiceRouter      string = "service-router"
	ServiceSplitter    string = "service-splitter"
	ServiceResolver    string = "service-resolver"
	IngressGateway     string = "ingress-gateway"
	TerminatingGateway string = "terminating-gateway"

	ProxyConfigGlobal string = "global"
)
const (
	DiscoveryGraphNodeTypeRouter   = "router"
	DiscoveryGraphNodeTypeSplitter = "splitter"
	DiscoveryGraphNodeTypeResolver = "resolver"
)
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"
)
const AllSegments = "_all"

AllSegments is used to select for all segments in MembersOpts.

const IntentionDefaultNamespace = "default"

IntentionDefaultNamespace is the default namespace value.

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

func IsRetryableError

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

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

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

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

type ACL

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

ACL can be used to query the ACL endpoints

func (*ACL) AuthMethodCreate

func (a *ACL) AuthMethodCreate(method *ACLAuthMethod, q *WriteOptions) (*ACLAuthMethod, *WriteMeta, error)

AuthMethodCreate will create a new auth method.

func (*ACL) AuthMethodDelete

func (a *ACL) AuthMethodDelete(methodName string, q *WriteOptions) (*WriteMeta, error)

AuthMethodDelete deletes an auth method given its Name.

func (*ACL) AuthMethodList

func (a *ACL) AuthMethodList(q *QueryOptions) ([]*ACLAuthMethodListEntry, *QueryMeta, error)

AuthMethodList retrieves a listing of all auth methods. The listing does not include some metadata for the auth method as those should be retrieved by subsequent calls to AuthMethodRead.

func (*ACL) AuthMethodRead

func (a *ACL) AuthMethodRead(methodName string, q *QueryOptions) (*ACLAuthMethod, *QueryMeta, error)

AuthMethodRead retrieves the auth method. Returns nil if not found.

func (*ACL) AuthMethodUpdate

func (a *ACL) AuthMethodUpdate(method *ACLAuthMethod, q *WriteOptions) (*ACLAuthMethod, *WriteMeta, error)

AuthMethodUpdate updates an auth method.

func (*ACL) BindingRuleCreate

func (a *ACL) BindingRuleCreate(rule *ACLBindingRule, q *WriteOptions) (*ACLBindingRule, *WriteMeta, error)

BindingRuleCreate will create a new binding rule. It is not allowed for the binding rule parameter's ID field to be set as this will be generated by Consul while processing the request.

func (*ACL) BindingRuleDelete

func (a *ACL) BindingRuleDelete(bindingRuleID string, q *WriteOptions) (*WriteMeta, error)

BindingRuleDelete deletes a binding rule given its ID.

func (*ACL) BindingRuleList

func (a *ACL) BindingRuleList(methodName string, q *QueryOptions) ([]*ACLBindingRule, *QueryMeta, error)

BindingRuleList retrieves a listing of all binding rules.

func (*ACL) BindingRuleRead

func (a *ACL) BindingRuleRead(bindingRuleID string, q *QueryOptions) (*ACLBindingRule, *QueryMeta, error)

BindingRuleRead retrieves the binding rule details. Returns nil if not found.

func (*ACL) BindingRuleUpdate

func (a *ACL) BindingRuleUpdate(rule *ACLBindingRule, q *WriteOptions) (*ACLBindingRule, *WriteMeta, error)

BindingRuleUpdate updates a binding rule. The ID field of the role binding rule parameter must be set to an existing binding rule ID.

func (*ACL) Bootstrap

func (a *ACL) Bootstrap() (*ACLToken, *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

Deprecated: Use TokenClone instead.

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

Deprecated: Use TokenCreate instead.

func (*ACL) Destroy

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

Destroy is used to destroy a given ACL token ID

Deprecated: Use TokenDelete instead.

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

Deprecated: Use TokenRead instead.

func (*ACL) List

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

List is used to get all the ACL tokens

Deprecated: Use TokenList instead.

func (*ACL) Login

func (a *ACL) Login(auth *ACLLoginParams, q *WriteOptions) (*ACLToken, *WriteMeta, error)

Login is used to exchange auth method credentials for a newly-minted Consul Token.

func (*ACL) Logout

func (a *ACL) Logout(q *WriteOptions) (*WriteMeta, error)

Logout is used to destroy a Consul Token created via Login().

func (*ACL) OIDCAuthURL

func (a *ACL) OIDCAuthURL(auth *ACLOIDCAuthURLParams, q *WriteOptions) (string, *WriteMeta, error)

OIDCAuthURL requests an authorization URL to start an OIDC login flow.

func (*ACL) OIDCCallback

func (a *ACL) OIDCCallback(auth *ACLOIDCCallbackParams, q *WriteOptions) (*ACLToken, *WriteMeta, error)

OIDCCallback is the callback endpoint to complete an OIDC login.

func (*ACL) PolicyCreate

func (a *ACL) PolicyCreate(policy *ACLPolicy, q *WriteOptions) (*ACLPolicy, *WriteMeta, error)

PolicyCreate will create a new policy. It is not allowed for the policy parameters ID field to be set as this will be generated by Consul while processing the request.

func (*ACL) PolicyDelete

func (a *ACL) PolicyDelete(policyID string, q *WriteOptions) (*WriteMeta, error)

PolicyDelete deletes a policy given its ID.

func (*ACL) PolicyList

func (a *ACL) PolicyList(q *QueryOptions) ([]*ACLPolicyListEntry, *QueryMeta, error)

PolicyList retrieves a listing of all policies. The listing does not include the rules for any policy as those should be retrieved by subsequent calls to PolicyRead.

func (*ACL) PolicyRead

func (a *ACL) PolicyRead(policyID string, q *QueryOptions) (*ACLPolicy, *QueryMeta, error)

PolicyRead retrieves the policy details including the rule set.

func (*ACL) PolicyReadByName

func (a *ACL) PolicyReadByName(policyName string, q *QueryOptions) (*ACLPolicy, *QueryMeta, error)

PolicyReadByName retrieves the policy details including the rule set with name.

func (*ACL) PolicyUpdate

func (a *ACL) PolicyUpdate(policy *ACLPolicy, q *WriteOptions) (*ACLPolicy, *WriteMeta, error)

PolicyUpdate updates a policy. The ID field of the policy parameter must be set to an existing policy ID

func (*ACL) Replication

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

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

func (*ACL) RoleCreate

func (a *ACL) RoleCreate(role *ACLRole, q *WriteOptions) (*ACLRole, *WriteMeta, error)

RoleCreate will create a new role. It is not allowed for the role parameters ID field to be set as this will be generated by Consul while processing the request.

func (*ACL) RoleDelete

func (a *ACL) RoleDelete(roleID string, q *WriteOptions) (*WriteMeta, error)

RoleDelete deletes a role given its ID.

func (*ACL) RoleList

func (a *ACL) RoleList(q *QueryOptions) ([]*ACLRole, *QueryMeta, error)

RoleList retrieves a listing of all roles. The listing does not include some metadata for the role as those should be retrieved by subsequent calls to RoleRead.

func (*ACL) RoleRead

func (a *ACL) RoleRead(roleID string, q *QueryOptions) (*ACLRole, *QueryMeta, error)

RoleRead retrieves the role details (by ID). Returns nil if not found.

func (*ACL) RoleReadByName

func (a *ACL) RoleReadByName(roleName string, q *QueryOptions) (*ACLRole, *QueryMeta, error)

RoleReadByName retrieves the role details (by name). Returns nil if not found.

func (*ACL) RoleUpdate

func (a *ACL) RoleUpdate(role *ACLRole, q *WriteOptions) (*ACLRole, *WriteMeta, error)

RoleUpdate updates a role. The ID field of the role parameter must be set to an existing role ID

func (*ACL) RulesTranslate

func (a *ACL) RulesTranslate(rules io.Reader) (string, error)

RulesTranslate translates the legacy rule syntax into the current syntax.

Deprecated: Support for the legacy syntax translation will be removed when legacy ACL support is removed.

func (*ACL) RulesTranslateToken

func (a *ACL) RulesTranslateToken(tokenID string) (string, error)

RulesTranslateToken translates the rules associated with the legacy syntax into the current syntax and returns the results.

Deprecated: Support for the legacy syntax translation will be removed when legacy ACL support is removed.

func (*ACL) TokenClone

func (a *ACL) TokenClone(tokenID string, description string, q *WriteOptions) (*ACLToken, *WriteMeta, error)

TokenClone will create a new token with the same policies and locality as the original token but will have its own auto-generated AccessorID and SecretID as well having the description passed to this function. The tokenID parameter must be a valid Accessor ID of an existing token.

func (*ACL) TokenCreate

func (a *ACL) TokenCreate(token *ACLToken, q *WriteOptions) (*ACLToken, *WriteMeta, error)

TokenCreate creates a new ACL token. If either the AccessorID or SecretID fields of the ACLToken structure are empty they will be filled in by Consul.

func (*ACL) TokenDelete

func (a *ACL) TokenDelete(tokenID string, q *WriteOptions) (*WriteMeta, error)

TokenDelete removes a single ACL token. The tokenID parameter must be a valid Accessor ID of an existing token.

func (*ACL) TokenList

func (a *ACL) TokenList(q *QueryOptions) ([]*ACLTokenListEntry, *QueryMeta, error)

TokenList lists all tokens. The listing does not contain any SecretIDs as those may only be retrieved by a call to TokenRead.

func (*ACL) TokenRead

func (a *ACL) TokenRead(tokenID string, q *QueryOptions) (*ACLToken, *QueryMeta, error)

TokenRead retrieves the full token details. The tokenID parameter must be a valid Accessor ID of an existing token.

func (*ACL) TokenReadSelf

func (a *ACL) TokenReadSelf(q *QueryOptions) (*ACLToken, *QueryMeta, error)

TokenReadSelf retrieves the full token details of the token currently assigned to the API Client. In this manner its possible to read a token by its Secret ID.

func (*ACL) TokenUpdate

func (a *ACL) TokenUpdate(token *ACLToken, q *WriteOptions) (*ACLToken, *WriteMeta, error)

TokenUpdate updates a token in place without modifying its AccessorID or SecretID. A valid AccessorID must be set in the ACLToken structure passed to this function but the SecretID may be omitted and will be filled in by Consul with its existing value.

func (*ACL) Update

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

Update is used to update the rules of an existing token

Deprecated: Use TokenUpdate instead.

type ACLAuthMethod

type ACLAuthMethod struct {
	Name        string
	Type        string
	DisplayName string        `json:",omitempty"`
	Description string        `json:",omitempty"`
	MaxTokenTTL time.Duration `json:",omitempty"`

	// TokenLocality defines the kind of token that this auth method produces.
	// This can be either 'local' or 'global'. If empty 'local' is assumed.
	TokenLocality string `json:",omitempty"`

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

	CreateIndex uint64
	ModifyIndex uint64

	// NamespaceRules apply only on auth methods defined in the default namespace.
	// Namespacing is a Consul Enterprise feature.
	NamespaceRules []*ACLAuthMethodNamespaceRule `json:",omitempty"`

	// Namespace is the namespace the ACLAuthMethod is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

func (*ACLAuthMethod) MarshalJSON

func (m *ACLAuthMethod) MarshalJSON() ([]byte, error)

func (*ACLAuthMethod) UnmarshalJSON

func (m *ACLAuthMethod) UnmarshalJSON(data []byte) error

type ACLAuthMethodListEntry

type ACLAuthMethodListEntry struct {
	Name        string
	Type        string
	DisplayName string `json:",omitempty"`
	Description string `json:",omitempty"`
	CreateIndex uint64
	ModifyIndex uint64

	// Namespace is the namespace the ACLAuthMethodListEntry is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

type ACLAuthMethodNamespaceRule

type ACLAuthMethodNamespaceRule struct {
	// Selector is an expression that matches against verified identity
	// attributes returned from the auth method during login.
	Selector string `json:",omitempty"`

	// BindNamespace is the target namespace of the binding. Can be lightly
	// templated using HIL ${foo} syntax from available field names.
	//
	// If empty it's created in the same namespace as the auth method.
	BindNamespace string `json:",omitempty"`
}

type ACLBindingRule

type ACLBindingRule struct {
	ID          string
	Description string
	AuthMethod  string
	Selector    string
	BindType    BindingRuleBindType
	BindName    string

	CreateIndex uint64
	ModifyIndex uint64

	// Namespace is the namespace the ACLBindingRule is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

type ACLEntry

type ACLEntry struct {
	CreateIndex uint64
	ModifyIndex uint64
	ID          string
	Name        string
	Type        string
	Rules       string
}

ACLEntry is used to represent a legacy ACL token The legacy tokens are deprecated.

type ACLLink struct {
	ID   string
	Name string
}

type ACLLoginParams

type ACLLoginParams struct {
	AuthMethod  string
	BearerToken string
	Meta        map[string]string `json:",omitempty"`
}

type ACLOIDCAuthURLParams

type ACLOIDCAuthURLParams struct {
	AuthMethod  string
	RedirectURI string
	ClientNonce string
	Meta        map[string]string `json:",omitempty"`
}

type ACLOIDCCallbackParams

type ACLOIDCCallbackParams struct {
	AuthMethod  string
	State       string
	Code        string
	ClientNonce string
}

type ACLPolicy

type ACLPolicy struct {
	ID          string
	Name        string
	Description string
	Rules       string
	Datacenters []string
	Hash        []byte
	CreateIndex uint64
	ModifyIndex uint64

	// Namespace is the namespace the ACLPolicy is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

ACLPolicy represents an ACL Policy.

type ACLPolicyListEntry

type ACLPolicyListEntry struct {
	ID          string
	Name        string
	Description string
	Datacenters []string
	Hash        []byte
	CreateIndex uint64
	ModifyIndex uint64

	// Namespace is the namespace the ACLPolicyListEntry is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

type ACLReplicationStatus

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

ACLReplicationStatus is used to represent the status of ACL replication.

type ACLRole

type ACLRole struct {
	ID                string
	Name              string
	Description       string
	Policies          []*ACLRolePolicyLink  `json:",omitempty"`
	ServiceIdentities []*ACLServiceIdentity `json:",omitempty"`
	Hash              []byte
	CreateIndex       uint64
	ModifyIndex       uint64

	// Namespace is the namespace the ACLRole is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

ACLRole represents an ACL Role.

type ACLRolePolicyLink = ACLLink

type ACLServiceIdentity

type ACLServiceIdentity struct {
	ServiceName string
	Datacenters []string `json:",omitempty"`
}

ACLServiceIdentity represents a high-level grant of all necessary privileges to assume the identity of the named Service in the Catalog and within Connect.

type ACLToken

type ACLToken struct {
	CreateIndex       uint64
	ModifyIndex       uint64
	AccessorID        string
	SecretID          string
	Description       string
	Policies          []*ACLTokenPolicyLink `json:",omitempty"`
	Roles             []*ACLTokenRoleLink   `json:",omitempty"`
	ServiceIdentities []*ACLServiceIdentity `json:",omitempty"`
	Local             bool
	AuthMethod        string        `json:",omitempty"`
	ExpirationTTL     time.Duration `json:",omitempty"`
	ExpirationTime    *time.Time    `json:",omitempty"`
	CreateTime        time.Time     `json:",omitempty"`
	Hash              []byte        `json:",omitempty"`

	// DEPRECATED (ACL-Legacy-Compat)
	// Rules will only be present for legacy tokens returned via the new APIs
	Rules string `json:",omitempty"`

	// Namespace is the namespace the ACLToken is associated with.
	// Namespaces is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

ACLToken represents an ACL Token

type ACLTokenListEntry

type ACLTokenListEntry struct {
	CreateIndex       uint64
	ModifyIndex       uint64
	AccessorID        string
	Description       string
	Policies          []*ACLTokenPolicyLink `json:",omitempty"`
	Roles             []*ACLTokenRoleLink   `json:",omitempty"`
	ServiceIdentities []*ACLServiceIdentity `json:",omitempty"`
	Local             bool
	AuthMethod        string     `json:",omitempty"`
	ExpirationTime    *time.Time `json:",omitempty"`
	CreateTime        time.Time
	Hash              []byte
	Legacy            bool

	// Namespace is the namespace the ACLTokenListEntry is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}
type ACLTokenPolicyLink = ACLLink
type ACLTokenRoleLink = ACLLink

type Agent

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

Agent can be used to query the Agent endpoints

func (*Agent) AgentHealthServiceByID

func (a *Agent) AgentHealthServiceByID(serviceID string) (string, *AgentServiceChecksInfo, error)

AgentHealthServiceByID returns for a given serviceID: the aggregated health status, the service definition or an error if any - If the service is not found, will return status (critical, nil, nil) - If the service is found, will return (critical|passing|warning), AgentServiceChecksInfo, nil) - In all other cases, will return an error

func (*Agent) AgentHealthServiceByName

func (a *Agent) AgentHealthServiceByName(service string) (string, []AgentServiceChecksInfo, error)

AgentHealthServiceByName returns for a given service name: the aggregated health status for all services having the specified name. - If no service is not found, will return status (critical, [], nil) - If the service is found, will return (critical|passing|warning), []api.AgentServiceChecksInfo, nil) - In all other cases, will return an error

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

func (a *Agent) ChecksWithFilter(filter string) (map[string]*AgentCheck, error)

ChecksWithFilter returns a subset of the locally registered checks that match the given filter expression

func (*Agent) ConnectAuthorize

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

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

ConnectCALeaf gets the leaf certificate for the given service ID.

func (*Agent) ConnectCARoots

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

ConnectCARoots returns the list of roots.

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

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

ForceLeavePrune is used to have an a failed agent removed from the list of members

func (*Agent) Host

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

Host is used to retrieve information about the host the agent is running on such as CPU, memory, and disk. Requires a operator:read ACL token.

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

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

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

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

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

func (a *Agent) MonitorJSON(loglevel string, stopCh <-chan struct{}, q *QueryOptions) (chan string, error)

MonitorJSON is like Monitor except it returns logs in JSON format.

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

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

func (a *Agent) Service(serviceID string, q *QueryOptions) (*AgentService, *QueryMeta, error)

Service returns a locally registered service instance and allows for hash-based blocking.

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

func (a *Agent) ServiceRegisterOpts(service *AgentServiceRegistration, opts ServiceRegisterOpts) error

ServiceRegister is used to register a new service with the local agent and can be passed additional options.

func (*Agent) Services

func (a *Agent) Services() (map[string]*AgentService, error)

Services returns the locally registered services

func (*Agent) ServicesWithFilter

func (a *Agent) ServicesWithFilter(filter string) (map[string]*AgentService, error)

ServicesWithFilter returns a subset of the locally registered services that match the given filter expression

func (*Agent) UpdateACLAgentMasterToken

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

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

DEPRECATED (ACL-Legacy-Compat) - Prefer UpdateAgentMasterACLToken for v1.4.3 and above

func (*Agent) UpdateACLAgentToken

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

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

DEPRECATED (ACL-Legacy-Compat) - Prefer UpdateAgentACLToken for v1.4.3 and above

func (*Agent) UpdateACLReplicationToken

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

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

DEPRECATED (ACL-Legacy-Compat) - Prefer UpdateReplicationACLToken for v1.4.3 and above

func (*Agent) UpdateACLToken

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

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

DEPRECATED (ACL-Legacy-Compat) - Prefer UpdateDefaultACLToken for v1.4.3 and above

func (*Agent) UpdateAgentACLToken

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

UpdateAgentACLToken updates the agent's "agent" token. See updateToken for more details

func (*Agent) UpdateAgentMasterACLToken

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

UpdateAgentMasterACLToken updates the agent's "agent_master" token. See updateToken for more details

func (*Agent) UpdateDefaultACLToken

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

UpdateDefaultACLToken updates the agent's "default" token. See updateToken for more details

func (*Agent) UpdateReplicationACLToken

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

UpdateReplicationACLToken updates the agent's "replication" 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

type AgentAuthorize struct {
	Authorized bool
	Reason     string
}

AgentAuthorize is the response structure for Connect authorization.

type AgentAuthorizeParams

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
	Type        string
	Definition  HealthCheckDefinition
	Namespace   string `json:",omitempty"`
}

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
	Namespace string `json:",omitempty"`
}

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 `json:",omitempty"`
	ID                string
	Service           string
	Tags              []string
	Meta              map[string]string
	Port              int
	Address           string
	TaggedAddresses   map[string]ServiceAddress `json:",omitempty"`
	Weights           AgentWeights
	EnableTagOverride bool
	CreateIndex       uint64                          `json:",omitempty" bexpr:"-"`
	ModifyIndex       uint64                          `json:",omitempty" bexpr:"-"`
	ContentHash       string                          `json:",omitempty" bexpr:"-"`
	Proxy             *AgentServiceConnectProxyConfig `json:",omitempty"`
	Connect           *AgentServiceConnect            `json:",omitempty"`
	// NOTE: If we ever set the ContentHash outside of singular service lookup then we may need
	// to include the Namespace in the hash. When we do, then we are in for lots of fun with tests.
	// For now though, ignoring it works well enough.
	Namespace string `json:",omitempty" bexpr:"-" hash:"ignore"`
}

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"`
	Body              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"`
	AliasNode         string              `json:",omitempty"`
	AliasService      string              `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 AgentServiceChecksInfo

type AgentServiceChecksInfo struct {
	AggregatedStatus string
	Service          *AgentService
	Checks           HealthChecks
}

AgentServiceChecksInfo returns information about a Service and its checks

type AgentServiceConnect

type AgentServiceConnect struct {
	Native         bool                      `json:",omitempty"`
	SidecarService *AgentServiceRegistration `json:",omitempty" bexpr:"-"`
}

AgentServiceConnect represents the Connect configuration of a service.

type AgentServiceConnectProxyConfig

type AgentServiceConnectProxyConfig struct {
	DestinationServiceName string                 `json:",omitempty"`
	DestinationServiceID   string                 `json:",omitempty"`
	LocalServiceAddress    string                 `json:",omitempty"`
	LocalServicePort       int                    `json:",omitempty"`
	Config                 map[string]interface{} `json:",omitempty" bexpr:"-"`
	Upstreams              []Upstream             `json:",omitempty"`
	MeshGateway            MeshGatewayConfig      `json:",omitempty"`
	Expose                 ExposeConfig           `json:",omitempty"`
}

AgentServiceConnectProxyConfig is the proxy configuration in a connect-proxy ServiceDefinition or response.

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"`
	TaggedAddresses   map[string]ServiceAddress `json:",omitempty"`
	EnableTagOverride bool                      `json:",omitempty"`
	Meta              map[string]string         `json:",omitempty"`
	Weights           *AgentWeights             `json:",omitempty"`
	Check             *AgentServiceCheck
	Checks            AgentServiceChecks
	Proxy             *AgentServiceConnectProxyConfig `json:",omitempty"`
	Connect           *AgentServiceConnect            `json:",omitempty"`
	Namespace         string                          `json:",omitempty" bexpr:"-" hash:"ignore"`
}

AgentServiceRegistration is used to register a new service

type AgentToken

type AgentToken struct {
	Token string
}

AgentToken is used when updating ACL tokens for an agent.

type AgentWeights

type AgentWeights struct {
	Passing int
	Warning int
}

AgentWeights represent optional weights for a service

type Area

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

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

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

	// MinQuorum sets the minimum number of servers allowed in a cluster before
	// autopilot can prune dead servers.
	MinQuorum uint

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

type BindingRuleBindType string

BindingRuleBindType is the type of binding rule mechanism used.

const (
	// BindingRuleBindTypeService binds to a service identity with the given name.
	BindingRuleBindTypeService BindingRuleBindType = "service"

	// BindingRuleBindTypeRole binds to pre-existing roles with the given name.
	BindingRuleBindTypeRole BindingRuleBindType = "role"
)

type CAConfig

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{}

	// State is read-only data that the provider might have persisted for use
	// after restart or leadership transition. For example this might include
	// UUIDs of resources it has created. Setting this when writing a
	// configuration is an error.
	State map[string]string

	CreateIndex uint64
	ModifyIndex uint64
}

CAConfig is the structure for the Connect CA configuration.

type CARoot

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

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

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

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

Supports multiple tags for filtering

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

func (c *Catalog) NodeServiceList(node string, q *QueryOptions) (*CatalogNodeServiceList, *QueryMeta, error)

NodeServiceList is used to query for service information about a single node. It differs from the Node function only in its return type which will contain a list of services as opposed to a map of service ids to services. This different structure allows for using the wildcard specifier '*' for the Namespace in the QueryOptions.

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

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

Supports multiple tags for filtering

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 `json:",omitempty"` // Obsolete.
	Datacenter string
	ServiceID  string
	CheckID    string
	Namespace  string `json:",omitempty"`
}

type CatalogNode

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

type CatalogNodeServiceList

type CatalogNodeServiceList struct {
	Node     *Node
	Services []*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
	Checks          HealthChecks
	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
	ServiceTaggedAddresses   map[string]ServiceAddress
	ServiceTags              []string
	ServiceMeta              map[string]string
	ServicePort              int
	ServiceWeights           Weights
	ServiceEnableTagOverride bool
	ServiceProxy             *AgentServiceConnectProxyConfig
	CreateIndex              uint64
	Checks                   HealthChecks
	ModifyIndex              uint64
	Namespace                string `json:",omitempty"`
}

type CheckOp

type CheckOp string

CheckOp constants give possible operations available in a transaction.

const (
	CheckGet       CheckOp = "get"
	CheckSet       CheckOp = "set"
	CheckCAS       CheckOp = "cas"
	CheckDelete    CheckOp = "delete"
	CheckDeleteCAS CheckOp = "delete-cas"
)

type CheckTxnOp

type CheckTxnOp struct {
	Verb  CheckOp
	Check HealthCheck
}

CheckTxnOp defines a single operation inside a transaction.

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

func (c *Client) ConfigEntries() *ConfigEntries

Config returns a handle to the Config endpoints

func (*Client) Connect

func (c *Client) Connect() *Connect

Connect returns a handle to the connect-related endpoints

func (*Client) Coordinate

func (c *Client) Coordinate() *Coordinate

Coordinate returns a handle to the coordinate endpoints

func (*Client) Debug

func (c *Client) Debug() *Debug

Debug returns a handle that exposes the internal debug endpoints.

func (*Client) DiscoveryChain

func (c *Client) DiscoveryChain() *DiscoveryChain

DiscoveryChain returns a handle to the discovery-chain 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) Namespaces

func (c *Client) Namespaces() *Namespaces

Operator returns a handle to the operator endpoints.

func (*Client) Operator

func (c *Client) Operator() *Operator

Operator returns a handle to the operator endpoints.

func (*Client) PreparedQuery

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

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

func (*Client) Txn

func (c *Client) Txn() *Txn

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

type CommonCAProviderConfig

type CommonCAProviderConfig struct {
	LeafCertTTL      time.Duration
	SkipValidate     bool
	CSRMaxPerSecond  float32
	CSRMaxConcurrent int
}

CommonCAProviderConfig is the common options available to all CA providers.

type CompiledDiscoveryChain

type CompiledDiscoveryChain struct {
	ServiceName string
	Namespace   string
	Datacenter  string

	// CustomizationHash is a unique hash of any data that affects the
	// compilation of the discovery chain other than config entries or the
	// name/namespace/datacenter evaluation criteria.
	//
	// If set, this value should be used to prefix/suffix any generated load
	// balancer data plane objects to avoid sharing customized and
	// non-customized versions.
	CustomizationHash string

	// Protocol is the overall protocol shared by everything in the chain.
	Protocol string

	// StartNode is the first key into the Nodes map that should be followed
	// when walking the discovery chain.
	StartNode string

	// Nodes contains all nodes available for traversal in the chain keyed by a
	// unique name.  You can walk this by starting with StartNode.
	//
	// NOTE: The names should be treated as opaque values and are only
	// guaranteed to be consistent within a single compilation.
	Nodes map[string]*DiscoveryGraphNode

	// Targets is a list of all targets used in this chain.
	//
	// NOTE: The names should be treated as opaque values and are only
	// guaranteed to be consistent within a single compilation.
	Targets map[string]*DiscoveryTarget
}

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

	// TokenFile is a file containing the current token to use for this client.
	// If provided it is read once at startup and never again.
	TokenFile string

	// Namespace is the name of the namespace to send along for the request
	// when no other Namespace ispresent in the QueryOptions
	Namespace 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 DefaultConfigWithLogger

func DefaultConfigWithLogger(logger hclog.Logger) *Config

DefaultConfigWithLogger returns a default configuration for the client. It is exactly the same as DefaultConfig, but allows for a pre-configured logger object to be passed through.

func DefaultNonPooledConfig

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

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

type ConfigEntries

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

ConfigEntries can be used to query the Config endpoints

func (*ConfigEntries) CAS

func (conf *ConfigEntries) CAS(entry ConfigEntry, index uint64, w *WriteOptions) (bool, *WriteMeta, error)

func (*ConfigEntries) Delete

func (conf *ConfigEntries) Delete(kind string, name string, w *WriteOptions) (*WriteMeta, error)

func (*ConfigEntries) Get

func (conf *ConfigEntries) Get(kind string, name string, q *QueryOptions) (ConfigEntry, *QueryMeta, error)

func (*ConfigEntries) List

func (conf *ConfigEntries) List(kind string, q *QueryOptions) ([]ConfigEntry, *QueryMeta, error)

func (*ConfigEntries) Set

func (conf *ConfigEntries) Set(entry ConfigEntry, w *WriteOptions) (bool, *WriteMeta, error)

type ConfigEntry

type ConfigEntry interface {
	GetKind() string
	GetName() string
	GetCreateIndex() uint64
	GetModifyIndex() uint64
}

func DecodeConfigEntry

func DecodeConfigEntry(raw map[string]interface{}) (ConfigEntry, error)

DecodeConfigEntry will decode the result of using json.Unmarshal of a config entry into a map[string]interface{}.

Important caveats:

- This will NOT work if the map[string]interface{} was produced using HCL decoding as that requires more extensive parsing to work around the issues with map[string][]interface{} that arise.

- This will only decode fields using their camel case json field representations.

func DecodeConfigEntryFromJSON

func DecodeConfigEntryFromJSON(data []byte) (ConfigEntry, error)

func MakeConfigEntry

func MakeConfigEntry(kind, name string) (ConfigEntry, error)

type Connect

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

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

CAGetConfig returns the current CA configuration.

func (*Connect) CARoots

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

CARoots queries the list of available roots.

func (*Connect) CASetConfig

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

CASetConfig sets the current CA configuration.

func (*Connect) IntentionCheck

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

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

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

IntentionDelete deletes a single intention.

func (*Connect) IntentionGet

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

IntentionGet retrieves a single intention.

func (*Connect) IntentionMatch

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

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

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

Intentions returns the list of intentions.

type ConnectProxyConfig

type ConnectProxyConfig struct {
	ProxyServiceID    string
	TargetServiceID   string
	TargetServiceName string
	ContentHash       string
	Config            map[string]interface{} `bexpr:"-"`
	Upstreams         []Upstream
}

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

type ConsulCAProviderConfig

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

	PrivateKey          string
	RootCert            string
	RotationPeriod      time.Duration
	IntermediateCertTTL time.Duration
}

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

func ParseConsulCAConfig

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

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

type Coordinate

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

Coordinate can be used to query the coordinate endpoints

func (*Coordinate) Datacenters

func (c *Coordinate) Datacenters() ([]*CoordinateDatacenterMap, error)

Datacenters is used to return the coordinates of all the servers in the WAN pool.

func (*Coordinate) Node

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

Node is used to return the coordinates of a single node in the LAN pool.

func (*Coordinate) Nodes

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

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

Update inserts or updates the LAN coordinate of a node.

type CoordinateDatacenterMap

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

type CoordinateEntry struct {
	Node    string
	Segment string
	Coord   *coordinate.Coordinate
}

CoordinateEntry represents a node and its associated network coordinate.

type Debug

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

Debug can be used to query the /debug/pprof endpoints to gather profiling information about the target agent.Debug

The agent must have enable_debug set to true for profiling to be enabled and for these endpoints to function.

func (*Debug) Goroutine

func (d *Debug) Goroutine() ([]byte, error)

Goroutine returns a pprof goroutine profile

func (*Debug) Heap

func (d *Debug) Heap() ([]byte, error)

Heap returns a pprof heap dump

func (*Debug) Profile

func (d *Debug) Profile(seconds int) ([]byte, error)

Profile returns a pprof CPU profile for the specified number of seconds

func (*Debug) Trace

func (d *Debug) Trace(seconds int) ([]byte, error)

Trace returns an execution trace

type DiscoveryChain

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

DiscoveryChain can be used to query the discovery-chain endpoints

func (*DiscoveryChain) Get

func (d *DiscoveryChain) Get(name string, opts *DiscoveryChainOptions, q *QueryOptions) (*DiscoveryChainResponse, *QueryMeta, error)

type DiscoveryChainOptions

type DiscoveryChainOptions struct {
	EvaluateInDatacenter string `json:"-"`

	// OverrideMeshGateway allows for the mesh gateway setting to be overridden
	// for any resolver in the compiled chain.
	OverrideMeshGateway MeshGatewayConfig `json:",omitempty"`

	// OverrideProtocol allows for the final protocol for the chain to be
	// altered.
	//
	// - If the chain ordinarily would be TCP and an L7 protocol is passed here
	// the chain will not include Routers or Splitters.
	//
	// - If the chain ordinarily would be L7 and TCP is passed here the chain
	// will not include Routers or Splitters.
	OverrideProtocol string `json:",omitempty"`

	// OverrideConnectTimeout allows for the ConnectTimeout setting to be
	// overridden for any resolver in the compiled chain.
	OverrideConnectTimeout time.Duration `json:",omitempty"`
}

type DiscoveryChainResponse

type DiscoveryChainResponse struct {
	Chain *CompiledDiscoveryChain
}

type DiscoveryFailover

type DiscoveryFailover struct {
	Targets []string
}

compiled form of ServiceResolverFailover

type DiscoveryGraphNode

type DiscoveryGraphNode struct {
	Type string
	Name string // this is NOT necessarily a service

	// fields for Type==router
	Routes []*DiscoveryRoute

	// fields for Type==splitter
	Splits []*DiscoverySplit

	// fields for Type==resolver
	Resolver *DiscoveryResolver
}

DiscoveryGraphNode is a single node in the compiled discovery chain.

type DiscoveryResolver

type DiscoveryResolver struct {
	Default        bool
	ConnectTimeout time.Duration
	Target         string
	Failover       *DiscoveryFailover
}

compiled form of ServiceResolverConfigEntry

func (*DiscoveryResolver) MarshalJSON

func (r *DiscoveryResolver) MarshalJSON() ([]byte, error)

func (*DiscoveryResolver) UnmarshalJSON

func (r *DiscoveryResolver) UnmarshalJSON(data []byte) error

type DiscoveryRoute

type DiscoveryRoute struct {
	Definition *ServiceRoute
	NextNode   string
}

compiled form of ServiceRoute

type DiscoverySplit

type DiscoverySplit struct {
	Weight   float32
	NextNode string
}

compiled form of ServiceSplit

type DiscoveryTarget

type DiscoveryTarget struct {
	ID string

	Service       string
	ServiceSubset string
	Namespace     string
	Datacenter    string

	MeshGateway MeshGatewayConfig
	Subset      ServiceResolverSubset
	External    bool
	SNI         string
	Name        string
}

DiscoveryTarget represents all of the inputs necessary to use a resolver config entry to execute a catalog query to generate a list of service instances during discovery.

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 ExposeConfig

type ExposeConfig struct {
	// Checks defines whether paths associated with Consul checks will be exposed.
	// This flag triggers exposing all HTTP and GRPC check paths registered for the service.
	Checks bool `json:",omitempty"`

	// Paths is the list of paths exposed through the proxy.
	Paths []ExposePath `json:",omitempty"`
}

ExposeConfig describes HTTP paths to expose through Envoy outside of Connect. Users can expose individual paths and/or all HTTP/GRPC paths for checks.

type ExposePath

type ExposePath struct {
	// ListenerPort defines the port of the proxy's listener for exposed paths.
	ListenerPort int `json:",omitempty" alias:"listener_port"`

	// Path is the path to expose through the proxy, ie. "/metrics."
	Path string `json:",omitempty"`

	// LocalPathPort is the port that the service is listening on for the given path.
	LocalPathPort int `json:",omitempty" alias:"local_path_port"`

	// Protocol describes the upstream's service protocol.
	// Valid values are "http" and "http2", defaults to "http"
	Protocol string `json:",omitempty"`

	// ParsedFromCheck is set if this path was parsed from a registered check
	ParsedFromCheck bool
}

type GatewayTLSConfig

type GatewayTLSConfig struct {
	// Indicates that TLS should be enabled for this gateway service
	Enabled bool
}

type GaugeValue

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

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

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

func (*Health) Ingress

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

Ingress is equivalent to Connect except that it will only return associated ingress gateways for the requested 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) ServiceMultipleTags

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

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
	Type        string
	Namespace   string `json:",omitempty"`

	Definition HealthCheckDefinition

	CreateIndex uint64
	ModifyIndex uint64
}

HealthCheck is used to represent a single check

type HealthCheckDefinition

type HealthCheckDefinition struct {
	HTTP                                   string
	Header                                 map[string][]string
	Method                                 string
	Body                                   string
	TLSSkipVerify                          bool
	TCP                                    string
	IntervalDuration                       time.Duration `json:"-"`
	TimeoutDuration                        time.Duration `json:"-"`
	DeregisterCriticalServiceAfterDuration time.Duration `json:"-"`

	// DEPRECATED in Consul 1.4.1. Use the above time.Duration fields instead.
	Interval                       ReadableDuration
	Timeout                        ReadableDuration
	DeregisterCriticalServiceAfter ReadableDuration
}

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

func (*HealthCheckDefinition) MarshalJSON

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

func (*HealthCheckDefinition) UnmarshalJSON

func (t *HealthCheckDefinition) UnmarshalJSON(data []byte) (err error)

type HealthChecks

type HealthChecks []*HealthCheck

HealthChecks is a collection of HealthCheck structs.

func (HealthChecks) AggregatedStatus

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 IngressGatewayConfigEntry

type IngressGatewayConfigEntry struct {
	// Kind of the config entry. This should be set to api.IngressGateway.
	Kind string

	// Name is used to match the config entry with its associated ingress gateway
	// service. This should match the name provided in the service definition.
	Name string

	// Namespace is the namespace the IngressGateway is associated with
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`

	// TLS holds the TLS configuration for this gateway.
	TLS GatewayTLSConfig

	// Listeners declares what ports the ingress gateway should listen on, and
	// what services to associated to those ports.
	Listeners []IngressListener

	// CreateIndex is the Raft index this entry was created at. 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
}

IngressGatewayConfigEntry manages the configuration for an ingress service with the given name.

func (*IngressGatewayConfigEntry) GetCreateIndex

func (i *IngressGatewayConfigEntry) GetCreateIndex() uint64

func (*IngressGatewayConfigEntry) GetKind

func (i *IngressGatewayConfigEntry) GetKind() string

func (*IngressGatewayConfigEntry) GetModifyIndex

func (i *IngressGatewayConfigEntry) GetModifyIndex() uint64

func (*IngressGatewayConfigEntry) GetName

func (i *IngressGatewayConfigEntry) GetName() string

type IngressListener

type IngressListener struct {
	// Port declares the port on which the ingress gateway should listen for traffic.
	Port int

	// Protocol declares what type of traffic this listener is expected to
	// receive. Depending on the protocol, a listener might support multiplexing
	// services over a single port, or additional discovery chain features. The
	// current supported values are: (tcp | http).
	Protocol string

	// Services declares the set of services to which the listener forwards
	// traffic.
	//
	// For "tcp" protocol listeners, only a single service is allowed.
	// For "http" listeners, multiple services can be declared.
	Services []IngressService
}

IngressListener manages the configuration for a listener on a specific port.

type IngressService

type IngressService struct {
	// Name declares the service to which traffic should be forwarded.
	//
	// This can either be a specific service, or the wildcard specifier,
	// "*". If the wildcard specifier is provided, the listener must be of "http"
	// protocol and means that the listener will forward traffic to all services.
	//
	// A name can be specified on multiple listeners, and will be exposed on both
	// of the listeners
	Name string

	// Hosts is a list of hostnames which should be associated to this service on
	// the defined listener. Only allowed on layer 7 protocols, this will be used
	// to route traffic to the service by matching the Host header of the HTTP
	// request.
	//
	// If a host is provided for a service that also has a wildcard specifier
	// defined, the host will override the wildcard-specifier-provided
	// "<service-name>.*" domain for that listener.
	//
	// This cannot be specified when using the wildcard specifier, "*", or when
	// using a "tcp" listener.
	Hosts []string

	// Namespace is the namespace where the service is located.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

IngressService manages configuration for services that are exposed to ingress traffic.

type Intention

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 an allowlist or denylist 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

	// Hash of the contents of the intention
	//
	// This is needed mainly for replication purposes. When replicating from
	// one DC to another keeping the content Hash will allow us to detect
	// content changes more efficiently than checking every single field
	Hash []byte

	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

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

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

func (i *Intention) String() string

String returns human-friendly output describing ths intention.

type IntentionAction

type IntentionAction string

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

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

type IntentionCheck

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

type IntentionMatch struct {
	By    IntentionMatchType
	Names []string
}

IntentionMatch are the arguments for the intention match API.

type IntentionMatchType

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

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

func (k *KV) Txn(txn KVTxnOps, q *QueryOptions) (bool, *KVTxnResponse, *QueryMeta, error)

The Txn function has been deprecated from the KV object; please see the Txn object for more information about Transactions.

type KVOp

type KVOp string

KVOp constants give possible operations available in a transaction.

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

	// Namespace is the namespace the KVPair is associated with
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

KVPair is used to represent a single K/V entry

type KVPairs

type KVPairs []*KVPair

KVPairs is a list of KVPair objects

type KVTxnOp

type KVTxnOp struct {
	Verb      KVOp
	Key       string
	Value     []byte
	Flags     uint64
	Index     uint64
	Session   string
	Namespace string `json:",omitempty"`
}

KVTxnOp defines a single operation inside a transaction.

type KVTxnOps

type KVTxnOps []*KVTxnOp

KVTxnOps defines a set of operations to be performed inside a single transaction.

type KVTxnResponse

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

KVTxnResponse has the outcome of a transaction.

type KeyringResponse

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

	// Messages has information or errors from serf
	Messages map[string]string `json:",omitempty"`

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

type KubernetesAuthMethodConfig struct {
	Host              string `json:",omitempty"`
	CACert            string `json:",omitempty"`
	ServiceAccountJWT string `json:",omitempty"`
}

KubernetesAuthMethodConfig is the config for the built-in Consul auth method for Kubernetes.

func ParseKubernetesAuthMethodConfig

func ParseKubernetesAuthMethodConfig(raw map[string]interface{}) (*KubernetesAuthMethodConfig, error)

ParseKubernetesAuthMethodConfig takes a raw config map and returns a parsed KubernetesAuthMethodConfig.

func (*KubernetesAuthMethodConfig) RenderToConfig

func (c *KubernetesAuthMethodConfig) RenderToConfig() map[string]interface{}

RenderToConfig converts this into a map[string]interface{} suitable for use in the ACLAuthMethod.Config field.

type LeafCert

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 License

type License struct {
	// The unique identifier of the license
	LicenseID string `json:"license_id"`

	// The customer ID associated with the license
	CustomerID string `json:"customer_id"`

	// If set, an identifier that should be used to lock the license to a
	// particular site, cluster, etc.
	InstallationID string `json:"installation_id"`

	// The time at which the license was issued
	IssueTime time.Time `json:"issue_time"`

	// The time at which the license starts being valid
	StartTime time.Time `json:"start_time"`

	// The time after which the license expires
	ExpirationTime time.Time `json:"expiration_time"`

	// The time at which the license ceases to function and can
	// no longer be used in any capacity
	TerminationTime time.Time `json:"termination_time"`

	// The product the license is valid for
	Product string `json:"product"`

	// License Specific Flags
	Flags map[string]interface{} `json:"flags"`

	// Modules is a list of the licensed enterprise modules
	Modules []string `json:"modules"`

	// List of features enabled by the license
	Features []string `json:"features"`
}

type LicenseReply

type LicenseReply struct {
	Valid    bool
	License  *License
	Warnings []string
}

type LinkedService

type LinkedService struct {
	// The namespace the service is registered in
	Namespace string `json:",omitempty"`

	// Name is the name of the service, as defined in Consul's catalog
	Name string `json:",omitempty"`

	// CAFile is the optional path to a CA certificate to use for TLS connections
	// from the gateway to the linked service
	CAFile string `json:",omitempty" alias:"ca_file"`

	// CertFile is the optional path to a client certificate to use for TLS connections
	// from the gateway to the linked service
	CertFile string `json:",omitempty" alias:"cert_file"`

	// KeyFile is the optional path to a private key to use for TLS connections
	// from the gateway to the linked service
	KeyFile string `json:",omitempty" alias:"key_file"`

	// SNI is the optional name to specify during the TLS handshake with a linked service
	SNI string `json:",omitempty"`
}

A LinkedService is a service represented by a terminating gateway

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
	Namespace        string        `json:",omitempty"` // Optional, defaults to API client config, namespace of ACL token, or "default" namespace
}

LockOptions is used to parameterize the Lock behavior.

type MembersOpts

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 MeshGatewayConfig

type MeshGatewayConfig struct {
	// Mode is the mode that should be used for the upstream connection.
	Mode MeshGatewayMode `json:",omitempty"`
}

MeshGatewayConfig controls how Mesh Gateways are used for upstream Connect services

type MeshGatewayMode

type MeshGatewayMode string
const (
	// MeshGatewayModeDefault represents no specific mode and should
	// be used to indicate that a different layer of the configuration
	// chain should take precedence
	MeshGatewayModeDefault MeshGatewayMode = ""

	// MeshGatewayModeNone represents that the Upstream Connect connections
	// should be direct and not flow through a mesh gateway.
	MeshGatewayModeNone MeshGatewayMode = "none"

	// MeshGatewayModeLocal represents that the Upstrea Connect connections
	// should be made to a mesh gateway in the local datacenter. This is
	MeshGatewayModeLocal MeshGatewayMode = "local"

	// MeshGatewayModeRemote represents that the Upstream Connect connections
	// should be made to a mesh gateway in a remote datacenter.
	MeshGatewayModeRemote MeshGatewayMode = "remote"
)

type MetricsInfo

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 Namespace

type Namespace struct {
	// Name is the name of the Namespace. It must be unique and
	// must be a DNS hostname. There are also other reserved names
	// that may not be used.
	Name string `json:"Name"`

	// Description is where the user puts any information they want
	// about the namespace. It is not used internally.
	Description string `json:"Description,omitempty"`

	// ACLs is the configuration of ACLs for this namespace. It has its
	// own struct so that we can add more to it in the future.
	// This is nullable so that we can omit if empty when encoding in JSON
	ACLs *NamespaceACLConfig `json:"ACLs,omitempty"`

	// Meta is a map that can be used to add kv metadata to the namespace definition
	Meta map[string]string `json:"Meta,omitempty"`

	// DeletedAt is the time when the Namespace was marked for deletion
	// This is nullable so that we can omit if empty when encoding in JSON
	DeletedAt *time.Time `json:"DeletedAt,omitempty"`

	// CreateIndex is the Raft index at which the Namespace was created
	CreateIndex uint64 `json:"CreateIndex,omitempty"`

	// ModifyIndex is the latest Raft index at which the Namespace was modified.
	ModifyIndex uint64 `json:"ModifyIndex,omitempty"`
}

Namespace is the configuration of a single namespace. Namespacing is a Consul Enterprise feature.

type NamespaceACLConfig

type NamespaceACLConfig struct {
	// PolicyDefaults is the list of policies that should be used for the parent authorizer
	// of all tokens in the associated namespace.
	PolicyDefaults []ACLLink `json:"PolicyDefaults"`
	// RoleDefaults is the list of roles that should be used for the parent authorizer
	// of all tokens in the associated namespace.
	RoleDefaults []ACLLink `json:"RoleDefaults"`
}

NamespaceACLConfig is the Namespace specific ACL configuration container

type Namespaces

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

Namespaces can be used to manage Namespaces in Consul Enterprise..

func (*Namespaces) Create

func (n *Namespaces) Create(ns *Namespace, q *WriteOptions) (*Namespace, *WriteMeta, error)

func (*Namespaces) Delete

func (n *Namespaces) Delete(name string, q *WriteOptions) (*WriteMeta, error)

func (*Namespaces) List

func (n *Namespaces) List(q *QueryOptions) ([]*Namespace, *QueryMeta, error)

func (*Namespaces) Read

func (n *Namespaces) Read(name string, q *QueryOptions) (*Namespace, *QueryMeta, error)

func (*Namespaces) Update

func (n *Namespaces) Update(ns *Namespace, q *WriteOptions) (*Namespace, *WriteMeta, error)

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 NodeOp

type NodeOp string

NodeOp constants give possible operations available in a transaction.

const (
	NodeGet       NodeOp = "get"
	NodeSet       NodeOp = "set"
	NodeCAS       NodeOp = "cas"
	NodeDelete    NodeOp = "delete"
	NodeDeleteCAS NodeOp = "delete-cas"
)

type NodeTxnOp

type NodeTxnOp struct {
	Verb NodeOp
	Node Node
}

NodeTxnOp defines a single operation inside a transaction.

type OIDCAuthMethodConfig

type OIDCAuthMethodConfig struct {
	// common for type=oidc and type=jwt
	JWTSupportedAlgs    []string          `json:",omitempty"`
	BoundAudiences      []string          `json:",omitempty"`
	ClaimMappings       map[string]string `json:",omitempty"`
	ListClaimMappings   map[string]string `json:",omitempty"`
	OIDCDiscoveryURL    string            `json:",omitempty"`
	OIDCDiscoveryCACert string            `json:",omitempty"`
	// just for type=oidc
	OIDCClientID        string   `json:",omitempty"`
	OIDCClientSecret    string   `json:",omitempty"`
	OIDCScopes          []string `json:",omitempty"`
	AllowedRedirectURIs []string `json:",omitempty"`
	VerboseOIDCLogging  bool     `json:",omitempty"`
	// just for type=jwt
	JWKSURL              string        `json:",omitempty"`
	JWKSCACert           string        `json:",omitempty"`
	JWTValidationPubKeys []string      `json:",omitempty"`
	BoundIssuer          string        `json:",omitempty"`
	ExpirationLeeway     time.Duration `json:",omitempty"`
	NotBeforeLeeway      time.Duration `json:",omitempty"`
	ClockSkewLeeway      time.Duration `json:",omitempty"`
}

OIDCAuthMethodConfig is the config for the built-in Consul auth method for OIDC and JWT.

func (*OIDCAuthMethodConfig) RenderToConfig

func (c *OIDCAuthMethodConfig) RenderToConfig() map[string]interface{}

RenderToConfig converts this into a map[string]interface{} suitable for use in the ACLAuthMethod.Config field.

type Operator

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

Operator can be used to perform low-level operator tasks for Consul.

func (*Operator) AreaCreate

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

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

AreaDelete deletes the given network area.

func (*Operator) AreaGet

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

AreaGet returns a single network area.

func (*Operator) AreaJoin

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

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

AreaList returns all the available network areas.

func (*Operator) AreaMembers

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

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

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

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

AutopilotGetConfiguration is used to query the current Autopilot configuration.

func (*Operator) AutopilotServerHealth

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

AutopilotServerHealth

func (*Operator) AutopilotSetConfiguration

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

AutopilotSetConfiguration is used to set the current Autopilot configuration.

func (*Operator) KeyringInstall

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

func (op *Operator) KeyringList(q *QueryOptions) ([]*KeyringResponse, error)

KeyringList is used to list the gossip keys installed in the cluster

func (*Operator) KeyringRemove

func (op *Operator) KeyringRemove(key string, q *WriteOptions) error

KeyringRemove is used to remove a gossip encryption key from the cluster

func (*Operator) KeyringUse

func (op *Operator) KeyringUse(key string, q *WriteOptions) error

KeyringUse is used to change the active gossip encryption key

func (*Operator) LicenseGet

func (op *Operator) LicenseGet(q *QueryOptions) (*LicenseReply, error)

func (*Operator) LicenseGetSigned

func (op *Operator) LicenseGetSigned(q *QueryOptions) (string, error)

func (*Operator) LicensePut

func (op *Operator) LicensePut(license string, opts *WriteOptions) (*LicenseReply, error)

func (*Operator) LicenseReset

func (op *Operator) LicenseReset(opts *WriteOptions) (*LicenseReply, error)

LicenseReset will reset the license to the builtin one if it is still valid. If the builtin license is invalid, the current license stays active.

func (*Operator) RaftGetConfiguration

func (op *Operator) RaftGetConfiguration(q *QueryOptions) (*RaftConfiguration, error)

RaftGetConfiguration is used to query the current Raft peer set.

func (*Operator) RaftRemovePeerByAddress

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

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

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

SegmentList returns all the available LAN segments.

type OperatorHealthReply

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

type PointValue struct {
	Name   string
	Points []float32
}

PointValue holds a series of points for a metric.

type PreparedQuery

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

PreparedQuery can be used to query the prepared query endpoints.

func (*PreparedQuery) Create

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

func (c *PreparedQuery) Delete(queryID string, q *WriteOptions) (*WriteMeta, error)

Delete is used to delete a specific prepared query.

func (*PreparedQuery) Execute

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

func (c *PreparedQuery) Get(queryID string, q *QueryOptions) ([]*PreparedQueryDefinition, *QueryMeta, error)

Get is used to fetch a specific prepared query.

func (*PreparedQuery) List

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

func (c *PreparedQuery) Update(query *PreparedQueryDefinition, q *WriteOptions) (*WriteMeta, error)

Update makes updates to an existing prepared query.

type PreparedQueryDefinition

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

type PreparedQueryExecuteResponse struct {
	// Service is the service that was queried.
	Service string

	// Namespace of the service that was queried
	Namespace string `json:",omitempty"`

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

type ProxyConfigEntry struct {
	Kind        string
	Name        string
	Namespace   string                 `json:",omitempty"`
	Config      map[string]interface{} `json:",omitempty"`
	MeshGateway MeshGatewayConfig      `json:",omitempty" alias:"mesh_gateway"`
	Expose      ExposeConfig           `json:",omitempty"`
	CreateIndex uint64
	ModifyIndex uint64
}

func (*ProxyConfigEntry) GetCreateIndex

func (p *ProxyConfigEntry) GetCreateIndex() uint64

func (*ProxyConfigEntry) GetKind

func (p *ProxyConfigEntry) GetKind() string

func (*ProxyConfigEntry) GetModifyIndex

func (p *ProxyConfigEntry) GetModifyIndex() uint64

func (*ProxyConfigEntry) GetName

func (p *ProxyConfigEntry) GetName() string

type QueryDNSOptions

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

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

	// CacheHit is true if the result was served from agent-local cache.
	CacheHit bool

	// CacheAge is set if request was ?cached and indicates how stale the cached
	// response is.
	CacheAge time.Duration
}

QueryMeta is used to return meta data about a query

type QueryOptions

type QueryOptions struct {
	// Namespace overrides the `default` namespace
	// Note: Namespaces are available only in Consul Enterprise
	Namespace string

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

	// UseCache requests that the agent cache results locally. See
	// https://www.consul.io/api/features/caching.html for more details on the
	// semantics.
	UseCache bool

	// MaxAge limits how old a cached value will be returned if UseCache is true.
	// If there is a cached response that is older than the MaxAge, it is treated
	// as a cache miss and a new fetch invoked. If the fetch fails, the error is
	// returned. Clients that wish to allow for stale results on error can set
	// StaleIfError to a longer duration to change this behavior. It is ignored
	// if the endpoint supports background refresh caching. See
	// https://www.consul.io/api/features/caching.html for more details.
	MaxAge time.Duration

	// StaleIfError specifies how stale the client will accept a cached response
	// if the servers are unavailable to fetch a fresh one. Only makes sense when
	// UseCache is true and MaxAge is set to a lower, non-zero value. It is
	// ignored if the endpoint supports background refresh caching. See
	// https://www.consul.io/api/features/caching.html for more details.
	StaleIfError time.Duration

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

	// LocalOnly is used in keyring list operation to force the keyring
	// query to only hit local servers (no WAN traffic).
	LocalOnly bool

	// Connect filters prepared query execution to only include Connect-capable
	// services. This currently affects prepared query execution.
	Connect bool

	// Filter requests filtering data prior to it being returned. The string
	// is a go-bexpr compatible expression.
	Filter string
	// contains filtered or unexported fields
}

QueryOptions are used to parameterize a query

func (*QueryOptions) Context

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

func (*QueryOptions) WithContext

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

type QueryTemplate

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

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

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

type ReadableDuration time.Duration

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

func NewReadableDuration

func NewReadableDuration(dur time.Duration) *ReadableDuration

func (*ReadableDuration) Duration

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

func (*ReadableDuration) MarshalJSON

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

func (*ReadableDuration) String

func (d *ReadableDuration) String() string

func (*ReadableDuration) UnmarshalJSON

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

type SampledValue

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
	Namespace         string        `json:",omitempty"` // Optional, defaults to API client config, namespace of ACL token, or "default" namespace
}

SemaphoreOptions is used to parameterize the Semaphore

type SerfMember

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

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 ServiceAddress

type ServiceAddress struct {
	Address string
	Port    int
}

func ParseServiceAddr

func ParseServiceAddr(addrPort string) (ServiceAddress, error)

type ServiceCheck

type ServiceCheck struct {
	ID        string
	Namespace string
}

type ServiceConfigEntry

type ServiceConfigEntry struct {
	Kind        string
	Name        string
	Namespace   string            `json:",omitempty"`
	Protocol    string            `json:",omitempty"`
	MeshGateway MeshGatewayConfig `json:",omitempty" alias:"mesh_gateway"`
	Expose      ExposeConfig      `json:",omitempty"`
	ExternalSNI string            `json:",omitempty" alias:"external_sni"`
	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceConfigEntry) GetCreateIndex

func (s *ServiceConfigEntry) GetCreateIndex() uint64

func (*ServiceConfigEntry) GetKind

func (s *ServiceConfigEntry) GetKind() string

func (*ServiceConfigEntry) GetModifyIndex

func (s *ServiceConfigEntry) GetModifyIndex() uint64

func (*ServiceConfigEntry) GetName

func (s *ServiceConfigEntry) GetName() string

type ServiceEntry

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

ServiceEntry is used for the health service endpoint

type ServiceKind

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"

	// ServiceKindMeshGateway is a Mesh Gateway for the Connect feature. This
	// service will proxy connections based off the SNI header set by other
	// connect proxies
	ServiceKindMeshGateway ServiceKind = "mesh-gateway"

	// ServiceKindTerminatingGateway is a Terminating Gateway for the Connect
	// feature. This service will proxy connections to services outside the mesh.
	ServiceKindTerminatingGateway ServiceKind = "terminating-gateway"

	// ServiceKindIngressGateway is an Ingress Gateway for the Connect feature.
	// This service will ingress connections based of configuration defined in
	// the ingress-gateway config entry.
	ServiceKindIngressGateway ServiceKind = "ingress-gateway"
)

type ServiceOp

type ServiceOp string

ServiceOp constants give possible operations available in a transaction.

const (
	ServiceGet       ServiceOp = "get"
	ServiceSet       ServiceOp = "set"
	ServiceCAS       ServiceOp = "cas"
	ServiceDelete    ServiceOp = "delete"
	ServiceDeleteCAS ServiceOp = "delete-cas"
)

type ServiceQuery

type ServiceQuery struct {
	// Service is the service to query.
	Service string

	// Namespace of the service to query
	Namespace string `json:",omitempty"`

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

	// ServiceMeta is a map of required service 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.
	ServiceMeta 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 ServiceRegisterOpts

type ServiceRegisterOpts struct {
	//Missing healthchecks will be deleted from the agent.
	//Using this parameter allows to idempotently register a service and its checks without
	//having to manually deregister checks.
	ReplaceExistingChecks bool
}

ServiceRegisterOpts is used to pass extra options to the service register.

type ServiceResolverConfigEntry

type ServiceResolverConfigEntry struct {
	Kind      string
	Name      string
	Namespace string `json:",omitempty"`

	DefaultSubset  string                             `json:",omitempty" alias:"default_subset"`
	Subsets        map[string]ServiceResolverSubset   `json:",omitempty"`
	Redirect       *ServiceResolverRedirect           `json:",omitempty"`
	Failover       map[string]ServiceResolverFailover `json:",omitempty"`
	ConnectTimeout time.Duration                      `json:",omitempty" alias:"connect_timeout"`

	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceResolverConfigEntry) GetCreateIndex

func (e *ServiceResolverConfigEntry) GetCreateIndex() uint64

func (*ServiceResolverConfigEntry) GetKind

func (e *ServiceResolverConfigEntry) GetKind() string

func (*ServiceResolverConfigEntry) GetModifyIndex

func (e *ServiceResolverConfigEntry) GetModifyIndex() uint64

func (*ServiceResolverConfigEntry) GetName

func (e *ServiceResolverConfigEntry) GetName() string

func (*ServiceResolverConfigEntry) MarshalJSON

func (e *ServiceResolverConfigEntry) MarshalJSON() ([]byte, error)

func (*ServiceResolverConfigEntry) UnmarshalJSON

func (e *ServiceResolverConfigEntry) UnmarshalJSON(data []byte) error

type ServiceResolverFailover

type ServiceResolverFailover struct {
	Service       string   `json:",omitempty"`
	ServiceSubset string   `json:",omitempty" alias:"service_subset"`
	Namespace     string   `json:",omitempty"`
	Datacenters   []string `json:",omitempty"`
}

type ServiceResolverRedirect

type ServiceResolverRedirect struct {
	Service       string `json:",omitempty"`
	ServiceSubset string `json:",omitempty" alias:"service_subset"`
	Namespace     string `json:",omitempty"`
	Datacenter    string `json:",omitempty"`
}

type ServiceResolverSubset

type ServiceResolverSubset struct {
	Filter      string `json:",omitempty"`
	OnlyPassing bool   `json:",omitempty" alias:"only_passing"`
}

type ServiceRoute

type ServiceRoute struct {
	Match       *ServiceRouteMatch       `json:",omitempty"`
	Destination *ServiceRouteDestination `json:",omitempty"`
}

type ServiceRouteDestination

type ServiceRouteDestination struct {
	Service               string        `json:",omitempty"`
	ServiceSubset         string        `json:",omitempty" alias:"service_subset"`
	Namespace             string        `json:",omitempty"`
	PrefixRewrite         string        `json:",omitempty" alias:"prefix_rewrite"`
	RequestTimeout        time.Duration `json:",omitempty" alias:"request_timeout"`
	NumRetries            uint32        `json:",omitempty" alias:"num_retries"`
	RetryOnConnectFailure bool          `json:",omitempty" alias:"retry_on_connect_failure"`
	RetryOnStatusCodes    []uint32      `json:",omitempty" alias:"retry_on_status_codes"`
}

func (*ServiceRouteDestination) MarshalJSON

func (e *ServiceRouteDestination) MarshalJSON() ([]byte, error)

func (*ServiceRouteDestination) UnmarshalJSON

func (e *ServiceRouteDestination) UnmarshalJSON(data []byte) error

type ServiceRouteHTTPMatch

type ServiceRouteHTTPMatch struct {
	PathExact  string `json:",omitempty" alias:"path_exact"`
	PathPrefix string `json:",omitempty" alias:"path_prefix"`
	PathRegex  string `json:",omitempty" alias:"path_regex"`

	Header     []ServiceRouteHTTPMatchHeader     `json:",omitempty"`
	QueryParam []ServiceRouteHTTPMatchQueryParam `json:",omitempty" alias:"query_param"`
	Methods    []string                          `json:",omitempty"`
}

type ServiceRouteHTTPMatchHeader

type ServiceRouteHTTPMatchHeader struct {
	Name    string
	Present bool   `json:",omitempty"`
	Exact   string `json:",omitempty"`
	Prefix  string `json:",omitempty"`
	Suffix  string `json:",omitempty"`
	Regex   string `json:",omitempty"`
	Invert  bool   `json:",omitempty"`
}

type ServiceRouteHTTPMatchQueryParam

type ServiceRouteHTTPMatchQueryParam struct {
	Name    string
	Present bool   `json:",omitempty"`
	Exact   string `json:",omitempty"`
	Regex   string `json:",omitempty"`
}

type ServiceRouteMatch

type ServiceRouteMatch struct {
	HTTP *ServiceRouteHTTPMatch `json:",omitempty"`
}

type ServiceRouterConfigEntry

type ServiceRouterConfigEntry struct {
	Kind      string
	Name      string
	Namespace string `json:",omitempty"`

	Routes []ServiceRoute `json:",omitempty"`

	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceRouterConfigEntry) GetCreateIndex

func (e *ServiceRouterConfigEntry) GetCreateIndex() uint64

func (*ServiceRouterConfigEntry) GetKind

func (e *ServiceRouterConfigEntry) GetKind() string

func (*ServiceRouterConfigEntry) GetModifyIndex

func (e *ServiceRouterConfigEntry) GetModifyIndex() uint64

func (*ServiceRouterConfigEntry) GetName

func (e *ServiceRouterConfigEntry) GetName() string

type ServiceSplit

type ServiceSplit struct {
	Weight        float32
	Service       string `json:",omitempty"`
	ServiceSubset string `json:",omitempty" alias:"service_subset"`
	Namespace     string `json:",omitempty"`
}

type ServiceSplitterConfigEntry

type ServiceSplitterConfigEntry struct {
	Kind      string
	Name      string
	Namespace string `json:",omitempty"`

	Splits []ServiceSplit `json:",omitempty"`

	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceSplitterConfigEntry) GetCreateIndex

func (e *ServiceSplitterConfigEntry) GetCreateIndex() uint64

func (*ServiceSplitterConfigEntry) GetKind

func (e *ServiceSplitterConfigEntry) GetKind() string

func (*ServiceSplitterConfigEntry) GetModifyIndex

func (e *ServiceSplitterConfigEntry) GetModifyIndex() uint64

func (*ServiceSplitterConfigEntry) GetName

func (e *ServiceSplitterConfigEntry) GetName() string

type ServiceTxnOp

type ServiceTxnOp struct {
	Verb    ServiceOp
	Node    string
	Service AgentService
}

ServiceTxnOp defines a single operation inside a transaction.

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
	LockDelay   time.Duration
	Behavior    string
	TTL         string
	Namespace   string `json:",omitempty"`

	// Deprecated for Consul Enterprise in v1.7.0.
	Checks []string

	// NodeChecks and ServiceChecks are new in Consul 1.7.0.
	// When associating checks with sessions, namespaces can be specified for service checks.
	NodeChecks    []string
	ServiceChecks []ServiceCheck
}

SessionEntry represents a session in consul

type SessionOp

type SessionOp string

SessionOp constants give possible operations available in a transaction.

const (
	SessionDelete SessionOp = "delete"
)

type SessionTxnOp

type SessionTxnOp struct {
	Verb    SessionOp
	Session Session
}

SessionTxnOp defines a single operation inside a transaction.

type Snapshot

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

func (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error

Restore streams in an existing snapshot and attempts to restore it.

func (*Snapshot) Save

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

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

	// CAPem is the optional PEM-encoded CA certificate used for Consul
	// communication, defaults to the system bundle if not specified.
	CAPem []byte

	// CertFile is the optional path to the certificate for Consul
	// communication. If this is set then you need to also set KeyFile.
	CertFile string

	// CertPEM is the optional PEM-encoded certificate for Consul
	// communication. If this is set then you need to also set KeyPEM.
	CertPEM []byte

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

	// KeyPEM is the optional PEM-encoded private key for Consul communication.
	// If this is set then you need to also set CertPEM.
	KeyPEM []byte

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

type TerminatingGatewayConfigEntry struct {
	// Kind of the config entry. This should be set to api.TerminatingGateway.
	Kind string

	// Name is used to match the config entry with its associated terminating gateway
	// service. This should match the name provided in the service definition.
	Name string

	// Services is a list of service names represented by the terminating gateway.
	Services []LinkedService `json:",omitempty"`

	// CreateIndex is the Raft index this entry was created at. 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

	// Namespace is the namespace the config entry is associated with
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

TerminatingGatewayConfigEntry manages the configuration for a terminating gateway with the given name.

func (*TerminatingGatewayConfigEntry) GetCreateIndex

func (g *TerminatingGatewayConfigEntry) GetCreateIndex() uint64

func (*TerminatingGatewayConfigEntry) GetKind

func (g *TerminatingGatewayConfigEntry) GetKind() string

func (*TerminatingGatewayConfigEntry) GetModifyIndex

func (g *TerminatingGatewayConfigEntry) GetModifyIndex() uint64

func (*TerminatingGatewayConfigEntry) GetName

func (g *TerminatingGatewayConfigEntry) GetName() string

type Txn

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

Txn is used to manipulate the Txn API

func (*Txn) Txn

func (t *Txn) Txn(txn TxnOps, q *QueryOptions) (bool, *TxnResponse, *QueryMeta, error)

Txn is used to apply multiple Consul 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 different fields in the TxnOp structure to define operations. If any operation fails, none of the changes are applied to the state store.

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",
	   },
	   &CheckTxnOp{
		   Verb:        CheckSet,
		   HealthCheck: HealthCheck{
			   Node:    "foo",
			   CheckID: "redis:a",
			   Name:    "Redis Health Check",
			   Status:  "passing",
		   },
	   }
   }
   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. For KV operations, Deleted keys will have a nil entry in the results, 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 TxnError

type TxnError struct {
	OpIndex int
	What    string
}

TxnError is used to return information about an operation in a transaction.

type TxnErrors

type TxnErrors []*TxnError

TxnErrors is a list of TxnError objects.

type TxnOp

type TxnOp struct {
	KV      *KVTxnOp
	Node    *NodeTxnOp
	Service *ServiceTxnOp
	Check   *CheckTxnOp
}

TxnOp is the internal format we send to Consul. Currently only K/V and check operations are supported.

type TxnOps

type TxnOps []*TxnOp

TxnOps is a list of transaction operations.

type TxnResponse

type TxnResponse struct {
	Results TxnResults
	Errors  TxnErrors
}

TxnResponse is the internal format we receive from Consul.

type TxnResult

type TxnResult struct {
	KV      *KVPair
	Node    *Node
	Service *CatalogService
	Check   *HealthCheck
}

TxnResult is the internal format we receive from Consul.

type TxnResults

type TxnResults []*TxnResult

TxnResults is a list of TxnResult objects.

type Upstream

type Upstream struct {
	DestinationType      UpstreamDestType `json:",omitempty"`
	DestinationNamespace string           `json:",omitempty"`
	DestinationName      string
	Datacenter           string                 `json:",omitempty"`
	LocalBindAddress     string                 `json:",omitempty"`
	LocalBindPort        int                    `json:",omitempty"`
	Config               map[string]interface{} `json:",omitempty" bexpr:"-"`
	MeshGateway          MeshGatewayConfig      `json:",omitempty"`
}

Upstream is the response structure for a proxy upstream configuration.

type UpstreamDestType

type UpstreamDestType string

UpstreamDestType is the type of upstream discovery mechanism.

const (
	// UpstreamDestTypeService discovers instances via healthy service lookup.
	UpstreamDestTypeService UpstreamDestType = "service"

	// UpstreamDestTypePreparedQuery discovers instances via prepared query
	// execution.
	UpstreamDestTypePreparedQuery UpstreamDestType = "prepared_query"
)

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 Weights

type Weights struct {
	Passing int
	Warning int
}

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 {
	// Namespace overrides the `default` namespace
	// Note: Namespaces are available only in Consul Enterprise
	Namespace string

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

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

func (*WriteOptions) WithContext

func (o *WriteOptions) WithContext(ctx context.Context) *WriteOptions
Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier