2023-03-28 20:12:41 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2017-02-11 02:11:21 +00:00
|
|
|
"context"
|
2015-03-18 14:41:00 +00:00
|
|
|
"crypto/tls"
|
2015-01-06 18:40:00 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-06-04 21:55:53 +00:00
|
|
|
"math"
|
2015-01-08 16:38:09 +00:00
|
|
|
"net"
|
2015-01-06 18:40:00 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2015-01-08 16:38:09 +00:00
|
|
|
"os"
|
2015-01-06 18:40:00 +00:00
|
|
|
"strconv"
|
2015-01-08 16:38:09 +00:00
|
|
|
"strings"
|
2021-01-07 23:48:53 +00:00
|
|
|
"sync"
|
2015-01-06 18:40:00 +00:00
|
|
|
"time"
|
2015-10-22 14:47:50 +00:00
|
|
|
|
2015-10-22 18:14:22 +00:00
|
|
|
"github.com/hashicorp/go-cleanhttp"
|
2020-01-28 23:50:41 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2017-04-14 20:37:29 +00:00
|
|
|
"github.com/hashicorp/go-rootcerts"
|
2015-01-06 18:40:00 +00:00
|
|
|
)
|
|
|
|
|
2016-08-03 06:10:11 +00:00
|
|
|
const (
|
|
|
|
// HTTPAddrEnvName defines an environment variable name which sets
|
|
|
|
// the HTTP address if there is no -http-addr specified.
|
|
|
|
HTTPAddrEnvName = "CONSUL_HTTP_ADDR"
|
2016-08-03 06:11:04 +00:00
|
|
|
|
|
|
|
// HTTPTokenEnvName defines an environment variable name which sets
|
|
|
|
// the HTTP token.
|
|
|
|
HTTPTokenEnvName = "CONSUL_HTTP_TOKEN"
|
|
|
|
|
2019-04-26 17:49:28 +00:00
|
|
|
// HTTPTokenFileEnvName defines an environment variable name which sets
|
|
|
|
// the HTTP token file.
|
|
|
|
HTTPTokenFileEnvName = "CONSUL_HTTP_TOKEN_FILE"
|
|
|
|
|
2016-08-03 06:11:04 +00:00
|
|
|
// 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"
|
|
|
|
|
2017-04-14 20:37:29 +00:00
|
|
|
// 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"
|
|
|
|
|
2016-08-03 06:11:04 +00:00
|
|
|
// HTTPSSLVerifyEnvName defines an environment variable name which sets
|
|
|
|
// whether or not to disable certificate checking.
|
|
|
|
HTTPSSLVerifyEnvName = "CONSUL_HTTP_SSL_VERIFY"
|
2018-10-03 19:37:53 +00:00
|
|
|
|
|
|
|
// 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"
|
2019-12-18 16:06:39 +00:00
|
|
|
|
2022-11-18 20:36:20 +00:00
|
|
|
// 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"
|
|
|
|
|
2019-12-18 16:06:39 +00:00
|
|
|
// HTTPNamespaceEnvVar defines an environment variable name which sets
|
|
|
|
// the HTTP Namespace to be used by default. This can still be overridden.
|
|
|
|
HTTPNamespaceEnvName = "CONSUL_NAMESPACE"
|
2021-07-22 18:58:08 +00:00
|
|
|
|
|
|
|
// HTTPPartitionEnvName defines an environment variable name which sets
|
|
|
|
// the HTTP Partition to be used by default. This can still be overridden.
|
|
|
|
HTTPPartitionEnvName = "CONSUL_PARTITION"
|
2022-04-14 16:48:19 +00:00
|
|
|
|
|
|
|
// QueryBackendStreaming Query backend of type streaming
|
|
|
|
QueryBackendStreaming = "streaming"
|
|
|
|
|
|
|
|
// QueryBackendBlockingQuery Query backend of type blocking query
|
|
|
|
QueryBackendBlockingQuery = "blocking-query"
|
2016-08-03 06:10:11 +00:00
|
|
|
)
|
|
|
|
|
2021-09-20 21:04:13 +00:00
|
|
|
type StatusError struct {
|
|
|
|
Code int
|
|
|
|
Body string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e StatusError) Error() string {
|
|
|
|
return fmt.Sprintf("Unexpected response code: %d (%s)", e.Code, e.Body)
|
|
|
|
}
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// QueryOptions are used to parameterize a query
|
|
|
|
type QueryOptions struct {
|
2019-09-26 16:05:13 +00:00
|
|
|
// Namespace overrides the `default` namespace
|
|
|
|
// Note: Namespaces are available only in Consul Enterprise
|
|
|
|
Namespace string
|
|
|
|
|
2021-07-22 18:58:08 +00:00
|
|
|
// Partition overrides the `default` partition
|
|
|
|
// Note: Partitions are available only in Consul Enterprise
|
|
|
|
Partition string
|
|
|
|
|
2024-05-14 13:32:49 +00:00
|
|
|
// SamenessGroup is used find the SamenessGroup in the given
|
|
|
|
// Partition and will find the failover order for the Service
|
|
|
|
// from the SamenessGroup Members, with the given Partition being
|
|
|
|
// the first member.
|
|
|
|
// Note: SamenessGroups are available only in Consul Enterprise
|
|
|
|
SamenessGroup string
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// Providing a datacenter overwrites the DC provided
|
|
|
|
// by the Config
|
|
|
|
Datacenter string
|
|
|
|
|
2022-10-05 14:04:08 +00:00
|
|
|
// Providing a peer name in the query option
|
|
|
|
Peer string
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// AllowStale allows any Consul server (non-leader) to service
|
|
|
|
// a read. This allows for lower latency and higher throughput
|
|
|
|
AllowStale bool
|
|
|
|
|
|
|
|
// RequireConsistent forces the read to be fully consistent.
|
|
|
|
// This is more expensive but prevents ever performing a stale
|
|
|
|
// read.
|
|
|
|
RequireConsistent bool
|
|
|
|
|
2018-09-06 10:34:28 +00:00
|
|
|
// UseCache requests that the agent cache results locally. See
|
2019-06-13 21:56:19 +00:00
|
|
|
// https://www.consul.io/api/features/caching.html for more details on the
|
2018-09-06 10:34:28 +00:00
|
|
|
// semantics.
|
|
|
|
UseCache bool
|
|
|
|
|
|
|
|
// MaxAge limits how old a cached value will be returned if UseCache is true.
|
|
|
|
// If there is a cached response that is older than the MaxAge, it is treated
|
|
|
|
// as a cache miss and a new fetch invoked. If the fetch fails, the error is
|
|
|
|
// returned. Clients that wish to allow for stale results on error can set
|
2019-03-06 17:13:28 +00:00
|
|
|
// StaleIfError to a longer duration to change this behavior. It is ignored
|
2018-09-06 10:34:28 +00:00
|
|
|
// if the endpoint supports background refresh caching. See
|
2019-06-13 21:56:19 +00:00
|
|
|
// https://www.consul.io/api/features/caching.html for more details.
|
2018-09-06 10:34:28 +00:00
|
|
|
MaxAge time.Duration
|
|
|
|
|
|
|
|
// StaleIfError specifies how stale the client will accept a cached response
|
|
|
|
// if the servers are unavailable to fetch a fresh one. Only makes sense when
|
|
|
|
// UseCache is true and MaxAge is set to a lower, non-zero value. It is
|
|
|
|
// ignored if the endpoint supports background refresh caching. See
|
2019-06-13 21:56:19 +00:00
|
|
|
// https://www.consul.io/api/features/caching.html for more details.
|
2018-09-06 10:34:28 +00:00
|
|
|
StaleIfError time.Duration
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// WaitIndex is used to enable a blocking query. Waits
|
|
|
|
// until the timeout or the next index is reached
|
|
|
|
WaitIndex uint64
|
|
|
|
|
2018-04-20 13:24:24 +00:00
|
|
|
// WaitHash is used by some endpoints instead of WaitIndex to perform blocking
|
|
|
|
// on state based on a hash of the response rather than a monotonic index.
|
|
|
|
// This is required when the state being blocked on is not stored in Raft, for
|
|
|
|
// example agent-local proxy configuration.
|
|
|
|
WaitHash string
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// WaitTime is used to bound the duration of a wait.
|
2015-09-15 12:22:08 +00:00
|
|
|
// Defaults to that of the Config, but can be overridden.
|
2015-01-06 18:40:00 +00:00
|
|
|
WaitTime time.Duration
|
|
|
|
|
|
|
|
// Token is used to provide a per-request ACL token
|
|
|
|
// which overrides the agent's default token.
|
|
|
|
Token string
|
2015-10-16 04:42:09 +00:00
|
|
|
|
|
|
|
// Near is used to provide a node name that will sort the results
|
|
|
|
// in ascending order based on the estimated round trip time from
|
|
|
|
// that node. Setting this to "_agent" will use the agent's node
|
|
|
|
// for the sort.
|
|
|
|
Near string
|
2017-01-11 23:44:13 +00:00
|
|
|
|
|
|
|
// NodeMeta is used to filter results by nodes with the given
|
|
|
|
// metadata key/value pairs. Currently, only one key/value pair can
|
|
|
|
// be provided for filtering.
|
|
|
|
NodeMeta map[string]string
|
2017-02-08 23:25:47 +00:00
|
|
|
|
2018-02-19 07:13:57 +00:00
|
|
|
// RelayFactor is used in keyring operations to cause responses to be
|
2017-02-08 23:25:47 +00:00
|
|
|
// relayed back to the sender through N other random nodes. Must be
|
|
|
|
// a value from 0 to 5 (inclusive).
|
|
|
|
RelayFactor uint8
|
2017-06-26 20:52:03 +00:00
|
|
|
|
2019-08-12 18:11:11 +00:00
|
|
|
// LocalOnly is used in keyring list operation to force the keyring
|
|
|
|
// query to only hit local servers (no WAN traffic).
|
|
|
|
LocalOnly bool
|
|
|
|
|
2018-06-06 18:50:23 +00:00
|
|
|
// Connect filters prepared query execution to only include Connect-capable
|
|
|
|
// services. This currently affects prepared query execution.
|
|
|
|
Connect bool
|
|
|
|
|
2017-07-15 00:30:08 +00:00
|
|
|
// ctx is an optional context pass through to the underlying HTTP
|
|
|
|
// request layer. Use Context() and WithContext() to manage this.
|
|
|
|
ctx context.Context
|
2019-04-16 16:00:15 +00:00
|
|
|
|
|
|
|
// Filter requests filtering data prior to it being returned. The string
|
|
|
|
// is a go-bexpr compatible expression.
|
|
|
|
Filter string
|
2022-05-25 20:20:17 +00:00
|
|
|
|
|
|
|
// MergeCentralConfig returns a service definition merged with the
|
|
|
|
// proxy-defaults/global and service-defaults/:service config entries.
|
|
|
|
// This can be used to ensure a full service definition is returned in the response
|
|
|
|
// especially when the service might not be written into the catalog that way.
|
|
|
|
MergeCentralConfig bool
|
2023-02-08 20:07:21 +00:00
|
|
|
|
|
|
|
// Global is used to request information from all datacenters. Currently only
|
|
|
|
// used for operator usage requests.
|
|
|
|
Global bool
|
2017-07-15 00:30:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (o *QueryOptions) Context() context.Context {
|
|
|
|
if o != nil && o.ctx != nil {
|
|
|
|
return o.ctx
|
|
|
|
}
|
|
|
|
return context.Background()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (o *QueryOptions) WithContext(ctx context.Context) *QueryOptions {
|
|
|
|
o2 := new(QueryOptions)
|
|
|
|
if o != nil {
|
|
|
|
*o2 = *o
|
|
|
|
}
|
|
|
|
o2.ctx = ctx
|
|
|
|
return o2
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WriteOptions are used to parameterize a write
|
|
|
|
type WriteOptions struct {
|
2019-09-26 16:05:13 +00:00
|
|
|
// Namespace overrides the `default` namespace
|
|
|
|
// Note: Namespaces are available only in Consul Enterprise
|
|
|
|
Namespace string
|
|
|
|
|
2021-07-22 18:58:08 +00:00
|
|
|
// Partition overrides the `default` partition
|
|
|
|
// Note: Partitions are available only in Consul Enterprise
|
|
|
|
Partition string
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// Providing a datacenter overwrites the DC provided
|
|
|
|
// by the Config
|
|
|
|
Datacenter string
|
|
|
|
|
|
|
|
// Token is used to provide a per-request ACL token
|
|
|
|
// which overrides the agent's default token.
|
|
|
|
Token string
|
2017-02-08 23:25:47 +00:00
|
|
|
|
2018-03-19 16:56:00 +00:00
|
|
|
// RelayFactor is used in keyring operations to cause responses to be
|
2017-02-08 23:25:47 +00:00
|
|
|
// relayed back to the sender through N other random nodes. Must be
|
|
|
|
// a value from 0 to 5 (inclusive).
|
|
|
|
RelayFactor uint8
|
2017-07-15 00:30:08 +00:00
|
|
|
|
|
|
|
// ctx is an optional context pass through to the underlying HTTP
|
|
|
|
// request layer. Use Context() and WithContext() to manage this.
|
|
|
|
ctx context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
func (o *WriteOptions) Context() context.Context {
|
|
|
|
if o != nil && o.ctx != nil {
|
|
|
|
return o.ctx
|
|
|
|
}
|
|
|
|
return context.Background()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (o *WriteOptions) WithContext(ctx context.Context) *WriteOptions {
|
|
|
|
o2 := new(WriteOptions)
|
|
|
|
if o != nil {
|
|
|
|
*o2 = *o
|
|
|
|
}
|
|
|
|
o2.ctx = ctx
|
|
|
|
return o2
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// QueryMeta is used to return meta data about a query
|
|
|
|
type QueryMeta struct {
|
|
|
|
// LastIndex. This can be used as a WaitIndex to perform
|
|
|
|
// a blocking query
|
|
|
|
LastIndex uint64
|
|
|
|
|
2018-04-05 16:15:43 +00:00
|
|
|
// LastContentHash. This can be used as a WaitHash to perform a blocking query
|
|
|
|
// for endpoints that support hash-based blocking. Endpoints that do not
|
|
|
|
// support it will return an empty hash.
|
|
|
|
LastContentHash string
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// Time of last contact from the leader for the
|
|
|
|
// server servicing the request
|
|
|
|
LastContact time.Duration
|
|
|
|
|
|
|
|
// Is there a known leader
|
|
|
|
KnownLeader bool
|
|
|
|
|
|
|
|
// How long did the request take
|
|
|
|
RequestTime time.Duration
|
2016-08-16 18:31:41 +00:00
|
|
|
|
|
|
|
// Is address translation enabled for HTTP responses on this agent
|
|
|
|
AddressTranslationEnabled bool
|
2018-09-06 10:34:28 +00:00
|
|
|
|
|
|
|
// CacheHit is true if the result was served from agent-local cache.
|
|
|
|
CacheHit bool
|
|
|
|
|
|
|
|
// CacheAge is set if request was ?cached and indicates how stale the cached
|
|
|
|
// response is.
|
|
|
|
CacheAge time.Duration
|
2020-11-12 16:38:32 +00:00
|
|
|
|
2022-04-14 16:48:19 +00:00
|
|
|
// QueryBackend represent which backend served the request.
|
|
|
|
QueryBackend string
|
|
|
|
|
2020-11-12 16:38:32 +00:00
|
|
|
// DefaultACLPolicy is used to control the ACL interaction when there is no
|
|
|
|
// defined policy. This can be "allow" which means ACLs are used to
|
|
|
|
// deny-list, or "deny" which means ACLs are allow-lists.
|
|
|
|
DefaultACLPolicy string
|
2021-12-03 17:11:26 +00:00
|
|
|
|
|
|
|
// ResultsFilteredByACLs is true when some of the query's results were
|
|
|
|
// filtered out by enforcing ACLs. It may be false because nothing was
|
|
|
|
// removed, or because the endpoint does not yet support this flag.
|
|
|
|
ResultsFilteredByACLs bool
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WriteMeta is used to return meta data about a write
|
|
|
|
type WriteMeta struct {
|
|
|
|
// How long did the request take
|
|
|
|
RequestTime time.Duration
|
|
|
|
}
|
|
|
|
|
2015-01-07 21:01:44 +00:00
|
|
|
// HttpBasicAuth is used to authenticate http client with HTTP Basic Authentication
|
|
|
|
type HttpBasicAuth struct {
|
|
|
|
// Username to use for HTTP Basic Authentication
|
|
|
|
Username string
|
|
|
|
|
|
|
|
// Password to use for HTTP Basic Authentication
|
|
|
|
Password string
|
|
|
|
}
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// Config is used to configure the creation of a client
|
|
|
|
type Config struct {
|
|
|
|
// Address is the address of the Consul server
|
|
|
|
Address string
|
|
|
|
|
|
|
|
// Scheme is the URI scheme for the Consul server
|
|
|
|
Scheme string
|
|
|
|
|
2022-05-19 23:07:59 +00:00
|
|
|
// 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
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// Datacenter to use. If not provided, the default agent datacenter is used.
|
|
|
|
Datacenter string
|
|
|
|
|
2017-04-18 23:39:23 +00:00
|
|
|
// Transport is the Transport to use for the http client.
|
|
|
|
Transport *http.Transport
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// HttpClient is the client to use. Default will be
|
|
|
|
// used if not provided.
|
|
|
|
HttpClient *http.Client
|
|
|
|
|
2015-01-07 21:01:44 +00:00
|
|
|
// HttpAuth is the auth info to use for http access.
|
|
|
|
HttpAuth *HttpBasicAuth
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// 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
|
2017-04-14 20:37:29 +00:00
|
|
|
|
2019-04-26 17:49:28 +00:00
|
|
|
// 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
|
|
|
|
|
2019-11-25 17:57:35 +00:00
|
|
|
// Namespace is the name of the namespace to send along for the request
|
2020-11-16 23:37:19 +00:00
|
|
|
// when no other Namespace is present in the QueryOptions
|
2019-11-25 17:57:35 +00:00
|
|
|
Namespace string
|
|
|
|
|
2021-07-22 18:58:08 +00:00
|
|
|
// Partition is the name of the partition to send along for the request
|
|
|
|
// when no other Partition is present in the QueryOptions
|
|
|
|
Partition string
|
|
|
|
|
2017-04-14 20:37:29 +00:00
|
|
|
TLSConfig TLSConfig
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
2016-03-24 18:24:18 +00:00
|
|
|
// TLSConfig is used to generate a TLSClientConfig that's useful for talking to
|
|
|
|
// Consul using TLS.
|
|
|
|
type TLSConfig struct {
|
2016-03-24 18:33:44 +00:00
|
|
|
// Address is the optional address of the Consul server. The port, if any
|
|
|
|
// will be removed from here and this will be set to the ServerName of the
|
|
|
|
// resulting config.
|
2016-03-24 18:24:18 +00:00
|
|
|
Address string
|
|
|
|
|
|
|
|
// CAFile is the optional path to the CA certificate used for Consul
|
|
|
|
// communication, defaults to the system bundle if not specified.
|
|
|
|
CAFile string
|
|
|
|
|
2017-04-14 20:37:29 +00:00
|
|
|
// CAPath is the optional path to a directory of CA certificates to use for
|
|
|
|
// Consul communication, defaults to the system bundle if not specified.
|
|
|
|
CAPath string
|
|
|
|
|
2020-01-28 10:54:49 +00:00
|
|
|
// CAPem is the optional PEM-encoded CA certificate used for Consul
|
|
|
|
// communication, defaults to the system bundle if not specified.
|
|
|
|
CAPem []byte
|
|
|
|
|
2016-03-24 18:24:18 +00:00
|
|
|
// CertFile is the optional path to the certificate for Consul
|
|
|
|
// communication. If this is set then you need to also set KeyFile.
|
|
|
|
CertFile string
|
|
|
|
|
2020-01-28 10:54:49 +00:00
|
|
|
// CertPEM is the optional PEM-encoded certificate for Consul
|
|
|
|
// communication. If this is set then you need to also set KeyPEM.
|
|
|
|
CertPEM []byte
|
|
|
|
|
2016-03-24 18:24:18 +00:00
|
|
|
// KeyFile is the optional path to the private key for Consul communication.
|
|
|
|
// If this is set then you need to also set CertFile.
|
|
|
|
KeyFile string
|
|
|
|
|
2020-01-28 10:54:49 +00:00
|
|
|
// KeyPEM is the optional PEM-encoded private key for Consul communication.
|
|
|
|
// If this is set then you need to also set CertPEM.
|
|
|
|
KeyPEM []byte
|
|
|
|
|
2016-03-24 18:24:18 +00:00
|
|
|
// InsecureSkipVerify if set to true will disable TLS host verification.
|
|
|
|
InsecureSkipVerify bool
|
|
|
|
}
|
|
|
|
|
2016-03-10 20:29:50 +00:00
|
|
|
// 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
|
2018-11-06 21:34:36 +00:00
|
|
|
// use of the connections to Consul. If you don't reuse a client object, which
|
2016-03-10 20:29:50 +00:00
|
|
|
// is not recommended, then you may notice idle connections building up over
|
|
|
|
// time. To avoid this, use the DefaultNonPooledConfig() instead.
|
2015-01-06 18:40:00 +00:00
|
|
|
func DefaultConfig() *Config {
|
2020-01-28 23:50:41 +00:00
|
|
|
return defaultConfig(nil, cleanhttp.DefaultPooledTransport)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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 DefaultConfigWithLogger(logger hclog.Logger) *Config {
|
|
|
|
return defaultConfig(logger, cleanhttp.DefaultPooledTransport)
|
2016-03-10 20:29:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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 DefaultNonPooledConfig() *Config {
|
2020-01-28 23:50:41 +00:00
|
|
|
return defaultConfig(nil, cleanhttp.DefaultTransport)
|
2016-03-10 20:29:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// defaultConfig returns the default configuration for the client, using the
|
|
|
|
// given function to make the transport.
|
2020-01-28 23:50:41 +00:00
|
|
|
func defaultConfig(logger hclog.Logger, transportFn func() *http.Transport) *Config {
|
|
|
|
if logger == nil {
|
|
|
|
logger = hclog.New(&hclog.LoggerOptions{
|
|
|
|
Name: "consul-api",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2015-01-08 16:38:09 +00:00
|
|
|
config := &Config{
|
2017-04-21 01:59:42 +00:00
|
|
|
Address: "127.0.0.1:8500",
|
|
|
|
Scheme: "http",
|
2017-04-18 23:39:23 +00:00
|
|
|
Transport: transportFn(),
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
2015-01-08 16:38:09 +00:00
|
|
|
|
2016-08-03 06:10:11 +00:00
|
|
|
if addr := os.Getenv(HTTPAddrEnvName); addr != "" {
|
2015-01-16 01:24:15 +00:00
|
|
|
config.Address = addr
|
2015-01-08 16:38:09 +00:00
|
|
|
}
|
|
|
|
|
2019-04-26 17:49:28 +00:00
|
|
|
if tokenFile := os.Getenv(HTTPTokenFileEnvName); tokenFile != "" {
|
|
|
|
config.TokenFile = tokenFile
|
|
|
|
}
|
|
|
|
|
2016-08-03 06:11:04 +00:00
|
|
|
if token := os.Getenv(HTTPTokenEnvName); token != "" {
|
2015-03-18 14:41:00 +00:00
|
|
|
config.Token = token
|
|
|
|
}
|
|
|
|
|
2016-08-03 06:11:04 +00:00
|
|
|
if auth := os.Getenv(HTTPAuthEnvName); auth != "" {
|
2015-03-18 14:41:00 +00:00
|
|
|
var username, password string
|
|
|
|
if strings.Contains(auth, ":") {
|
|
|
|
split := strings.SplitN(auth, ":", 2)
|
|
|
|
username = split[0]
|
|
|
|
password = split[1]
|
|
|
|
} else {
|
|
|
|
username = auth
|
|
|
|
}
|
|
|
|
|
|
|
|
config.HttpAuth = &HttpBasicAuth{
|
|
|
|
Username: username,
|
|
|
|
Password: password,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-03 06:11:04 +00:00
|
|
|
if ssl := os.Getenv(HTTPSSLEnvName); ssl != "" {
|
2015-03-18 14:41:00 +00:00
|
|
|
enabled, err := strconv.ParseBool(ssl)
|
|
|
|
if err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
logger.Warn(fmt.Sprintf("could not parse %s", HTTPSSLEnvName), "error", err)
|
2015-03-18 14:41:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if enabled {
|
|
|
|
config.Scheme = "https"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-14 20:37:29 +00:00
|
|
|
if v := os.Getenv(HTTPTLSServerName); v != "" {
|
|
|
|
config.TLSConfig.Address = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv(HTTPCAFile); v != "" {
|
|
|
|
config.TLSConfig.CAFile = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv(HTTPCAPath); v != "" {
|
|
|
|
config.TLSConfig.CAPath = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv(HTTPClientCert); v != "" {
|
|
|
|
config.TLSConfig.CertFile = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv(HTTPClientKey); v != "" {
|
|
|
|
config.TLSConfig.KeyFile = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv(HTTPSSLVerifyEnvName); v != "" {
|
|
|
|
doVerify, err := strconv.ParseBool(v)
|
2015-03-18 14:41:00 +00:00
|
|
|
if err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
logger.Warn(fmt.Sprintf("could not parse %s", HTTPSSLVerifyEnvName), "error", err)
|
2015-03-18 14:41:00 +00:00
|
|
|
}
|
|
|
|
if !doVerify {
|
2017-04-14 20:37:29 +00:00
|
|
|
config.TLSConfig.InsecureSkipVerify = true
|
2015-03-18 14:41:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-18 16:06:39 +00:00
|
|
|
if v := os.Getenv(HTTPNamespaceEnvName); v != "" {
|
|
|
|
config.Namespace = v
|
|
|
|
}
|
|
|
|
|
2021-07-22 18:58:08 +00:00
|
|
|
if v := os.Getenv(HTTPPartitionEnvName); v != "" {
|
|
|
|
config.Partition = v
|
|
|
|
}
|
|
|
|
|
2015-01-08 16:38:09 +00:00
|
|
|
return config
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
2016-03-24 18:24:18 +00:00
|
|
|
// TLSConfig is used to generate a TLSClientConfig that's useful for talking to
|
|
|
|
// Consul using TLS.
|
|
|
|
func SetupTLSConfig(tlsConfig *TLSConfig) (*tls.Config, error) {
|
|
|
|
tlsClientConfig := &tls.Config{
|
|
|
|
InsecureSkipVerify: tlsConfig.InsecureSkipVerify,
|
|
|
|
}
|
|
|
|
|
|
|
|
if tlsConfig.Address != "" {
|
|
|
|
server := tlsConfig.Address
|
|
|
|
hasPort := strings.LastIndex(server, ":") > strings.LastIndex(server, "]")
|
|
|
|
if hasPort {
|
|
|
|
var err error
|
|
|
|
server, _, err = net.SplitHostPort(server)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
tlsClientConfig.ServerName = server
|
|
|
|
}
|
|
|
|
|
2020-01-28 10:54:49 +00:00
|
|
|
if len(tlsConfig.CertPEM) != 0 && len(tlsConfig.KeyPEM) != 0 {
|
|
|
|
tlsCert, err := tls.X509KeyPair(tlsConfig.CertPEM, tlsConfig.KeyPEM)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
tlsClientConfig.Certificates = []tls.Certificate{tlsCert}
|
|
|
|
} else if len(tlsConfig.CertPEM) != 0 || len(tlsConfig.KeyPEM) != 0 {
|
|
|
|
return nil, fmt.Errorf("both client cert and client key must be provided")
|
|
|
|
}
|
|
|
|
|
2016-03-24 18:24:18 +00:00
|
|
|
if tlsConfig.CertFile != "" && tlsConfig.KeyFile != "" {
|
|
|
|
tlsCert, err := tls.LoadX509KeyPair(tlsConfig.CertFile, tlsConfig.KeyFile)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
tlsClientConfig.Certificates = []tls.Certificate{tlsCert}
|
2020-01-28 10:54:49 +00:00
|
|
|
} else if tlsConfig.CertFile != "" || tlsConfig.KeyFile != "" {
|
|
|
|
return nil, fmt.Errorf("both client cert and client key must be provided")
|
2016-03-24 18:24:18 +00:00
|
|
|
}
|
|
|
|
|
2020-01-28 10:54:49 +00:00
|
|
|
if tlsConfig.CAFile != "" || tlsConfig.CAPath != "" || len(tlsConfig.CAPem) != 0 {
|
2017-11-08 02:22:09 +00:00
|
|
|
rootConfig := &rootcerts.Config{
|
2020-01-28 10:54:49 +00:00
|
|
|
CAFile: tlsConfig.CAFile,
|
|
|
|
CAPath: tlsConfig.CAPath,
|
|
|
|
CACertificate: tlsConfig.CAPem,
|
2017-11-08 02:22:09 +00:00
|
|
|
}
|
|
|
|
if err := rootcerts.ConfigureTLS(tlsClientConfig, rootConfig); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-03-24 18:24:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return tlsClientConfig, nil
|
|
|
|
}
|
|
|
|
|
2018-07-10 16:13:51 +00:00
|
|
|
func (c *Config) GenerateEnv() []string {
|
2018-07-11 13:22:47 +00:00
|
|
|
env := make([]string, 0, 10)
|
|
|
|
|
|
|
|
env = append(env,
|
|
|
|
fmt.Sprintf("%s=%s", HTTPAddrEnvName, c.Address),
|
|
|
|
fmt.Sprintf("%s=%s", HTTPTokenEnvName, c.Token),
|
2019-04-26 17:49:28 +00:00
|
|
|
fmt.Sprintf("%s=%s", HTTPTokenFileEnvName, c.TokenFile),
|
2018-07-11 13:22:47 +00:00
|
|
|
fmt.Sprintf("%s=%t", HTTPSSLEnvName, c.Scheme == "https"),
|
|
|
|
fmt.Sprintf("%s=%s", HTTPCAFile, c.TLSConfig.CAFile),
|
|
|
|
fmt.Sprintf("%s=%s", HTTPCAPath, c.TLSConfig.CAPath),
|
|
|
|
fmt.Sprintf("%s=%s", HTTPClientCert, c.TLSConfig.CertFile),
|
|
|
|
fmt.Sprintf("%s=%s", HTTPClientKey, c.TLSConfig.KeyFile),
|
|
|
|
fmt.Sprintf("%s=%s", HTTPTLSServerName, c.TLSConfig.Address),
|
|
|
|
fmt.Sprintf("%s=%t", HTTPSSLVerifyEnvName, !c.TLSConfig.InsecureSkipVerify))
|
2018-07-10 16:13:51 +00:00
|
|
|
|
|
|
|
if c.HttpAuth != nil {
|
2018-07-11 13:22:47 +00:00
|
|
|
env = append(env, fmt.Sprintf("%s=%s:%s", HTTPAuthEnvName, c.HttpAuth.Username, c.HttpAuth.Password))
|
2018-07-10 16:13:51 +00:00
|
|
|
} else {
|
2018-07-11 13:22:47 +00:00
|
|
|
env = append(env, fmt.Sprintf("%s=", HTTPAuthEnvName))
|
2018-07-10 16:13:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return env
|
|
|
|
}
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// Client provides a client to the Consul API
|
|
|
|
type Client struct {
|
2021-01-07 23:48:53 +00:00
|
|
|
modifyLock sync.RWMutex
|
|
|
|
headers http.Header
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
config Config
|
|
|
|
}
|
|
|
|
|
2021-01-07 23:48:53 +00:00
|
|
|
// Headers gets the current set of headers used for requests. This returns a
|
|
|
|
// copy; to modify it call AddHeader or SetHeaders.
|
|
|
|
func (c *Client) Headers() http.Header {
|
|
|
|
c.modifyLock.RLock()
|
|
|
|
defer c.modifyLock.RUnlock()
|
|
|
|
|
|
|
|
if c.headers == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
ret := make(http.Header)
|
|
|
|
for k, v := range c.headers {
|
|
|
|
for _, val := range v {
|
|
|
|
ret[k] = append(ret[k], val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddHeader allows a single header key/value pair to be added
|
|
|
|
// in a race-safe fashion.
|
|
|
|
func (c *Client) AddHeader(key, value string) {
|
|
|
|
c.modifyLock.Lock()
|
|
|
|
defer c.modifyLock.Unlock()
|
|
|
|
c.headers.Add(key, value)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetHeaders clears all previous headers and uses only the given
|
|
|
|
// ones going forward.
|
|
|
|
func (c *Client) SetHeaders(headers http.Header) {
|
|
|
|
c.modifyLock.Lock()
|
|
|
|
defer c.modifyLock.Unlock()
|
|
|
|
c.headers = headers
|
|
|
|
}
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// NewClient returns a new client
|
|
|
|
func NewClient(config *Config) (*Client, error) {
|
|
|
|
// bootstrap the config
|
|
|
|
defConfig := DefaultConfig()
|
|
|
|
|
2020-04-07 22:02:56 +00:00
|
|
|
if config.Address == "" {
|
2015-01-06 18:40:00 +00:00
|
|
|
config.Address = defConfig.Address
|
|
|
|
}
|
|
|
|
|
2020-04-07 22:02:56 +00:00
|
|
|
if config.Scheme == "" {
|
2015-01-06 18:40:00 +00:00
|
|
|
config.Scheme = defConfig.Scheme
|
|
|
|
}
|
|
|
|
|
2017-04-18 23:39:23 +00:00
|
|
|
if config.Transport == nil {
|
|
|
|
config.Transport = defConfig.Transport
|
|
|
|
}
|
|
|
|
|
2017-04-14 20:37:29 +00:00
|
|
|
if config.TLSConfig.Address == "" {
|
|
|
|
config.TLSConfig.Address = defConfig.TLSConfig.Address
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.TLSConfig.CAFile == "" {
|
|
|
|
config.TLSConfig.CAFile = defConfig.TLSConfig.CAFile
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.TLSConfig.CAPath == "" {
|
|
|
|
config.TLSConfig.CAPath = defConfig.TLSConfig.CAPath
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.TLSConfig.CertFile == "" {
|
|
|
|
config.TLSConfig.CertFile = defConfig.TLSConfig.CertFile
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.TLSConfig.KeyFile == "" {
|
|
|
|
config.TLSConfig.KeyFile = defConfig.TLSConfig.KeyFile
|
|
|
|
}
|
|
|
|
|
|
|
|
if !config.TLSConfig.InsecureSkipVerify {
|
|
|
|
config.TLSConfig.InsecureSkipVerify = defConfig.TLSConfig.InsecureSkipVerify
|
|
|
|
}
|
|
|
|
|
2017-04-18 23:39:23 +00:00
|
|
|
if config.HttpClient == nil {
|
|
|
|
var err error
|
|
|
|
config.HttpClient, err = NewHttpClient(config.Transport, config.TLSConfig)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-04-14 20:37:29 +00:00
|
|
|
}
|
|
|
|
|
2021-09-15 23:22:22 +00:00
|
|
|
if config.Namespace == "" {
|
|
|
|
config.Namespace = defConfig.Namespace
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.Partition == "" {
|
|
|
|
config.Partition = defConfig.Partition
|
|
|
|
}
|
|
|
|
|
2017-02-10 23:08:39 +00:00
|
|
|
parts := strings.SplitN(config.Address, "://", 2)
|
|
|
|
if len(parts) == 2 {
|
2017-02-11 00:55:54 +00:00
|
|
|
switch parts[0] {
|
|
|
|
case "http":
|
2020-04-07 22:02:56 +00:00
|
|
|
// Never revert to http if TLS was explicitly requested.
|
2017-02-11 00:55:54 +00:00
|
|
|
case "https":
|
2017-02-10 23:08:39 +00:00
|
|
|
config.Scheme = "https"
|
2017-02-11 00:55:54 +00:00
|
|
|
case "unix":
|
2017-02-10 23:08:39 +00:00
|
|
|
trans := cleanhttp.DefaultTransport()
|
2017-02-11 02:11:21 +00:00
|
|
|
trans.DialContext = func(_ context.Context, _, _ string) (net.Conn, error) {
|
2017-02-10 23:08:39 +00:00
|
|
|
return net.Dial("unix", parts[1])
|
|
|
|
}
|
2020-09-06 16:27:39 +00:00
|
|
|
httpClient, err := NewHttpClient(trans, config.TLSConfig)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2017-02-10 23:08:39 +00:00
|
|
|
}
|
2020-09-06 16:27:39 +00:00
|
|
|
config.HttpClient = httpClient
|
2017-02-11 00:55:54 +00:00
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("Unknown protocol scheme: %s", parts[0])
|
2015-12-17 06:27:07 +00:00
|
|
|
}
|
2015-12-17 15:56:50 +00:00
|
|
|
config.Address = parts[1]
|
2022-05-19 23:07:59 +00:00
|
|
|
|
|
|
|
// separate out a reverse proxy prefix, if it is present.
|
|
|
|
// NOTE: Rewriting this code to use url.Parse() instead of
|
|
|
|
// strings.SplitN() breaks existing test cases.
|
|
|
|
switch parts[0] {
|
|
|
|
case "http", "https":
|
|
|
|
parts := strings.SplitN(parts[1], "/", 2)
|
|
|
|
if len(parts) == 2 {
|
|
|
|
config.Address = parts[0]
|
|
|
|
config.PathPrefix = "/" + parts[1]
|
|
|
|
}
|
|
|
|
}
|
2015-01-08 16:38:09 +00:00
|
|
|
}
|
|
|
|
|
2019-04-26 17:49:28 +00:00
|
|
|
// If the TokenFile is set, always use that, even if a Token is configured.
|
|
|
|
// This is because when TokenFile is set it is read into the Token field.
|
|
|
|
// We want any derived clients to have to re-read the token file.
|
2022-12-02 17:19:52 +00:00
|
|
|
// The precedence of ACL token should be:
|
|
|
|
// 1. -token-file cli option
|
|
|
|
// 2. -token cli option
|
|
|
|
// 3. CONSUL_HTTP_TOKEN_FILE environment variable
|
|
|
|
// 4. CONSUL_HTTP_TOKEN environment variable
|
|
|
|
if config.TokenFile != "" && config.TokenFile != defConfig.TokenFile {
|
2022-10-27 13:25:18 +00:00
|
|
|
data, err := os.ReadFile(config.TokenFile)
|
2019-04-26 17:49:28 +00:00
|
|
|
if err != nil {
|
2022-12-02 17:19:52 +00:00
|
|
|
return nil, fmt.Errorf("Error loading token file %s : %s", config.TokenFile, err)
|
2019-04-26 17:49:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if token := strings.TrimSpace(string(data)); token != "" {
|
|
|
|
config.Token = token
|
|
|
|
}
|
2022-12-02 17:19:52 +00:00
|
|
|
} else if config.Token != "" && defConfig.Token != config.Token {
|
|
|
|
// Fall through
|
|
|
|
} else if defConfig.TokenFile != "" {
|
|
|
|
data, err := os.ReadFile(defConfig.TokenFile)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error loading token file %s : %s", defConfig.TokenFile, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if token := strings.TrimSpace(string(data)); token != "" {
|
|
|
|
config.Token = token
|
|
|
|
config.TokenFile = defConfig.TokenFile
|
|
|
|
}
|
|
|
|
} else {
|
2017-08-15 22:51:18 +00:00
|
|
|
config.Token = defConfig.Token
|
|
|
|
}
|
2021-01-07 23:48:53 +00:00
|
|
|
return &Client{config: *config, headers: make(http.Header)}, nil
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
2017-04-18 23:39:23 +00:00
|
|
|
// NewHttpClient returns an http client configured with the given Transport and TLS
|
|
|
|
// config.
|
|
|
|
func NewHttpClient(transport *http.Transport, tlsConf TLSConfig) (*http.Client, error) {
|
|
|
|
client := &http.Client{
|
|
|
|
Transport: transport,
|
|
|
|
}
|
|
|
|
|
2017-11-07 23:06:59 +00:00
|
|
|
// TODO (slackpad) - Once we get some run time on the HTTP/2 support we
|
|
|
|
// should turn it on by default if TLS is enabled. We would basically
|
|
|
|
// just need to call http2.ConfigureTransport(transport) here. We also
|
|
|
|
// don't want to introduce another external dependency on
|
|
|
|
// golang.org/x/net/http2 at this time. For a complete recipe for how
|
|
|
|
// to enable HTTP/2 support on a transport suitable for the API client
|
|
|
|
// library see agent/http_test.go:TestHTTPServer_H2.
|
|
|
|
|
2017-05-24 20:45:19 +00:00
|
|
|
if transport.TLSClientConfig == nil {
|
|
|
|
tlsClientConfig, err := SetupTLSConfig(&tlsConf)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
transport.TLSClientConfig = tlsClientConfig
|
|
|
|
}
|
|
|
|
|
2017-04-18 23:39:23 +00:00
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// request is used to help build up a request
|
|
|
|
type request struct {
|
|
|
|
config *Config
|
|
|
|
method string
|
|
|
|
url *url.URL
|
|
|
|
params url.Values
|
|
|
|
body io.Reader
|
2016-08-02 20:54:59 +00:00
|
|
|
header http.Header
|
2015-01-06 18:40:00 +00:00
|
|
|
obj interface{}
|
2017-06-26 20:52:03 +00:00
|
|
|
ctx context.Context
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// setQueryOptions is used to annotate the request with
|
|
|
|
// additional query options
|
|
|
|
func (r *request) setQueryOptions(q *QueryOptions) {
|
|
|
|
if q == nil {
|
|
|
|
return
|
|
|
|
}
|
2019-09-26 16:05:13 +00:00
|
|
|
if q.Namespace != "" {
|
Accept ap, datacenter, and namespace query params (#17525)
This commit only contains the OSS PR (datacenter query param support).
A separate enterprise PR adds support for ap and namespace query params.
Resources in Consul can exists within scopes such as datacenters, cluster
peers, admin partitions, and namespaces. You can refer to those resources from
interfaces such as the CLI, HTTP API, DNS, and configuration files.
Some scope levels have consistent naming: cluster peers are always referred to
as "peer".
Other scope levels use a short-hand in DNS lookups...
- "ns" for namespace
- "ap" for admin partition
- "dc" for datacenter
...But use long-hand in CLI commands:
- "namespace" for namespace
- "partition" for admin partition
- and "datacenter"
However, HTTP API query parameters do not follow a consistent pattern,
supporting short-hand for some scopes but long-hand for others:
- "ns" for namespace
- "partition" for admin partition
- and "dc" for datacenter.
This inconsistency is confusing, especially for users who have been exposed to
providing scope names through another interface such as CLI or DNS queries.
This commit improves UX by consistently supporting both short-hand and
long-hand forms of the namespace, partition, and datacenter scopes in HTTP API
query parameters.
2023-05-31 15:50:24 +00:00
|
|
|
// For backwards-compatibility with existing tests,
|
|
|
|
// use the short-hand query param name "ns"
|
|
|
|
// rather than the alternative long-hand "namespace"
|
2019-09-26 16:05:13 +00:00
|
|
|
r.params.Set("ns", q.Namespace)
|
|
|
|
}
|
2021-07-22 18:58:08 +00:00
|
|
|
if q.Partition != "" {
|
Accept ap, datacenter, and namespace query params (#17525)
This commit only contains the OSS PR (datacenter query param support).
A separate enterprise PR adds support for ap and namespace query params.
Resources in Consul can exists within scopes such as datacenters, cluster
peers, admin partitions, and namespaces. You can refer to those resources from
interfaces such as the CLI, HTTP API, DNS, and configuration files.
Some scope levels have consistent naming: cluster peers are always referred to
as "peer".
Other scope levels use a short-hand in DNS lookups...
- "ns" for namespace
- "ap" for admin partition
- "dc" for datacenter
...But use long-hand in CLI commands:
- "namespace" for namespace
- "partition" for admin partition
- and "datacenter"
However, HTTP API query parameters do not follow a consistent pattern,
supporting short-hand for some scopes but long-hand for others:
- "ns" for namespace
- "partition" for admin partition
- and "dc" for datacenter.
This inconsistency is confusing, especially for users who have been exposed to
providing scope names through another interface such as CLI or DNS queries.
This commit improves UX by consistently supporting both short-hand and
long-hand forms of the namespace, partition, and datacenter scopes in HTTP API
query parameters.
2023-05-31 15:50:24 +00:00
|
|
|
// For backwards-compatibility with existing tests,
|
|
|
|
// use the long-hand query param name "partition"
|
|
|
|
// rather than the alternative short-hand "ap"
|
2021-07-22 18:58:08 +00:00
|
|
|
r.params.Set("partition", q.Partition)
|
|
|
|
}
|
2024-05-14 13:32:49 +00:00
|
|
|
if q.SamenessGroup != "" {
|
|
|
|
// For backwards-compatibility with existing tests,
|
|
|
|
// use the long-hand query param name "sameness-group"
|
|
|
|
// rather than the alternative short-hand "sg"
|
|
|
|
r.params.Set("sameness-group", q.SamenessGroup)
|
|
|
|
}
|
2015-01-06 18:40:00 +00:00
|
|
|
if q.Datacenter != "" {
|
Accept ap, datacenter, and namespace query params (#17525)
This commit only contains the OSS PR (datacenter query param support).
A separate enterprise PR adds support for ap and namespace query params.
Resources in Consul can exists within scopes such as datacenters, cluster
peers, admin partitions, and namespaces. You can refer to those resources from
interfaces such as the CLI, HTTP API, DNS, and configuration files.
Some scope levels have consistent naming: cluster peers are always referred to
as "peer".
Other scope levels use a short-hand in DNS lookups...
- "ns" for namespace
- "ap" for admin partition
- "dc" for datacenter
...But use long-hand in CLI commands:
- "namespace" for namespace
- "partition" for admin partition
- and "datacenter"
However, HTTP API query parameters do not follow a consistent pattern,
supporting short-hand for some scopes but long-hand for others:
- "ns" for namespace
- "partition" for admin partition
- and "dc" for datacenter.
This inconsistency is confusing, especially for users who have been exposed to
providing scope names through another interface such as CLI or DNS queries.
This commit improves UX by consistently supporting both short-hand and
long-hand forms of the namespace, partition, and datacenter scopes in HTTP API
query parameters.
2023-05-31 15:50:24 +00:00
|
|
|
// For backwards-compatibility with existing tests,
|
|
|
|
// use the short-hand query param name "dc"
|
|
|
|
// rather than the alternative long-hand "datacenter"
|
2015-01-06 18:40:00 +00:00
|
|
|
r.params.Set("dc", q.Datacenter)
|
|
|
|
}
|
2022-10-05 14:04:08 +00:00
|
|
|
if q.Peer != "" {
|
|
|
|
r.params.Set("peer", q.Peer)
|
|
|
|
}
|
2015-01-06 18:40:00 +00:00
|
|
|
if q.AllowStale {
|
|
|
|
r.params.Set("stale", "")
|
|
|
|
}
|
|
|
|
if q.RequireConsistent {
|
|
|
|
r.params.Set("consistent", "")
|
|
|
|
}
|
|
|
|
if q.WaitIndex != 0 {
|
|
|
|
r.params.Set("index", strconv.FormatUint(q.WaitIndex, 10))
|
|
|
|
}
|
|
|
|
if q.WaitTime != 0 {
|
|
|
|
r.params.Set("wait", durToMsec(q.WaitTime))
|
|
|
|
}
|
2018-04-20 13:24:24 +00:00
|
|
|
if q.WaitHash != "" {
|
|
|
|
r.params.Set("hash", q.WaitHash)
|
|
|
|
}
|
2015-01-06 18:40:00 +00:00
|
|
|
if q.Token != "" {
|
2016-08-02 20:54:59 +00:00
|
|
|
r.header.Set("X-Consul-Token", q.Token)
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
2015-10-16 04:42:09 +00:00
|
|
|
if q.Near != "" {
|
|
|
|
r.params.Set("near", q.Near)
|
|
|
|
}
|
2019-04-16 16:00:15 +00:00
|
|
|
if q.Filter != "" {
|
|
|
|
r.params.Set("filter", q.Filter)
|
|
|
|
}
|
2017-01-11 23:44:13 +00:00
|
|
|
if len(q.NodeMeta) > 0 {
|
|
|
|
for key, value := range q.NodeMeta {
|
|
|
|
r.params.Add("node-meta", key+":"+value)
|
|
|
|
}
|
|
|
|
}
|
2017-02-08 23:25:47 +00:00
|
|
|
if q.RelayFactor != 0 {
|
|
|
|
r.params.Set("relay-factor", strconv.Itoa(int(q.RelayFactor)))
|
|
|
|
}
|
2019-08-12 18:11:11 +00:00
|
|
|
if q.LocalOnly {
|
|
|
|
r.params.Set("local-only", fmt.Sprintf("%t", q.LocalOnly))
|
|
|
|
}
|
2018-06-06 18:50:23 +00:00
|
|
|
if q.Connect {
|
|
|
|
r.params.Set("connect", "true")
|
|
|
|
}
|
2018-09-06 10:34:28 +00:00
|
|
|
if q.UseCache && !q.RequireConsistent {
|
|
|
|
r.params.Set("cached", "")
|
|
|
|
|
|
|
|
cc := []string{}
|
|
|
|
if q.MaxAge > 0 {
|
|
|
|
cc = append(cc, fmt.Sprintf("max-age=%.0f", q.MaxAge.Seconds()))
|
|
|
|
}
|
|
|
|
if q.StaleIfError > 0 {
|
|
|
|
cc = append(cc, fmt.Sprintf("stale-if-error=%.0f", q.StaleIfError.Seconds()))
|
|
|
|
}
|
|
|
|
if len(cc) > 0 {
|
|
|
|
r.header.Set("Cache-Control", strings.Join(cc, ", "))
|
|
|
|
}
|
|
|
|
}
|
2022-05-25 20:20:17 +00:00
|
|
|
if q.MergeCentralConfig {
|
|
|
|
r.params.Set("merge-central-config", "")
|
|
|
|
}
|
2023-02-08 20:07:21 +00:00
|
|
|
if q.Global {
|
|
|
|
r.params.Set("global", "")
|
|
|
|
}
|
2019-10-04 21:10:02 +00:00
|
|
|
|
2017-07-15 00:30:08 +00:00
|
|
|
r.ctx = q.ctx
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
2016-01-06 19:05:11 +00:00
|
|
|
// durToMsec converts a duration to a millisecond specified string. If the
|
|
|
|
// user selected a positive value that rounds to 0 ms, then we will use 1 ms
|
|
|
|
// so they get a short delay, otherwise Consul will translate the 0 ms into
|
|
|
|
// a huge default delay.
|
2015-01-06 18:40:00 +00:00
|
|
|
func durToMsec(dur time.Duration) string {
|
2016-01-06 19:05:11 +00:00
|
|
|
ms := dur / time.Millisecond
|
|
|
|
if dur > 0 && ms == 0 {
|
|
|
|
ms = 1
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%dms", ms)
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
2016-01-06 19:35:16 +00:00
|
|
|
// serverError is a string we look for to detect 500 errors.
|
|
|
|
const serverError = "Unexpected response code: 500"
|
|
|
|
|
2017-10-11 14:42:10 +00:00
|
|
|
// 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 IsRetryableError(err error) bool {
|
2016-01-06 19:35:16 +00:00
|
|
|
if err == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2017-10-11 14:42:10 +00:00
|
|
|
if _, ok := err.(net.Error); ok {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2016-01-06 19:35:16 +00:00
|
|
|
// TODO (slackpad) - Make a real error type here instead of using
|
|
|
|
// a string check.
|
|
|
|
return strings.Contains(err.Error(), serverError)
|
|
|
|
}
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// setWriteOptions is used to annotate the request with
|
|
|
|
// additional write options
|
|
|
|
func (r *request) setWriteOptions(q *WriteOptions) {
|
|
|
|
if q == nil {
|
|
|
|
return
|
|
|
|
}
|
Accept ap, datacenter, and namespace query params (#17525)
This commit only contains the OSS PR (datacenter query param support).
A separate enterprise PR adds support for ap and namespace query params.
Resources in Consul can exists within scopes such as datacenters, cluster
peers, admin partitions, and namespaces. You can refer to those resources from
interfaces such as the CLI, HTTP API, DNS, and configuration files.
Some scope levels have consistent naming: cluster peers are always referred to
as "peer".
Other scope levels use a short-hand in DNS lookups...
- "ns" for namespace
- "ap" for admin partition
- "dc" for datacenter
...But use long-hand in CLI commands:
- "namespace" for namespace
- "partition" for admin partition
- and "datacenter"
However, HTTP API query parameters do not follow a consistent pattern,
supporting short-hand for some scopes but long-hand for others:
- "ns" for namespace
- "partition" for admin partition
- and "dc" for datacenter.
This inconsistency is confusing, especially for users who have been exposed to
providing scope names through another interface such as CLI or DNS queries.
This commit improves UX by consistently supporting both short-hand and
long-hand forms of the namespace, partition, and datacenter scopes in HTTP API
query parameters.
2023-05-31 15:50:24 +00:00
|
|
|
// For backwards-compatibility, continue to use the shorthand "ns"
|
|
|
|
// rather than "namespace"
|
2019-09-26 16:05:13 +00:00
|
|
|
if q.Namespace != "" {
|
|
|
|
r.params.Set("ns", q.Namespace)
|
|
|
|
}
|
2021-07-22 18:58:08 +00:00
|
|
|
if q.Partition != "" {
|
|
|
|
r.params.Set("partition", q.Partition)
|
|
|
|
}
|
Accept ap, datacenter, and namespace query params (#17525)
This commit only contains the OSS PR (datacenter query param support).
A separate enterprise PR adds support for ap and namespace query params.
Resources in Consul can exists within scopes such as datacenters, cluster
peers, admin partitions, and namespaces. You can refer to those resources from
interfaces such as the CLI, HTTP API, DNS, and configuration files.
Some scope levels have consistent naming: cluster peers are always referred to
as "peer".
Other scope levels use a short-hand in DNS lookups...
- "ns" for namespace
- "ap" for admin partition
- "dc" for datacenter
...But use long-hand in CLI commands:
- "namespace" for namespace
- "partition" for admin partition
- and "datacenter"
However, HTTP API query parameters do not follow a consistent pattern,
supporting short-hand for some scopes but long-hand for others:
- "ns" for namespace
- "partition" for admin partition
- and "dc" for datacenter.
This inconsistency is confusing, especially for users who have been exposed to
providing scope names through another interface such as CLI or DNS queries.
This commit improves UX by consistently supporting both short-hand and
long-hand forms of the namespace, partition, and datacenter scopes in HTTP API
query parameters.
2023-05-31 15:50:24 +00:00
|
|
|
// For backwards-compatibility, continue to use the shorthand "dc"
|
|
|
|
// rather than "datacenter"
|
2015-01-06 18:40:00 +00:00
|
|
|
if q.Datacenter != "" {
|
|
|
|
r.params.Set("dc", q.Datacenter)
|
|
|
|
}
|
|
|
|
if q.Token != "" {
|
2016-08-02 20:54:59 +00:00
|
|
|
r.header.Set("X-Consul-Token", q.Token)
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
2017-02-08 23:25:47 +00:00
|
|
|
if q.RelayFactor != 0 {
|
2017-02-10 01:49:17 +00:00
|
|
|
r.params.Set("relay-factor", strconv.Itoa(int(q.RelayFactor)))
|
2017-02-08 23:25:47 +00:00
|
|
|
}
|
2017-07-15 00:30:08 +00:00
|
|
|
r.ctx = q.ctx
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// toHTTP converts the request to an HTTP request
|
|
|
|
func (r *request) toHTTP() (*http.Request, error) {
|
|
|
|
// Encode the query parameters
|
|
|
|
r.url.RawQuery = r.params.Encode()
|
|
|
|
|
|
|
|
// Check if we should encode the body
|
|
|
|
if r.body == nil && r.obj != nil {
|
2017-04-21 01:59:42 +00:00
|
|
|
b, err := encodeBody(r.obj)
|
|
|
|
if err != nil {
|
2015-01-06 18:40:00 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2017-04-21 01:59:42 +00:00
|
|
|
r.body = b
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create the HTTP request
|
2015-01-08 16:38:09 +00:00
|
|
|
req, err := http.NewRequest(r.method, r.url.RequestURI(), r.body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-07-14 20:53:27 +00:00
|
|
|
// validate that socket communications that do not use the host, detect
|
|
|
|
// slashes in the host name and replace it with local host.
|
|
|
|
// this is required since go started validating req.host in 1.20.6 and 1.19.11.
|
|
|
|
// prior to that they would strip out the slashes for you. They removed that
|
|
|
|
// behavior and added more strict validation as part of a CVE.
|
2023-07-24 21:27:19 +00:00
|
|
|
// This issue is being tracked by the Go team:
|
|
|
|
// https://github.com/golang/go/issues/61431
|
|
|
|
// If there is a resolution in this issue, we will remove this code.
|
|
|
|
// In the time being, this is the accepted workaround.
|
2023-07-14 20:53:27 +00:00
|
|
|
if strings.HasPrefix(r.url.Host, "/") {
|
|
|
|
r.url.Host = "localhost"
|
|
|
|
}
|
|
|
|
|
2015-01-08 16:38:09 +00:00
|
|
|
req.URL.Host = r.url.Host
|
|
|
|
req.URL.Scheme = r.url.Scheme
|
|
|
|
req.Host = r.url.Host
|
2016-08-02 20:54:59 +00:00
|
|
|
req.Header = r.header
|
2015-01-07 21:01:44 +00:00
|
|
|
|
2021-05-25 15:03:48 +00:00
|
|
|
// Content-Type must always be set when a body is present
|
|
|
|
// See https://github.com/hashicorp/consul/issues/10011
|
|
|
|
if req.Body != nil && req.Header.Get("Content-Type") == "" {
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
}
|
|
|
|
|
2015-01-07 21:01:44 +00:00
|
|
|
// Setup auth
|
2015-01-14 21:25:12 +00:00
|
|
|
if r.config.HttpAuth != nil {
|
2015-01-07 21:01:44 +00:00
|
|
|
req.SetBasicAuth(r.config.HttpAuth.Username, r.config.HttpAuth.Password)
|
|
|
|
}
|
2017-06-26 20:52:03 +00:00
|
|
|
if r.ctx != nil {
|
|
|
|
return req.WithContext(r.ctx), nil
|
|
|
|
}
|
2018-01-28 18:40:13 +00:00
|
|
|
|
|
|
|
return req, nil
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// newRequest is used to create a new request
|
|
|
|
func (c *Client) newRequest(method, path string) *request {
|
|
|
|
r := &request{
|
|
|
|
config: &c.config,
|
|
|
|
method: method,
|
|
|
|
url: &url.URL{
|
|
|
|
Scheme: c.config.Scheme,
|
|
|
|
Host: c.config.Address,
|
2022-05-19 23:07:59 +00:00
|
|
|
Path: c.config.PathPrefix + path,
|
2015-01-06 18:40:00 +00:00
|
|
|
},
|
|
|
|
params: make(map[string][]string),
|
2021-01-07 23:48:53 +00:00
|
|
|
header: c.Headers(),
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
2021-01-04 23:46:00 +00:00
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
if c.config.Datacenter != "" {
|
|
|
|
r.params.Set("dc", c.config.Datacenter)
|
|
|
|
}
|
2019-11-25 17:57:35 +00:00
|
|
|
if c.config.Namespace != "" {
|
|
|
|
r.params.Set("ns", c.config.Namespace)
|
|
|
|
}
|
2021-07-22 18:58:08 +00:00
|
|
|
if c.config.Partition != "" {
|
|
|
|
r.params.Set("partition", c.config.Partition)
|
|
|
|
}
|
2015-01-06 18:40:00 +00:00
|
|
|
if c.config.WaitTime != 0 {
|
|
|
|
r.params.Set("wait", durToMsec(r.config.WaitTime))
|
|
|
|
}
|
|
|
|
if c.config.Token != "" {
|
2016-08-02 20:54:59 +00:00
|
|
|
r.header.Set("X-Consul-Token", r.config.Token)
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
// doRequest runs a request with our client
|
|
|
|
func (c *Client) doRequest(r *request) (time.Duration, *http.Response, error) {
|
|
|
|
req, err := r.toHTTP()
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
|
|
|
start := time.Now()
|
|
|
|
resp, err := c.config.HttpClient.Do(req)
|
2017-10-17 18:38:24 +00:00
|
|
|
diff := time.Since(start)
|
2015-01-06 18:40:00 +00:00
|
|
|
return diff, resp, err
|
|
|
|
}
|
|
|
|
|
2015-02-11 21:53:33 +00:00
|
|
|
// Query is used to do a GET request against an endpoint
|
|
|
|
// and deserialize the response into an interface using
|
|
|
|
// standard Consul conventions.
|
|
|
|
func (c *Client) query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error) {
|
|
|
|
r := c.newRequest("GET", endpoint)
|
|
|
|
r.setQueryOptions(q)
|
2021-10-28 16:24:23 +00:00
|
|
|
rtt, resp, err := c.doRequest(r)
|
2015-02-11 21:53:33 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-06-14 22:49:32 +00:00
|
|
|
defer closeResponseBody(resp)
|
2021-10-28 16:24:23 +00:00
|
|
|
if err := requireOK(resp); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-02-11 21:53:33 +00:00
|
|
|
qm := &QueryMeta{}
|
|
|
|
parseQueryMeta(resp, qm)
|
|
|
|
qm.RequestTime = rtt
|
|
|
|
|
|
|
|
if err := decodeBody(resp, out); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return qm, nil
|
|
|
|
}
|
|
|
|
|
2015-02-11 22:01:29 +00:00
|
|
|
// write is used to do a PUT request against an endpoint
|
|
|
|
// and serialize/deserialized using the standard Consul conventions.
|
|
|
|
func (c *Client) write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error) {
|
|
|
|
r := c.newRequest("PUT", endpoint)
|
|
|
|
r.setWriteOptions(q)
|
|
|
|
r.obj = in
|
2021-10-28 16:24:23 +00:00
|
|
|
rtt, resp, err := c.doRequest(r)
|
2015-02-11 22:01:29 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-06-14 22:49:32 +00:00
|
|
|
defer closeResponseBody(resp)
|
2021-10-28 16:24:23 +00:00
|
|
|
if err := requireOK(resp); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-02-11 22:01:29 +00:00
|
|
|
|
|
|
|
wm := &WriteMeta{RequestTime: rtt}
|
|
|
|
if out != nil {
|
|
|
|
if err := decodeBody(resp, &out); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-10-27 13:25:18 +00:00
|
|
|
} else if _, err := io.ReadAll(resp.Body); err != nil {
|
2017-05-26 03:51:27 +00:00
|
|
|
return nil, err
|
2015-02-11 22:01:29 +00:00
|
|
|
}
|
|
|
|
return wm, nil
|
|
|
|
}
|
|
|
|
|
2024-03-05 14:52:55 +00:00
|
|
|
// delete is used to do a DELETE request against an endpoint
|
|
|
|
func (c *Client) delete(endpoint string, q *QueryOptions) (*WriteMeta, error) {
|
|
|
|
r := c.newRequest("DELETE", endpoint)
|
|
|
|
r.setQueryOptions(q)
|
|
|
|
rtt, resp, err := c.doRequest(r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer closeResponseBody(resp)
|
|
|
|
if err = requireHttpCodes(resp, 204, 200); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
wm := &WriteMeta{RequestTime: rtt}
|
|
|
|
return wm, nil
|
|
|
|
}
|
|
|
|
|
2015-01-06 18:40:00 +00:00
|
|
|
// parseQueryMeta is used to help parse query meta-data
|
2019-04-26 17:49:28 +00:00
|
|
|
//
|
|
|
|
// TODO(rb): bug? the error from this function is never handled
|
2015-01-06 18:40:00 +00:00
|
|
|
func parseQueryMeta(resp *http.Response, q *QueryMeta) error {
|
|
|
|
header := resp.Header
|
|
|
|
|
2018-04-05 16:15:43 +00:00
|
|
|
// Parse the X-Consul-Index (if it's set - hash based blocking queries don't
|
|
|
|
// set this)
|
|
|
|
if indexStr := header.Get("X-Consul-Index"); indexStr != "" {
|
|
|
|
index, err := strconv.ParseUint(indexStr, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to parse X-Consul-Index: %v", err)
|
|
|
|
}
|
|
|
|
q.LastIndex = index
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
2018-04-05 16:15:43 +00:00
|
|
|
q.LastContentHash = header.Get("X-Consul-ContentHash")
|
2015-01-06 18:40:00 +00:00
|
|
|
|
|
|
|
// Parse the X-Consul-LastContact
|
|
|
|
last, err := strconv.ParseUint(header.Get("X-Consul-LastContact"), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to parse X-Consul-LastContact: %v", err)
|
|
|
|
}
|
2024-06-04 21:55:53 +00:00
|
|
|
if last > math.MaxInt64 {
|
|
|
|
return fmt.Errorf("X-Consul-LastContact Header value is out of range: %d", last)
|
|
|
|
}
|
2015-01-06 18:40:00 +00:00
|
|
|
q.LastContact = time.Duration(last) * time.Millisecond
|
|
|
|
|
|
|
|
// Parse the X-Consul-KnownLeader
|
|
|
|
switch header.Get("X-Consul-KnownLeader") {
|
|
|
|
case "true":
|
|
|
|
q.KnownLeader = true
|
|
|
|
default:
|
|
|
|
q.KnownLeader = false
|
|
|
|
}
|
2016-08-16 18:31:41 +00:00
|
|
|
|
|
|
|
// Parse X-Consul-Translate-Addresses
|
|
|
|
switch header.Get("X-Consul-Translate-Addresses") {
|
|
|
|
case "true":
|
|
|
|
q.AddressTranslationEnabled = true
|
|
|
|
default:
|
|
|
|
q.AddressTranslationEnabled = false
|
|
|
|
}
|
2020-11-12 16:38:32 +00:00
|
|
|
|
|
|
|
// Parse X-Consul-Default-ACL-Policy
|
|
|
|
switch v := header.Get("X-Consul-Default-ACL-Policy"); v {
|
|
|
|
case "allow", "deny":
|
|
|
|
q.DefaultACLPolicy = v
|
|
|
|
}
|
2016-08-16 18:31:41 +00:00
|
|
|
|
2021-12-03 17:11:26 +00:00
|
|
|
// Parse the X-Consul-Results-Filtered-By-ACLs
|
|
|
|
switch header.Get("X-Consul-Results-Filtered-By-ACLs") {
|
|
|
|
case "true":
|
|
|
|
q.ResultsFilteredByACLs = true
|
|
|
|
default:
|
|
|
|
q.ResultsFilteredByACLs = false
|
|
|
|
}
|
|
|
|
|
2018-09-06 10:34:28 +00:00
|
|
|
// Parse Cache info
|
|
|
|
if cacheStr := header.Get("X-Cache"); cacheStr != "" {
|
|
|
|
q.CacheHit = strings.EqualFold(cacheStr, "HIT")
|
|
|
|
}
|
|
|
|
if ageStr := header.Get("Age"); ageStr != "" {
|
|
|
|
age, err := strconv.ParseUint(ageStr, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to parse Age Header: %v", err)
|
|
|
|
}
|
2024-06-04 21:55:53 +00:00
|
|
|
if age > math.MaxInt64 {
|
|
|
|
return fmt.Errorf("Age Header value is out of range: %d", last)
|
|
|
|
}
|
2018-09-06 10:34:28 +00:00
|
|
|
q.CacheAge = time.Duration(age) * time.Second
|
|
|
|
}
|
|
|
|
|
2022-04-14 16:48:19 +00:00
|
|
|
switch v := header.Get("X-Consul-Query-Backend"); v {
|
|
|
|
case QueryBackendStreaming, QueryBackendBlockingQuery:
|
|
|
|
q.QueryBackend = v
|
|
|
|
}
|
2015-01-06 18:40:00 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// decodeBody is used to JSON decode a body
|
|
|
|
func decodeBody(resp *http.Response, out interface{}) error {
|
|
|
|
dec := json.NewDecoder(resp.Body)
|
|
|
|
return dec.Decode(out)
|
|
|
|
}
|
|
|
|
|
|
|
|
// encodeBody is used to encode a request body
|
|
|
|
func encodeBody(obj interface{}) (io.Reader, error) {
|
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
enc := json.NewEncoder(buf)
|
|
|
|
if err := enc.Encode(obj); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return buf, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// requireOK is used to wrap doRequest and check for a 200
|
2021-10-28 16:24:23 +00:00
|
|
|
func requireOK(resp *http.Response) error {
|
|
|
|
return requireHttpCodes(resp, 200)
|
2021-09-20 21:04:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// requireHttpCodes checks for the "allowable" http codes for a response
|
2021-10-28 16:24:23 +00:00
|
|
|
func requireHttpCodes(resp *http.Response, httpCodes ...int) error {
|
2021-09-20 21:04:13 +00:00
|
|
|
// if there is an http code that we require, return w no error
|
|
|
|
for _, httpCode := range httpCodes {
|
|
|
|
if resp.StatusCode == httpCode {
|
2021-10-28 16:24:23 +00:00
|
|
|
return nil
|
2021-09-20 21:04:13 +00:00
|
|
|
}
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
2021-09-20 21:04:13 +00:00
|
|
|
|
|
|
|
// if we reached here, then none of the http codes in resp matched any that we expected
|
|
|
|
// so err out
|
2021-10-28 16:24:23 +00:00
|
|
|
return generateUnexpectedResponseCodeError(resp)
|
2015-01-06 18:40:00 +00:00
|
|
|
}
|
2019-04-16 16:00:15 +00:00
|
|
|
|
2021-06-14 22:49:32 +00:00
|
|
|
// closeResponseBody reads resp.Body until EOF, and then closes it. The read
|
|
|
|
// is necessary to ensure that the http.Client's underlying RoundTripper is able
|
|
|
|
// to re-use the TCP connection. See godoc on net/http.Client.Do.
|
|
|
|
func closeResponseBody(resp *http.Response) error {
|
2022-10-27 13:25:18 +00:00
|
|
|
_, _ = io.Copy(io.Discard, resp.Body)
|
2021-06-14 22:49:32 +00:00
|
|
|
return resp.Body.Close()
|
|
|
|
}
|
|
|
|
|
2019-04-16 16:00:15 +00:00
|
|
|
func (req *request) filterQuery(filter string) {
|
|
|
|
if filter == "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
req.params.Set("filter", filter)
|
|
|
|
}
|
2019-04-15 20:43:19 +00:00
|
|
|
|
|
|
|
// generateUnexpectedResponseCodeError consumes the rest of the body, closes
|
|
|
|
// the body stream and generates an error indicating the status code was
|
|
|
|
// unexpected.
|
|
|
|
func generateUnexpectedResponseCodeError(resp *http.Response) error {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
io.Copy(&buf, resp.Body)
|
2021-06-14 22:49:32 +00:00
|
|
|
closeResponseBody(resp)
|
2021-09-15 00:45:39 +00:00
|
|
|
|
|
|
|
trimmed := strings.TrimSpace(string(buf.Bytes()))
|
2021-09-20 21:04:13 +00:00
|
|
|
return StatusError{Code: resp.StatusCode, Body: trimmed}
|
2019-04-15 20:43:19 +00:00
|
|
|
}
|
|
|
|
|
2021-10-28 16:24:23 +00:00
|
|
|
func requireNotFoundOrOK(resp *http.Response) (bool, *http.Response, error) {
|
2019-04-15 20:43:19 +00:00
|
|
|
switch resp.StatusCode {
|
|
|
|
case 200:
|
2021-10-28 16:24:23 +00:00
|
|
|
return true, resp, nil
|
2019-04-15 20:43:19 +00:00
|
|
|
case 404:
|
2021-10-28 16:24:23 +00:00
|
|
|
return false, resp, nil
|
2019-04-15 20:43:19 +00:00
|
|
|
default:
|
2021-10-28 16:24:23 +00:00
|
|
|
return false, nil, generateUnexpectedResponseCodeError(resp)
|
2019-04-15 20:43:19 +00:00
|
|
|
}
|
|
|
|
}
|