2015-09-06 20:29:51 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2016-05-24 17:26:53 +00:00
|
|
|
"compress/gzip"
|
2016-10-25 00:07:44 +00:00
|
|
|
"crypto/tls"
|
2015-09-06 20:29:51 +00:00
|
|
|
"encoding/json"
|
|
|
|
"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-01-15 19:46:12 +00:00
|
|
|
cleanhttp "github.com/hashicorp/go-cleanhttp"
|
2016-10-25 00:07:44 +00:00
|
|
|
rootcerts "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
|
|
|
|
// server.
|
|
|
|
ClientConnTimeout = 1 * time.Second
|
|
|
|
)
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// QueryOptions are used to parameterize a query
|
|
|
|
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
|
|
|
|
2017-10-12 22:16:33 +00:00
|
|
|
// AuthToken is the secret ID of an ACL token
|
|
|
|
AuthToken string
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WriteOptions are used to parameterize a write
|
|
|
|
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
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
2017-08-29 21:22:11 +00:00
|
|
|
// httpClient is the client to use. Default will be used if not provided.
|
|
|
|
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
|
|
|
|
// client
|
|
|
|
TLSConfig *TLSConfig
|
|
|
|
}
|
|
|
|
|
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"
|
|
|
|
}
|
2017-08-29 21:22:11 +00:00
|
|
|
defaultConfig := DefaultConfig()
|
2016-10-26 18:13:53 +00:00
|
|
|
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,
|
2017-08-29 21:22:11 +00:00
|
|
|
httpClient: defaultConfig.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
|
|
|
|
|
|
|
|
// ClientCert is the path to the certificate for Nomad communication
|
|
|
|
ClientCert string
|
|
|
|
|
|
|
|
// ClientKey is the path to the private key for Nomad communication
|
|
|
|
ClientKey string
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// DefaultConfig returns a default configuration for the client
|
|
|
|
func DefaultConfig() *Config {
|
|
|
|
config := &Config{
|
2015-09-14 20:13:52 +00:00
|
|
|
Address: "http://127.0.0.1:4646",
|
2017-08-29 21:22:11 +00:00
|
|
|
httpClient: cleanhttp.DefaultClient(),
|
2016-10-25 00:07:44 +00:00
|
|
|
TLSConfig: &TLSConfig{},
|
|
|
|
}
|
2017-08-29 21:22:11 +00:00
|
|
|
transport := config.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
|
|
|
|
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
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2018-02-14 17:47:17 +00:00
|
|
|
// SetTimeout is used to place a timeout for connecting to Nomad. A negative
|
|
|
|
// duration is ignored, a duration of zero means no timeout, and any other value
|
|
|
|
// will add a timeout.
|
|
|
|
func (c *Config) SetTimeout(t time.Duration) error {
|
|
|
|
if c == nil {
|
|
|
|
return fmt.Errorf("nil config")
|
|
|
|
} else if c.httpClient == nil {
|
|
|
|
return fmt.Errorf("nil HTTP client")
|
|
|
|
} else if c.httpClient.Transport == nil {
|
|
|
|
return fmt.Errorf("nil HTTP client transport")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Apply a timeout.
|
|
|
|
if t.Nanoseconds() >= 0 {
|
|
|
|
transport, ok := c.httpClient.Transport.(*http.Transport)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("unexpected HTTP transport: %T", c.httpClient.Transport)
|
|
|
|
}
|
|
|
|
|
|
|
|
transport.DialContext = (&net.Dialer{
|
|
|
|
Timeout: t,
|
|
|
|
KeepAlive: 30 * time.Second,
|
|
|
|
}).DialContext
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-10-25 00:07:44 +00:00
|
|
|
// ConfigureTLS applies a set of TLS configurations to the the HTTP client.
|
|
|
|
func (c *Config) ConfigureTLS() error {
|
2017-08-29 18:11:19 +00:00
|
|
|
if c.TLSConfig == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2017-08-29 21:22:11 +00:00
|
|
|
if c.httpClient == nil {
|
2016-10-25 00:07:44 +00:00
|
|
|
return fmt.Errorf("config HTTP Client must be set")
|
|
|
|
}
|
|
|
|
|
|
|
|
var clientCert tls.Certificate
|
|
|
|
foundClientCert := false
|
|
|
|
if c.TLSConfig.ClientCert != "" || c.TLSConfig.ClientKey != "" {
|
|
|
|
if c.TLSConfig.ClientCert != "" && c.TLSConfig.ClientKey != "" {
|
|
|
|
var err error
|
|
|
|
clientCert, err = tls.LoadX509KeyPair(c.TLSConfig.ClientCert, c.TLSConfig.ClientKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
foundClientCert = true
|
2017-03-08 15:19:29 +00:00
|
|
|
} else {
|
2016-10-25 00:07:44 +00:00
|
|
|
return fmt.Errorf("Both client cert and client key must be provided")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-29 21:22:11 +00:00
|
|
|
clientTLSConfig := c.httpClient.Transport.(*http.Transport).TLSClientConfig
|
2016-10-25 00:07:44 +00:00
|
|
|
rootConfig := &rootcerts.Config{
|
|
|
|
CAFile: c.TLSConfig.CACert,
|
|
|
|
CAPath: c.TLSConfig.CAPath,
|
|
|
|
}
|
|
|
|
if err := rootcerts.ConfigureTLS(clientTLSConfig, rootConfig); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
clientTLSConfig.InsecureSkipVerify = c.TLSConfig.Insecure
|
|
|
|
|
|
|
|
if foundClientCert {
|
|
|
|
clientTLSConfig.Certificates = []tls.Certificate{clientCert}
|
|
|
|
}
|
|
|
|
if c.TLSConfig.TLSServerName != "" {
|
|
|
|
clientTLSConfig.ServerName = c.TLSConfig.TLSServerName
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// Client provides a client to the Nomad API
|
|
|
|
type Client struct {
|
|
|
|
config Config
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
}
|
|
|
|
|
2017-08-29 21:22:11 +00:00
|
|
|
if config.httpClient == nil {
|
|
|
|
config.httpClient = defConfig.httpClient
|
2015-09-06 20:29:51 +00:00
|
|
|
}
|
|
|
|
|
2018-03-11 17:47:24 +00:00
|
|
|
// Configure the TLS configurations
|
2016-10-25 00:07:44 +00:00
|
|
|
if err := config.ConfigureTLS(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
client := &Client{
|
|
|
|
config: *config,
|
|
|
|
}
|
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
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:
|
|
|
|
// No region information is given so use the default.
|
2017-08-29 18:11:19 +00:00
|
|
|
region = "global"
|
|
|
|
}
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
// Set the timeout
|
|
|
|
conf.SetTimeout(timeout)
|
|
|
|
|
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{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|
2016-07-28 21:24:01 +00:00
|
|
|
for k, v := range q.Params {
|
|
|
|
r.params.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
|
|
|
}
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the HTTP request
|
|
|
|
req, err := http.NewRequest(r.method, r.url.RequestURI(), r.body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
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{
|
|
|
|
Scheme: base.Scheme,
|
2016-07-18 13:16:28 +00:00
|
|
|
User: base.User,
|
2015-09-06 20:29:51 +00:00
|
|
|
Host: base.Host,
|
2015-09-08 21:26:26 +00:00
|
|
|
Path: u.Path,
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
start := time.Now()
|
2017-08-29 21:22:11 +00:00
|
|
|
resp, err := c.config.httpClient.Do(req)
|
2015-09-06 20:29:51 +00:00
|
|
|
diff := time.Now().Sub(start)
|
2016-05-24 17:26:53 +00:00
|
|
|
|
|
|
|
// If the response is compressed, we swap the body's reader.
|
2016-05-24 18:18:32 +00:00
|
|
|
if resp != nil && resp.Header != nil {
|
|
|
|
var reader io.ReadCloser
|
|
|
|
switch resp.Header.Get("Content-Encoding") {
|
|
|
|
case "gzip":
|
|
|
|
greader, err := gzip.NewReader(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// The gzip reader doesn't close the wrapped reader so we use
|
|
|
|
// multiCloser.
|
|
|
|
reader = &multiCloser{
|
|
|
|
reader: greader,
|
|
|
|
inorderClose: []io.Closer{greader, resp.Body},
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
reader = resp.Body
|
2016-05-24 17:26:53 +00:00
|
|
|
}
|
2016-05-24 18:18:32 +00:00
|
|
|
resp.Body = reader
|
2016-05-24 17:26:53 +00:00
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
return diff, resp, err
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
func (c *Client) query(endpoint string, out interface{}, 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
|
|
|
|
}
|
|
|
|
|
2017-08-28 05:17:51 +00:00
|
|
|
// putQuery is used to do a PUT request when doing a read against an endpoint
|
|
|
|
// and deserialize the response into an interface using standard Nomad
|
|
|
|
// conventions.
|
|
|
|
func (c *Client) putQuery(endpoint string, in, out interface{}, q *QueryOptions) (*QueryMeta, error) {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2015-09-06 20:29:51 +00:00
|
|
|
// write is used to do a PUT request against an endpoint
|
|
|
|
// and serialize/deserialized using the standard Nomad conventions.
|
|
|
|
func (c *Client) write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error) {
|
2017-02-20 19:12:34 +00:00
|
|
|
r, err := c.newRequest("PUT", endpoint)
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2017-02-20 19:12:34 +00:00
|
|
|
// delete is used to do a DELETE request against an endpoint
|
2015-09-06 20:29:51 +00:00
|
|
|
// and serialize/deserialized using the standard Nomad conventions.
|
|
|
|
func (c *Client) delete(endpoint string, out interface{}, 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)
|
|
|
|
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
|
|
|
|
|
|
|
|
// 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 {
|
|
|
|
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
|
|
|
|
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
|
|
|
|
io.Copy(&buf, resp.Body)
|
|
|
|
resp.Body.Close()
|
|
|
|
return d, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes())
|
|
|
|
}
|
|
|
|
return d, resp, nil
|
|
|
|
}
|