api

package module
v1.29.2 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2024 License: MPL-2.0 Imports: 25 Imported by: 8,811

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"
	ACLTemplatedPolicyWorkloadIdentityName = "builtin/workload-identity"
	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.28.0

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

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

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

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.