2015-09-06 20:29:51 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2016-05-24 17:26:53 +00:00
|
|
|
"compress/gzip"
|
2020-09-09 20:22:07 +00:00
|
|
|
"context"
|
2016-10-25 00:07:44 +00:00
|
|
|
"crypto/tls"
|
2015-09-06 20:29:51 +00:00
|
|
|
"encoding/json"
|
2019-11-08 15:04:15 +00:00
|
|
|
"errors"
|
2015-09-06 20:29:51 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2018-02-07 02:51:34 +00:00
|
|
|
"net"
|
2015-09-06 20:29:51 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
2016-08-17 19:11:59 +00:00
|
|
|
"strings"
|
2015-09-06 20:29:51 +00:00
|
|
|
"time"
|
2015-10-22 14:58:23 +00:00
|
|
|
|
2019-04-28 21:34:01 +00:00
|
|
|
"github.com/gorilla/websocket"
|
2022-06-25 14:20:52 +00:00
|
|
|
"github.com/hashicorp/go-cleanhttp"
|
|
|
|
"github.com/hashicorp/go-rootcerts"
|
2015-09-06 20:29:51 +00:00
|
|
|
)
|
|
|
|
|
2018-02-07 02:51:34 +00:00
|
|
|
var (
|
|
|
|
// ClientConnTimeout is the timeout applied when attempting to contact a
|
|
|
|
// client directly before switching to a connection through the Nomad
|
2022-08-15 20:06:02 +00:00
|
|
|
// server. For cluster topologies where API consumers don't have network
|
|
|
|
// access to Nomad clients, set this to a small value (ex 1ms) to avoid
|
|
|
|
// pausing on client APIs such as AllocFS.
|
2018-02-07 02:51:34 +00:00
|
|
|
ClientConnTimeout = 1 * time.Second
|
|
|
|
)
|
|
|
|
|
2020-06-17 19:39:50 +00:00
|
|
|
const (
|
|
|
|
// AllNamespacesNamespace is a sentinel Namespace value to indicate that api should search for
|
|
|
|
// jobs and allocations in all the namespaces the requester can access.
|
|
|
|
AllNamespacesNamespace = "*"
|
2022-08-02 14:33:08 +00:00
|
|
|
|
|
|
|
// PermissionDeniedErrorContent is the string content of an error returned
|
|
|
|
// by the API which indicates the caller does not have permission to
|
|
|
|
// perform the action.
|
|
|
|
PermissionDeniedErrorContent = "Permission denied"
|
2020-06-17 19:39:50 +00:00
|
|
|
)
|
|
|
|
|
2019-03-27 20:24:32 +00:00
|
|
|
// QueryOptions are used to parametrize a query
|
2015-09-06 20:29:51 +00:00
|
|
|
type QueryOptions struct {
|
|
|
|
// Providing a datacenter overwrites the region provided
|
|
|
|
// by the Config
|
|
|
|
Region string
|
|
|
|
|
2017-09-07 23:56:15 +00:00
|
|
|
// Namespace is the target namespace for the query.
|
|
|
|
Namespace string
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// AllowStale allows any Nomad server (non-leader) to service
|
|
|
|
// a read. This allows for lower latency and higher throughput
|
|
|
|
AllowStale bool
|
|
|
|
|
|
|
|
// WaitIndex is used to enable a blocking query. Waits
|
|
|
|
// until the timeout or the next index is reached
|
|
|
|
WaitIndex uint64
|
|
|
|
|
|
|
|
// WaitTime is used to bound the duration of a wait.
|
2016-05-15 16:41:34 +00:00
|
|
|
// Defaults to that of the Config, but can be overridden.
|
2015-09-06 20:29:51 +00:00
|
|
|
WaitTime time.Duration
|
2015-12-22 22:44:33 +00:00
|
|
|
|
|
|
|
// If set, used as prefix for resource list searches
|
|
|
|
Prefix string
|
2016-07-28 21:24:01 +00:00
|
|
|
|
|
|
|
// Set HTTP parameters on the query.
|
|
|
|
Params map[string]string
|
2017-08-21 04:39:36 +00:00
|
|
|
|
2022-03-01 13:47:01 +00:00
|
|
|
// Set HTTP headers on the query.
|
|
|
|
Headers map[string]string
|
|
|
|
|
2017-10-12 22:16:33 +00:00
|
|
|
// AuthToken is the secret ID of an ACL token
|
|
|
|
AuthToken string
|
2020-09-09 20:22:07 +00:00
|
|
|
|
2022-02-16 16:40:30 +00:00
|
|
|
// Filter specifies the go-bexpr filter expression to be used for
|
|
|
|
// filtering the data prior to returning a response
|
|
|
|
Filter string
|
|
|
|
|
2021-03-23 13:45:14 +00:00
|
|
|
// PerPage is the number of entries to be returned in queries that support
|
|
|
|
// paginated lists.
|
|
|
|
PerPage int32
|
|
|
|
|
2021-12-10 18:43:03 +00:00
|
|
|
// NextToken is the token used to indicate where to start paging
|
|
|
|
// for queries that support paginated lists. This token should be
|
|
|
|
// the ID of the next object after the last one seen in the
|
|
|
|
// previous response.
|
2021-03-23 13:45:14 +00:00
|
|
|
NextToken string
|
|
|
|
|
2022-03-09 01:54:17 +00:00
|
|
|
// Reverse is used to reverse the default order of list results.
|
2022-02-10 17:50:34 +00:00
|
|
|
//
|
2022-03-09 01:54:17 +00:00
|
|
|
// Currently only supported by specific endpoints.
|
|
|
|
Reverse bool
|
2022-02-10 17:50:34 +00:00
|
|
|
|
2020-09-09 20:22:07 +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
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
2019-03-27 20:24:32 +00:00
|
|
|
// WriteOptions are used to parametrize a write
|
2015-09-06 20:29:51 +00:00
|
|
|
type WriteOptions struct {
|
|
|
|
// Providing a datacenter overwrites the region provided
|
|
|
|
// by the Config
|
|
|
|
Region string
|
2017-08-21 04:39:36 +00:00
|
|
|
|
2017-09-07 23:56:15 +00:00
|
|
|
// Namespace is the target namespace for the write.
|
|
|
|
Namespace string
|
|
|
|
|
2017-10-12 22:16:33 +00:00
|
|
|
// AuthToken is the secret ID of an ACL token
|
|
|
|
AuthToken string
|
2020-09-09 20:22:07 +00:00
|
|
|
|
2022-03-01 13:47:01 +00:00
|
|
|
// Set HTTP headers on the query.
|
|
|
|
Headers map[string]string
|
|
|
|
|
2020-09-09 20:22:07 +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
|
2021-06-30 19:23:37 +00:00
|
|
|
|
|
|
|
// IdempotencyToken can be used to ensure the write is idempotent.
|
|
|
|
IdempotencyToken string
|
2015-09-06 20:29:51 +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
|
|
|
|
|
|
|
|
// 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
|
2021-12-10 18:43:03 +00:00
|
|
|
|
|
|
|
// NextToken is the token used to indicate where to start paging
|
|
|
|
// for queries that support paginated lists. To resume paging from
|
|
|
|
// this point, pass this token in the next request's QueryOptions
|
|
|
|
NextToken string
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WriteMeta is used to return meta data about a write
|
|
|
|
type WriteMeta struct {
|
|
|
|
// LastIndex. This can be used as a WaitIndex to perform
|
|
|
|
// a blocking query
|
|
|
|
LastIndex uint64
|
|
|
|
|
|
|
|
// How long did the request take
|
|
|
|
RequestTime time.Duration
|
|
|
|
}
|
|
|
|
|
2016-08-17 19:11:59 +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-09-06 20:29:51 +00:00
|
|
|
// Config is used to configure the creation of a client
|
|
|
|
type Config struct {
|
2015-09-14 20:13:52 +00:00
|
|
|
// Address is the address of the Nomad agent
|
|
|
|
Address string
|
2015-09-06 20:29:51 +00:00
|
|
|
|
|
|
|
// Region to use. If not provided, the default agent region is used.
|
|
|
|
Region string
|
|
|
|
|
2017-09-13 18:38:29 +00:00
|
|
|
// SecretID to use. This can be overwritten per request.
|
|
|
|
SecretID string
|
|
|
|
|
2017-09-07 23:56:15 +00:00
|
|
|
// Namespace to use. If not provided the default namespace is used.
|
|
|
|
Namespace string
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
// HttpClient is the client to use. Default will be used if not provided.
|
|
|
|
//
|
|
|
|
// If set, it expected to be configured for tls already, and TLSConfig is ignored.
|
|
|
|
// You may use ConfigureTLS() function to aid with initialization.
|
|
|
|
HttpClient *http.Client
|
2015-09-06 20:29:51 +00:00
|
|
|
|
2016-08-17 19:11:59 +00:00
|
|
|
// HttpAuth is the auth info to use for http access.
|
|
|
|
HttpAuth *HttpBasicAuth
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// WaitTime limits how long a Watch will block. If not provided,
|
|
|
|
// the agent default values will be used.
|
|
|
|
WaitTime time.Duration
|
2016-10-25 00:07:44 +00:00
|
|
|
|
|
|
|
// TLSConfig provides the various TLS related configurations for the http
|
2019-01-19 00:01:12 +00:00
|
|
|
// client.
|
|
|
|
//
|
|
|
|
// TLSConfig is ignored if HttpClient is set.
|
2016-10-25 00:07:44 +00:00
|
|
|
TLSConfig *TLSConfig
|
2021-01-05 01:07:35 +00:00
|
|
|
|
2021-01-06 01:39:18 +00:00
|
|
|
Headers http.Header
|
2016-10-25 00:07:44 +00:00
|
|
|
}
|
|
|
|
|
2017-08-28 21:58:15 +00:00
|
|
|
// ClientConfig copies the configuration with a new client address, region, and
|
2018-02-14 17:47:17 +00:00
|
|
|
// whether the client has TLS enabled.
|
|
|
|
func (c *Config) ClientConfig(region, address string, tlsEnabled bool) *Config {
|
2016-10-26 18:13:53 +00:00
|
|
|
scheme := "http"
|
|
|
|
if tlsEnabled {
|
|
|
|
scheme = "https"
|
|
|
|
}
|
|
|
|
config := &Config{
|
|
|
|
Address: fmt.Sprintf("%s://%s", scheme, address),
|
2017-08-28 21:41:21 +00:00
|
|
|
Region: region,
|
2017-09-07 23:56:15 +00:00
|
|
|
Namespace: c.Namespace,
|
2019-01-19 00:01:12 +00:00
|
|
|
HttpClient: c.HttpClient,
|
2017-08-25 00:03:29 +00:00
|
|
|
SecretID: c.SecretID,
|
2016-10-26 18:13:53 +00:00
|
|
|
HttpAuth: c.HttpAuth,
|
|
|
|
WaitTime: c.WaitTime,
|
2017-08-28 21:41:21 +00:00
|
|
|
TLSConfig: c.TLSConfig.Copy(),
|
2016-10-26 18:13:53 +00:00
|
|
|
}
|
2018-02-07 02:51:34 +00:00
|
|
|
|
2018-02-14 17:47:17 +00:00
|
|
|
// Update the tls server name for connecting to a client
|
2017-08-29 18:11:19 +00:00
|
|
|
if tlsEnabled && config.TLSConfig != nil {
|
|
|
|
config.TLSConfig.TLSServerName = fmt.Sprintf("client.%s.nomad", region)
|
|
|
|
}
|
2016-10-26 18:13:53 +00:00
|
|
|
|
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
2016-10-25 00:07:44 +00:00
|
|
|
// TLSConfig contains the parameters needed to configure TLS on the HTTP client
|
|
|
|
// used to communicate with Nomad.
|
|
|
|
type TLSConfig struct {
|
|
|
|
// CACert is the path to a PEM-encoded CA cert file to use to verify the
|
|
|
|
// Nomad server SSL certificate.
|
|
|
|
CACert string
|
|
|
|
|
|
|
|
// CAPath is the path to a directory of PEM-encoded CA cert files to verify
|
|
|
|
// the Nomad server SSL certificate.
|
|
|
|
CAPath string
|
|
|
|
|
2019-12-16 13:30:00 +00:00
|
|
|
// CACertPem is the PEM-encoded CA cert to use to verify the Nomad server
|
2019-12-16 09:59:27 +00:00
|
|
|
// SSL certificate.
|
2019-12-16 13:30:00 +00:00
|
|
|
CACertPEM []byte
|
2019-12-16 09:59:27 +00:00
|
|
|
|
2016-10-25 00:07:44 +00:00
|
|
|
// ClientCert is the path to the certificate for Nomad communication
|
|
|
|
ClientCert string
|
|
|
|
|
2019-12-16 13:30:00 +00:00
|
|
|
// ClientCertPEM is the PEM-encoded certificate for Nomad communication
|
|
|
|
ClientCertPEM []byte
|
|
|
|
|
2016-10-25 00:07:44 +00:00
|
|
|
// ClientKey is the path to the private key for Nomad communication
|
|
|
|
ClientKey string
|
|
|
|
|
2019-12-16 13:30:00 +00:00
|
|
|
// ClientKeyPEM is the PEM-encoded private key for Nomad communication
|
|
|
|
ClientKeyPEM []byte
|
|
|
|
|
2016-10-25 00:07:44 +00:00
|
|
|
// TLSServerName, if set, is used to set the SNI host when connecting via
|
|
|
|
// TLS.
|
|
|
|
TLSServerName string
|
|
|
|
|
|
|
|
// Insecure enables or disables SSL verification
|
|
|
|
Insecure bool
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
2017-08-28 21:41:21 +00:00
|
|
|
func (t *TLSConfig) Copy() *TLSConfig {
|
|
|
|
if t == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
nt := new(TLSConfig)
|
|
|
|
*nt = *t
|
|
|
|
return nt
|
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
func defaultHttpClient() *http.Client {
|
2022-04-06 20:14:53 +00:00
|
|
|
httpClient := cleanhttp.DefaultPooledClient()
|
2019-01-19 00:01:12 +00:00
|
|
|
transport := httpClient.Transport.(*http.Transport)
|
2016-10-25 00:07:44 +00:00
|
|
|
transport.TLSHandshakeTimeout = 10 * time.Second
|
|
|
|
transport.TLSClientConfig = &tls.Config{
|
|
|
|
MinVersion: tls.VersionTLS12,
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
2016-10-25 00:07:44 +00:00
|
|
|
|
2021-07-28 15:21:53 +00:00
|
|
|
// Default to http/1: alloc exec/websocket aren't supported in http/2
|
|
|
|
// well yet: https://github.com/gorilla/websocket/issues/417
|
|
|
|
transport.ForceAttemptHTTP2 = false
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
return httpClient
|
|
|
|
}
|
|
|
|
|
|
|
|
// DefaultConfig returns a default configuration for the client
|
|
|
|
func DefaultConfig() *Config {
|
|
|
|
config := &Config{
|
|
|
|
Address: "http://127.0.0.1:4646",
|
|
|
|
TLSConfig: &TLSConfig{},
|
|
|
|
}
|
2015-09-14 20:13:52 +00:00
|
|
|
if addr := os.Getenv("NOMAD_ADDR"); addr != "" {
|
|
|
|
config.Address = addr
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
2017-09-07 23:56:15 +00:00
|
|
|
if v := os.Getenv("NOMAD_REGION"); v != "" {
|
|
|
|
config.Region = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv("NOMAD_NAMESPACE"); v != "" {
|
|
|
|
config.Namespace = v
|
|
|
|
}
|
2016-08-17 19:11:59 +00:00
|
|
|
if auth := os.Getenv("NOMAD_HTTP_AUTH"); auth != "" {
|
|
|
|
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-10-25 00:07:44 +00:00
|
|
|
|
|
|
|
// Read TLS specific env vars
|
|
|
|
if v := os.Getenv("NOMAD_CACERT"); v != "" {
|
|
|
|
config.TLSConfig.CACert = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv("NOMAD_CAPATH"); v != "" {
|
|
|
|
config.TLSConfig.CAPath = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv("NOMAD_CLIENT_CERT"); v != "" {
|
|
|
|
config.TLSConfig.ClientCert = v
|
|
|
|
}
|
|
|
|
if v := os.Getenv("NOMAD_CLIENT_KEY"); v != "" {
|
|
|
|
config.TLSConfig.ClientKey = v
|
|
|
|
}
|
2019-09-24 14:05:40 +00:00
|
|
|
if v := os.Getenv("NOMAD_TLS_SERVER_NAME"); v != "" {
|
|
|
|
config.TLSConfig.TLSServerName = v
|
|
|
|
}
|
2016-10-25 00:07:44 +00:00
|
|
|
if v := os.Getenv("NOMAD_SKIP_VERIFY"); v != "" {
|
|
|
|
if insecure, err := strconv.ParseBool(v); err == nil {
|
|
|
|
config.TLSConfig.Insecure = insecure
|
|
|
|
}
|
|
|
|
}
|
2017-08-25 00:03:29 +00:00
|
|
|
if v := os.Getenv("NOMAD_TOKEN"); v != "" {
|
|
|
|
config.SecretID = v
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
// cloneWithTimeout returns a cloned httpClient with set timeout if positive;
|
|
|
|
// otherwise, returns the same client
|
|
|
|
func cloneWithTimeout(httpClient *http.Client, t time.Duration) (*http.Client, error) {
|
|
|
|
if httpClient == nil {
|
2022-08-05 15:05:47 +00:00
|
|
|
return nil, errors.New("nil HTTP client")
|
2019-01-19 00:01:12 +00:00
|
|
|
} else if httpClient.Transport == nil {
|
2022-08-05 15:05:47 +00:00
|
|
|
return nil, errors.New("nil HTTP client transport")
|
2018-02-14 17:47:17 +00:00
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
if t.Nanoseconds() < 0 {
|
|
|
|
return httpClient, nil
|
2018-02-14 17:47:17 +00:00
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
tr, ok := httpClient.Transport.(*http.Transport)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("unexpected HTTP transport: %T", httpClient.Transport)
|
|
|
|
}
|
|
|
|
|
|
|
|
// copy all public fields, to avoid copying transient state and locks
|
|
|
|
ntr := &http.Transport{
|
|
|
|
Proxy: tr.Proxy,
|
|
|
|
DialContext: tr.DialContext,
|
|
|
|
Dial: tr.Dial,
|
|
|
|
DialTLS: tr.DialTLS,
|
|
|
|
TLSClientConfig: tr.TLSClientConfig,
|
|
|
|
TLSHandshakeTimeout: tr.TLSHandshakeTimeout,
|
|
|
|
DisableKeepAlives: tr.DisableKeepAlives,
|
|
|
|
DisableCompression: tr.DisableCompression,
|
|
|
|
MaxIdleConns: tr.MaxIdleConns,
|
|
|
|
MaxIdleConnsPerHost: tr.MaxIdleConnsPerHost,
|
|
|
|
MaxConnsPerHost: tr.MaxConnsPerHost,
|
|
|
|
IdleConnTimeout: tr.IdleConnTimeout,
|
|
|
|
ResponseHeaderTimeout: tr.ResponseHeaderTimeout,
|
|
|
|
ExpectContinueTimeout: tr.ExpectContinueTimeout,
|
|
|
|
TLSNextProto: tr.TLSNextProto,
|
|
|
|
ProxyConnectHeader: tr.ProxyConnectHeader,
|
|
|
|
MaxResponseHeaderBytes: tr.MaxResponseHeaderBytes,
|
|
|
|
}
|
|
|
|
|
|
|
|
// apply timeout
|
|
|
|
ntr.DialContext = (&net.Dialer{
|
|
|
|
Timeout: t,
|
|
|
|
KeepAlive: 30 * time.Second,
|
|
|
|
}).DialContext
|
|
|
|
|
|
|
|
// clone http client with new transport
|
|
|
|
nc := *httpClient
|
|
|
|
nc.Transport = ntr
|
|
|
|
return &nc, nil
|
2018-02-14 17:47:17 +00:00
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
// ConfigureTLS applies a set of TLS configurations to the the HTTP client.
|
|
|
|
func ConfigureTLS(httpClient *http.Client, tlsConfig *TLSConfig) error {
|
|
|
|
if tlsConfig == nil {
|
2017-08-29 18:11:19 +00:00
|
|
|
return nil
|
|
|
|
}
|
2019-01-19 00:01:12 +00:00
|
|
|
if httpClient == nil {
|
2022-08-05 15:05:47 +00:00
|
|
|
return errors.New("config HTTP Client must be set")
|
2016-10-25 00:07:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var clientCert tls.Certificate
|
|
|
|
foundClientCert := false
|
2019-01-19 00:01:12 +00:00
|
|
|
if tlsConfig.ClientCert != "" || tlsConfig.ClientKey != "" {
|
|
|
|
if tlsConfig.ClientCert != "" && tlsConfig.ClientKey != "" {
|
2016-10-25 00:07:44 +00:00
|
|
|
var err error
|
2019-01-19 00:01:12 +00:00
|
|
|
clientCert, err = tls.LoadX509KeyPair(tlsConfig.ClientCert, tlsConfig.ClientKey)
|
2016-10-25 00:07:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
foundClientCert = true
|
2017-03-08 15:19:29 +00:00
|
|
|
} else {
|
2022-08-05 15:05:47 +00:00
|
|
|
return errors.New("Both client cert and client key must be provided")
|
2016-10-25 00:07:44 +00:00
|
|
|
}
|
2019-12-16 13:30:00 +00:00
|
|
|
} else if len(tlsConfig.ClientCertPEM) != 0 || len(tlsConfig.ClientKeyPEM) != 0 {
|
|
|
|
if len(tlsConfig.ClientCertPEM) != 0 && len(tlsConfig.ClientKeyPEM) != 0 {
|
|
|
|
var err error
|
|
|
|
clientCert, err = tls.X509KeyPair(tlsConfig.ClientCertPEM, tlsConfig.ClientKeyPEM)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
foundClientCert = true
|
|
|
|
} else {
|
2022-08-05 15:05:47 +00:00
|
|
|
return errors.New("Both client cert and client key must be provided")
|
2019-12-16 13:30:00 +00:00
|
|
|
}
|
2016-10-25 00:07:44 +00:00
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
clientTLSConfig := httpClient.Transport.(*http.Transport).TLSClientConfig
|
2016-10-25 00:07:44 +00:00
|
|
|
rootConfig := &rootcerts.Config{
|
2019-12-16 09:59:27 +00:00
|
|
|
CAFile: tlsConfig.CACert,
|
|
|
|
CAPath: tlsConfig.CAPath,
|
2019-12-16 13:30:00 +00:00
|
|
|
CACertificate: tlsConfig.CACertPEM,
|
2016-10-25 00:07:44 +00:00
|
|
|
}
|
|
|
|
if err := rootcerts.ConfigureTLS(clientTLSConfig, rootConfig); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
clientTLSConfig.InsecureSkipVerify = tlsConfig.Insecure
|
2016-10-25 00:07:44 +00:00
|
|
|
|
|
|
|
if foundClientCert {
|
|
|
|
clientTLSConfig.Certificates = []tls.Certificate{clientCert}
|
|
|
|
}
|
2019-01-19 00:01:12 +00:00
|
|
|
if tlsConfig.TLSServerName != "" {
|
|
|
|
clientTLSConfig.ServerName = tlsConfig.TLSServerName
|
2016-10-25 00:07:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// Client provides a client to the Nomad API
|
|
|
|
type Client struct {
|
2019-01-19 00:01:12 +00:00
|
|
|
httpClient *http.Client
|
|
|
|
config Config
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewClient returns a new client
|
|
|
|
func NewClient(config *Config) (*Client, error) {
|
|
|
|
// bootstrap the config
|
|
|
|
defConfig := DefaultConfig()
|
|
|
|
|
2015-09-14 20:13:52 +00:00
|
|
|
if config.Address == "" {
|
|
|
|
config.Address = defConfig.Address
|
|
|
|
} else if _, err := url.Parse(config.Address); err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid address '%s': %v", config.Address, err)
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
httpClient := config.HttpClient
|
|
|
|
if httpClient == nil {
|
|
|
|
httpClient = defaultHttpClient()
|
|
|
|
if err := ConfigureTLS(httpClient, config.TLSConfig); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-10-25 00:07:44 +00:00
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
client := &Client{
|
2019-01-19 00:01:12 +00:00
|
|
|
config: *config,
|
|
|
|
httpClient: httpClient,
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
2022-04-06 20:14:53 +00:00
|
|
|
// Close closes the client's idle keep-alived connections. The default
|
|
|
|
// client configuration uses keep-alive to maintain connections and
|
|
|
|
// you should instantiate a single Client and reuse it for all
|
|
|
|
// requests from the same host. Connections will be closed
|
|
|
|
// automatically once the client is garbage collected. If you are
|
|
|
|
// creating multiple clients on the same host (for example, for
|
|
|
|
// testing), it may be useful to call Close() to avoid hitting
|
|
|
|
// connection limits.
|
|
|
|
func (c *Client) Close() {
|
|
|
|
c.httpClient.CloseIdleConnections()
|
|
|
|
}
|
|
|
|
|
2017-10-10 06:01:55 +00:00
|
|
|
// Address return the address of the Nomad agent
|
|
|
|
func (c *Client) Address() string {
|
|
|
|
return c.config.Address
|
|
|
|
}
|
|
|
|
|
2016-06-07 18:28:02 +00:00
|
|
|
// SetRegion sets the region to forward API requests to.
|
|
|
|
func (c *Client) SetRegion(region string) {
|
|
|
|
c.config.Region = region
|
|
|
|
}
|
|
|
|
|
2017-09-07 23:56:15 +00:00
|
|
|
// SetNamespace sets the namespace to forward API requests to.
|
|
|
|
func (c *Client) SetNamespace(namespace string) {
|
|
|
|
c.config.Namespace = namespace
|
|
|
|
}
|
|
|
|
|
2017-08-28 18:32:52 +00:00
|
|
|
// GetNodeClient returns a new Client that will dial the specified node. If the
|
2017-08-28 21:41:21 +00:00
|
|
|
// QueryOptions is set, its region will be used.
|
|
|
|
func (c *Client) GetNodeClient(nodeID string, q *QueryOptions) (*Client, error) {
|
2018-02-07 02:51:34 +00:00
|
|
|
return c.getNodeClientImpl(nodeID, -1, q, c.Nodes().Info)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetNodeClientWithTimeout returns a new Client that will dial the specified
|
|
|
|
// node using the specified timeout. If the QueryOptions is set, its region will
|
|
|
|
// be used.
|
|
|
|
func (c *Client) GetNodeClientWithTimeout(
|
|
|
|
nodeID string, timeout time.Duration, q *QueryOptions) (*Client, error) {
|
|
|
|
return c.getNodeClientImpl(nodeID, timeout, q, c.Nodes().Info)
|
2017-08-29 18:11:19 +00:00
|
|
|
}
|
|
|
|
|
2017-08-29 23:09:53 +00:00
|
|
|
// nodeLookup is the definition of a function used to lookup a node. This is
|
|
|
|
// largely used to mock the lookup in tests.
|
2017-08-29 18:11:19 +00:00
|
|
|
type nodeLookup func(nodeID string, q *QueryOptions) (*Node, *QueryMeta, error)
|
|
|
|
|
|
|
|
// getNodeClientImpl is the implementation of creating a API client for
|
2017-08-29 23:09:53 +00:00
|
|
|
// contacting a node. It takes a function to lookup the node such that it can be
|
|
|
|
// mocked during tests.
|
2018-02-07 02:51:34 +00:00
|
|
|
func (c *Client) getNodeClientImpl(nodeID string, timeout time.Duration, q *QueryOptions, lookup nodeLookup) (*Client, error) {
|
2017-08-29 18:11:19 +00:00
|
|
|
node, _, err := lookup(nodeID, q)
|
2017-08-28 18:32:52 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if node.Status == "down" {
|
|
|
|
return nil, NodeDownErr
|
|
|
|
}
|
|
|
|
if node.HTTPAddr == "" {
|
|
|
|
return nil, fmt.Errorf("http addr of node %q (%s) is not advertised", node.Name, nodeID)
|
|
|
|
}
|
|
|
|
|
2017-08-29 23:09:53 +00:00
|
|
|
var region string
|
|
|
|
switch {
|
|
|
|
case q != nil && q.Region != "":
|
|
|
|
// Prefer the region set in the query parameter
|
2017-08-28 21:58:15 +00:00
|
|
|
region = q.Region
|
2017-08-29 23:09:53 +00:00
|
|
|
case c.config.Region != "":
|
|
|
|
// If the client is configured for a particular region use that
|
|
|
|
region = c.config.Region
|
|
|
|
default:
|
2019-08-05 21:28:02 +00:00
|
|
|
// No region information is given so use GlobalRegion as the default.
|
|
|
|
region = GlobalRegion
|
2017-08-29 18:11:19 +00:00
|
|
|
}
|
|
|
|
|
2017-08-28 18:32:52 +00:00
|
|
|
// Get an API client for the node
|
2018-02-14 17:47:17 +00:00
|
|
|
conf := c.config.ClientConfig(region, node.HTTPAddr, node.TLSEnabled)
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
// set timeout - preserve old behavior where errors are ignored and use untimed one
|
|
|
|
httpClient, err := cloneWithTimeout(c.httpClient, timeout)
|
2019-05-22 01:29:15 +00:00
|
|
|
// on error, fallback to using current http client
|
|
|
|
if err != nil {
|
2019-01-19 00:01:12 +00:00
|
|
|
httpClient = c.httpClient
|
|
|
|
}
|
|
|
|
conf.HttpClient = httpClient
|
2018-02-14 17:47:17 +00:00
|
|
|
|
2017-08-28 21:41:21 +00:00
|
|
|
return NewClient(conf)
|
2017-08-28 18:32:52 +00:00
|
|
|
}
|
|
|
|
|
2017-08-25 00:03:29 +00:00
|
|
|
// SetSecretID sets the ACL token secret for API requests.
|
|
|
|
func (c *Client) SetSecretID(secretID string) {
|
|
|
|
c.config.SecretID = secretID
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// request is used to help build up a request
|
|
|
|
type request struct {
|
|
|
|
config *Config
|
|
|
|
method string
|
|
|
|
url *url.URL
|
|
|
|
params url.Values
|
2017-08-25 00:03:29 +00:00
|
|
|
token string
|
2015-09-06 20:29:51 +00:00
|
|
|
body io.Reader
|
|
|
|
obj interface{}
|
2020-09-09 20:22:07 +00:00
|
|
|
ctx context.Context
|
2021-01-05 01:07:35 +00:00
|
|
|
header http.Header
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// setQueryOptions is used to annotate the request with
|
|
|
|
// additional query options
|
|
|
|
func (r *request) setQueryOptions(q *QueryOptions) {
|
|
|
|
if q == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if q.Region != "" {
|
|
|
|
r.params.Set("region", q.Region)
|
|
|
|
}
|
2017-09-07 23:56:15 +00:00
|
|
|
if q.Namespace != "" {
|
|
|
|
r.params.Set("namespace", q.Namespace)
|
|
|
|
}
|
2017-10-12 22:16:33 +00:00
|
|
|
if q.AuthToken != "" {
|
|
|
|
r.token = q.AuthToken
|
2017-08-25 00:03:29 +00:00
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
if q.AllowStale {
|
|
|
|
r.params.Set("stale", "")
|
|
|
|
}
|
|
|
|
if q.WaitIndex != 0 {
|
|
|
|
r.params.Set("index", strconv.FormatUint(q.WaitIndex, 10))
|
|
|
|
}
|
|
|
|
if q.WaitTime != 0 {
|
|
|
|
r.params.Set("wait", durToMsec(q.WaitTime))
|
|
|
|
}
|
2015-12-22 22:44:33 +00:00
|
|
|
if q.Prefix != "" {
|
|
|
|
r.params.Set("prefix", q.Prefix)
|
|
|
|
}
|
2022-02-16 16:40:30 +00:00
|
|
|
if q.Filter != "" {
|
|
|
|
r.params.Set("filter", q.Filter)
|
|
|
|
}
|
2021-12-10 18:43:03 +00:00
|
|
|
if q.PerPage != 0 {
|
|
|
|
r.params.Set("per_page", fmt.Sprint(q.PerPage))
|
|
|
|
}
|
|
|
|
if q.NextToken != "" {
|
|
|
|
r.params.Set("next_token", q.NextToken)
|
|
|
|
}
|
2022-03-09 01:54:17 +00:00
|
|
|
if q.Reverse {
|
|
|
|
r.params.Set("reverse", "true")
|
2022-02-10 17:50:34 +00:00
|
|
|
}
|
2016-07-28 21:24:01 +00:00
|
|
|
for k, v := range q.Params {
|
|
|
|
r.params.Set(k, v)
|
|
|
|
}
|
2020-09-09 20:22:07 +00:00
|
|
|
r.ctx = q.Context()
|
2022-03-01 13:47:01 +00:00
|
|
|
|
|
|
|
for k, v := range q.Headers {
|
|
|
|
r.header.Set(k, v)
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// durToMsec converts a duration to a millisecond specified string
|
|
|
|
func durToMsec(dur time.Duration) string {
|
|
|
|
return fmt.Sprintf("%dms", dur/time.Millisecond)
|
|
|
|
}
|
|
|
|
|
|
|
|
// setWriteOptions is used to annotate the request with
|
|
|
|
// additional write options
|
|
|
|
func (r *request) setWriteOptions(q *WriteOptions) {
|
|
|
|
if q == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if q.Region != "" {
|
|
|
|
r.params.Set("region", q.Region)
|
|
|
|
}
|
2017-09-07 23:56:15 +00:00
|
|
|
if q.Namespace != "" {
|
|
|
|
r.params.Set("namespace", q.Namespace)
|
|
|
|
}
|
2017-10-12 22:16:33 +00:00
|
|
|
if q.AuthToken != "" {
|
|
|
|
r.token = q.AuthToken
|
2017-08-25 00:03:29 +00:00
|
|
|
}
|
2021-07-07 21:26:35 +00:00
|
|
|
if q.IdempotencyToken != "" {
|
|
|
|
r.params.Set("idempotency_token", q.IdempotencyToken)
|
|
|
|
}
|
2020-09-09 20:22:07 +00:00
|
|
|
r.ctx = q.Context()
|
2022-03-01 13:47:01 +00:00
|
|
|
|
|
|
|
for k, v := range q.Headers {
|
|
|
|
r.header.Set(k, v)
|
|
|
|
}
|
2015-09-06 20:29:51 +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 {
|
|
|
|
if b, err := encodeBody(r.obj); err != nil {
|
|
|
|
return nil, err
|
|
|
|
} else {
|
|
|
|
r.body = b
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-09 20:22:07 +00:00
|
|
|
ctx := func() context.Context {
|
|
|
|
if r.ctx != nil {
|
|
|
|
return r.ctx
|
|
|
|
}
|
|
|
|
return context.Background()
|
|
|
|
}()
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// Create the HTTP request
|
2020-09-09 20:22:07 +00:00
|
|
|
req, err := http.NewRequestWithContext(ctx, r.method, r.url.RequestURI(), r.body)
|
2015-09-06 20:29:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-01-05 16:02:59 +00:00
|
|
|
req.Header = r.header
|
|
|
|
|
2016-07-18 13:16:28 +00:00
|
|
|
// Optionally configure HTTP basic authentication
|
|
|
|
if r.url.User != nil {
|
|
|
|
username := r.url.User.Username()
|
|
|
|
password, _ := r.url.User.Password()
|
|
|
|
req.SetBasicAuth(username, password)
|
2016-08-17 19:11:59 +00:00
|
|
|
} else if r.config.HttpAuth != nil {
|
|
|
|
req.SetBasicAuth(r.config.HttpAuth.Username, r.config.HttpAuth.Password)
|
2016-07-18 13:16:28 +00:00
|
|
|
}
|
|
|
|
|
2016-05-24 17:26:53 +00:00
|
|
|
req.Header.Add("Accept-Encoding", "gzip")
|
2017-08-25 00:03:29 +00:00
|
|
|
if r.token != "" {
|
|
|
|
req.Header.Set("X-Nomad-Token", r.token)
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
req.URL.Host = r.url.Host
|
|
|
|
req.URL.Scheme = r.url.Scheme
|
|
|
|
req.Host = r.url.Host
|
|
|
|
return req, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// newRequest is used to create a new request
|
2017-02-20 19:12:34 +00:00
|
|
|
func (c *Client) newRequest(method, path string) (*request, error) {
|
2015-09-14 20:13:52 +00:00
|
|
|
base, _ := url.Parse(c.config.Address)
|
2017-02-20 19:12:34 +00:00
|
|
|
u, err := url.Parse(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
r := &request{
|
|
|
|
config: &c.config,
|
|
|
|
method: method,
|
|
|
|
url: &url.URL{
|
2019-11-07 13:35:39 +00:00
|
|
|
Scheme: base.Scheme,
|
|
|
|
User: base.User,
|
|
|
|
Host: base.Host,
|
|
|
|
Path: u.Path,
|
|
|
|
RawPath: u.RawPath,
|
2015-09-06 20:29:51 +00:00
|
|
|
},
|
2021-01-05 01:07:35 +00:00
|
|
|
header: make(http.Header),
|
2015-09-06 20:29:51 +00:00
|
|
|
params: make(map[string][]string),
|
|
|
|
}
|
|
|
|
if c.config.Region != "" {
|
|
|
|
r.params.Set("region", c.config.Region)
|
|
|
|
}
|
2017-09-07 23:56:15 +00:00
|
|
|
if c.config.Namespace != "" {
|
|
|
|
r.params.Set("namespace", c.config.Namespace)
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
if c.config.WaitTime != 0 {
|
|
|
|
r.params.Set("wait", durToMsec(r.config.WaitTime))
|
|
|
|
}
|
2017-08-25 00:03:29 +00:00
|
|
|
if c.config.SecretID != "" {
|
|
|
|
r.token = r.config.SecretID
|
|
|
|
}
|
2015-09-08 21:26:26 +00:00
|
|
|
|
|
|
|
// Add in the query parameters, if any
|
|
|
|
for key, values := range u.Query() {
|
|
|
|
for _, value := range values {
|
|
|
|
r.params.Add(key, value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-06 18:04:56 +00:00
|
|
|
for key, values := range c.config.Headers {
|
|
|
|
r.header[key] = values
|
2021-01-05 16:03:16 +00:00
|
|
|
}
|
2021-01-05 01:07:35 +00:00
|
|
|
|
2017-02-20 19:12:34 +00:00
|
|
|
return r, nil
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
2016-05-24 17:26:53 +00:00
|
|
|
// multiCloser is to wrap a ReadCloser such that when close is called, multiple
|
|
|
|
// Closes occur.
|
|
|
|
type multiCloser struct {
|
|
|
|
reader io.Reader
|
|
|
|
inorderClose []io.Closer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *multiCloser) Close() error {
|
|
|
|
for _, c := range m.inorderClose {
|
|
|
|
if err := c.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *multiCloser) Read(p []byte) (int, error) {
|
|
|
|
return m.reader.Read(p)
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// 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
|
|
|
|
}
|
2022-01-13 15:57:36 +00:00
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
start := time.Now()
|
2019-01-19 00:01:12 +00:00
|
|
|
resp, err := c.httpClient.Do(req)
|
2021-04-03 07:50:23 +00:00
|
|
|
diff := time.Since(start)
|
2016-05-24 17:26:53 +00:00
|
|
|
|
|
|
|
// If the response is compressed, we swap the body's reader.
|
2022-01-13 15:57:36 +00:00
|
|
|
if zipErr := c.autoUnzip(resp); zipErr != nil {
|
|
|
|
return 0, nil, zipErr
|
|
|
|
}
|
2016-05-24 18:18:32 +00:00
|
|
|
|
2022-01-13 15:57:36 +00:00
|
|
|
return diff, resp, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// autoUnzip modifies resp in-place, wrapping the response body with a gzip
|
|
|
|
// reader if the Content-Encoding of the response is "gzip".
|
|
|
|
func (*Client) autoUnzip(resp *http.Response) error {
|
|
|
|
if resp == nil || resp.Header == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if resp.Header.Get("Content-Encoding") == "gzip" {
|
|
|
|
zReader, err := gzip.NewReader(resp.Body)
|
|
|
|
if err == io.EOF {
|
|
|
|
// zero length response, do not wrap
|
|
|
|
return nil
|
|
|
|
} else if err != nil {
|
|
|
|
// some other error (e.g. corrupt)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// The gzip reader does not close an underlying reader, so use a
|
|
|
|
// multiCloser to make sure response body does get closed.
|
|
|
|
resp.Body = &multiCloser{
|
|
|
|
reader: zReader,
|
|
|
|
inorderClose: []io.Closer{zReader, resp.Body},
|
2016-05-24 17:26:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-13 15:57:36 +00:00
|
|
|
return nil
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
2016-07-28 21:24:01 +00:00
|
|
|
// rawQuery makes a GET request to the specified endpoint but returns just the
|
|
|
|
// response body.
|
|
|
|
func (c *Client) rawQuery(endpoint string, q *QueryOptions) (io.ReadCloser, error) {
|
2017-02-20 19:12:34 +00:00
|
|
|
r, err := c.newRequest("GET", endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-07-28 21:24:01 +00:00
|
|
|
r.setQueryOptions(q)
|
|
|
|
_, resp, err := requireOK(c.doRequest(r))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return resp.Body, nil
|
|
|
|
}
|
|
|
|
|
2019-04-28 21:34:01 +00:00
|
|
|
// websocket makes a websocket request to the specific endpoint
|
|
|
|
func (c *Client) websocket(endpoint string, q *QueryOptions) (*websocket.Conn, *http.Response, error) {
|
|
|
|
|
2019-01-19 00:01:12 +00:00
|
|
|
transport, ok := c.httpClient.Transport.(*http.Transport)
|
2019-04-28 21:34:01 +00:00
|
|
|
if !ok {
|
2022-08-05 15:05:47 +00:00
|
|
|
return nil, nil, errors.New("unsupported transport")
|
2019-04-28 21:34:01 +00:00
|
|
|
}
|
|
|
|
dialer := websocket.Dialer{
|
|
|
|
ReadBufferSize: 4096,
|
|
|
|
WriteBufferSize: 4096,
|
2019-01-19 00:01:12 +00:00
|
|
|
HandshakeTimeout: c.httpClient.Timeout,
|
2019-04-28 21:34:01 +00:00
|
|
|
|
|
|
|
// values to inherit from http client configuration
|
|
|
|
NetDial: transport.Dial,
|
|
|
|
NetDialContext: transport.DialContext,
|
|
|
|
Proxy: transport.Proxy,
|
|
|
|
TLSClientConfig: transport.TLSClientConfig,
|
|
|
|
}
|
|
|
|
|
|
|
|
// build request object for header and parameters
|
|
|
|
r, err := c.newRequest("GET", endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
r.setQueryOptions(q)
|
|
|
|
|
|
|
|
rhttp, err := r.toHTTP()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// convert scheme
|
|
|
|
wsScheme := ""
|
|
|
|
switch rhttp.URL.Scheme {
|
|
|
|
case "http":
|
|
|
|
wsScheme = "ws"
|
|
|
|
case "https":
|
|
|
|
wsScheme = "wss"
|
|
|
|
default:
|
|
|
|
return nil, nil, fmt.Errorf("unsupported scheme: %v", rhttp.URL.Scheme)
|
|
|
|
}
|
|
|
|
rhttp.URL.Scheme = wsScheme
|
|
|
|
|
|
|
|
conn, resp, err := dialer.Dial(rhttp.URL.String(), rhttp.Header)
|
|
|
|
|
|
|
|
// check resp status code, as it's more informative than handshake error we get from ws library
|
|
|
|
if resp != nil && resp.StatusCode != 101 {
|
|
|
|
var buf bytes.Buffer
|
2019-11-07 20:39:41 +00:00
|
|
|
|
|
|
|
if resp.Header.Get("Content-Encoding") == "gzip" {
|
|
|
|
greader, err := gzip.NewReader(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, fmt.Errorf("Unexpected response code: %d", resp.StatusCode)
|
|
|
|
}
|
|
|
|
io.Copy(&buf, greader)
|
|
|
|
} else {
|
|
|
|
io.Copy(&buf, resp.Body)
|
|
|
|
}
|
2019-04-28 21:34:01 +00:00
|
|
|
resp.Body.Close()
|
|
|
|
|
|
|
|
return nil, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes())
|
|
|
|
}
|
|
|
|
|
|
|
|
return conn, resp, err
|
|
|
|
}
|
|
|
|
|
2017-08-28 05:17:51 +00:00
|
|
|
// query is used to do a GET request against an endpoint
|
2015-09-06 20:29:51 +00:00
|
|
|
// and deserialize the response into an interface using
|
|
|
|
// standard Nomad conventions.
|
2023-02-07 22:42:25 +00:00
|
|
|
func (c *Client) query(endpoint string, out any, q *QueryOptions) (*QueryMeta, error) {
|
2017-02-20 19:12:34 +00:00
|
|
|
r, err := c.newRequest("GET", endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
r.setQueryOptions(q)
|
|
|
|
rtt, resp, err := requireOK(c.doRequest(r))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
qm := &QueryMeta{}
|
|
|
|
parseQueryMeta(resp, qm)
|
|
|
|
qm.RequestTime = rtt
|
|
|
|
|
|
|
|
if err := decodeBody(resp, out); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return qm, nil
|
|
|
|
}
|
|
|
|
|
2023-03-20 23:32:32 +00:00
|
|
|
// putQuery is used to do a PUT request when doing a "write" to a Client RPC.
|
|
|
|
// Client RPCs must use QueryOptions to allow setting AllowStale=true.
|
2023-02-07 22:42:25 +00:00
|
|
|
func (c *Client) putQuery(endpoint string, in, out any, q *QueryOptions) (*QueryMeta, error) {
|
2017-08-28 05:17:51 +00:00
|
|
|
r, err := c.newRequest("PUT", endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
r.setQueryOptions(q)
|
|
|
|
r.obj = in
|
|
|
|
rtt, resp, err := requireOK(c.doRequest(r))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
qm := &QueryMeta{}
|
|
|
|
parseQueryMeta(resp, qm)
|
|
|
|
qm.RequestTime = rtt
|
|
|
|
|
|
|
|
if err := decodeBody(resp, out); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return qm, nil
|
|
|
|
}
|
|
|
|
|
2023-02-07 22:42:25 +00:00
|
|
|
// put is used to do a PUT request against an endpoint and
|
|
|
|
// serialize/deserialized using the standard Nomad conventions.
|
|
|
|
func (c *Client) put(endpoint string, in, out any, q *WriteOptions) (*WriteMeta, error) {
|
|
|
|
return c.write(http.MethodPut, endpoint, in, out, q)
|
|
|
|
}
|
|
|
|
|
2023-03-20 23:32:32 +00:00
|
|
|
// postQuery is used to do a POST request when doing a "write" to a Client RPC.
|
|
|
|
// Client RPCs must use QueryOptions to allow setting AllowStale=true.
|
|
|
|
func (c *Client) postQuery(endpoint string, in, out any, q *QueryOptions) (*QueryMeta, error) {
|
|
|
|
r, err := c.newRequest("POST", endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
r.setQueryOptions(q)
|
|
|
|
r.obj = in
|
|
|
|
rtt, resp, err := requireOK(c.doRequest(r))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
qm := &QueryMeta{}
|
|
|
|
parseQueryMeta(resp, qm)
|
|
|
|
qm.RequestTime = rtt
|
|
|
|
|
|
|
|
if err := decodeBody(resp, out); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return qm, nil
|
|
|
|
}
|
|
|
|
|
2023-02-07 22:42:25 +00:00
|
|
|
// post is used to do a POST request against an endpoint and
|
|
|
|
// serialize/deserialized using the standard Nomad conventions.
|
|
|
|
func (c *Client) post(endpoint string, in, out any, q *WriteOptions) (*WriteMeta, error) {
|
|
|
|
return c.write(http.MethodPost, endpoint, in, out, q)
|
|
|
|
}
|
|
|
|
|
|
|
|
// write is used to do a write request against an endpoint and
|
|
|
|
// serialize/deserialized using the standard Nomad conventions.
|
|
|
|
//
|
|
|
|
// You probably want the delete, post, or put methods.
|
|
|
|
func (c *Client) write(verb, endpoint string, in, out any, q *WriteOptions) (*WriteMeta, error) {
|
|
|
|
r, err := c.newRequest(verb, endpoint)
|
2017-02-20 19:12:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
r.setWriteOptions(q)
|
|
|
|
r.obj = in
|
|
|
|
rtt, resp, err := requireOK(c.doRequest(r))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
wm := &WriteMeta{RequestTime: rtt}
|
|
|
|
parseWriteMeta(resp, wm)
|
|
|
|
|
|
|
|
if out != nil {
|
|
|
|
if err := decodeBody(resp, &out); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return wm, nil
|
|
|
|
}
|
|
|
|
|
2022-07-06 14:30:11 +00:00
|
|
|
// delete is used to do a DELETE request against an endpoint and
|
|
|
|
// serialize/deserialized using the standard Nomad conventions.
|
2023-02-07 22:42:25 +00:00
|
|
|
func (c *Client) delete(endpoint string, in, out any, q *WriteOptions) (*WriteMeta, error) {
|
2017-02-20 19:12:34 +00:00
|
|
|
r, err := c.newRequest("DELETE", endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
r.setWriteOptions(q)
|
2022-07-06 14:30:11 +00:00
|
|
|
r.obj = in
|
2015-09-06 20:29:51 +00:00
|
|
|
rtt, resp, err := requireOK(c.doRequest(r))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
wm := &WriteMeta{RequestTime: rtt}
|
|
|
|
parseWriteMeta(resp, wm)
|
|
|
|
|
|
|
|
if out != nil {
|
|
|
|
if err := decodeBody(resp, &out); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return wm, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// parseQueryMeta is used to help parse query meta-data
|
|
|
|
func parseQueryMeta(resp *http.Response, q *QueryMeta) error {
|
|
|
|
header := resp.Header
|
|
|
|
|
|
|
|
// Parse the X-Nomad-Index
|
|
|
|
index, err := strconv.ParseUint(header.Get("X-Nomad-Index"), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to parse X-Nomad-Index: %v", err)
|
|
|
|
}
|
|
|
|
q.LastIndex = index
|
|
|
|
|
|
|
|
// Parse the X-Nomad-LastContact
|
|
|
|
last, err := strconv.ParseUint(header.Get("X-Nomad-LastContact"), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to parse X-Nomad-LastContact: %v", err)
|
|
|
|
}
|
|
|
|
q.LastContact = time.Duration(last) * time.Millisecond
|
2021-12-10 18:43:03 +00:00
|
|
|
q.NextToken = header.Get("X-Nomad-NextToken")
|
2015-09-06 20:29:51 +00:00
|
|
|
|
|
|
|
// Parse the X-Nomad-KnownLeader
|
|
|
|
switch header.Get("X-Nomad-KnownLeader") {
|
|
|
|
case "true":
|
|
|
|
q.KnownLeader = true
|
|
|
|
default:
|
|
|
|
q.KnownLeader = false
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// parseWriteMeta is used to help parse write meta-data
|
|
|
|
func parseWriteMeta(resp *http.Response, q *WriteMeta) error {
|
|
|
|
header := resp.Header
|
|
|
|
|
|
|
|
// Parse the X-Nomad-Index
|
|
|
|
index, err := strconv.ParseUint(header.Get("X-Nomad-Index"), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to parse X-Nomad-Index: %v", err)
|
|
|
|
}
|
|
|
|
q.LastIndex = index
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// decodeBody is used to JSON decode a body
|
|
|
|
func decodeBody(resp *http.Response, out interface{}) error {
|
2019-11-08 15:04:15 +00:00
|
|
|
switch resp.ContentLength {
|
|
|
|
case 0:
|
|
|
|
if out == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return errors.New("Got 0 byte response with non-nil decode object")
|
|
|
|
default:
|
|
|
|
dec := json.NewDecoder(resp.Body)
|
|
|
|
return dec.Decode(out)
|
|
|
|
}
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
2020-06-09 16:00:09 +00:00
|
|
|
// encodeBody prepares the reader to serve as the request body.
|
|
|
|
//
|
|
|
|
// Returns the `obj` input if it is a raw io.Reader object; otherwise
|
|
|
|
// returns a reader of the json format of the passed argument.
|
2015-09-06 20:29:51 +00:00
|
|
|
func encodeBody(obj interface{}) (io.Reader, error) {
|
2020-06-06 12:19:10 +00:00
|
|
|
if reader, ok := obj.(io.Reader); ok {
|
|
|
|
return reader, nil
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
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
|
|
|
|
func requireOK(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) {
|
|
|
|
if e != nil {
|
|
|
|
if resp != nil {
|
|
|
|
resp.Body.Close()
|
|
|
|
}
|
|
|
|
return d, nil, e
|
|
|
|
}
|
|
|
|
if resp.StatusCode != 200 {
|
|
|
|
var buf bytes.Buffer
|
2022-08-16 19:55:38 +00:00
|
|
|
_, _ = io.Copy(&buf, resp.Body)
|
|
|
|
_ = resp.Body.Close()
|
|
|
|
body := strings.TrimSpace(buf.String())
|
|
|
|
return d, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, body)
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
return d, resp, nil
|
|
|
|
}
|
2020-09-09 20:22:07 +00:00
|
|
|
|
|
|
|
// Context returns the context used for canceling HTTP requests related to this query
|
|
|
|
func (o *QueryOptions) Context() context.Context {
|
|
|
|
if o != nil && o.ctx != nil {
|
|
|
|
return o.ctx
|
|
|
|
}
|
|
|
|
return context.Background()
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithContext creates a copy of the query options using the provided context to cancel related HTTP requests
|
|
|
|
func (o *QueryOptions) WithContext(ctx context.Context) *QueryOptions {
|
|
|
|
o2 := new(QueryOptions)
|
|
|
|
if o != nil {
|
|
|
|
*o2 = *o
|
|
|
|
}
|
|
|
|
o2.ctx = ctx
|
|
|
|
return o2
|
|
|
|
}
|
|
|
|
|
|
|
|
// Context returns the context used for canceling HTTP requests related to this write
|
|
|
|
func (o *WriteOptions) Context() context.Context {
|
|
|
|
if o != nil && o.ctx != nil {
|
|
|
|
return o.ctx
|
|
|
|
}
|
|
|
|
return context.Background()
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithContext creates a copy of the write options using the provided context to cancel related HTTP requests
|
|
|
|
func (o *WriteOptions) WithContext(ctx context.Context) *WriteOptions {
|
|
|
|
o2 := new(WriteOptions)
|
|
|
|
if o != nil {
|
|
|
|
*o2 = *o
|
|
|
|
}
|
|
|
|
o2.ctx = ctx
|
|
|
|
return o2
|
|
|
|
}
|