api

package module
v1.30.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2024 License: MPL-2.0 Imports: 25 Imported by: 9,045

README

Consul API Client

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

The full documentation is available on Godoc.

Usage

Below is an example of using the Consul client. To run the example, you must first install Consul and Go.

To run the client API, create a new Go module.

go mod init consul-demo

Copy the example code into a file called main.go in the directory where the module is defined. As seen in the example, the Consul API is often imported with the alias capi.

package main

import (
	"fmt"

	capi "github.com/hashicorp/consul/api"
)

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

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

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

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

Install the Consul API dependency with go mod tidy.

In a separate terminal window, start a local Consul server.

consul agent -dev -node machine

Run the example.

go run .

You should get the following result printed to the terminal.

KV: REDIS_MAXCLIENTS 1000

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

Documentation

Index

Constants

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

	// ACLManagementType is the management type token
	ACLManagementType = "management"

	// ACLTemplatedPolicy names
	ACLTemplatedPolicyServiceName     = "builtin/service"
	ACLTemplatedPolicyNodeName        = "builtin/node"
	ACLTemplatedPolicyDNSName         = "builtin/dns"
	ACLTemplatedPolicyNomadServerName = "builtin/nomad-server"
	ACLTemplatedPolicyAPIGatewayName  = "builtin/api-gateway"
	ACLTemplatedPolicyNomadClientName = "builtin/nomad-client"
)
View Source
const (
	// MemberTagKeyACLMode is the key used to indicate what ACL mode the agent is
	// operating in. The values of this key will be one of the MemberACLMode constants
	// with the key not being present indicating ACLModeUnknown.
	MemberTagKeyACLMode = "acls"

	// MemberTagRole is the key used to indicate that the member is a server or not.
	MemberTagKeyRole = "role"

	// MemberTagValueRoleServer is the value of the MemberTagKeyRole used to indicate
	// that the member represents a Consul server.
	MemberTagValueRoleServer = "consul"

	// MemberTagValueRoleClient is the value of the MemberTagKeyRole used to indicate
	// that the member represents a Consul client.
	MemberTagValueRoleClient = "node"

	// MemberTagKeyDatacenter is the key used to indicate which datacenter this member is in.
	MemberTagKeyDatacenter = "dc"

	// MemberTagKeySegment is the key name of the tag used to indicate which network
	// segment this member is in.
	// Network Segments are a Consul Enterprise feature.
	MemberTagKeySegment = "segment"

	// MemberTagKeyPartition is the key name of the tag used to indicate which partition
	// this member is in.
	// Partitions are a Consul Enterprise feature.
	MemberTagKeyPartition = "ap"

	// MemberTagKeyBootstrap is the key name of the tag used to indicate whether this
	// agent was started with the "bootstrap" configuration enabled
	MemberTagKeyBootstrap = "bootstrap"
	// MemberTagValueBootstrap is the value of the MemberTagKeyBootstrap key when the
	// agent was started with the "bootstrap" configuration enabled.
	MemberTagValueBootstrap = "1"

	// MemberTagKeyBootstrapExpect is the key name of the tag used to indicate whether
	// this agent was started with the "bootstrap_expect" configuration set to a non-zero
	// value. The value of this key will be the string for of that configuration value.
	MemberTagKeyBootstrapExpect = "expect"

	// MemberTagKeyUseTLS is the key name of the tag used to indicate whther this agent
	// was configured to use TLS.
	MemberTagKeyUseTLS = "use_tls"
	// MemberTagValueUseTLS is the value of the MemberTagKeyUseTLS when the agent was
	// configured to use TLS. Any other value indicates that it was not setup in
	// that manner.
	MemberTagValueUseTLS = "1"

	// MemberTagKeyReadReplica is the key used to indicate that the member is a read
	// replica server (will remain a Raft non-voter).
	// Read Replicas are a Consul Enterprise feature.
	MemberTagKeyReadReplica = "read_replica"
	// MemberTagValueReadReplica is the value of the MemberTagKeyReadReplica key when
	// the member is in fact a read-replica. Any other value indicates that it is not.
	// Read Replicas are a Consul Enterprise feature.
	MemberTagValueReadReplica = "1"
)
View Source
const (
	// HTTPAddrEnvName defines an environment variable name which sets
	// the HTTP address if there is no -http-addr specified.
	HTTPAddrEnvName = "CONSUL_HTTP_ADDR"

	// HTTPTokenEnvName defines an environment variable name which sets
	// the HTTP token.
	HTTPTokenEnvName = "CONSUL_HTTP_TOKEN"

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

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

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

	// HTTPNamespaceEnvVar defines an environment variable name which sets
	// the HTTP Namespace to be used by default. This can still be overridden.
	HTTPNamespaceEnvName = "CONSUL_NAMESPACE"

	// HTTPPartitionEnvName defines an environment variable name which sets
	// the HTTP Partition to be used by default. This can still be overridden.
	HTTPPartitionEnvName = "CONSUL_PARTITION"

	// QueryBackendStreaming Query backend of type streaming
	QueryBackendStreaming = "streaming"

	// QueryBackendBlockingQuery Query backend of type blocking query
	QueryBackendBlockingQuery = "blocking-query"
)
View Source
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"
	ServiceIntentions  string = "service-intentions"
	MeshConfig         string = "mesh"
	ExportedServices   string = "exported-services"
	SamenessGroup      string = "sameness-group"
	RateLimitIPConfig  string = "control-plane-request-limit"

	ProxyConfigGlobal     string = "global"
	MeshConfigMesh        string = "mesh"
	APIGateway            string = "api-gateway"
	TCPRoute              string = "tcp-route"
	FileSystemCertificate string = "file-system-certificate"
	InlineCertificate     string = "inline-certificate"
	HTTPRoute             string = "http-route"
	JWTProvider           string = "jwt-provider"
)
View Source
const (
	BuiltinAWSLambdaExtension         string = "builtin/aws/lambda"
	BuiltinExtAuthzExtension          string = "builtin/ext-authz"
	BuiltinLuaExtension               string = "builtin/lua"
	BuiltinOTELAccessLoggingExtension string = "builtin/otel-access-logging"
	BuiltinPropertyOverrideExtension  string = "builtin/property-override"
	BuiltinWasmExtension              string = "builtin/wasm"
	// BuiltinValidateExtension should not be exposed directly or accepted as a valid configured
	// extension type, as it is only used indirectly via troubleshooting tools. It is included here
	// for common reference alongside other builtin extensions.
	BuiltinValidateExtension string = "builtin/proxy/validate"
)
View Source
const (
	// This condition is true when the controller managing the Gateway is
	// syntactically and semantically valid enough to produce some configuration
	// in the underlying data plane. This does not indicate whether or not the
	// configuration has been propagated to the data plane.
	//
	// Possible reasons for this condition to be True are:
	//
	// * "Accepted"
	//
	// Possible reasons for this condition to be False are:
	//
	// * InvalidCertificates
	//
	GatewayConditionAccepted GatewayConditionType = "Accepted"

	// This reason is used with the "Accepted" condition when the condition is
	// True.
	GatewayReasonAccepted GatewayConditionReason = "Accepted"

	// This reason is used with the "Accepted" condition when the gateway has multiple invalid
	// certificates and cannot bind to any routes
	GatewayReasonInvalidCertificates GatewayConditionReason = "InvalidCertificates"

	// This reason is used with the "Accepted" condition when the gateway has multiple invalid
	// JWT providers and cannot bind to any routes
	GatewayReasonInvalidJWTProviders GatewayConditionReason = "InvalidJWTProviders"

	// This condition indicates that the gateway was unable to resolve
	// conflicting specification requirements for this Listener. If a
	// Listener is conflicted, its network port should not be configured
	// on any network elements.
	//
	// Possible reasons for this condition to be true are:
	//
	// * "RouteConflict"
	//
	// Possible reasons for this condition to be False are:
	//
	// * "NoConflict"
	//
	// Controllers may raise this condition with other reasons,
	// but should prefer to use the reasons listed above to improve
	// interoperability.
	GatewayConditionConflicted GatewayConditionType = "Conflicted"
	// This reason is used with the "Conflicted" condition when the condition
	// is False.
	GatewayReasonNoConflict GatewayConditionReason = "NoConflict"
	// This reason is used with the "Conflicted" condition when the route is
	// in a conflicted state, such as when a TCPListener attempts to bind to two routes
	GatewayReasonRouteConflict GatewayConditionReason = "RouteConflict"

	// This condition indicates whether the controller was able to
	// resolve all the object references for the Gateway. When setting this
	// condition to False, a ResourceReference to the misconfigured Listener should
	// be provided.
	//
	// Possible reasons for this condition to be true are:
	//
	// * "ResolvedRefs"
	//
	// Possible reasons for this condition to be False are:
	//
	// * "InvalidCertificateRef"
	// * "InvalidRouteKinds"
	// * "RefNotPermitted"
	//
	GatewayConditionResolvedRefs GatewayConditionType = "ResolvedRefs"

	// This reason is used with the "ResolvedRefs" condition when the condition
	// is true.
	GatewayReasonResolvedRefs GatewayConditionReason = "ResolvedRefs"

	// This reason is used with the "ResolvedRefs" condition when a
	// Listener has a TLS configuration with at least one TLS CertificateRef
	// that is invalid or does not exist.
	// A CertificateRef is considered invalid when it refers to a nonexistent
	// or unsupported resource or kind, or when the data within that resource
	// is malformed.
	// This reason must be used only when the reference is allowed, either by
	// referencing an object in the same namespace as the Gateway, or when
	// a cross-namespace reference has been explicitly allowed by a ReferenceGrant.
	// If the reference is not allowed, the reason RefNotPermitted must be used
	// instead.
	GatewayListenerReasonInvalidCertificateRef GatewayConditionReason = "InvalidCertificateRef"

	// This reason is used with the "ResolvedRefs" condition when a
	// Listener has a JWT configuration with at least one JWTProvider
	// that is invalid or does not exist.
	// A JWTProvider is considered invalid when it refers to a nonexistent
	// or unsupported resource or kind, or when the data within that resource
	// is malformed.
	GatewayListenerReasonInvalidJWTProviderRef GatewayConditionReason = "InvalidJWTProviderRef"
)

the following are directly from the k8s spec

View Source
const (
	// This condition indicates whether the route has been accepted or rejected
	// by a Gateway, and why.
	//
	// Possible reasons for this condition to be true are:
	//
	// * "Accepted"
	//
	// Possible reasons for this condition to be False are:
	//
	// * "InvalidDiscoveryChain"
	// * "NoUpstreamServicesTargeted"
	//
	//
	// Controllers may raise this condition with other reasons,
	// but should prefer to use the reasons listed above to improve
	// interoperability.
	RouteConditionAccepted RouteConditionType = "Accepted"

	// This reason is used with the "Accepted" condition when the Route has been
	// accepted by the Gateway.
	RouteReasonAccepted RouteConditionReason = "Accepted"

	// This reason is used with the "Accepted" condition when the route has an
	// invalid discovery chain, this includes conditions like the protocol being invalid
	// or the discovery chain failing to compile
	RouteReasonInvalidDiscoveryChain RouteConditionReason = "InvalidDiscoveryChain"

	// This reason is used with the "Accepted" condition when the route
	RouteReasonNoUpstreamServicesTargeted RouteConditionReason = "NoUpstreamServicesTargeted"
)

The following statuses are taken from the K8's Spec With the exception of: "RouteReasonInvalidDiscoveryChain" and "NoUpstreamServicesTargeted"

View Source
const (
	// This condition indicates whether the route was able to successfully bind the
	// Listener on the gateway
	// Possible reasons for this condition to be true are:
	//
	// * "Bound"
	//
	// Possible reasons for this condition to be false are:
	//
	// * "FailedToBind"
	// * "GatewayNotFound"
	//
	RouteConditionBound RouteConditionType = "Bound"

	// This reason is used with the "Bound" condition when the condition
	// is true
	RouteReasonBound RouteConditionReason = "Bound"

	// This reason is used with the "Bound" condition when the route failed
	// to bind to the gateway
	RouteReasonFailedToBind RouteConditionReason = "FailedToBind"

	// This reason is used with the "Bound" condition when the route fails
	// to find the gateway
	RouteReasonGatewayNotFound RouteConditionReason = "GatewayNotFound"

	// This reason is used with the "Accepted" condition when the route references non-existent
	// JWTProviders
	RouteReasonJWTProvidersNotFound RouteConditionReason = "JWTProvidersNotFound"
)

the following statuses are custom to Consul

View Source
const (
	DiscoveryGraphNodeTypeRouter   = "router"
	DiscoveryGraphNodeTypeSplitter = "splitter"
	DiscoveryGraphNodeTypeResolver = "resolver"
)
View Source
const (
	// HealthAny is special, and is used as a wild card,
	// not as a specific state.
	HealthAny      = "any"
	HealthPassing  = "passing"
	HealthWarning  = "warning"
	HealthCritical = "critical"
	HealthMaint    = "maintenance"
)
View Source
const (
	// NodeMaint is the special key set by a node in maintenance mode.
	NodeMaint = "_node_maintenance"

	// ServiceMaintPrefix is the prefix for a service in maintenance mode.
	ServiceMaintPrefix = "_service_maintenance:"
)
View Source
const (
	// DefaultLockSessionName is the Session Name we assign if none is provided
	DefaultLockSessionName = "Consul API Lock"

	// DefaultLockSessionTTL is the default session TTL if no Session is provided
	// when creating a new Lock. This is used because we do not have another
	// other check to depend upon.
	DefaultLockSessionTTL = "15s"

	// DefaultLockWaitTime is how long we block for at a time to check if lock
	// acquisition is possible. This affects the minimum time it takes to cancel
	// a Lock acquisition.
	DefaultLockWaitTime = 15 * time.Second

	// DefaultLockRetryTime is how long we wait after a failed lock acquisition
	// before attempting to do the lock again. This is so that once a lock-delay
	// is in effect, we do not hot loop retrying the acquisition.
	DefaultLockRetryTime = 5 * time.Second

	// DefaultMonitorRetryTime is how long we wait after a failed monitor check
	// of a lock (500 response code). This allows the monitor to ride out brief
	// periods of unavailability, subject to the MonitorRetries setting in the
	// lock options which is by default set to 0, disabling this feature. This
	// affects locks and semaphores.
	DefaultMonitorRetryTime = 2 * time.Second

	// LockFlagValue is a magic flag we set to indicate a key
	// is being used for a lock. It is used to detect a potential
	// conflict with a semaphore.
	LockFlagValue = 0x2ddccbc058a50c18
)
View Source
const (
	// DefaultSemaphoreSessionName is the Session Name we assign if none is provided
	DefaultSemaphoreSessionName = "Consul API Semaphore"

	// DefaultSemaphoreSessionTTL is the default session TTL if no Session is provided
	// when creating a new Semaphore. This is used because we do not have another
	// other check to depend upon.
	DefaultSemaphoreSessionTTL = "15s"

	// DefaultSemaphoreWaitTime is how long we block for at a time to check if semaphore
	// acquisition is possible. This affects the minimum time it takes to cancel
	// a Semaphore acquisition.
	DefaultSemaphoreWaitTime = 15 * time.Second

	// DefaultSemaphoreKey is the key used within the prefix to
	// use for coordination between all the contenders.
	DefaultSemaphoreKey = ".lock"

	// SemaphoreFlagValue is a magic flag we set to indicate a key
	// is being used for a semaphore. It is used to detect a potential
	// conflict with a lock.
	SemaphoreFlagValue = 0xe0f69a2baa414de0
)
View Source
const (
	// SessionBehaviorRelease is the default behavior and causes
	// all associated locks to be released on session invalidation.
	SessionBehaviorRelease = "release"

	// SessionBehaviorDelete is new in Consul 0.5 and changes the
	// behavior to delete all associated locks on session invalidation.
	// It can be used in a way similar to Ephemeral Nodes in ZooKeeper.
	SessionBehaviorDelete = "delete"
)
View Source
const AllSegments = "_all"

AllSegments is used to select for all segments in MembersOpts.

View Source
const IntentionDefaultNamespace = "default"

IntentionDefaultNamespace is the default namespace value.

View Source
const PartitionDefaultName = "default"

PartitionDefaultName is the default partition value.

View Source
const TelemetryCollectorName string = "consul-telemetry-collector"

TelemetryCollectorName is the service name for the Consul Telemetry Collector

Variables

View Source
var (
	// ErrLockHeld is returned if we attempt to double lock
	ErrLockHeld = fmt.Errorf("Lock already held")

	// ErrLockNotHeld is returned if we attempt to unlock a lock
	// that we do not hold.
	ErrLockNotHeld = fmt.Errorf("Lock not held")

	// ErrLockInUse is returned if we attempt to destroy a lock
	// that is in use.
	ErrLockInUse = fmt.Errorf("Lock in use")

	// ErrLockConflict is returned if the flags on a key
	// used for a lock do not match expectation
	ErrLockConflict = fmt.Errorf("Existing key does not match lock use")
)
View Source
var (
	// ErrSemaphoreHeld is returned if we attempt to double lock
	ErrSemaphoreHeld = fmt.Errorf("Semaphore already held")

	// ErrSemaphoreNotHeld is returned if we attempt to unlock a semaphore
	// that we do not hold.
	ErrSemaphoreNotHeld = fmt.Errorf("Semaphore not held")

	// ErrSemaphoreInUse is returned if we attempt to destroy a semaphore
	// that is in use.
	ErrSemaphoreInUse = fmt.Errorf("Semaphore in use")

	// ErrSemaphoreConflict is returned if the flags on a key
	// used for a semaphore do not match expectation
	ErrSemaphoreConflict = fmt.Errorf("Existing key does not match semaphore use")
)
View Source
var ErrSessionExpired = errors.New("session expired")

Functions

func IsRetryableError

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.

func ValidateGatewayConditionReason added in v1.21.1

func ValidateGatewayConditionReason(name GatewayConditionType, status ConditionStatus, reason GatewayConditionReason) error

func ValidateRouteConditionReason added in v1.21.1

func ValidateRouteConditionReason(name RouteConditionType, status ConditionStatus, reason RouteConditionReason) error

Types

type ACL

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

ACL can be used to query the ACL endpoints

func (*ACL) AuthMethodCreate added in v1.1.0

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

AuthMethodCreate will create a new auth method.

func (*ACL) AuthMethodDelete added in v1.1.0

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

AuthMethodDelete deletes an auth method given its Name.

func (*ACL) AuthMethodList added in v1.1.0

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

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

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

func (*ACL) AuthMethodUpdate added in v1.1.0

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

AuthMethodUpdate updates an auth method.

func (*ACL) BindingRuleCreate added in v1.1.0

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

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

BindingRuleDelete deletes a binding rule given its ID.

func (*ACL) BindingRuleList added in v1.1.0

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

BindingRuleList retrieves a listing of all binding rules.

func (*ACL) BindingRuleRead added in v1.1.0

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

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) BootstrapWithToken added in v1.19.0

func (a *ACL) BootstrapWithToken(btoken string) (*ACLToken, *WriteMeta, error)

BootstrapWithToken is used to get the initial bootstrap token or pass in the one that was provided in the API

func (*ACL) Clone deprecated

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 deprecated

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 deprecated

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 deprecated

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 deprecated

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

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

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

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

func (*ACL) OIDCAuthURL added in v1.5.0

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

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

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

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

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

RoleDelete deletes a role given its ID.

func (*ACL) RoleList added in v1.1.0

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

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

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

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 deprecated

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 has been removed. This function always returns an error.

func (*ACL) RulesTranslateToken deprecated

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 has been removed. This function always returns an error.

func (*ACL) TemplatedPolicyList added in v1.26.1

func (a *ACL) TemplatedPolicyList(q *QueryOptions) (map[string]ACLTemplatedPolicyResponse, *QueryMeta, error)

TemplatedPolicyList retrieves a listing of all templated policies.

func (*ACL) TemplatedPolicyPreview added in v1.26.1

func (a *ACL) TemplatedPolicyPreview(tp *ACLTemplatedPolicy, q *WriteOptions) (*ACLPolicy, *WriteMeta, error)

TemplatedPolicyPreview is used to preview the policy rendered by the templated policy.

func (*ACL) TemplatedPolicyReadByName added in v1.26.1

func (a *ACL) TemplatedPolicyReadByName(templateName string, q *QueryOptions) (*ACLTemplatedPolicyResponse, *QueryMeta, error)

TemplatedPolicyReadByName retrieves the templated policy details (by name). Returns nil if not found.

func (*ACL) TokenClone

func (a *ACL) TokenClone(accessorID 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 accessorID 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(accessorID string, q *WriteOptions) (*WriteMeta, error)

TokenDelete removes a single ACL token. The accessorID 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) TokenListFiltered added in v1.18.1

func (a *ACL) TokenListFiltered(t ACLTokenFilterOptions, q *QueryOptions) ([]*ACLTokenListEntry, *QueryMeta, error)

TokenListFiltered lists all tokens that match the given filter options. 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(accessorID string, q *QueryOptions) (*ACLToken, *QueryMeta, error)

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

func (*ACL) TokenReadExpanded added in v1.13.0

func (a *ACL) TokenReadExpanded(accessorID string, q *QueryOptions) (*ACLTokenExpanded, *QueryMeta, error)

TokenReadExpanded retrieves the full token details, as well as the contents of any policies affecting the token. The accessorID 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 deprecated

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

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

	// Partition is the partition the ACLAuthMethod is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition string `json:",omitempty"`
}

func (*ACLAuthMethod) MarshalJSON added in v1.5.0

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

func (*ACLAuthMethod) UnmarshalJSON added in v1.5.0

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

type ACLAuthMethodListEntry added in v1.1.0

type ACLAuthMethodListEntry 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"`
	CreateIndex   uint64
	ModifyIndex   uint64

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

	// Partition is the partition the ACLAuthMethodListEntry is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition string `json:",omitempty"`
}

func (*ACLAuthMethodListEntry) MarshalJSON added in v1.9.0

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

This is nearly identical to the ACLAuthMethod MarshalJSON

func (*ACLAuthMethodListEntry) UnmarshalJSON added in v1.9.0

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

This is nearly identical to the ACLAuthMethod UnmarshalJSON

type ACLAuthMethodNamespaceRule added in v1.5.0

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

type ACLBindingRule struct {
	ID          string
	Description string
	AuthMethod  string
	Selector    string
	BindType    BindingRuleBindType
	BindName    string
	BindVars    *ACLTemplatedPolicyVariables `json:",omitempty"`

	CreateIndex uint64
	ModifyIndex uint64

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

	// Partition is the partition the ACLBindingRule is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition 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 added in v1.1.0

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

type ACLNodeIdentity added in v1.6.0

type ACLNodeIdentity struct {
	NodeName   string
	Datacenter string
}

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

type ACLOIDCAuthURLParams added in v1.5.0

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

type ACLOIDCCallbackParams added in v1.5.0

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

	// Partition is the partition the ACLPolicy is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition 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"`

	// Partition is the partition the ACLPolicyListEntry is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition 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
	LastErrorMessage     string
}

ACLReplicationStatus is used to represent the status of ACL replication.

type ACLRole added in v1.1.0

type ACLRole struct {
	ID                string
	Name              string
	Description       string
	Policies          []*ACLRolePolicyLink  `json:",omitempty"`
	ServiceIdentities []*ACLServiceIdentity `json:",omitempty"`
	NodeIdentities    []*ACLNodeIdentity    `json:",omitempty"`
	TemplatedPolicies []*ACLTemplatedPolicy `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"`

	// Partition is the partition the ACLRole is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition string `json:",omitempty"`
}

ACLRole represents an ACL Role.

type ACLRolePolicyLink = ACLLink

type ACLServiceIdentity added in v1.1.0

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 ACLTemplatedPolicy added in v1.26.1

type ACLTemplatedPolicy struct {
	TemplateName      string
	TemplateVariables *ACLTemplatedPolicyVariables `json:",omitempty"`

	// Datacenters are an artifact of Nodeidentity & ServiceIdentity.
	// It is used to facilitate the future migration away from both
	Datacenters []string `json:",omitempty"`
}

ACLTemplatedPolicy represents a template used to generate a `synthetic` policy given some input variables.

type ACLTemplatedPolicyResponse added in v1.26.1

type ACLTemplatedPolicyResponse struct {
	TemplateName string
	Schema       string
	Template     string
	Description  string
}

type ACLTemplatedPolicyVariables added in v1.26.1

type ACLTemplatedPolicyVariables struct {
	Name string
}

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"`
	NodeIdentities    []*ACLNodeIdentity    `json:",omitempty"`
	TemplatedPolicies []*ACLTemplatedPolicy `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 are an artifact of legacy tokens deprecated in Consul 1.4
	Rules string `json:"-"`

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

	// Partition is the partition the ACLToken is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// AuthMethodNamespace is the namespace the token's AuthMethod is associated with.
	// Namespacing is a Consul Enterprise feature.
	AuthMethodNamespace string `json:",omitempty"`
}

ACLToken represents an ACL Token

type ACLTokenExpanded added in v1.13.0

type ACLTokenExpanded struct {
	ExpandedPolicies []ACLPolicy
	ExpandedRoles    []ACLRole

	NamespaceDefaultPolicyIDs []string
	NamespaceDefaultRoleIDs   []string

	AgentACLDefaultPolicy string
	AgentACLDownPolicy    string
	ResolvedByAgent       string

	ACLToken
}

type ACLTokenFilterOptions added in v1.18.1

type ACLTokenFilterOptions struct {
	AuthMethod  string `json:",omitempty"`
	Policy      string `json:",omitempty"`
	Role        string `json:",omitempty"`
	ServiceName string `json:",omitempty"`
}

type ACLTokenListEntry

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

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

	// Partition is the partition the ACLTokenListEntry is associated with.
	// Partitions are a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// AuthMethodNamespace is the namespace the token's AuthMethod is associated with.
	// Namespacing is a Consul Enterprise feature.
	AuthMethodNamespace string `json:",omitempty"`
}
type ACLTokenPolicyLink = ACLLink
type ACLTokenRoleLink = ACLLink

type APIGatewayConfigEntry added in v1.19.0

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

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

	Meta map[string]string `json:",omitempty"`

	// Listeners is the set of listener configuration to which an API Gateway
	// might bind.
	Listeners []APIGatewayListener
	// Status is the asynchronous status which an APIGateway propagates to the user.
	Status ConfigEntryStatus

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

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

APIGatewayConfigEntry manages the configuration for an API gateway with the given name.

func (*APIGatewayConfigEntry) GetCreateIndex added in v1.19.0

func (g *APIGatewayConfigEntry) GetCreateIndex() uint64

func (*APIGatewayConfigEntry) GetKind added in v1.19.0

func (g *APIGatewayConfigEntry) GetKind() string

func (*APIGatewayConfigEntry) GetMeta added in v1.19.0

func (g *APIGatewayConfigEntry) GetMeta() map[string]string

func (*APIGatewayConfigEntry) GetModifyIndex added in v1.19.0

func (g *APIGatewayConfigEntry) GetModifyIndex() uint64

func (*APIGatewayConfigEntry) GetName added in v1.19.0

func (g *APIGatewayConfigEntry) GetName() string

func (*APIGatewayConfigEntry) GetNamespace added in v1.19.0

func (g *APIGatewayConfigEntry) GetNamespace() string

func (*APIGatewayConfigEntry) GetPartition added in v1.19.0

func (g *APIGatewayConfigEntry) GetPartition() string

type APIGatewayJWTClaimVerification added in v1.26.1

type APIGatewayJWTClaimVerification struct {
	// Path is the path to the claim in the token JSON.
	Path []string `json:",omitempty"`

	// Value is the expected value at the given path:
	// - If the type at the path is a list then we verify
	//   that this value is contained in the list.
	//
	// - If the type at the path is a string then we verify
	//   that this value matches.
	Value string `json:",omitempty"`
}

APIGatewayJWTClaimVerification holds the actual claim information to be verified

type APIGatewayJWTProvider added in v1.26.1

type APIGatewayJWTProvider struct {
	// Name is the name of the JWT provider. There MUST be a corresponding
	// "jwt-provider" config entry with this name.
	Name string `json:",omitempty"`

	// VerifyClaims is a list of additional claims to verify in a JWT's payload.
	VerifyClaims []*APIGatewayJWTClaimVerification `json:",omitempty" alias:"verify_claims"`
}

APIGatewayJWTProvider holds the provider and claim verification information

type APIGatewayJWTRequirement added in v1.26.1

type APIGatewayJWTRequirement struct {
	// Providers is a list of providers to consider when verifying a JWT.
	Providers []*APIGatewayJWTProvider `json:",omitempty"`
}

APIGatewayJWTRequirement holds the list of JWT providers to be verified against

type APIGatewayListener added in v1.19.0

type APIGatewayListener struct {
	// Name is the name of the listener in a given gateway. This must be
	// unique within a gateway.
	Name string
	// Hostname is the host name that a listener should be bound to, if
	// unspecified, the listener accepts requests for all hostnames.
	Hostname string
	// Port is the port at which this listener should bind.
	Port int
	// Protocol is the protocol that a listener should use, it must
	// either be "http" or "tcp"
	Protocol string
	// TLS is the TLS settings for the listener.
	TLS APIGatewayTLSConfiguration
	// Override is the policy that overrides all other policy and route specific configuration
	Override *APIGatewayPolicy `json:",omitempty"`
	// Default is the policy that is the default for the listener and route, routes can override this behavior
	Default *APIGatewayPolicy `json:",omitempty"`
}

APIGatewayListener represents an individual listener for an APIGateway

type APIGatewayPolicy added in v1.26.1

type APIGatewayPolicy struct {
	// JWT holds the JWT configuration for the Listener
	JWT *APIGatewayJWTRequirement `json:",omitempty"`
}

APIGatewayPolicy holds the policy that configures the gateway listener, this is used in the `Override` and `Default` fields of a listener

type APIGatewayTLSConfiguration added in v1.19.0

type APIGatewayTLSConfiguration struct {
	// Certificates is a set of references to certificates
	// that a gateway listener uses for TLS termination.
	Certificates []ResourceReference
	// MaxVersion is the maximum TLS version that the listener
	// should support.
	MaxVersion string `json:",omitempty" alias:"tls_max_version"`
	// MinVersion is the minimum TLS version that the listener
	// should support.
	MinVersion string `json:",omitempty" alias:"tls_min_version"`
	// Define a subset of cipher suites to restrict
	// Only applicable to connections negotiated via TLS 1.2 or earlier
	CipherSuites []string `json:",omitempty" alias:"cipher_suites"`
}

APIGatewayTLSConfiguration specifies the configuration of a listener’s TLS settings.

type AccessLogsConfig added in v1.19.0

type AccessLogsConfig struct {
	// Enabled turns off all access logging
	Enabled bool `json:",omitempty" alias:"enabled"`

	// DisableListenerLogs turns off just listener logs for connections rejected by Envoy because they don't
	// have a matching listener filter.
	DisableListenerLogs bool `json:",omitempty" alias:"disable_listener_logs"`

	// Type selects the output for logs: "file", "stderr". "stdout"
	Type LogSinkType `json:",omitempty" alias:"type"`

	// Path is the output file to write logs
	Path string `json:",omitempty" alias:"path"`

	// The presence of one format string or the other implies the access log string encoding.
	// Defining Both is invalid.
	JSONFormat string `json:",omitempty" alias:"json_format"`
	TextFormat string `json:",omitempty" alias:"text_format"`
}

AccessLogsConfig contains the associated default settings for all Envoy instances within the datacenter or partition

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) AgentHealthServiceByIDOpts added in v1.10.0

func (a *Agent) AgentHealthServiceByIDOpts(serviceID string, q *QueryOptions) (string, *AgentServiceChecksInfo, 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) AgentHealthServiceByNameOpts added in v1.10.0

func (a *Agent) AgentHealthServiceByNameOpts(service string, q *QueryOptions) (string, []AgentServiceChecksInfo, error)

func (*Agent) CheckDeregister

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

CheckDeregister is used to deregister a check with the local agent

func (*Agent) CheckDeregisterOpts added in v1.9.0

func (a *Agent) CheckDeregisterOpts(checkID string, q *QueryOptions) error

CheckDeregisterOpts is used to deregister a check with the local agent using query options

func (*Agent) CheckRegister

func (a *Agent) CheckRegister(check *AgentCheckRegistration) error

CheckRegister is used to register a new check with the local agent

func (*Agent) CheckRegisterOpts added in v1.26.1

func (a *Agent) CheckRegisterOpts(check *AgentCheckRegistration, q *QueryOptions) error

CheckRegisterOpts is used to register a new check with the local agent using query options

func (*Agent) Checks

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

Checks returns the locally registered checks

func (*Agent) ChecksWithFilter added in v1.1.0

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) ChecksWithFilterOpts added in v1.9.0

func (a *Agent) ChecksWithFilterOpts(filter string, q *QueryOptions) (map[string]*AgentCheck, error)

ChecksWithFilterOpts returns a subset of the locally registered checks that match the given filter expression and QueryOptions.

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) DisableServiceMaintenanceOpts added in v1.10.0

func (a *Agent) DisableServiceMaintenanceOpts(serviceID string, q *QueryOptions) error

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) EnableServiceMaintenanceOpts added in v1.10.0

func (a *Agent) EnableServiceMaintenanceOpts(serviceID, reason string, q *QueryOptions) error

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) ForceLeaveOptions added in v1.22.0

func (a *Agent) ForceLeaveOptions(node string, opts ForceLeaveOpts, q *QueryOptions) error

ForceLeaveOptions is used to have the agent eject a failed node or remove it completely from the list of members. Allows usage of QueryOptions on-top of ForceLeaveOpts

func (*Agent) ForceLeaveOpts added in v1.12.0

func (a *Agent) ForceLeaveOpts(node string, opts ForceLeaveOpts) error

ForceLeaveOpts is used to have the agent eject a failed node or remove it completely from the list of members.

DEPRECATED - Use ForceLeaveOptions instead.

func (*Agent) ForceLeavePrune added in v1.3.0

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) MetricsStream added in v1.10.0

func (a *Agent) MetricsStream(ctx context.Context) (io.ReadCloser, error)

MetricsStream returns an io.ReadCloser which will emit a stream of metrics until the context is cancelled. The metrics are json encoded. The caller is responsible for closing the returned io.ReadCloser.

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

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) ServiceDeregisterOpts added in v1.9.0

func (a *Agent) ServiceDeregisterOpts(serviceID string, q *QueryOptions) error

ServiceDeregisterOpts is used to deregister a service with the local agent with QueryOptions.

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

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

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) ServicesWithFilterOpts added in v1.9.0

func (a *Agent) ServicesWithFilterOpts(filter string, q *QueryOptions) (map[string]*AgentService, error)

ServicesWithFilterOpts returns a subset of the locally registered services that match the given filter expression and QueryOptions.

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 in Consul 1.4.

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 in Consul 1.4.

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 in Consul 1.4.

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 in Consul 1.4.

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.

DEPRECATED - Prefer UpdateAgentRecoveryACLToken for v1.11 and above.

func (*Agent) UpdateAgentRecoveryACLToken added in v1.12.0

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

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

func (*Agent) UpdateConfigFileRegistrationToken added in v1.19.0

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

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

func (*Agent) UpdateDNSToken added in v1.26.1

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

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) UpdateTTLOpts added in v1.9.0

func (a *Agent) UpdateTTLOpts(checkID, output, status string, q *QueryOptions) error

func (*Agent) Version added in v1.22.0

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

Version is used to retrieve information about the running Consul version and build.

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
	ExposedPort int
	Definition  HealthCheckDefinition
	Namespace   string `json:",omitempty"`
	Partition   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"`
	Partition 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 of the Member which corresponds to  github.com/hashicorp/serf/serf.MemberStatus
	// Value is one of:
	//
	// 	  AgentMemberNone    = 0
	//	  AgentMemberAlive   = 1
	//	  AgentMemberLeaving = 2
	//	  AgentMemberLeft    = 3
	//	  AgentMemberFailed  = 4
	Status      int
	ProtocolMin uint8
	ProtocolMax uint8
	ProtocolCur uint8
	DelegateMin uint8
	DelegateMax uint8
	DelegateCur uint8
}

AgentMember represents a cluster member known to the agent

func (*AgentMember) ACLMode added in v1.7.0

func (m *AgentMember) ACLMode() MemberACLMode

ACLMode returns the ACL mode this agent is operating in.

func (*AgentMember) IsConsulServer added in v1.7.0

func (m *AgentMember) IsConsulServer() bool

IsConsulServer returns true when this member is a Consul server.

type AgentService

type AgentService struct {
	Kind              ServiceKind `json:",omitempty"`
	ID                string
	Service           string
	Tags              []string
	Meta              map[string]string
	Port              int
	Address           string
	SocketPath        string                    `json:",omitempty"`
	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"`
	PeerName          string                          `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"`
	Partition string `json:",omitempty" bexpr:"-" hash:"ignore"`
	// Datacenter is only ever returned and is ignored if presented.
	Datacenter string    `json:",omitempty" bexpr:"-" hash:"ignore"`
	Locality   *Locality `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"`
	TCPUseTLS              bool                `json:",omitempty"`
	UDP                    string              `json:",omitempty"`
	Status                 string              `json:",omitempty"`
	Notes                  string              `json:",omitempty"`
	TLSServerName          string              `json:",omitempty"`
	TLSSkipVerify          bool                `json:",omitempty"`
	GRPC                   string              `json:",omitempty"`
	GRPCUseTLS             bool                `json:",omitempty"`
	H2PING                 string              `json:",omitempty"`
	H2PingUseTLS           bool                `json:",omitempty"`
	AliasNode              string              `json:",omitempty"`
	AliasService           string              `json:",omitempty"`
	SuccessBeforePassing   int                 `json:",omitempty"`
	FailuresBeforeWarning  int                 `json:",omitempty"`
	FailuresBeforeCritical int                 `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 {
	EnvoyExtensions        []EnvoyExtension        `json:",omitempty"`
	DestinationServiceName string                  `json:",omitempty"`
	DestinationServiceID   string                  `json:",omitempty"`
	LocalServiceAddress    string                  `json:",omitempty"`
	LocalServicePort       int                     `json:",omitempty"`
	LocalServiceSocketPath string                  `json:",omitempty"`
	Mode                   ProxyMode               `json:",omitempty"`
	TransparentProxy       *TransparentProxyConfig `json:",omitempty"`
	Config                 map[string]interface{}  `json:",omitempty" bexpr:"-"`
	Upstreams              []Upstream              `json:",omitempty"`
	MeshGateway            MeshGatewayConfig       `json:",omitempty"`
	Expose                 ExposeConfig            `json:",omitempty"`
	AccessLogs             *AccessLogsConfig       `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"`
	SocketPath        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"`
	Partition         string                          `json:",omitempty" bexpr:"-" hash:"ignore"`
	Locality          *Locality                       `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 AssignServiceManualVIPsRequest added in v1.22.0

type AssignServiceManualVIPsRequest struct {
	Service    string
	ManualVIPs []string
}

type AssignServiceManualVIPsResponse added in v1.22.0

type AssignServiceManualVIPsResponse struct {
	ServiceFound   bool `json:"Found"`
	UnassignedFrom []PeeredServiceName
}

type AuditHashRequest added in v1.25.1

type AuditHashRequest struct {
	Input string
}

type AuditHashResponse added in v1.25.1

type AuditHashResponse struct {
	Hash string
}

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.

func NewAutopilotConfiguration added in v1.10.0

func NewAutopilotConfiguration() AutopilotConfiguration

Defines default values for the AutopilotConfiguration type, consistent with https://www.consul.io/api-docs/operator/autopilot#parameters-1

type AutopilotServer added in v1.8.0

type AutopilotServer struct {
	ID             string
	Name           string
	Address        string
	NodeStatus     string
	Version        string
	LastContact    *ReadableDuration
	LastTerm       uint64
	LastIndex      uint64
	Healthy        bool
	StableSince    time.Time
	RedundancyZone string `json:",omitempty"`
	UpgradeVersion string `json:",omitempty"`
	ReadReplica    bool
	Status         AutopilotServerStatus
	Meta           map[string]string
	NodeType       AutopilotServerType
}

type AutopilotServerStatus added in v1.8.0

type AutopilotServerStatus string
const (
	AutopilotServerNone     AutopilotServerStatus = "none"
	AutopilotServerLeader   AutopilotServerStatus = "leader"
	AutopilotServerVoter    AutopilotServerStatus = "voter"
	AutopilotServerNonVoter AutopilotServerStatus = "non-voter"
	AutopilotServerStaging  AutopilotServerStatus = "staging"
)

type AutopilotServerType added in v1.8.0

type AutopilotServerType string
const (
	AutopilotTypeVoter          AutopilotServerType = "voter"
	AutopilotTypeReadReplica    AutopilotServerType = "read-replica"
	AutopilotTypeZoneVoter      AutopilotServerType = "zone-voter"
	AutopilotTypeZoneExtraVoter AutopilotServerType = "zone-extra-voter"
	AutopilotTypeZoneStandby    AutopilotServerType = "zone-standby"
)

type AutopilotState added in v1.8.0

type AutopilotState struct {
	Healthy                    bool
	FailureTolerance           int
	OptimisticFailureTolerance int

	Servers         map[string]AutopilotServer
	Leader          string
	Voters          []string
	ReadReplicas    []string                 `json:",omitempty"`
	RedundancyZones map[string]AutopilotZone `json:",omitempty"`
	Upgrade         *AutopilotUpgrade        `json:",omitempty"`
}

type AutopilotUpgrade added in v1.8.0

type AutopilotUpgrade struct {
	Status                    AutopilotUpgradeStatus
	TargetVersion             string                                  `json:",omitempty"`
	TargetVersionVoters       []string                                `json:",omitempty"`
	TargetVersionNonVoters    []string                                `json:",omitempty"`
	TargetVersionReadReplicas []string                                `json:",omitempty"`
	OtherVersionVoters        []string                                `json:",omitempty"`
	OtherVersionNonVoters     []string                                `json:",omitempty"`
	OtherVersionReadReplicas  []string                                `json:",omitempty"`
	RedundancyZones           map[string]AutopilotZoneUpgradeVersions `json:",omitempty"`
}

type AutopilotUpgradeStatus added in v1.8.0

type AutopilotUpgradeStatus string
const (
	// AutopilotUpgradeIdle is the status when no upgrade is in progress.
	AutopilotUpgradeIdle AutopilotUpgradeStatus = "idle"

	// AutopilotUpgradeAwaitNewVoters is the status when more servers of
	// the target version must be added in order to start the promotion
	// phase of the upgrade
	AutopilotUpgradeAwaitNewVoters AutopilotUpgradeStatus = "await-new-voters"

	// AutopilotUpgradePromoting is the status when autopilot is promoting
	// servers of the target version.
	AutopilotUpgradePromoting AutopilotUpgradeStatus = "promoting"

	// AutopilotUpgradeDemoting is the status when autopilot is demoting
	// servers not on the target version
	AutopilotUpgradeDemoting AutopilotUpgradeStatus = "demoting"

	// AutopilotUpgradeLeaderTransfer is the status when autopilot is transferring
	// leadership from a server running an older version to a server
	// using the target version.
	AutopilotUpgradeLeaderTransfer AutopilotUpgradeStatus = "leader-transfer"

	// AutopilotUpgradeAwaitNewServers is the status when autpilot has finished
	// transferring leadership and has demoted all the other versioned
	// servers but wants to indicate that more target version servers
	// are needed to replace all the existing other version servers.
	AutopilotUpgradeAwaitNewServers AutopilotUpgradeStatus = "await-new-servers"

	// AutopilotUpgradeAwaitServerRemoval is the status when autopilot is waiting
	// for the servers on non-target versions to be removed
	AutopilotUpgradeAwaitServerRemoval AutopilotUpgradeStatus = "await-server-removal"

	// AutopilotUpgradeDisabled is the status when automated ugprades are
	// disabled in the autopilot configuration
	AutopilotUpgradeDisabled AutopilotUpgradeStatus = "disabled"
)

type AutopilotZone added in v1.8.0

type AutopilotZone struct {
	Servers          []string
	Voters           []string
	FailureTolerance int
}

type AutopilotZoneUpgradeVersions added in v1.8.0

type AutopilotZoneUpgradeVersions struct {
	TargetVersionVoters    []string `json:",omitempty"`
	TargetVersionNonVoters []string `json:",omitempty"`
	OtherVersionVoters     []string `json:",omitempty"`
	OtherVersionNonVoters  []string `json:",omitempty"`
}

type BindingRuleBindType added in v1.1.0

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"

	// BindingRuleBindTypeNode binds to a node identity with given name.
	BindingRuleBindTypeNode BindingRuleBindType = "node"

	// BindingRuleBindTypePolicy binds to a specific policy with given name.
	BindingRuleBindTypePolicy BindingRuleBindType = "policy"

	// BindingRuleBindTypeTemplatedPolicy binds to a templated policy with given template name and variables.
	BindingRuleBindTypeTemplatedPolicy BindingRuleBindType = "templated-policy"
)

type BootstrapRequest added in v1.19.0

type BootstrapRequest struct {
	BootstrapSecret string
}

BootstrapRequest is used for when operators provide an ACL Bootstrap Token

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

	// ForceWithoutCrossSigning indicates that the CA reconfiguration should go
	// ahead even if the current CA is unable to cross sign certificates. This
	// risks temporary connection failures during the rollout as new leafs will be
	// rejected by proxies that have not yet observed the new root cert but is the
	// only option if a CA that doesn't support cross signing needs to be
	// reconfigured or mirated away from.
	ForceWithoutCrossSigning bool

	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) GatewayServices added in v1.6.0

func (c *Catalog) GatewayServices(gateway string, q *QueryOptions) ([]*GatewayService, *QueryMeta, error)

GatewayServices is used to query the services associated with an ingress gateway or terminating gateway.

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

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

type CatalogNode

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

type CatalogNodeServiceList added in v1.4.0

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

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
	ServiceLocality          *Locality `json:",omitempty"`
	CreateIndex              uint64
	Checks                   HealthChecks
	ModifyIndex              uint64
	Namespace                string `json:",omitempty"`
	Partition                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) AddHeader added in v1.9.0

func (c *Client) AddHeader(key, value string)

AddHeader allows a single header key/value pair to be added in a race-safe fashion.

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

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

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) ExportedServices added in v1.27.1

func (c *Client) ExportedServices(q *QueryOptions) ([]ResolvedExportedService, *QueryMeta, error)

func (*Client) Headers added in v1.9.0

func (c *Client) Headers() http.Header

Headers gets the current set of headers used for requests. This returns a copy; to modify it call AddHeader or SetHeaders.

func (*Client) Health

func (c *Client) Health() *Health

Health returns a handle to the health endpoints

func (*Client) Internal added in v1.22.0

func (c *Client) Internal() *Internal

Internal returns a handle to endpoints that are for internal Hashicorp usage only. There is not guarantee that these will be backwards-compatible or supported, so usage of these is not encouraged.

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

func (c *Client) Namespaces() *Namespaces

Namespaces returns a handle to the namespaces endpoints.

func (*Client) Operator

func (c *Client) Operator() *Operator

Operator returns a handle to the operator endpoints.

func (*Client) Partitions added in v1.10.0

func (c *Client) Partitions() *Partitions

Operator returns a handle to the operator endpoints.

func (*Client) Peerings added in v1.14.0

func (c *Client) Peerings() *Peerings

Peerings 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) SetHeaders added in v1.9.0

func (c *Client) SetHeaders(headers http.Header)

SetHeaders clears all previous headers and uses only the given ones going forward.

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 ClusterDiscoveryType added in v1.23.0

type ClusterDiscoveryType string
const (
	DiscoveryTypeStrictDNS   ClusterDiscoveryType = "STRICT_DNS"
	DiscoveryTypeStatic      ClusterDiscoveryType = "STATIC"
	DiscoveryTypeLogicalDNS  ClusterDiscoveryType = "LOGICAL_DNS"
	DiscoveryTypeEDS         ClusterDiscoveryType = "EDS"
	DiscoveryTypeOriginalDST ClusterDiscoveryType = "ORIGINAL_DST"
)

type CommonCAProviderConfig

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

CommonCAProviderConfig is the common options available to all CA providers.

type CompiledDiscoveryChain added in v1.2.0

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

	// Default indicates if this discovery chain is based on no
	// service-resolver, service-splitter, or service-router config entries.
	Default bool

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

	// ServiceMeta is the metadata from the underlying service-defaults config
	// entry for the service named ServiceName.
	ServiceMeta map[string]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 CompoundServiceName added in v1.6.0

type CompoundServiceName struct {
	Name string

	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
	// Partitions are a Consul Enterprise feature.
	Partition string `json:",omitempty"`
}

type Condition added in v1.19.0

type Condition struct {
	// Type is a value from a bounded set of types that an object might have
	Type string
	// Status is a value from a bounded set of statuses that an object might have
	Status ConditionStatus
	// Reason is a value from a bounded set of reasons for a given status
	Reason string
	// Message is a message that gives more detailed information about
	// why a Condition has a given status and reason
	Message string
	// Resource is an optional reference to a resource for which this
	// condition applies
	Resource *ResourceReference
	// LastTransitionTime is the time at which this Condition was created
	LastTransitionTime *time.Time
}

Condition is used for a single message and state associated with an object. For example, a ConfigEntry that references multiple other resources may have different statuses with respect to each of those resources.

type ConditionStatus added in v1.21.1

type ConditionStatus string
const (
	ConditionStatusTrue    ConditionStatus = "True"
	ConditionStatusFalse   ConditionStatus = "False"
	ConditionStatusUnknown ConditionStatus = "Unknown"
)

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

	// Prefix for URIs for when consul is behind an API gateway (reverse
	// proxy).  The API gateway must strip off the PathPrefix before
	// passing the request onto consul.
	PathPrefix 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 is present in the QueryOptions
	Namespace string

	// Partition is the name of the partition to send along for the request
	// when no other Partition is present in the QueryOptions
	Partition 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 added in v1.4.0

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

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

ConfigEntries can be used to query the Config endpoints

func (*ConfigEntries) CAS added in v1.1.0

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

func (*ConfigEntries) Delete added in v1.1.0

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

func (*ConfigEntries) DeleteCAS added in v1.12.0

func (conf *ConfigEntries) DeleteCAS(kind, name string, index uint64, w *WriteOptions) (bool, *WriteMeta, error)

DeleteCAS performs a Check-And-Set deletion of the given config entry, and returns true if it was successful. If the provided index no longer matches the entry's ModifyIndex (i.e. it was modified by another process) then the operation will fail and return false.

func (*ConfigEntries) Get added in v1.1.0

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

func (*ConfigEntries) List added in v1.1.0

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

func (*ConfigEntries) Set added in v1.1.0

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

type ConfigEntry added in v1.1.0

type ConfigEntry interface {
	GetKind() string
	GetName() string
	GetPartition() string
	GetNamespace() string
	GetMeta() map[string]string
	GetCreateIndex() uint64
	GetModifyIndex() uint64
}

func DecodeConfigEntry added in v1.1.0

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

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

func MakeConfigEntry added in v1.2.0

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

type ConfigEntryStatus added in v1.19.0

type ConfigEntryStatus struct {
	// Conditions is the set of condition objects associated with
	// a ConfigEntry status.
	Conditions []Condition
}

ConfigEntryStatus is used for propagating back asynchronously calculated messages from control loops to a user

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 deprecated

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.

Deprecated: use IntentionUpsert instead

func (*Connect) IntentionDelete deprecated

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

IntentionDelete deletes a single intention.

Deprecated: use IntentionDeleteExact instead

func (*Connect) IntentionDeleteExact added in v1.8.0

func (h *Connect) IntentionDeleteExact(source, destination string, q *WriteOptions) (*WriteMeta, error)

IntentionDeleteExact deletes a single intention by its unique name instead of its ID.

func (*Connect) IntentionGet deprecated

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

IntentionGet retrieves a single intention.

Deprecated: use IntentionGetExact instead

func (*Connect) IntentionGetExact added in v1.8.0

func (h *Connect) IntentionGetExact(source, destination string, q *QueryOptions) (*Intention, *QueryMeta, error)

IntentionGetExact retrieves a single intention by its unique name instead of its ID.

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 deprecated

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.

Deprecated: use IntentionUpsert instead

func (*Connect) IntentionUpsert added in v1.8.0

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

IntentionUpsert will update an existing intention. The Source & Destination parameters in the structure must be non-empty. The ID must be 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
	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 CookieConfig added in v1.8.0

type CookieConfig struct {
	// Generates a session cookie with no expiration.
	Session bool `json:",omitempty"`

	// TTL for generated cookies. Cannot be specified for session cookies.
	TTL time.Duration `json:",omitempty"`

	// The path to set for the cookie
	Path string `json:",omitempty"`
}

CookieConfig contains configuration for the "cookie" hash policy type. This is specified to have Envoy generate a cookie for a client on its first request.

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
	Partition string `json:",omitempty"`
	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) PProf added in v1.10.0

func (d *Debug) PProf(ctx context.Context, name string, seconds int) (io.ReadCloser, error)

PProf returns a pprof profile for the specified number of seconds. The caller is responsible for closing the returned io.ReadCloser once all bytes are read.

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 DestinationConfig added in v1.14.0

type DestinationConfig struct {
	// Addresses of the endpoint; hostname or IP
	Addresses []string `json:",omitempty"`

	// Port allowed within this endpoint
	Port int `json:",omitempty"`
}

DestinationConfig represents a virtual service, i.e. one that is external to Consul

type DiscoveryChain added in v1.2.0

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

DiscoveryChain can be used to query the discovery-chain endpoints

func (*DiscoveryChain) Get added in v1.2.0

type DiscoveryChainOptions added in v1.2.0

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

type DiscoveryChainResponse struct {
	Chain *CompiledDiscoveryChain
}

type DiscoveryFailover added in v1.2.0

type DiscoveryFailover struct {
	Targets []string
	Policy  ServiceResolverFailoverPolicy `json:",omitempty"`
}

compiled form of ServiceResolverFailover

type DiscoveryGraphNode added in v1.2.0

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

	// shared by Type==resolver || Type==splitter
	LoadBalancer *LoadBalancer `json:",omitempty"`
}

DiscoveryGraphNode is a single node in the compiled discovery chain.

type DiscoveryResolver added in v1.2.0

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

compiled form of ServiceResolverConfigEntry

func (*DiscoveryResolver) MarshalJSON added in v1.2.0

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

func (*DiscoveryResolver) UnmarshalJSON added in v1.2.0

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

type DiscoveryRoute added in v1.2.0

type DiscoveryRoute struct {
	Definition *ServiceRoute
	NextNode   string
}

compiled form of ServiceRoute

type DiscoverySplit added in v1.2.0

type DiscoverySplit struct {
	Weight   float32
	NextNode string
}

compiled form of ServiceSplit

type DiscoveryTarget added in v1.2.0

type DiscoveryTarget struct {
	ID string

	Service       string
	ServiceSubset string
	Namespace     string
	Datacenter    string

	MeshGateway    MeshGatewayConfig
	Subset         ServiceResolverSubset
	ConnectTimeout time.Duration
	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.

func (*DiscoveryTarget) MarshalJSON added in v1.13.0

func (t *DiscoveryTarget) MarshalJSON() ([]byte, error)

func (*DiscoveryTarget) UnmarshalJSON added in v1.13.0

func (t *DiscoveryTarget) UnmarshalJSON(data []byte) error

type EnvoyExtension added in v1.19.0

type EnvoyExtension struct {
	Name          string
	Required      bool
	Arguments     map[string]interface{} `bexpr:"-"`
	ConsulVersion string
	EnvoyVersion  string
}

EnvoyExtension has configuration for an extension that patches Envoy resources.

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 ExportedService added in v1.12.0

type ExportedService struct {
	// Name is the name of the service to be exported.
	Name string

	// Namespace is the namespace to export the service from.
	Namespace string `json:",omitempty"`

	// Consumers is a list of downstream consumers of the service to be exported.
	Consumers []ServiceConsumer `json:",omitempty"`
}

ExportedService manages the exporting of a service in the local partition to other partitions.

type ExportedServicesConfigEntry added in v1.12.0

type ExportedServicesConfigEntry struct {
	// Name is the name of the partition the ExportedServicesConfigEntry applies to.
	// Partitioning is a Consul Enterprise feature.
	Name string `json:",omitempty"`

	// Partition is the partition where the ExportedServicesConfigEntry is stored.
	// If the partition does not match the name, the name will overwrite the partition.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// Services is a list of services to be exported and the list of partitions
	// to expose them to.
	Services []ExportedService `json:",omitempty"`

	Meta map[string]string `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
}

ExportedServicesConfigEntry manages the exported services for a single admin partition. Admin Partitions are a Consul Enterprise feature.

func (*ExportedServicesConfigEntry) GetCreateIndex added in v1.12.0

func (e *ExportedServicesConfigEntry) GetCreateIndex() uint64

func (*ExportedServicesConfigEntry) GetKind added in v1.12.0

func (e *ExportedServicesConfigEntry) GetKind() string

func (*ExportedServicesConfigEntry) GetMeta added in v1.12.0

func (e *ExportedServicesConfigEntry) GetMeta() map[string]string

func (*ExportedServicesConfigEntry) GetModifyIndex added in v1.12.0

func (e *ExportedServicesConfigEntry) GetModifyIndex() uint64

func (*ExportedServicesConfigEntry) GetName added in v1.12.0

func (e *ExportedServicesConfigEntry) GetName() string

func (*ExportedServicesConfigEntry) GetNamespace added in v1.12.0

func (e *ExportedServicesConfigEntry) GetNamespace() string

func (*ExportedServicesConfigEntry) GetPartition added in v1.12.0

func (e *ExportedServicesConfigEntry) GetPartition() string

func (*ExportedServicesConfigEntry) MarshalJSON added in v1.12.0

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

MarshalJSON adds the Kind field so that the JSON can be decoded back into the correct type.

type ExposeConfig added in v1.3.0

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

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 FileSystemCertificateConfigEntry added in v1.29.0

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

	Name string

	// Certificate is the path to a client certificate to use for TLS connections.
	Certificate string `json:",omitempty" alias:"certificate"`

	// PrivateKey is the path to a private key to use for TLS connections.
	PrivateKey string `json:",omitempty" alias:"private_key"`

	Meta map[string]string `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

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

func (*FileSystemCertificateConfigEntry) GetCreateIndex added in v1.29.0

func (a *FileSystemCertificateConfigEntry) GetCreateIndex() uint64

func (*FileSystemCertificateConfigEntry) GetKind added in v1.29.0

func (*FileSystemCertificateConfigEntry) GetMeta added in v1.29.0

func (*FileSystemCertificateConfigEntry) GetModifyIndex added in v1.29.0

func (a *FileSystemCertificateConfigEntry) GetModifyIndex() uint64

func (*FileSystemCertificateConfigEntry) GetName added in v1.29.0

func (*FileSystemCertificateConfigEntry) GetNamespace added in v1.29.0

func (a *FileSystemCertificateConfigEntry) GetNamespace() string

func (*FileSystemCertificateConfigEntry) GetPartition added in v1.29.0

func (a *FileSystemCertificateConfigEntry) GetPartition() string

type ForceLeaveOpts added in v1.12.0

type ForceLeaveOpts struct {
	// Prune indicates if we should remove a failed agent from the list of
	// members in addition to ejecting it.
	Prune bool

	// WAN indicates that the request should exclusively target the WAN pool.
	WAN bool
}

type GatewayConditionReason added in v1.21.1

type GatewayConditionReason string

GatewayConditionReason defines the set of reasons that explain why a particular Gateway condition type has been raised.

type GatewayConditionType added in v1.21.1

type GatewayConditionType string

GatewayConditionType is a type of condition associated with a Gateway. This type should be used with the GatewayStatus.Conditions field.

type GatewayService added in v1.6.0

type GatewayService struct {
	Gateway      CompoundServiceName
	Service      CompoundServiceName
	GatewayKind  ServiceKind
	Port         int      `json:",omitempty"`
	Protocol     string   `json:",omitempty"`
	Hosts        []string `json:",omitempty"`
	CAFile       string   `json:",omitempty"`
	CertFile     string   `json:",omitempty"`
	KeyFile      string   `json:",omitempty"`
	SNI          string   `json:",omitempty"`
	FromWildcard bool     `json:",omitempty"`
}

GatewayService associates a gateway with a linked service. It also contains service-specific gateway configuration like ingress listener port and protocol.

type GatewayServiceTLSConfig added in v1.12.0

type GatewayServiceTLSConfig struct {
	// SDS allows configuring TLS certificate from an SDS service.
	SDS *GatewayTLSSDSConfig `json:",omitempty"`
}

type GatewayTLSConfig added in v1.5.0

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

	// SDS allows configuring TLS certificate from an SDS service.
	SDS *GatewayTLSSDSConfig `json:",omitempty"`

	TLSMinVersion string `json:",omitempty" alias:"tls_min_version"`
	TLSMaxVersion string `json:",omitempty" alias:"tls_max_version"`

	// Define a subset of cipher suites to restrict
	// Only applicable to connections negotiated via TLS 1.2 or earlier
	CipherSuites []string `json:",omitempty" alias:"cipher_suites"`
}

type GatewayTLSSDSConfig added in v1.12.0

type GatewayTLSSDSConfig struct {
	ClusterName  string `json:",omitempty" alias:"cluster_name"`
	CertResource string `json:",omitempty" alias:"cert_resource"`
}

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 HTTPFilters added in v1.19.0

type HTTPFilters struct {
	Headers       []HTTPHeaderFilter
	URLRewrite    *URLRewrite
	RetryFilter   *RetryFilter
	TimeoutFilter *TimeoutFilter
	JWT           *JWTFilter
}

HTTPFilters specifies a list of filters used to modify a request before it is routed to an upstream.

type HTTPHeaderFilter added in v1.19.0

type HTTPHeaderFilter struct {
	Add    map[string]string
	Remove []string
	Set    map[string]string
}

HTTPHeaderFilter specifies how HTTP headers should be modified.

type HTTPHeaderMatch added in v1.19.0

type HTTPHeaderMatch struct {
	Match HTTPHeaderMatchType
	Name  string
	Value string
}

HTTPHeaderMatch specifies how a match should be done on a request's headers.

type HTTPHeaderMatchType added in v1.19.0

type HTTPHeaderMatchType string

HTTPHeaderMatchType specifies how header matching criteria should be applied to a request.

const (
	HTTPHeaderMatchExact             HTTPHeaderMatchType = "exact"
	HTTPHeaderMatchPrefix            HTTPHeaderMatchType = "prefix"
	HTTPHeaderMatchPresent           HTTPHeaderMatchType = "present"
	HTTPHeaderMatchRegularExpression HTTPHeaderMatchType = "regex"
	HTTPHeaderMatchSuffix            HTTPHeaderMatchType = "suffix"
)

type HTTPHeaderModifiers added in v1.12.0

type HTTPHeaderModifiers struct {
	// Add is a set of name -> value pairs that should be appended to the request
	// or response (i.e. allowing duplicates if the same header already exists).
	Add map[string]string `json:",omitempty"`

	// Set is a set of name -> value pairs that should be added to the request or
	// response, overwriting any existing header values of the same name.
	Set map[string]string `json:",omitempty"`

	// Remove is the set of header names that should be stripped from the request
	// or response.
	Remove []string `json:",omitempty"`
}

HTTPHeaderModifiers is a set of rules for HTTP header modification that should be performed by proxies as the request passes through them. It can operate on either request or response headers depending on the context in which it is used.

type HTTPMatch added in v1.19.0

type HTTPMatch struct {
	Headers []HTTPHeaderMatch
	Method  HTTPMatchMethod
	Path    HTTPPathMatch
	Query   []HTTPQueryMatch
}

HTTPMatch specifies the criteria that should be used in determining whether or not a request should be routed to a given set of services.

type HTTPMatchMethod added in v1.19.0

type HTTPMatchMethod string

HTTPMatchMethod specifies which type of HTTP verb should be used for matching a given request.

const (
	HTTPMatchMethodAll     HTTPMatchMethod = ""
	HTTPMatchMethodConnect HTTPMatchMethod = "CONNECT"
	HTTPMatchMethodDelete  HTTPMatchMethod = "DELETE"
	HTTPMatchMethodGet     HTTPMatchMethod = "GET"
	HTTPMatchMethodHead    HTTPMatchMethod = "HEAD"
	HTTPMatchMethodOptions HTTPMatchMethod = "OPTIONS"
	HTTPMatchMethodPatch   HTTPMatchMethod = "PATCH"
	HTTPMatchMethodPost    HTTPMatchMethod = "POST"
	HTTPMatchMethodPut     HTTPMatchMethod = "PUT"
	HTTPMatchMethodTrace   HTTPMatchMethod = "TRACE"
)

type HTTPPathMatch added in v1.19.0

type HTTPPathMatch struct {
	Match HTTPPathMatchType
	Value string
}

HTTPPathMatch specifies how a match should be done on a request's path.

type HTTPPathMatchType added in v1.19.0

type HTTPPathMatchType string

HTTPPathMatchType specifies how path matching criteria should be applied to a request.

const (
	HTTPPathMatchExact             HTTPPathMatchType = "exact"
	HTTPPathMatchPrefix            HTTPPathMatchType = "prefix"
	HTTPPathMatchRegularExpression HTTPPathMatchType = "regex"
)

type HTTPQueryMatch added in v1.19.0

type HTTPQueryMatch struct {
	Match HTTPQueryMatchType
	Name  string
	Value string
}

HTTPQueryMatch specifies how a match should be done on a request's query parameters.

type HTTPQueryMatchType added in v1.19.0

type HTTPQueryMatchType string

HTTPQueryMatchType specifies how querys matching criteria should be applied to a request.

const (
	HTTPQueryMatchExact             HTTPQueryMatchType = "exact"
	HTTPQueryMatchPresent           HTTPQueryMatchType = "present"
	HTTPQueryMatchRegularExpression HTTPQueryMatchType = "regex"
)

type HTTPResponseFilters added in v1.26.1

type HTTPResponseFilters struct {
	Headers []HTTPHeaderFilter
}

HTTPResponseFilters specifies a list of filters used to modify a response returned by an upstream

type HTTPRouteConfigEntry added in v1.19.0

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

	// Name is used to match the config entry with its associated http-route.
	Name string

	// Parents is a list of gateways that this route should be bound to
	Parents []ResourceReference
	// Rules are a list of HTTP-based routing rules that this route should
	// use for constructing a routing table.
	Rules []HTTPRouteRule
	// Hostnames are the hostnames for which this HTTPRoute should respond to requests.
	Hostnames []string

	Meta map[string]string `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

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

	// Status is the asynchronous status which an HTTPRoute propagates to the user.
	Status ConfigEntryStatus
}

HTTPRouteConfigEntry manages the configuration for a HTTP route with the given name.

func (*HTTPRouteConfigEntry) GetCreateIndex added in v1.19.0

func (r *HTTPRouteConfigEntry) GetCreateIndex() uint64

func (*HTTPRouteConfigEntry) GetKind added in v1.19.0

func (r *HTTPRouteConfigEntry) GetKind() string

func (*HTTPRouteConfigEntry) GetMeta added in v1.19.0

func (r *HTTPRouteConfigEntry) GetMeta() map[string]string

func (*HTTPRouteConfigEntry) GetModifyIndex added in v1.19.0

func (r *HTTPRouteConfigEntry) GetModifyIndex() uint64

func (*HTTPRouteConfigEntry) GetName added in v1.19.0

func (r *HTTPRouteConfigEntry) GetName() string

func (*HTTPRouteConfigEntry) GetNamespace added in v1.19.0

func (r *HTTPRouteConfigEntry) GetNamespace() string

func (*HTTPRouteConfigEntry) GetPartition added in v1.19.0

func (r *HTTPRouteConfigEntry) GetPartition() string

type HTTPRouteRule added in v1.19.0

type HTTPRouteRule struct {
	// Filters is a list of HTTP-based filters used to modify a request prior
	// to routing it to the upstream service
	Filters HTTPFilters
	// ResponseFilters is a list of HTTP-based filters used to modify a response
	// returned by the upstream service
	ResponseFilters HTTPResponseFilters
	// Matches specified the matching criteria used in the routing table. If a
	// request matches the given HTTPMatch configuration, then traffic is routed
	// to services specified in the Services field.
	Matches []HTTPMatch
	// Services is a list of HTTP-based services to route to if the request matches
	// the rules specified in the Matches field.
	Services []HTTPService
}

HTTPRouteRule specifies the routing rules used to determine what upstream service an HTTP request is routed to.

type HTTPService added in v1.19.0

type HTTPService struct {
	Name string
	// Weight is an arbitrary integer used in calculating how much
	// traffic should be sent to the given service.
	Weight int

	// Filters is a list of HTTP-based filters used to modify a request prior
	// to routing it to the upstream service
	Filters HTTPFilters

	// ResponseFilters is a list of HTTP-based filters used to modify the
	// response returned from the upstream service
	ResponseFilters HTTPResponseFilters

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

HTTPService is a service reference for HTTP-based routing rules

type HashPolicy added in v1.8.0

type HashPolicy struct {
	// Field is the attribute type to hash on.
	// Must be one of "header","cookie", or "query_parameter".
	// Cannot be specified along with SourceIP.
	Field string `json:",omitempty"`

	// FieldValue is the value to hash.
	// ie. header name, cookie name, URL query parameter name
	// Cannot be specified along with SourceIP.
	FieldValue string `json:",omitempty" alias:"field_value"`

	// CookieConfig contains configuration for the "cookie" hash policy type.
	CookieConfig *CookieConfig `json:",omitempty" alias:"cookie_config"`

	// SourceIP determines whether the hash should be of the source IP rather than of a field and field value.
	// Cannot be specified along with Field or FieldValue.
	SourceIP bool `json:",omitempty" alias:"source_ip"`

	// Terminal will short circuit the computation of the hash when multiple hash policies are present.
	// If a hash is computed when a Terminal policy is evaluated,
	// then that hash will be used and subsequent hash policies will be ignored.
	Terminal bool `json:",omitempty"`
}

HashPolicy defines which attributes will be hashed by hash-based LB algorithms

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

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"`
	Partition   string `json:",omitempty"`
	ExposedPort int
	PeerName    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
	TLSServerName                          string
	TLSSkipVerify                          bool
	TCP                                    string
	TCPUseTLS                              bool
	UDP                                    string
	GRPC                                   string
	OSService                              string
	GRPCUseTLS                             bool
	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 added in v1.5.0

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

	// Partition is the partition the IngressGateway is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

	Meta map[string]string `json:",omitempty"`

	// Defaults is default configuration for all upstream services
	Defaults *IngressServiceConfig `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
}

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

func (*IngressGatewayConfigEntry) GetCreateIndex added in v1.5.0

func (i *IngressGatewayConfigEntry) GetCreateIndex() uint64

func (*IngressGatewayConfigEntry) GetKind added in v1.5.0

func (i *IngressGatewayConfigEntry) GetKind() string

func (*IngressGatewayConfigEntry) GetMeta added in v1.8.0

func (i *IngressGatewayConfigEntry) GetMeta() map[string]string

func (*IngressGatewayConfigEntry) GetModifyIndex added in v1.5.0

func (i *IngressGatewayConfigEntry) GetModifyIndex() uint64

func (*IngressGatewayConfigEntry) GetName added in v1.5.0

func (i *IngressGatewayConfigEntry) GetName() string

func (*IngressGatewayConfigEntry) GetNamespace added in v1.8.0

func (i *IngressGatewayConfigEntry) GetNamespace() string

func (*IngressGatewayConfigEntry) GetPartition added in v1.12.0

func (i *IngressGatewayConfigEntry) GetPartition() string

type IngressListener added in v1.5.0

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

	// TLS allows specifying some TLS configuration per listener.
	TLS *GatewayTLSConfig `json:",omitempty"`
}

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

type IngressService added in v1.5.0

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

	// Partition is the partition where the service is located.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// TLS allows specifying some TLS configuration per listener.
	TLS *GatewayServiceTLSConfig `json:",omitempty"`

	// Allow HTTP header manipulation to be configured.
	RequestHeaders  *HTTPHeaderModifiers `json:",omitempty" alias:"request_headers"`
	ResponseHeaders *HTTPHeaderModifiers `json:",omitempty" alias:"response_headers"`

	MaxConnections        *uint32 `json:",omitempty" alias:"max_connections"`
	MaxPendingRequests    *uint32 `json:",omitempty" alias:"max_pending_requests"`
	MaxConcurrentRequests *uint32 `json:",omitempty" alias:"max_concurrent_requests"`

	// PassiveHealthCheck configuration determines how upstream proxy instances will
	// be monitored for removal from the load balancing pool.
	PassiveHealthCheck *PassiveHealthCheck `json:",omitempty" alias:"passive_health_check"`
}

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

type IngressServiceConfig added in v1.15.3

type IngressServiceConfig struct {
	MaxConnections        *uint32
	MaxPendingRequests    *uint32
	MaxConcurrentRequests *uint32

	// PassiveHealthCheck configuration determines how upstream proxy instances will
	// be monitored for removal from the load balancing pool.
	PassiveHealthCheck *PassiveHealthCheck `json:",omitempty" alias:"passive_health_check"`
}

type InlineCertificateConfigEntry added in v1.19.0

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

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

	// Certificate is the public certificate component of an x509 key pair encoded in raw PEM format.
	Certificate string
	// PrivateKey is the private key component of an x509 key pair encoded in raw PEM format.
	PrivateKey string `alias:"private_key"`

	Meta map[string]string `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

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

InlineCertificateConfigEntry -- TODO stub

func (*InlineCertificateConfigEntry) GetCreateIndex added in v1.19.0

func (a *InlineCertificateConfigEntry) GetCreateIndex() uint64

func (*InlineCertificateConfigEntry) GetKind added in v1.19.0

func (a *InlineCertificateConfigEntry) GetKind() string

func (*InlineCertificateConfigEntry) GetMeta added in v1.19.0

func (a *InlineCertificateConfigEntry) GetMeta() map[string]string

func (*InlineCertificateConfigEntry) GetModifyIndex added in v1.19.0

func (a *InlineCertificateConfigEntry) GetModifyIndex() uint64

func (*InlineCertificateConfigEntry) GetName added in v1.19.0

func (a *InlineCertificateConfigEntry) GetName() string

func (*InlineCertificateConfigEntry) GetNamespace added in v1.19.0

func (a *InlineCertificateConfigEntry) GetNamespace() string

func (*InlineCertificateConfigEntry) GetPartition added in v1.19.0

func (a *InlineCertificateConfigEntry) GetPartition() string

type InstanceLevelRateLimits added in v1.26.1

type InstanceLevelRateLimits struct {
	// RequestsPerSecond is the average number of requests per second that can be
	// made without being throttled. This field is required if RequestsMaxBurst
	// is set. The allowed number of requests may exceed RequestsPerSecond up to
	// the value specified in RequestsMaxBurst.
	//
	// Internally, this is the refill rate of the token bucket used for rate limiting.
	RequestsPerSecond int `alias:"requests_per_second"`

	// RequestsMaxBurst is the maximum number of requests that can be sent
	// in a burst. Should be equal to or greater than RequestsPerSecond.
	// If unset, defaults to RequestsPerSecond.
	//
	// Internally, this is the maximum size of the token bucket used for rate limiting.
	RequestsMaxBurst int `alias:"requests_max_burst"`

	// Routes is a list of rate limits applied to specific routes.
	// For a given request, the first matching route will be applied, if any
	// Overrides any top-level configuration.
	Routes []InstanceLevelRouteRateLimits
}

InstanceLevelRateLimits represents rate limit configuration that are applied per service instance.

type InstanceLevelRouteRateLimits added in v1.26.1

type InstanceLevelRouteRateLimits struct {
	PathExact  string `alias:"path_exact"`
	PathPrefix string `alias:"path_prefix"`
	PathRegex  string `alias:"path_regex"`

	RequestsPerSecond int `alias:"requests_per_second"`
	RequestsMaxBurst  int `alias:"requests_max_burst"`
}

InstanceLevelRouteRateLimits represents rate limit configuration applied to a route matching one of PathExact/PathPrefix/PathRegex.

type Intention

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

	// 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 `json:",omitempty"`

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

	// SourcePartition and DestinationPartition cannot be wildcards "*" and
	// are not compatible with legacy intentions.
	SourcePartition      string `json:",omitempty"`
	DestinationPartition string `json:",omitempty"`

	// SourcePeer cannot be a wildcard "*" and is not compatible with legacy
	// intentions. Cannot be used with SourcePartition, as both represent the
	// same level of tenancy (partition is local to cluster, peer is remote).
	SourcePeer string `json:",omitempty"`

	// SourceSamenessGroup cannot be wildcards "*" and
	// is not compatible with legacy intentions.
	SourceSamenessGroup string `json:",omitempty"`

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

	// Action is whether this is an allowlist or denylist intention.
	Action IntentionAction `json:",omitempty"`

	// Permissions is the list of additional L7 attributes that extend the
	// intention definition.
	//
	// NOTE: This field is not editable unless editing the underlying
	// service-intentions config entry directly.
	Permissions []*IntentionPermission `json:",omitempty"`

	// DefaultAddr is not used.
	// Deprecated: DefaultAddr is not used and may be removed in a future version.
	DefaultAddr string `json:",omitempty"`
	// DefaultPort is not used.
	// Deprecated: DefaultPort is not used and may be removed in a future version.
	DefaultPort int `json:",omitempty"`

	// Meta is arbitrary metadata associated with the intention. This is
	// opaque to Consul but is served in API responses.
	Meta map[string]string `json:",omitempty"`

	// 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 `json:",omitempty"`

	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 IntentionHTTPHeaderPermission added in v1.8.0

type IntentionHTTPHeaderPermission struct {
	Name       string
	Present    bool   `json:",omitempty"`
	Exact      string `json:",omitempty"`
	Prefix     string `json:",omitempty"`
	Suffix     string `json:",omitempty"`
	Contains   string `json:",omitempty"`
	Regex      string `json:",omitempty"`
	Invert     bool   `json:",omitempty"`
	IgnoreCase bool   `json:",omitempty" alias:"ignore_case"`
}

type IntentionHTTPPermission added in v1.8.0

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

	Header []IntentionHTTPHeaderPermission `json:",omitempty"`

	Methods []string `json:",omitempty"`
}

type IntentionJWTClaimVerification added in v1.22.0

type IntentionJWTClaimVerification struct {
	// Path is the path to the claim in the token JSON.
	Path []string `json:",omitempty"`

	// Value is the expected value at the given path:
	// - If the type at the path is a list then we verify
	//   that this value is contained in the list.
	//
	// - If the type at the path is a string then we verify
	//   that this value matches.
	Value string `json:",omitempty"`
}

type IntentionJWTProvider added in v1.22.0

type IntentionJWTProvider struct {
	// Name is the name of the JWT provider. There MUST be a corresponding
	// "jwt-provider" config entry with this name.
	Name string `json:",omitempty"`

	// VerifyClaims is a list of additional claims to verify in a JWT's payload.
	VerifyClaims []*IntentionJWTClaimVerification `json:",omitempty" alias:"verify_claims"`
}

type IntentionJWTRequirement added in v1.22.0

type IntentionJWTRequirement struct {
	// Providers is a list of providers to consider when verifying a JWT.
	Providers []*IntentionJWTProvider `json:",omitempty"`
}

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 IntentionPermission added in v1.8.0

type IntentionPermission struct {
	Action IntentionAction
	HTTP   *IntentionHTTPPermission `json:",omitempty"`
	JWT    *IntentionJWTRequirement `json:",omitempty"`
}

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 Internal added in v1.22.0

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

Internal can be used to query endpoints that are intended for Hashicorp internal-use only.

func (*Internal) AssignServiceVirtualIP added in v1.22.0

func (i *Internal) AssignServiceVirtualIP(
	ctx context.Context,
	service string,
	manualVIPs []string,
	wo *WriteOptions,
) (*AssignServiceManualVIPsResponse, *QueryMeta, error)

type JSONWebKeySet added in v1.22.0

type JSONWebKeySet struct {
	// Local specifies a local source for the key set.
	Local *LocalJWKS `json:",omitempty"`

	// Remote specifies how to fetch a key set from a remote server.
	Remote *RemoteJWKS `json:",omitempty"`
}

JSONWebKeySet defines a key set, its location on disk, or the means with which to fetch a key set from a remote server.

Exactly one of Local or Remote must be specified.

type JWKSCluster added in v1.23.0

type JWKSCluster struct {
	// DiscoveryType refers to the service discovery type to use for resolving the cluster.
	//
	// This defaults to STRICT_DNS.
	// Other options include STATIC, LOGICAL_DNS, EDS or ORIGINAL_DST.
	DiscoveryType ClusterDiscoveryType `json:",omitempty" alias:"discovery_type"`

	// TLSCertificates refers to the data containing certificate authority certificates to use
	// in verifying a presented peer certificate.
	// If not specified and a peer certificate is presented it will not be verified.
	//
	// Must be either CaCertificateProviderInstance or TrustedCA.
	TLSCertificates *JWKSTLSCertificate `json:",omitempty" alias:"tls_certificates"`

	// The timeout for new network connections to hosts in the cluster.
	// If not set, a default value of 5s will be used.
	ConnectTimeout time.Duration `json:",omitempty" alias:"connect_timeout"`
}

type JWKSRetryPolicy added in v1.22.0

type JWKSRetryPolicy struct {
	// NumRetries is the number of times to retry fetching the JWKS.
	// The retry strategy uses jittered exponential backoff with
	// a base interval of 1s and max of 10s.
	//
	// Default value is 0.
	NumRetries int `json:",omitempty" alias:"num_retries"`

	// Backoff policy
	//
	// Defaults to Envoy's backoff policy
	RetryPolicyBackOff *RetryPolicyBackOff `json:",omitempty" alias:"retry_policy_back_off"`
}

type JWKSTLSCertProviderInstance added in v1.23.0

type JWKSTLSCertProviderInstance struct {
	// InstanceName refers to the certificate provider instance name
	//
	// The default value is "default".
	InstanceName string `json:",omitempty" alias:"instance_name"`

	// CertificateName is used to specify certificate instances or types. For example, "ROOTCA" to specify
	// a root-certificate (validation context) or "example.com" to specify a certificate for a
	// particular domain.
	//
	// The default value is the empty string.
	CertificateName string `json:",omitempty" alias:"certificate_name"`
}

type JWKSTLSCertTrustedCA added in v1.23.0

type JWKSTLSCertTrustedCA struct {
	Filename            string `json:",omitempty" alias:"filename"`
	EnvironmentVariable string `json:",omitempty" alias:"environment_variable"`
	InlineString        string `json:",omitempty" alias:"inline_string"`
	InlineBytes         []byte `json:",omitempty" alias:"inline_bytes"`
}

JWKSTLSCertTrustedCA defines TLS certificate data containing certificate authority certificates to use in verifying a presented peer certificate.

Exactly one of Filename, EnvironmentVariable, InlineString or InlineBytes must be specified.

type JWKSTLSCertificate added in v1.23.0

type JWKSTLSCertificate struct {
	// CaCertificateProviderInstance Certificate provider instance for fetching TLS certificates.
	CaCertificateProviderInstance *JWKSTLSCertProviderInstance `json:",omitempty" alias:"ca_certificate_provider_instance"`

	// TrustedCA defines TLS certificate data containing certificate authority certificates
	// to use in verifying a presented peer certificate.
	//
	// Exactly one of Filename, EnvironmentVariable, InlineString or InlineBytes must be specified.
	TrustedCA *JWKSTLSCertTrustedCA `json:",omitempty" alias:"trusted_ca"`
}

JWKSTLSCertificate refers to the data containing certificate authority certificates to use in verifying a presented peer certificate. If not specified and a peer certificate is presented it will not be verified.

Must be either CaCertificateProviderInstance or TrustedCA.

type JWTCacheConfig added in v1.22.0

type JWTCacheConfig struct {
	// Size specifies the maximum number of JWT verification
	// results to cache.
	//
	// Defaults to 0, meaning that JWT caching is disabled.
	Size int `json:",omitempty"`
}

type JWTFilter added in v1.26.1

type JWTFilter struct {
	Providers []*APIGatewayJWTProvider `json:",omitempty"`
}

JWTFilter specifies the JWT configuration for a route

type JWTForwardingConfig added in v1.22.0

type JWTForwardingConfig struct {
	// HeaderName is a header name to use when forwarding a verified
	// JWT to the backend. The verified JWT could have been extracted
	// from any location (query param, header, or cookie).
	//
	// The header value will be base64-URL-encoded, and will not be
	// padded unless PadForwardPayloadHeader is true.
	HeaderName string `json:",omitempty" alias:"header_name"`

	// PadForwardPayloadHeader determines whether padding should be added
	// to the base64 encoded token forwarded with ForwardPayloadHeader.
	//
	// Default value is false.
	PadForwardPayloadHeader bool `json:",omitempty" alias:"pad_forward_payload_header"`
}

type JWTLocation added in v1.22.0

type JWTLocation struct {
	// Header defines how to extract a JWT from an HTTP request header.
	Header *JWTLocationHeader `json:",omitempty"`

	// QueryParam defines how to extract a JWT from an HTTP request
	// query parameter.
	QueryParam *JWTLocationQueryParam `json:",omitempty" alias:"query_param"`

	// Cookie defines how to extract a JWT from an HTTP request cookie.
	Cookie *JWTLocationCookie `json:",omitempty"`
}

JWTLocation is a location where the JWT could be present in requests.

Only one of Header, QueryParam, or Cookie can be specified.

type JWTLocationCookie added in v1.22.0

type JWTLocationCookie struct {
	// Name is the name of the cookie containing the token.
	Name string `json:",omitempty"`
}

JWTLocationCookie defines how to extract a JWT from an HTTP request cookie.

type JWTLocationHeader added in v1.22.0

type JWTLocationHeader struct {
	// Name is the name of the header containing the token.
	Name string `json:",omitempty"`

	// ValuePrefix is an optional prefix that precedes the token in the
	// header value.
	// For example, "Bearer " is a standard value prefix for a header named
	// "Authorization", but the prefix is not part of the token itself:
	// "Authorization: Bearer <token>"
	ValuePrefix string `json:",omitempty" alias:"value_prefix"`

	// Forward defines whether the header with the JWT should be
	// forwarded after the token has been verified. If false, the
	// header will not be forwarded to the backend.
	//
	// Default value is false.
	Forward bool `json:",omitempty"`
}

JWTLocationHeader defines how to extract a JWT from an HTTP request header.

type JWTLocationQueryParam added in v1.22.0

type JWTLocationQueryParam struct {
	// Name is the name of the query param containing the token.
	Name string `json:",omitempty"`
}

JWTLocationQueryParam defines how to extract a JWT from an HTTP request query parameter.

type JWTProviderConfigEntry added in v1.22.0

type JWTProviderConfigEntry struct {
	// Kind is the kind of configuration entry and must be "jwt-provider".
	Kind string `json:",omitempty"`

	// Name is the name of the provider being configured.
	Name string `json:",omitempty"`

	// JSONWebKeySet defines a JSON Web Key Set, its location on disk, or the
	// means with which to fetch a key set from a remote server.
	JSONWebKeySet *JSONWebKeySet `json:",omitempty" alias:"json_web_key_set"`

	// Issuer is the entity that must have issued the JWT.
	// This value must match the "iss" claim of the token.
	Issuer string `json:",omitempty"`

	// Audiences is the set of audiences the JWT is allowed to access.
	// If specified, all JWTs verified with this provider must address
	// at least one of these to be considered valid.
	Audiences []string `json:",omitempty"`

	// Locations where the JWT will be present in requests.
	// Envoy will check all of these locations to extract a JWT.
	// If no locations are specified Envoy will default to:
	// 1. Authorization header with Bearer schema:
	//    "Authorization: Bearer <token>"
	// 2. access_token query parameter.
	Locations []*JWTLocation `json:",omitempty"`

	// Forwarding defines rules for forwarding verified JWTs to the backend.
	Forwarding *JWTForwardingConfig `json:",omitempty"`

	// ClockSkewSeconds specifies the maximum allowable time difference
	// from clock skew when validating the "exp" (Expiration) and "nbf"
	// (Not Before) claims.
	//
	// Default value is 30 seconds.
	ClockSkewSeconds int `json:",omitempty" alias:"clock_skew_seconds"`

	// CacheConfig defines configuration for caching the validation
	// result for previously seen JWTs. Caching results can speed up
	// verification when individual tokens are expected to be handled
	// multiple times.
	CacheConfig *JWTCacheConfig `json:",omitempty" alias:"cache_config"`

	Meta map[string]string `json:",omitempty"`

	// CreateIndex is the Raft index this entry was created at. This is a
	// read-only field.
	CreateIndex uint64 `json:",omitempty"`

	// 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 `json:",omitempty"`

	// Partition is the partition the JWTProviderConfigEntry applies to.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// Namespace is the namespace the JWTProviderConfigEntry applies to.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`
}

func (*JWTProviderConfigEntry) GetCreateIndex added in v1.22.0

func (e *JWTProviderConfigEntry) GetCreateIndex() uint64

func (*JWTProviderConfigEntry) GetKind added in v1.22.0

func (e *JWTProviderConfigEntry) GetKind() string

func (*JWTProviderConfigEntry) GetMeta added in v1.22.0

func (e *JWTProviderConfigEntry) GetMeta() map[string]string

func (*JWTProviderConfigEntry) GetModifyIndex added in v1.22.0

func (e *JWTProviderConfigEntry) GetModifyIndex() uint64

func (*JWTProviderConfigEntry) GetName added in v1.22.0

func (e *JWTProviderConfigEntry) GetName() string

func (*JWTProviderConfigEntry) GetNamespace added in v1.22.0

func (e *JWTProviderConfigEntry) GetNamespace() string

func (*JWTProviderConfigEntry) GetPartition added in v1.22.0

func (e *JWTProviderConfigEntry) GetPartition() string

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"
	KVGetOrEmpty     KVOp = "get-or-empty"
	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"`

	// Partition is the partition the KVPair is associated with
	// Admin Partition is a Consul Enterprise feature.
	Partition 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"`
	Partition 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

	// Partition has the admin partition this request corresponds to.
	Partition string `json:",omitempty"`

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

	// A map of the encryption primary keys to the number of nodes they're installed on
	PrimaryKeys map[string]int

	// The total number of nodes in this ring
	NumNodes int
}

KeyringResponse is returned when listing the gossip encryption keys

type KubernetesAuthMethodConfig added in v1.1.0

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

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

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

func (*KubernetesAuthMethodConfig) RenderToConfig added in v1.1.0

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 LeastRequestConfig added in v1.8.0

type LeastRequestConfig struct {
	// ChoiceCount determines the number of random healthy hosts from which to select the one with the least requests.
	ChoiceCount uint32 `json:",omitempty" alias:"choice_count"`
}

LeastRequestConfig contains configuration for the "least_request" policy type

type License added in v1.2.0

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

	// Whether the license will ignore termination
	IgnoreTermination bool `json:"ignore_termination"`

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

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

type LinkedService added in v1.5.0

type LinkedService struct {

	//DisableAutoHostRewrite disables terminating gateways auto host rewrite feature when set to true.
	DisableAutoHostRewrite bool `json:",omitempty"`

	// Namespace is where the service is registered.
	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 LoadBalancer added in v1.8.0

type LoadBalancer struct {
	// Policy is the load balancing policy used to select a host
	Policy string `json:",omitempty"`

	// RingHashConfig contains configuration for the "ring_hash" policy type
	RingHashConfig *RingHashConfig `json:",omitempty" alias:"ring_hash_config"`

	// LeastRequestConfig contains configuration for the "least_request" policy type
	LeastRequestConfig *LeastRequestConfig `json:",omitempty" alias:"least_request_config"`

	// HashPolicies is a list of hash policies to use for hashing load balancing algorithms.
	// Hash policies are evaluated individually and combined such that identical lists
	// result in the same hash.
	// If no hash policies are present, or none are successfully evaluated,
	// then a random backend host will be selected.
	HashPolicies []HashPolicy `json:",omitempty" alias:"hash_policies"`
}

LoadBalancer determines the load balancing policy and configuration for services issuing requests to this upstream service.

type LocalJWKS added in v1.22.0

type LocalJWKS struct {
	// JWKS contains a base64 encoded JWKS.
	JWKS string `json:",omitempty"`

	// Filename configures a location on disk where the JWKS can be
	// found. If specified, the file must be present on the disk of ALL
	// proxies with intentions referencing this provider.
	Filename string `json:",omitempty"`
}

LocalJWKS specifies a location for a local JWKS.

Only one of String and Filename can be specified.

type Locality added in v1.22.0

type Locality struct {
	// Region is region the zone belongs to.
	Region string

	// Zone is the zone the entity is running in.
	Zone string
}

Locality identifies where a given entity is running.

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
	LockDelay        time.Duration // Optional, defaults to 15s
	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 LogSinkType added in v1.19.0

type LogSinkType string
const (
	DefaultLogSinkType LogSinkType = ""
	FileLogSinkType    LogSinkType = "file"
	StdErrLogSinkType  LogSinkType = "stderr"
	StdOutLogSinkType  LogSinkType = "stdout"
)

type MemberACLMode added in v1.7.0

type MemberACLMode string
const (
	// ACLModeDisables indicates that ACLs are disabled for this agent
	ACLModeDisabled MemberACLMode = "0"
	// ACLModeEnabled indicates that ACLs are enabled and operating in new ACL
	// mode (v1.4.0+ ACLs)
	ACLModeEnabled MemberACLMode = "1"
	// ACLModeLegacy has been deprecated, and will be treated as ACLModeUnknown.
	ACLModeLegacy MemberACLMode = "2" // DEPRECATED
	// ACLModeUnkown is used to indicate that the AgentMember.Tags didn't advertise
	// an ACL mode at all. This is the case for Consul versions before v1.4.0 and
	// should be treated the same as ACLModeLegacy.
	ACLModeUnknown MemberACLMode = "3"
)

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

	Filter string
}

MembersOpts is used for querying member information.

type MeshConfigEntry added in v1.9.0

type MeshConfigEntry struct {
	// Partition is the partition the MeshConfigEntry applies to.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// Namespace is the namespace the MeshConfigEntry applies to.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `json:",omitempty"`

	// TransparentProxy applies configuration specific to proxies
	// in transparent mode.
	TransparentProxy TransparentProxyMeshConfig `alias:"transparent_proxy"`

	// AllowEnablingPermissiveMutualTLS must be true in order to allow setting
	// MutualTLSMode=permissive in either service-defaults or proxy-defaults.
	AllowEnablingPermissiveMutualTLS bool `json:",omitempty" alias:"allow_enabling_permissive_mutual_tls"`

	// ValidateClusters controls whether the clusters the route table refers to are validated. The default value is
	// false. When set to false and a route refers to a cluster that does not exist, the route table loads and routing
	// to a non-existent cluster results in a 404. When set to true and the route is set to a cluster that do not exist,
	// the route table will not load. For more information, refer to
	// [HTTP route configuration in the Envoy docs](https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route.proto#envoy-v3-api-field-config-route-v3-routeconfiguration-validate-clusters)
	// for more details.
	ValidateClusters bool `json:",omitempty" alias:"validate_clusters"`

	TLS *MeshTLSConfig `json:",omitempty"`

	HTTP *MeshHTTPConfig `json:",omitempty"`

	Peering *PeeringMeshConfig `json:",omitempty"`

	Meta map[string]string `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
}

MeshConfigEntry manages the global configuration for all service mesh proxies.

func (*MeshConfigEntry) GetCreateIndex added in v1.9.0

func (e *MeshConfigEntry) GetCreateIndex() uint64

func (*MeshConfigEntry) GetKind added in v1.9.0

func (e *MeshConfigEntry) GetKind() string

func (*MeshConfigEntry) GetMeta added in v1.9.0

func (e *MeshConfigEntry) GetMeta() map[string]string

func (*MeshConfigEntry) GetModifyIndex added in v1.9.0

func (e *MeshConfigEntry) GetModifyIndex() uint64

func (*MeshConfigEntry) GetName added in v1.9.0

func (e *MeshConfigEntry) GetName() string

func (*MeshConfigEntry) GetNamespace added in v1.9.0

func (e *MeshConfigEntry) GetNamespace() string

func (*MeshConfigEntry) GetPartition added in v1.12.0

func (e *MeshConfigEntry) GetPartition() string

func (*MeshConfigEntry) MarshalJSON added in v1.9.0

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

MarshalJSON adds the Kind field so that the JSON can be decoded back into the correct type.

type MeshDirectionalHTTPConfig added in v1.28.5

type MeshDirectionalHTTPConfig struct {
	RequestNormalization *RequestNormalizationMeshConfig `json:",omitempty" alias:"request_normalization"`
}

MeshDirectionalHTTPConfig holds mesh configuration specific to HTTP requests for a given traffic direction.

type MeshDirectionalTLSConfig added in v1.13.0

type MeshDirectionalTLSConfig struct {
	TLSMinVersion string   `json:",omitempty" alias:"tls_min_version"`
	TLSMaxVersion string   `json:",omitempty" alias:"tls_max_version"`
	CipherSuites  []string `json:",omitempty" alias:"cipher_suites"`
}

type MeshGatewayConfig added in v1.2.0

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

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 Upstream Connect connections
	// should be made to a mesh gateway in the local datacenter.
	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 MeshHTTPConfig added in v1.13.0

type MeshHTTPConfig struct {
	SanitizeXForwardedClientCert bool `alias:"sanitize_x_forwarded_client_cert"`
	// Incoming configures settings for incoming HTTP traffic to mesh proxies.
	Incoming *MeshDirectionalHTTPConfig `json:",omitempty"`
}

type MeshTLSConfig added in v1.13.0

type MeshTLSConfig struct {
	Incoming *MeshDirectionalTLSConfig `json:",omitempty"`
	Outgoing *MeshDirectionalTLSConfig `json:",omitempty"`
}

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 MutualTLSMode added in v1.22.0

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

	// MutualTLSModeStrict requires mTLS for incoming traffic.
	MutualTLSModeStrict MutualTLSMode = "strict"

	// MutualTLSModePermissive allows incoming non-mTLS traffic.
	MutualTLSModePermissive MutualTLSMode = "permissive"
)

type Namespace added in v1.4.0

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" alias:"deleted_at"`

	// Partition which contains the Namespace.
	Partition string `json:"Partition,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.

func (*Namespace) UnmarshalJSON added in v1.13.0

func (n *Namespace) UnmarshalJSON(data []byte) error

type NamespaceACLConfig added in v1.4.0

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" alias:"policy_defaults"`
	// 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" alias:"role_defaults"`
}

NamespaceACLConfig is the Namespace specific ACL configuration container

func (*NamespaceACLConfig) UnmarshalJSON added in v1.13.0

func (n *NamespaceACLConfig) UnmarshalJSON(data []byte) error

type Namespaces added in v1.4.0

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

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

func (*Namespaces) Create added in v1.4.0

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

func (*Namespaces) Delete added in v1.4.0

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

func (*Namespaces) List added in v1.4.0

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

func (*Namespaces) Read added in v1.4.0

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

func (*Namespaces) Update added in v1.4.0

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
	Partition       string    `json:",omitempty"`
	PeerName        string    `json:",omitempty"`
	Locality        *Locality `json:",omitempty"`
}

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

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"`
	OIDCACRValues       []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 added in v1.5.0

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) AuditHash added in v1.25.1

func (op *Operator) AuditHash(a *AuditHashRequest, q *QueryOptions) (*AuditHashResponse, error)

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) AutopilotState added in v1.8.0

func (op *Operator) AutopilotState(q *QueryOptions) (*AutopilotState, error)

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

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

func (*Operator) LicenseGetSigned added in v1.2.0

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

func (*Operator) LicensePut added in v1.2.0

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

LicensePut will configure the Consul Enterprise license for the target datacenter

DEPRECATED: Consul 1.10 removes the corresponding HTTP endpoint as licenses are now set via agent configuration instead of through the API

func (*Operator) LicenseReset added in v1.2.0

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.

DEPRECATED: Consul 1.10 removes the corresponding HTTP endpoint as licenses are now set via agent configuration instead of through the API

func (*Operator) RaftGetConfiguration

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

RaftGetConfiguration is used to query the current Raft peer set.

func (*Operator) RaftLeaderTransfer added in v1.19.0

func (op *Operator) RaftLeaderTransfer(id string, q *QueryOptions) (*TransferLeaderResponse, error)

RaftLeaderTransfer is used to transfer the current raft leader to another node Optionally accepts a non-empty id of another node to transfer leadership to.

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.

func (*Operator) Usage added in v1.19.0

func (op *Operator) Usage(q *QueryOptions) (*Usage, *QueryMeta, error)

Usage is used to query for usage information in the given datacenter.

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 Partition added in v1.12.0

type Partition struct {
	// Name is the name of the Partition.
	Name string `json:"Name"`

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

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

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

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

	// DisableGossip will not enable a gossip pool for the partition
	DisableGossip bool `json:"DisableGossip,omitempty"`
}

Partition is the configuration of a single admin partition. Admin Partitions are a Consul Enterprise feature.

type Partitions added in v1.10.0

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

Partitions can be used to manage Partitions in Consul Enterprise.

func (*Partitions) Create added in v1.10.0

func (p *Partitions) Create(ctx context.Context, partition *Partition, q *WriteOptions) (*Partition, *WriteMeta, error)

func (*Partitions) Delete added in v1.10.0

func (p *Partitions) Delete(ctx context.Context, name string, q *WriteOptions) (*WriteMeta, error)

func (*Partitions) List added in v1.10.0

func (p *Partitions) List(ctx context.Context, q *QueryOptions) ([]*Partition, *QueryMeta, error)

func (*Partitions) Read added in v1.10.0

func (p *Partitions) Read(ctx context.Context, name string, q *QueryOptions) (*Partition, *QueryMeta, error)

func (*Partitions) Update added in v1.10.0

func (p *Partitions) Update(ctx context.Context, partition *Partition, q *WriteOptions) (*Partition, *WriteMeta, error)

type PassiveHealthCheck added in v1.9.0

type PassiveHealthCheck struct {
	// Interval between health check analysis sweeps. Each sweep may remove
	// hosts or return hosts to the pool.
	Interval time.Duration `json:",omitempty"`

	// MaxFailures is the count of consecutive failures that results in a host
	// being removed from the pool.
	MaxFailures uint32 `alias:"max_failures"`

	// EnforcingConsecutive5xx is the % chance that a host will be actually ejected
	// when an outlier status is detected through consecutive 5xx.
	// This setting can be used to disable ejection or to ramp it up slowly.
	EnforcingConsecutive5xx *uint32 `json:",omitempty" alias:"enforcing_consecutive_5xx"`

	// The maximum % of an upstream cluster that can be ejected due to outlier detection.
	// Defaults to 10% but will eject at least one host regardless of the value.
	MaxEjectionPercent *uint32 `json:",omitempty" alias:"max_ejection_percent"`

	// The base time that a host is ejected for. The real time is equal to the base time
	// multiplied by the number of times the host has been ejected and is capped by
	// max_ejection_time (Default 300s). Defaults to 30000ms or 30s.
	BaseEjectionTime *time.Duration `json:",omitempty" alias:"base_ejection_time"`
}

type PeeredServiceName added in v1.22.0

type PeeredServiceName struct {
	ServiceName CompoundServiceName
	Peer        string
}

type Peering added in v1.14.0

type Peering struct {
	// ID is a datacenter-scoped UUID for the peering.
	ID string
	// Name is the local alias for the peering relationship.
	Name string
	// Partition is the local partition connecting to the peer.
	Partition string `json:",omitempty"`
	// DeletedAt is the time when the Peering was marked for deletion
	DeletedAt *time.Time `json:",omitempty" alias:"deleted_at"`
	// Meta is a mapping of some string value to any other string value
	Meta map[string]string `json:",omitempty"`
	// State is one of the valid PeeringState values to represent the status of
	// peering relationship.
	State PeeringState
	// PeerID is the ID that our peer assigned to this peering. This ID is to
	// be used when dialing the peer, so that it can know who dialed it.
	PeerID string `json:",omitempty"`
	// PeerCAPems contains all the CA certificates for the remote peer.
	PeerCAPems []string `json:",omitempty"`
	// PeerServerName is the name of the remote server as it relates to TLS.
	PeerServerName string `json:",omitempty"`
	// PeerServerAddresses contains all the connection addresses for the remote peer.
	PeerServerAddresses []string `json:",omitempty"`
	// StreamStatus contains information computed on read based on the state of the stream.
	StreamStatus PeeringStreamStatus
	// CreateIndex is the Raft index at which the Peering was created.
	CreateIndex uint64
	// ModifyIndex is the latest Raft index at which the Peering was modified.
	ModifyIndex uint64
	// Remote contains metadata for the remote peer.
	Remote PeeringRemoteInfo
}

type PeeringEstablishRequest added in v1.14.0

type PeeringEstablishRequest struct {
	// Name of the remote peer.
	PeerName string
	// The peering token returned from the peer's GenerateToken endpoint.
	PeeringToken string `json:",omitempty"`
	// Partition to be peered.
	Partition string `json:",omitempty"`
	// Meta is a mapping of some string value to any other string value
	Meta map[string]string `json:",omitempty"`
}

type PeeringEstablishResponse added in v1.14.0

type PeeringEstablishResponse struct {
}

type PeeringGenerateTokenRequest added in v1.14.0

type PeeringGenerateTokenRequest struct {
	// PeerName is the name of the remote peer.
	PeerName string
	// Partition to be peered.
	Partition string `json:",omitempty"`
	// Meta is a mapping of some string value to any other string value
	Meta map[string]string `json:",omitempty"`
	// ServerExternalAddresses is a list of addresses to put into the generated token. This could be used to specify
	// load balancer(s) or external IPs to reach the servers from the dialing side, and will override any server
	// addresses obtained from the "consul" service.
	ServerExternalAddresses []string `json:",omitempty"`
}

type PeeringGenerateTokenResponse added in v1.14.0

type PeeringGenerateTokenResponse struct {
	// PeeringToken is an opaque string provided to the remote peer for it to complete
	// the peering initialization handshake.
	PeeringToken string
}

type PeeringListRequest added in v1.14.0

type PeeringListRequest struct {
}

type PeeringMeshConfig added in v1.16.0

type PeeringMeshConfig struct {
	PeerThroughMeshGateways bool `json:",omitempty" alias:"peer_through_mesh_gateways"`
}

type PeeringReadResponse added in v1.14.0

type PeeringReadResponse struct {
	Peering *Peering
}

type PeeringRemoteInfo added in v1.16.0

type PeeringRemoteInfo struct {
	// Partition is the remote peer's partition.
	Partition string
	// Datacenter is the remote peer's datacenter.
	Datacenter string
	Locality   *Locality `json:",omitempty"`
}

type PeeringState added in v1.14.0

type PeeringState string

PeeringState enumerates all the states a peering can be in

const (
	// PeeringStateUndefined represents an unset value for PeeringState during
	// writes.
	PeeringStateUndefined PeeringState = "UNDEFINED"

	// PeeringStatePending means the peering was created by generating a peering token.
	// Peerings stay in a pending state until the peer uses the token to dial
	// the local cluster.
	PeeringStatePending PeeringState = "PENDING"

	// PeeringStateEstablishing means the peering is being established from a peering token.
	// This is the initial state for dialing peers.
	PeeringStateEstablishing PeeringState = "ESTABLISHING"

	// PeeringStateActive means that the peering connection is active and
	// healthy.
	PeeringStateActive PeeringState = "ACTIVE"

	// PeeringStateFailing means the peering connection has been interrupted
	// but has not yet been terminated.
	PeeringStateFailing PeeringState = "FAILING"

	// PeeringStateDeleting means a peering was marked for deletion and is in the process
	// of being deleted.
	PeeringStateDeleting PeeringState = "DELETING"

	// PeeringStateTerminated means the peering relationship has been removed.
	PeeringStateTerminated PeeringState = "TERMINATED"
)

type PeeringStreamStatus added in v1.16.0

type PeeringStreamStatus struct {
	// ImportedServices is the list of services imported from this peering.
	ImportedServices []string
	// ExportedServices is the list of services exported to this peering.
	ExportedServices []string
	// LastHeartbeat represents when the last heartbeat message was received.
	LastHeartbeat *time.Time
	// LastReceive represents when any message was last received, regardless of success or error.
	LastReceive *time.Time
	// LastSend represents when any message was last sent, regardless of success or error.
	LastSend *time.Time
}

type Peerings added in v1.14.0

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

func (*Peerings) Delete added in v1.14.0

func (p *Peerings) Delete(ctx context.Context, name string, q *WriteOptions) (*WriteMeta, error)

func (*Peerings) Establish added in v1.14.0

TODO(peering): verify this is the ultimate signature we want

func (*Peerings) GenerateToken added in v1.14.0

TODO(peering): verify this is the ultimate signature we want

func (*Peerings) List added in v1.14.0

func (p *Peerings) List(ctx context.Context, q *QueryOptions) ([]*Peering, *QueryMeta, error)

func (*Peerings) Read added in v1.14.0

func (p *Peerings) Read(ctx context.Context, name string, q *QueryOptions) (*Peering, *QueryMeta, error)

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

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

Get is used to fetch a specific prepared query.

func (*PreparedQuery) List

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

func (*PreparedQuery) Update

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

type ProxyConfigEntry struct {
	Kind                 string
	Name                 string
	Partition            string                               `json:",omitempty"`
	Namespace            string                               `json:",omitempty"`
	Mode                 ProxyMode                            `json:",omitempty"`
	TransparentProxy     *TransparentProxyConfig              `json:",omitempty" alias:"transparent_proxy"`
	MutualTLSMode        MutualTLSMode                        `json:",omitempty" alias:"mutual_tls_mode"`
	Config               map[string]interface{}               `json:",omitempty"`
	MeshGateway          MeshGatewayConfig                    `json:",omitempty" alias:"mesh_gateway"`
	Expose               ExposeConfig                         `json:",omitempty"`
	AccessLogs           *AccessLogsConfig                    `json:",omitempty" alias:"access_logs"`
	EnvoyExtensions      []EnvoyExtension                     `json:",omitempty" alias:"envoy_extensions"`
	FailoverPolicy       *ServiceResolverFailoverPolicy       `json:",omitempty" alias:"failover_policy"`
	PrioritizeByLocality *ServiceResolverPrioritizeByLocality `json:",omitempty" alias:"prioritize_by_locality"`

	Meta        map[string]string `json:",omitempty"`
	CreateIndex uint64
	ModifyIndex uint64
}

func (*ProxyConfigEntry) GetCreateIndex added in v1.1.0

func (p *ProxyConfigEntry) GetCreateIndex() uint64

func (*ProxyConfigEntry) GetKind added in v1.1.0

func (p *ProxyConfigEntry) GetKind() string

func (*ProxyConfigEntry) GetMeta added in v1.8.0

func (p *ProxyConfigEntry) GetMeta() map[string]string

func (*ProxyConfigEntry) GetModifyIndex added in v1.1.0

func (p *ProxyConfigEntry) GetModifyIndex() uint64

func (*ProxyConfigEntry) GetName added in v1.1.0

func (p *ProxyConfigEntry) GetName() string

func (*ProxyConfigEntry) GetNamespace added in v1.8.0

func (p *ProxyConfigEntry) GetNamespace() string

func (*ProxyConfigEntry) GetPartition added in v1.12.0

func (p *ProxyConfigEntry) GetPartition() string

type ProxyMode added in v1.9.0

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

	// ProxyModeTransparent represents that inbound and outbound application
	// traffic is being captured and redirected through the proxy.
	ProxyModeTransparent ProxyMode = "transparent"

	// ProxyModeDirect represents that the proxy's listeners must be dialed directly
	// by the local application and other proxies.
	ProxyModeDirect ProxyMode = "direct"
)

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 deprecated

type QueryDatacenterOptions = QueryFailoverOptions

Deprecated: use QueryFailoverOptions instead.

type QueryFailoverOptions added in v1.14.0

type QueryFailoverOptions 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

	// Targets is a fixed list of datacenters and peers to try. This field cannot
	// be populated with NearestN or Datacenters.
	Targets []QueryFailoverTarget
}

QueryFailoverOptions sets options about how we fail over if there are no healthy nodes in the local datacenter.

type QueryFailoverTarget added in v1.14.0

type QueryFailoverTarget struct {
	// Peer specifies a peer to try during failover.
	Peer string

	// Datacenter specifies a datacenter to try during failover.
	Datacenter string

	// Partition specifies a partition to try during failover
	// Note: Partition are available only in Consul Enterprise
	Partition string `json:",omitempty"`

	// Namespace specifies a namespace to try during failover
	// Note: Namespaces are available only in Consul Enterprise
	Namespace string `json:",omitempty"`
}

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

	// QueryBackend represent which backend served the request.
	QueryBackend string

	// DefaultACLPolicy is used to control the ACL interaction when there is no
	// defined policy. This can be "allow" which means ACLs are used to
	// deny-list, or "deny" which means ACLs are allow-lists.
	DefaultACLPolicy string

	// ResultsFilteredByACLs is true when some of the query's results were
	// filtered out by enforcing ACLs. It may be false because nothing was
	// removed, or because the endpoint does not yet support this flag.
	ResultsFilteredByACLs bool
}

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

	// Partition overrides the `default` partition
	// Note: Partitions are available only in Consul Enterprise
	Partition string

	// SamenessGroup is used find the SamenessGroup in the given
	// Partition and will find the failover order for the Service
	// from the SamenessGroup Members, with the given Partition being
	// the first member.
	// Note: SamenessGroups are available only in Consul Enterprise
	SamenessGroup string

	// Providing a datacenter overwrites the DC provided
	// by the Config
	Datacenter string

	// Providing a peer name in the query option
	Peer 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

	// MergeCentralConfig returns a service definition merged with the
	// proxy-defaults/global and service-defaults/:service config entries.
	// This can be used to ensure a full service definition is returned in the response
	// especially when the service might not be written into the catalog that way.
	MergeCentralConfig bool

	// Global is used to request information from all datacenters. Currently only
	// used for operator usage requests.
	Global bool
	// 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

	// RemoveEmptyTags if set to true, will cause the Tags list inside
	// the Service structure to be stripped of any empty strings. This is useful
	// when interpolating into tags in a way where the tag is optional, and
	// where searching for an empty tag would yield no results from the query.
	RemoveEmptyTags bool
}

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

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

RaftServer has information about a server in the Raft configuration.

type RateLimitIPConfigEntry added in v1.22.0

type RateLimitIPConfigEntry struct {
	// Kind of the config entry. This will be set to structs.RateLimitIPConfig
	Kind string
	Name string
	Mode string // {permissive, enforcing, disabled}

	Meta map[string]string `json:",omitempty"`
	// overall limits
	ReadRate  float64 `alias:"read_rate"`
	WriteRate float64 `alias:"write_rate"`

	//limits specific to a type of call
	ACL             *ReadWriteRatesConfig `json:",omitempty"` //	OperationCategoryACL             OperationCategory = "ACL"
	Catalog         *ReadWriteRatesConfig `json:",omitempty"` //   OperationCategoryCatalog         OperationCategory = "Catalog"
	ConfigEntry     *ReadWriteRatesConfig `json:",omitempty"` //   OperationCategoryConfigEntry     OperationCategory = "ConfigEntry"
	ConnectCA       *ReadWriteRatesConfig `json:",omitempty"` //   OperationCategoryConnectCA       OperationCategory = "ConnectCA"
	Coordinate      *ReadWriteRatesConfig `json:",omitempty"` //   OperationCategoryCoordinate      OperationCategory = "Coordinate"
	DiscoveryChain  *ReadWriteRatesConfig `json:",omitempty"` //   OperationCategoryDiscoveryChain  OperationCategory = "DiscoveryChain"
	ServerDiscovery *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryServerDiscovery OperationCategory = "ServerDiscovery"
	Health          *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryHealth          OperationCategory = "Health"
	Intention       *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryIntention       OperationCategory = "Intention"
	KV              *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryKV              OperationCategory = "KV"
	Tenancy         *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryPartition        OperationCategory = "Tenancy"
	PreparedQuery   *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryPreparedQuery   OperationCategory = "PreparedQuery"
	Session         *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategorySession         OperationCategory = "Session"
	Txn             *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryTxn             OperationCategory = "Txn"
	AutoConfig      *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryAutoConfig      OperationCategory = "AutoConfig"
	FederationState *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryFederationState OperationCategory = "FederationState"
	Internal        *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryInternal        OperationCategory = "Internal"
	PeerStream      *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryPeerStream      OperationCategory = "PeerStream"
	Peering         *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryPeering         OperationCategory = "Peering"
	DataPlane       *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryDataPlane       OperationCategory = "DataPlane"
	DNS             *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryDNS             OperationCategory = "DNS"
	Subscribe       *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategorySubscribe       OperationCategory = "Subscribe"
	Resource        *ReadWriteRatesConfig `json:",omitempty"` //  OperationCategoryResource        OperationCategory = "Resource"

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// Namespace is the namespace the config entry is associated with.
	// Namespacing is a Consul Enterprise feature.
	Namespace string `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
}

func (*RateLimitIPConfigEntry) GetCreateIndex added in v1.22.0

func (r *RateLimitIPConfigEntry) GetCreateIndex() uint64

func (*RateLimitIPConfigEntry) GetKind added in v1.22.0

func (r *RateLimitIPConfigEntry) GetKind() string

func (*RateLimitIPConfigEntry) GetMeta added in v1.22.0

func (r *RateLimitIPConfigEntry) GetMeta() map[string]string

func (*RateLimitIPConfigEntry) GetModifyIndex added in v1.22.0

func (r *RateLimitIPConfigEntry) GetModifyIndex() uint64

func (*RateLimitIPConfigEntry) GetName added in v1.22.0

func (r *RateLimitIPConfigEntry) GetName() string

func (*RateLimitIPConfigEntry) GetNamespace added in v1.22.0

func (r *RateLimitIPConfigEntry) GetNamespace() string

func (*RateLimitIPConfigEntry) GetPartition added in v1.22.0

func (r *RateLimitIPConfigEntry) GetPartition() string

type RateLimits added in v1.26.1

type RateLimits struct {
	InstanceLevel InstanceLevelRateLimits `alias:"instance_level"`
}

RateLimits is rate limiting configuration that is applied to inbound traffic for a service. Rate limiting is a Consul enterprise feature.

type Raw

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

Raw can be used to do raw queries against custom endpoints

func (*Raw) Delete added in v1.28.3

func (raw *Raw) Delete(endpoint string, q *QueryOptions) (*WriteMeta, error)

Delete is used to do a DELETE request against an endpoint

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 ReadWriteRatesConfig added in v1.22.0

type ReadWriteRatesConfig struct {
	ReadRate  float64 `alias:"read_rate"`
	WriteRate float64 `alias:"write_rate"`
}

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 RemoteJWKS added in v1.22.0

type RemoteJWKS struct {
	// URI is the URI of the server to query for the JWKS.
	URI string `json:",omitempty"`

	// RequestTimeoutMs is the number of milliseconds to
	// time out when making a request for the JWKS.
	RequestTimeoutMs int `json:",omitempty" alias:"request_timeout_ms"`

	// CacheDuration is the duration after which cached keys
	// should be expired.
	//
	// Default value is 5 minutes.
	CacheDuration time.Duration `json:",omitempty" alias:"cache_duration"`

	// FetchAsynchronously indicates that the JWKS should be fetched
	// when a client request arrives. Client requests will be paused
	// until the JWKS is fetched.
	// If false, the proxy listener will wait for the JWKS to be
	// fetched before being activated.
	//
	// Default value is false.
	FetchAsynchronously bool `json:",omitempty" alias:"fetch_asynchronously"`

	// RetryPolicy defines a retry policy for fetching JWKS.
	//
	// There is no retry by default.
	RetryPolicy *JWKSRetryPolicy `json:",omitempty" alias:"retry_policy"`

	// JWKSCluster defines how the specified Remote JWKS URI is to be fetched.
	JWKSCluster *JWKSCluster `json:",omitempty" alias:"jwks_cluster"`
}

RemoteJWKS specifies how to fetch a JWKS from a remote server.

type RequestNormalizationMeshConfig added in v1.28.5

type RequestNormalizationMeshConfig struct {
	// InsecureDisablePathNormalization sets the value of the \`normalize_path\` option in the Envoy listener's
	// `HttpConnectionManager`. The default value is \`false\`. When set to \`true\` in Consul, \`normalize_path\` is
	// set to \`false\` for the Envoy proxy. This parameter disables the normalization of request URL paths according to
	// RFC 3986, conversion of \`\\\` to \`/\`, and decoding non-reserved %-encoded characters. When using L7 intentions
	// with path match rules, we recommend enabling path normalization in order to avoid match rule circumvention with
	// non-normalized path values.
	InsecureDisablePathNormalization bool `json:",omitempty" alias:"insecure_disable_path_normalization"`
	// MergeSlashes sets the value of the \`merge_slashes\` option in the Envoy listener's \`HttpConnectionManager\`.
	// The default value is \`false\`. This option controls the normalization of request URL paths by merging
	// consecutive \`/\` characters. This normalization is not part of RFC 3986. When using L7 intentions with path
	// match rules, we recommend enabling this setting to avoid match rule circumvention through non-normalized path
	// values, unless legitimate service traffic depends on allowing for repeat \`/\` characters, or upstream services
	// are configured to differentiate between single and multiple slashes.
	MergeSlashes bool `json:",omitempty" alias:"merge_slashes"`
	// PathWithEscapedSlashesAction sets the value of the \`path_with_escaped_slashes_action\` option in the Envoy
	// listener's \`HttpConnectionManager\`. The default value of this option is empty, which is equivalent to
	// \`IMPLEMENTATION_SPECIFIC_DEFAULT\`. This parameter controls the action taken in response to request URL paths
	// with escaped slashes in the path. When using L7 intentions with path match rules, we recommend enabling this
	// setting to avoid match rule circumvention through non-normalized path values, unless legitimate service traffic
	// depends on allowing for escaped \`/\` or \`\\\` characters, or upstream services are configured to differentiate
	// between escaped and unescaped slashes. Refer to the Envoy documentation for more information on available
	// options.
	PathWithEscapedSlashesAction string `json:",omitempty" alias:"path_with_escaped_slashes_action"`
	// HeadersWithUnderscoresAction sets the value of the \`headers_with_underscores_action\` option in the Envoy
	// listener's \`HttpConnectionManager\` under \`common_http_protocol_options\`. The default value of this option is
	// empty, which is equivalent to \`ALLOW\`. Refer to the Envoy documentation for more information on available
	// options.
	HeadersWithUnderscoresAction string `json:",omitempty" alias:"headers_with_underscores_action"`
}

RequestNormalizationMeshConfig contains options pertaining to the normalization of HTTP requests processed by mesh proxies.

type ResolvedConsumers added in v1.27.1

type ResolvedConsumers struct {
	Peers      []string `json:",omitempty"`
	Partitions []string `json:",omitempty"`
}

type ResolvedExportedService added in v1.27.1

type ResolvedExportedService struct {
	// Service is the name of the service which is exported.
	Service string

	// Partition of the service
	Partition string `json:",omitempty"`

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

	// Consumers is a list of downstream consumers of the service.
	Consumers ResolvedConsumers
}

type ResourceReference added in v1.19.0

type ResourceReference struct {
	// Kind is the kind of ConfigEntry that this resource refers to.
	Kind string
	// Name is the identifier for the ConfigEntry this resource refers to.
	Name string
	// SectionName is a generic subresource identifier that specifies
	// a subset of the ConfigEntry to which this reference applies. Usage
	// of this field should be up to the controller that leverages it. If
	// unused, this should be blank.
	SectionName string

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

ResourceReference is a reference to a ConfigEntry with an optional reference to a subsection of that ConfigEntry that can be specified as SectionName

type RetryFilter added in v1.26.1

type RetryFilter struct {
	NumRetries            uint32
	RetryOn               []string
	RetryOnStatusCodes    []uint32
	RetryOnConnectFailure bool
}

type RetryPolicyBackOff added in v1.22.0

type RetryPolicyBackOff struct {
	// BaseInterval to be used for the next back off computation
	//
	// The default value from envoy is 1s
	BaseInterval time.Duration `json:",omitempty" alias:"base_interval"`

	// MaxInternal to be used to specify the maximum interval between retries.
	// Optional but should be greater or equal to BaseInterval.
	//
	// Defaults to 10 times BaseInterval
	MaxInterval time.Duration `json:",omitempty" alias:"max_interval"`
}

type RingHashConfig added in v1.8.0

type RingHashConfig struct {
	// MinimumRingSize determines the minimum number of entries in the hash ring
	MinimumRingSize uint64 `json:",omitempty" alias:"minimum_ring_size"`

	// MaximumRingSize determines the maximum number of entries in the hash ring
	MaximumRingSize uint64 `json:",omitempty" alias:"maximum_ring_size"`
}

RingHashConfig contains configuration for the "ring_hash" policy type

type RouteConditionReason added in v1.21.1

type RouteConditionReason string

RouteConditionReason is a reason for a route condition.

type RouteConditionType added in v1.21.1

type RouteConditionType string

RouteConditionType is a type of condition for a route.

type SamenessGroupConfigEntry added in v1.22.0

type SamenessGroupConfigEntry struct {
	Kind               string
	Name               string
	Partition          string `json:",omitempty"`
	DefaultForFailover bool   `json:",omitempty" alias:"default_for_failover"`
	IncludeLocal       bool   `json:",omitempty" alias:"include_local"`
	Members            []SamenessGroupMember
	Meta               map[string]string `json:",omitempty"`
	CreateIndex        uint64
	ModifyIndex        uint64
}

func (*SamenessGroupConfigEntry) GetCreateIndex added in v1.22.0

func (s *SamenessGroupConfigEntry) GetCreateIndex() uint64

func (*SamenessGroupConfigEntry) GetKind added in v1.22.0

func (s *SamenessGroupConfigEntry) GetKind() string

func (*SamenessGroupConfigEntry) GetMeta added in v1.22.0

func (s *SamenessGroupConfigEntry) GetMeta() map[string]string

func (*SamenessGroupConfigEntry) GetModifyIndex added in v1.22.0

func (s *SamenessGroupConfigEntry) GetModifyIndex() uint64

func (*SamenessGroupConfigEntry) GetName added in v1.22.0

func (s *SamenessGroupConfigEntry) GetName() string

func (*SamenessGroupConfigEntry) GetNamespace added in v1.22.0

func (s *SamenessGroupConfigEntry) GetNamespace() string

func (*SamenessGroupConfigEntry) GetPartition added in v1.22.0

func (s *SamenessGroupConfigEntry) GetPartition() string

type SamenessGroupMember added in v1.22.0

type SamenessGroupMember struct {
	Partition string `json:",omitempty"`
	Peer      string `json:",omitempty"`
}

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

type ServiceAddress struct {
	Address string
	Port    int
}

func ParseServiceAddr added in v1.2.0

func ParseServiceAddr(addrPort string) (ServiceAddress, error)

type ServiceCheck added in v1.4.0

type ServiceCheck struct {
	ID        string
	Namespace string
}

type ServiceConfigEntry added in v1.1.0

type ServiceConfigEntry struct {
	Kind                      string
	Name                      string
	Partition                 string                  `json:",omitempty"`
	Namespace                 string                  `json:",omitempty"`
	Protocol                  string                  `json:",omitempty"`
	Mode                      ProxyMode               `json:",omitempty"`
	TransparentProxy          *TransparentProxyConfig `json:",omitempty" alias:"transparent_proxy"`
	MutualTLSMode             MutualTLSMode           `json:",omitempty" alias:"mutual_tls_mode"`
	MeshGateway               MeshGatewayConfig       `json:",omitempty" alias:"mesh_gateway"`
	Expose                    ExposeConfig            `json:",omitempty"`
	ExternalSNI               string                  `json:",omitempty" alias:"external_sni"`
	UpstreamConfig            *UpstreamConfiguration  `json:",omitempty" alias:"upstream_config"`
	Destination               *DestinationConfig      `json:",omitempty"`
	MaxInboundConnections     int                     `json:",omitempty" alias:"max_inbound_connections"`
	LocalConnectTimeoutMs     int                     `json:",omitempty" alias:"local_connect_timeout_ms"`
	LocalRequestTimeoutMs     int                     `json:",omitempty" alias:"local_request_timeout_ms"`
	BalanceInboundConnections string                  `json:",omitempty" alias:"balance_inbound_connections"`
	RateLimits                *RateLimits             `json:",omitempty" alias:"rate_limits"`
	EnvoyExtensions           []EnvoyExtension        `json:",omitempty" alias:"envoy_extensions"`
	Meta                      map[string]string       `json:",omitempty"`
	CreateIndex               uint64
	ModifyIndex               uint64
}

func (*ServiceConfigEntry) GetCreateIndex added in v1.1.0

func (s *ServiceConfigEntry) GetCreateIndex() uint64

func (*ServiceConfigEntry) GetKind added in v1.1.0

func (s *ServiceConfigEntry) GetKind() string

func (*ServiceConfigEntry) GetMeta added in v1.8.0

func (s *ServiceConfigEntry) GetMeta() map[string]string

func (*ServiceConfigEntry) GetModifyIndex added in v1.1.0

func (s *ServiceConfigEntry) GetModifyIndex() uint64

func (*ServiceConfigEntry) GetName added in v1.1.0

func (s *ServiceConfigEntry) GetName() string

func (*ServiceConfigEntry) GetNamespace added in v1.8.0

func (s *ServiceConfigEntry) GetNamespace() string

func (*ServiceConfigEntry) GetPartition added in v1.12.0

func (s *ServiceConfigEntry) GetPartition() string

type ServiceConsumer added in v1.12.0

type ServiceConsumer struct {
	// Partition is the admin partition to export the service to.
	Partition string `json:",omitempty"`

	// Peer is the name of the peer to export the service to.
	Peer string `json:",omitempty" alias:"peer_name"`

	// SamenessGroup is the name of the sameness group to export the service to.
	SamenessGroup string `json:",omitempty" alias:"sameness_group"`
}

ServiceConsumer represents a downstream consumer of the service to be exported. At most one of Partition or Peer must be specified.

type ServiceEntry

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

ServiceEntry is used for the health service endpoint

type ServiceIntentionsConfigEntry added in v1.8.0

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

	Sources []*SourceIntention
	JWT     *IntentionJWTRequirement `json:",omitempty"`

	Meta map[string]string `json:",omitempty"`

	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceIntentionsConfigEntry) GetCreateIndex added in v1.8.0

func (e *ServiceIntentionsConfigEntry) GetCreateIndex() uint64

func (*ServiceIntentionsConfigEntry) GetKind added in v1.8.0

func (e *ServiceIntentionsConfigEntry) GetKind() string

func (*ServiceIntentionsConfigEntry) GetMeta added in v1.8.0

func (e *ServiceIntentionsConfigEntry) GetMeta() map[string]string

func (*ServiceIntentionsConfigEntry) GetModifyIndex added in v1.8.0

func (e *ServiceIntentionsConfigEntry) GetModifyIndex() uint64

func (*ServiceIntentionsConfigEntry) GetName added in v1.8.0

func (e *ServiceIntentionsConfigEntry) GetName() string

func (*ServiceIntentionsConfigEntry) GetNamespace added in v1.8.0

func (e *ServiceIntentionsConfigEntry) GetNamespace() string

func (*ServiceIntentionsConfigEntry) GetPartition added in v1.12.0

func (e *ServiceIntentionsConfigEntry) GetPartition() string

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"

	// ServiceKindAPIGateway is an API Gateway for the Connect feature.
	// This service will ingress connections based of configuration defined in
	// the api-gateway config entry.
	ServiceKindAPIGateway ServiceKind = "api-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

	// SamenessGroup specifies a sameness group to query. The first member of the Sameness Group will
	// be targeted first on PQ execution and subsequent members will be targeted during failover scenarios.
	// This field is mutually exclusive with Failover.
	SamenessGroup string `json:",omitempty"`

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

	// Partition of the service to query
	Partition 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 QueryFailoverOptions `json:",omitempty"`

	// 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 added in v1.4.0

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

	// Token is used to provide a per-request ACL token
	// which overrides the agent's default token.
	Token string
	// contains filtered or unexported fields
}

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

func (ServiceRegisterOpts) WithContext added in v1.9.0

WithContext sets the context to be used for the request on a new ServiceRegisterOpts, and returns the opts.

type ServiceResolverConfigEntry added in v1.2.0

type ServiceResolverConfigEntry struct {
	Kind      string
	Name      string
	Partition string `json:",omitempty"`
	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"`
	RequestTimeout time.Duration                      `json:",omitempty" alias:"request_timeout"`

	// PrioritizeByLocality controls whether the locality of services within the
	// local partition will be used to prioritize connectivity.
	PrioritizeByLocality *ServiceResolverPrioritizeByLocality `json:",omitempty" alias:"prioritize_by_locality"`

	// LoadBalancer determines the load balancing policy and configuration for services
	// issuing requests to this upstream service.
	LoadBalancer *LoadBalancer `json:",omitempty" alias:"load_balancer"`

	Meta        map[string]string `json:",omitempty"`
	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceResolverConfigEntry) GetCreateIndex added in v1.2.0

func (e *ServiceResolverConfigEntry) GetCreateIndex() uint64

func (*ServiceResolverConfigEntry) GetKind added in v1.2.0

func (e *ServiceResolverConfigEntry) GetKind() string

func (*ServiceResolverConfigEntry) GetMeta added in v1.8.0

func (e *ServiceResolverConfigEntry) GetMeta() map[string]string

func (*ServiceResolverConfigEntry) GetModifyIndex added in v1.2.0

func (e *ServiceResolverConfigEntry) GetModifyIndex() uint64

func (*ServiceResolverConfigEntry) GetName added in v1.2.0

func (e *ServiceResolverConfigEntry) GetName() string

func (*ServiceResolverConfigEntry) GetNamespace added in v1.8.0

func (e *ServiceResolverConfigEntry) GetNamespace() string

func (*ServiceResolverConfigEntry) GetPartition added in v1.12.0

func (e *ServiceResolverConfigEntry) GetPartition() string

func (*ServiceResolverConfigEntry) MarshalJSON added in v1.2.0

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

func (*ServiceResolverConfigEntry) UnmarshalJSON added in v1.2.0

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

type ServiceResolverFailover added in v1.2.0

type ServiceResolverFailover struct {
	Service       string `json:",omitempty"`
	ServiceSubset string `json:",omitempty" alias:"service_subset"`
	// Referencing other partitions is not supported.
	Namespace     string                          `json:",omitempty"`
	Datacenters   []string                        `json:",omitempty"`
	Targets       []ServiceResolverFailoverTarget `json:",omitempty"`
	Policy        *ServiceResolverFailoverPolicy  `json:",omitempty"`
	SamenessGroup string                          `json:",omitempty" alias:"sameness_group"`
}

type ServiceResolverFailoverPolicy added in v1.22.0

type ServiceResolverFailoverPolicy struct {
	// Mode specifies the type of failover that will be performed. Valid values are
	// "sequential", "" (equivalent to "sequential") and "order-by-locality".
	Mode    string   `json:",omitempty"`
	Regions []string `json:",omitempty"`
}

type ServiceResolverFailoverTarget added in v1.16.0

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

type ServiceResolverPrioritizeByLocality added in v1.22.0

type ServiceResolverPrioritizeByLocality struct {
	// Mode specifies the type of prioritization that will be performed
	// when selecting nodes in the local partition.
	// Valid values are: "" (default "none"), "none", and "failover".
	Mode string `json:",omitempty"`
}

type ServiceResolverRedirect added in v1.2.0

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

type ServiceResolverSubset added in v1.2.0

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

type ServiceRoute added in v1.2.0

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

type ServiceRouteDestination added in v1.2.0

type ServiceRouteDestination struct {
	Service               string               `json:",omitempty"`
	ServiceSubset         string               `json:",omitempty" alias:"service_subset"`
	Namespace             string               `json:",omitempty"`
	Partition             string               `json:",omitempty"`
	PrefixRewrite         string               `json:",omitempty" alias:"prefix_rewrite"`
	RequestTimeout        time.Duration        `json:",omitempty" alias:"request_timeout"`
	IdleTimeout           time.Duration        `json:",omitempty" alias:"idle_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"`
	RetryOn               []string             `json:",omitempty" alias:"retry_on"`
	RequestHeaders        *HTTPHeaderModifiers `json:",omitempty" alias:"request_headers"`
	ResponseHeaders       *HTTPHeaderModifiers `json:",omitempty" alias:"response_headers"`
}

func (*ServiceRouteDestination) MarshalJSON added in v1.2.0

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

func (*ServiceRouteDestination) UnmarshalJSON added in v1.2.0

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

type ServiceRouteHTTPMatch added in v1.2.0

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

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

type ServiceRouteHTTPMatchHeader added in v1.2.0

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

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

type ServiceRouteMatch added in v1.2.0

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

type ServiceRouterConfigEntry added in v1.2.0

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

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

	Meta        map[string]string `json:",omitempty"`
	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceRouterConfigEntry) GetCreateIndex added in v1.2.0

func (e *ServiceRouterConfigEntry) GetCreateIndex() uint64

func (*ServiceRouterConfigEntry) GetKind added in v1.2.0

func (e *ServiceRouterConfigEntry) GetKind() string

func (*ServiceRouterConfigEntry) GetMeta added in v1.8.0

func (e *ServiceRouterConfigEntry) GetMeta() map[string]string

func (*ServiceRouterConfigEntry) GetModifyIndex added in v1.2.0

func (e *ServiceRouterConfigEntry) GetModifyIndex() uint64

func (*ServiceRouterConfigEntry) GetName added in v1.2.0

func (e *ServiceRouterConfigEntry) GetName() string

func (*ServiceRouterConfigEntry) GetNamespace added in v1.8.0

func (e *ServiceRouterConfigEntry) GetNamespace() string

func (*ServiceRouterConfigEntry) GetPartition added in v1.12.0

func (e *ServiceRouterConfigEntry) GetPartition() string

type ServiceSplit added in v1.2.0

type ServiceSplit struct {
	Weight          float32
	Service         string               `json:",omitempty"`
	ServiceSubset   string               `json:",omitempty" alias:"service_subset"`
	Namespace       string               `json:",omitempty"`
	Partition       string               `json:",omitempty"`
	RequestHeaders  *HTTPHeaderModifiers `json:",omitempty" alias:"request_headers"`
	ResponseHeaders *HTTPHeaderModifiers `json:",omitempty" alias:"response_headers"`
}

type ServiceSplitterConfigEntry added in v1.2.0

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

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

	Meta        map[string]string `json:",omitempty"`
	CreateIndex uint64
	ModifyIndex uint64
}

func (*ServiceSplitterConfigEntry) GetCreateIndex added in v1.2.0

func (e *ServiceSplitterConfigEntry) GetCreateIndex() uint64

func (*ServiceSplitterConfigEntry) GetKind added in v1.2.0

func (e *ServiceSplitterConfigEntry) GetKind() string

func (*ServiceSplitterConfigEntry) GetMeta added in v1.8.0

func (e *ServiceSplitterConfigEntry) GetMeta() map[string]string

func (*ServiceSplitterConfigEntry) GetModifyIndex added in v1.2.0

func (e *ServiceSplitterConfigEntry) GetModifyIndex() uint64

func (*ServiceSplitterConfigEntry) GetName added in v1.2.0

func (e *ServiceSplitterConfigEntry) GetName() string

func (*ServiceSplitterConfigEntry) GetNamespace added in v1.8.0

func (e *ServiceSplitterConfigEntry) GetNamespace() string

func (*ServiceSplitterConfigEntry) GetPartition added in v1.12.0

func (e *ServiceSplitterConfigEntry) GetPartition() string

type ServiceTxnOp

type ServiceTxnOp struct {
	Verb    ServiceOp
	Node    string
	Service AgentService
}

ServiceTxnOp defines a single operation inside a transaction.

type ServiceUsage added in v1.19.0

type ServiceUsage struct {
	Nodes                   int
	Services                int
	ServiceInstances        int
	ConnectServiceInstances map[string]int

	// Billable services are of "typical" service kind (i.e. non-connect or connect-native),
	// excluding the "consul" service.
	BillableServiceInstances int

	// A map of partition+namespace to number of unique services registered in that namespace
	PartitionNamespaceServices map[string]map[string]int

	// A map of partition+namespace to number of service instances registered in that namespace
	PartitionNamespaceServiceInstances map[string]map[string]int

	// A map of partition+namespace+kind to number of service-mesh instances registered in that namespace
	PartitionNamespaceConnectServiceInstances map[string]map[string]map[string]int

	// A map of partition+namespace to number of billable instances registered in that namespace
	PartitionNamespaceBillableServiceInstances map[string]map[string]int
}

ServiceUsage contains information about the number of services and service instances for a datacenter.

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

type SessionOp string

SessionOp constants give possible operations available in a transaction.

const (
	SessionDelete SessionOp = "delete"
)

type SessionTxnOp added in v1.4.0

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 SourceIntention added in v1.8.0

type SourceIntention struct {
	Name          string
	Peer          string                 `json:",omitempty"`
	Partition     string                 `json:",omitempty"`
	Namespace     string                 `json:",omitempty"`
	SamenessGroup string                 `json:",omitempty" alias:"sameness_group"`
	Action        IntentionAction        `json:",omitempty"`
	Permissions   []*IntentionPermission `json:",omitempty"`
	Precedence    int
	Type          IntentionSourceType
	Description   string `json:",omitempty"`

	LegacyID         string            `json:",omitempty" alias:"legacy_id"`
	LegacyMeta       map[string]string `json:",omitempty" alias:"legacy_meta"`
	LegacyCreateTime *time.Time        `json:",omitempty" alias:"legacy_create_time"`
	LegacyUpdateTime *time.Time        `json:",omitempty" alias:"legacy_update_time"`
}

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)

func (*Status) LeaderWithQueryOptions added in v1.8.0

func (s *Status) LeaderWithQueryOptions(q *QueryOptions) (string, error)

Leader is used to query for a known leader

func (*Status) Peers

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

func (*Status) PeersWithQueryOptions added in v1.8.0

func (s *Status) PeersWithQueryOptions(q *QueryOptions) ([]string, error)

Peers is used to query for a known raft peers

type StatusError added in v1.12.0

type StatusError struct {
	Code int
	Body string
}

func (StatusError) Error added in v1.12.0

func (e StatusError) Error() string

type TCPRouteConfigEntry added in v1.19.0

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

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

	// Parents is a list of gateways that this route should be bound to.
	Parents []ResourceReference
	// Services is a list of TCP-based services that this should route to.
	// Currently, this must specify at maximum one service.
	Services []TCPService

	Meta map[string]string `json:",omitempty"`

	// Status is the asynchronous status which a TCPRoute propagates to the user.
	Status ConfigEntryStatus

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

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

TCPRouteConfigEntry -- TODO stub

func (*TCPRouteConfigEntry) GetCreateIndex added in v1.19.0

func (a *TCPRouteConfigEntry) GetCreateIndex() uint64

func (*TCPRouteConfigEntry) GetKind added in v1.19.0

func (a *TCPRouteConfigEntry) GetKind() string

func (*TCPRouteConfigEntry) GetMeta added in v1.19.0

func (a *TCPRouteConfigEntry) GetMeta() map[string]string

func (*TCPRouteConfigEntry) GetModifyIndex added in v1.19.0

func (a *TCPRouteConfigEntry) GetModifyIndex() uint64

func (*TCPRouteConfigEntry) GetName added in v1.19.0

func (a *TCPRouteConfigEntry) GetName() string

func (*TCPRouteConfigEntry) GetNamespace added in v1.19.0

func (a *TCPRouteConfigEntry) GetNamespace() string

func (*TCPRouteConfigEntry) GetPartition added in v1.19.0

func (a *TCPRouteConfigEntry) GetPartition() string

type TCPService added in v1.19.0

type TCPService struct {
	Name string

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

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

TCPService is a service reference for a TCPRoute

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

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

	Meta map[string]string `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

	// Partition is the partition the config entry is associated with.
	// Partitioning is a Consul Enterprise feature.
	Partition string `json:",omitempty"`

	// 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 added in v1.5.0

func (g *TerminatingGatewayConfigEntry) GetCreateIndex() uint64

func (*TerminatingGatewayConfigEntry) GetKind added in v1.5.0

func (*TerminatingGatewayConfigEntry) GetMeta added in v1.8.0

func (g *TerminatingGatewayConfigEntry) GetMeta() map[string]string

func (*TerminatingGatewayConfigEntry) GetModifyIndex added in v1.5.0

func (g *TerminatingGatewayConfigEntry) GetModifyIndex() uint64

func (*TerminatingGatewayConfigEntry) GetName added in v1.5.0

func (*TerminatingGatewayConfigEntry) GetNamespace added in v1.8.0

func (g *TerminatingGatewayConfigEntry) GetNamespace() string

func (*TerminatingGatewayConfigEntry) GetPartition added in v1.12.0

func (g *TerminatingGatewayConfigEntry) GetPartition() string

type TimeoutFilter added in v1.26.1

type TimeoutFilter struct {
	RequestTimeout time.Duration
	IdleTimeout    time.Duration
}

type TransferLeaderResponse added in v1.19.0

type TransferLeaderResponse struct {
	Success bool
}

TransferLeaderResponse is returned when querying for the current Raft configuration.

type TransparentProxyConfig added in v1.9.0

type TransparentProxyConfig struct {
	// The port of the listener where outbound application traffic is being redirected to.
	OutboundListenerPort int `json:",omitempty" alias:"outbound_listener_port"`

	// DialedDirectly indicates whether transparent proxies can dial this proxy instance directly.
	// The discovery chain is not considered when dialing a service instance directly.
	// This setting is useful when addressing stateful services, such as a database cluster with a leader node.
	DialedDirectly bool `json:",omitempty" alias:"dialed_directly"`
}

type TransparentProxyMeshConfig added in v1.9.0

type TransparentProxyMeshConfig struct {
	MeshDestinationsOnly bool `alias:"mesh_destinations_only"`
}

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 URLRewrite added in v1.19.0

type URLRewrite struct {
	Path string
}

type Upstream

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

Upstream is the response structure for a proxy upstream configuration.

type UpstreamConfig added in v1.9.0

type UpstreamConfig struct {
	// Name is only accepted within service-defaults.upstreamConfig.overrides .
	Name string `json:",omitempty"`

	// Partition is only accepted within service-defaults.upstreamConfig.overrides .
	Partition string `json:",omitempty"`

	// Namespace is only accepted within service-defaults.upstreamConfig.overrides .
	Namespace string `json:",omitempty"`

	// Peer is only accepted within service-defaults.upstreamConfig.overrides .
	Peer string `json:",omitempty"`

	// EnvoyListenerJSON is a complete override ("escape hatch") for the upstream's
	// listener.
	//
	// Note: This escape hatch is NOT compatible with the discovery chain and
	// will be ignored if a discovery chain is active.
	EnvoyListenerJSON string `json:",omitempty" alias:"envoy_listener_json"`

	// EnvoyClusterJSON is a complete override ("escape hatch") for the upstream's
	// cluster. The Connect client TLS certificate and context will be injected
	// overriding any TLS settings present.
	//
	// Note: This escape hatch is NOT compatible with the discovery chain and
	// will be ignored if a discovery chain is active.
	EnvoyClusterJSON string `json:",omitempty" alias:"envoy_cluster_json"`

	// Protocol describes the upstream's service protocol. Valid values are "tcp",
	// "http" and "grpc". Anything else is treated as tcp. The enables protocol
	// aware features like per-request metrics and connection pooling, tracing,
	// routing etc.
	Protocol string `json:",omitempty"`

	// ConnectTimeoutMs is the number of milliseconds to timeout making a new
	// connection to this upstream. Defaults to 5000 (5 seconds) if not set.
	ConnectTimeoutMs int `json:",omitempty" alias:"connect_timeout_ms"`

	// Limits are the set of limits that are applied to the proxy for a specific upstream of a
	// service instance.
	Limits *UpstreamLimits `json:",omitempty"`

	// PassiveHealthCheck configuration determines how upstream proxy instances will
	// be monitored for removal from the load balancing pool.
	PassiveHealthCheck *PassiveHealthCheck `json:",omitempty" alias:"passive_health_check"`

	// MeshGatewayConfig controls how Mesh Gateways are configured and used
	MeshGateway MeshGatewayConfig `json:",omitempty" alias:"mesh_gateway" `

	// BalanceOutboundConnections indicates that the proxy should attempt to evenly distribute
	// outbound connections across worker threads. Only used by envoy proxies.
	BalanceOutboundConnections string `json:",omitempty" alias:"balance_outbound_connections"`
}

type UpstreamConfiguration added in v1.9.0

type UpstreamConfiguration struct {
	// Overrides is a slice of per-service configuration. The name field is
	// required.
	Overrides []*UpstreamConfig `json:",omitempty"`

	// Defaults contains default configuration for all upstreams of a given
	// service. The name field must be empty.
	Defaults *UpstreamConfig `json:",omitempty"`
}

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 UpstreamLimits added in v1.9.0

type UpstreamLimits struct {
	// MaxConnections is the maximum number of connections the local proxy can
	// make to the upstream service.
	MaxConnections *int `alias:"max_connections"`

	// MaxPendingRequests is the maximum number of requests that will be queued
	// waiting for an available connection. This is mostly applicable to HTTP/1.1
	// clusters since all HTTP/2 requests are streamed over a single
	// connection.
	MaxPendingRequests *int `alias:"max_pending_requests"`

	// MaxConcurrentRequests is the maximum number of in-flight requests that will be allowed
	// to the upstream cluster at a point in time. This is mostly applicable to HTTP/2
	// clusters since all HTTP/1.1 requests are limited by MaxConnections.
	MaxConcurrentRequests *int `alias:"max_concurrent_requests"`
}

UpstreamLimits describes the limits that are associated with a specific upstream of a service instance.

type Usage added in v1.19.0

type Usage struct {
	// Usage is a map of datacenter -> usage information
	Usage map[string]ServiceUsage
}

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

	// Partition overrides the `default` partition
	// Note: Partitions are available only in Consul Enterprise
	Partition 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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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