2016-09-23 20:43:03 +00:00
|
|
|
// Copyright 2013 go-dockerclient authors. All rights reserved.
|
2016-02-12 18:02:16 +00:00
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// Package docker provides a client for the Docker remote API.
|
|
|
|
//
|
2017-02-15 01:34:05 +00:00
|
|
|
// See https://goo.gl/o2v3rk for more details on the remote API.
|
2016-02-12 18:02:16 +00:00
|
|
|
package docker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
2018-11-29 22:08:16 +00:00
|
|
|
"context"
|
2016-02-12 18:02:16 +00:00
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httputil"
|
|
|
|
"net/url"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"reflect"
|
2017-08-10 16:19:19 +00:00
|
|
|
"runtime"
|
2016-02-12 18:02:16 +00:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2016-05-27 10:30:04 +00:00
|
|
|
"sync/atomic"
|
2016-02-12 18:02:16 +00:00
|
|
|
"time"
|
|
|
|
|
2016-05-28 08:25:24 +00:00
|
|
|
"github.com/docker/docker/pkg/homedir"
|
2020-03-30 19:10:53 +00:00
|
|
|
"github.com/docker/docker/pkg/jsonmessage"
|
2016-05-28 08:25:24 +00:00
|
|
|
"github.com/docker/docker/pkg/stdcopy"
|
2016-02-12 18:02:16 +00:00
|
|
|
)
|
|
|
|
|
2016-09-23 20:43:03 +00:00
|
|
|
const (
|
|
|
|
userAgent = "go-dockerclient"
|
|
|
|
|
|
|
|
unixProtocol = "unix"
|
|
|
|
namedPipeProtocol = "npipe"
|
|
|
|
)
|
2016-02-12 18:02:16 +00:00
|
|
|
|
|
|
|
var (
|
|
|
|
// ErrInvalidEndpoint is returned when the endpoint is not a valid HTTP URL.
|
|
|
|
ErrInvalidEndpoint = errors.New("invalid endpoint")
|
|
|
|
|
|
|
|
// ErrConnectionRefused is returned when the client cannot connect to the given endpoint.
|
|
|
|
ErrConnectionRefused = errors.New("cannot connect to Docker endpoint")
|
|
|
|
|
2016-05-27 10:30:04 +00:00
|
|
|
// ErrInactivityTimeout is returned when a streamable call has been inactive for some time.
|
|
|
|
ErrInactivityTimeout = errors.New("inactivity time exceeded timeout")
|
|
|
|
|
2016-02-12 18:02:16 +00:00
|
|
|
apiVersion112, _ = NewAPIVersion("1.12")
|
2020-03-30 19:10:53 +00:00
|
|
|
apiVersion118, _ = NewAPIVersion("1.18")
|
2016-02-12 18:02:16 +00:00
|
|
|
apiVersion119, _ = NewAPIVersion("1.19")
|
2020-03-30 19:10:53 +00:00
|
|
|
apiVersion121, _ = NewAPIVersion("1.21")
|
2016-09-23 20:43:03 +00:00
|
|
|
apiVersion124, _ = NewAPIVersion("1.24")
|
2017-08-10 16:19:19 +00:00
|
|
|
apiVersion125, _ = NewAPIVersion("1.25")
|
2018-11-29 22:08:16 +00:00
|
|
|
apiVersion135, _ = NewAPIVersion("1.35")
|
2016-02-12 18:02:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// APIVersion is an internal representation of a version of the Remote API.
|
|
|
|
type APIVersion []int
|
|
|
|
|
|
|
|
// NewAPIVersion returns an instance of APIVersion for the given string.
|
|
|
|
//
|
|
|
|
// The given string must be in the form <major>.<minor>.<patch>, where <major>,
|
|
|
|
// <minor> and <patch> are integer numbers.
|
|
|
|
func NewAPIVersion(input string) (APIVersion, error) {
|
|
|
|
if !strings.Contains(input, ".") {
|
2020-03-30 19:10:53 +00:00
|
|
|
return nil, fmt.Errorf("unable to parse version %q", input)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
raw := strings.Split(input, "-")
|
|
|
|
arr := strings.Split(raw[0], ".")
|
|
|
|
ret := make(APIVersion, len(arr))
|
|
|
|
var err error
|
|
|
|
for i, val := range arr {
|
|
|
|
ret[i], err = strconv.Atoi(val)
|
|
|
|
if err != nil {
|
2020-03-30 19:10:53 +00:00
|
|
|
return nil, fmt.Errorf("unable to parse version %q: %q is not an integer", input, val)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return ret, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (version APIVersion) String() string {
|
|
|
|
var str string
|
|
|
|
for i, val := range version {
|
|
|
|
str += strconv.Itoa(val)
|
|
|
|
if i < len(version)-1 {
|
|
|
|
str += "."
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
|
|
|
|
// LessThan is a function for comparing APIVersion structs
|
|
|
|
func (version APIVersion) LessThan(other APIVersion) bool {
|
|
|
|
return version.compare(other) < 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// LessThanOrEqualTo is a function for comparing APIVersion structs
|
|
|
|
func (version APIVersion) LessThanOrEqualTo(other APIVersion) bool {
|
|
|
|
return version.compare(other) <= 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// GreaterThan is a function for comparing APIVersion structs
|
|
|
|
func (version APIVersion) GreaterThan(other APIVersion) bool {
|
|
|
|
return version.compare(other) > 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// GreaterThanOrEqualTo is a function for comparing APIVersion structs
|
|
|
|
func (version APIVersion) GreaterThanOrEqualTo(other APIVersion) bool {
|
|
|
|
return version.compare(other) >= 0
|
|
|
|
}
|
|
|
|
|
|
|
|
func (version APIVersion) compare(other APIVersion) int {
|
|
|
|
for i, v := range version {
|
|
|
|
if i <= len(other)-1 {
|
|
|
|
otherVersion := other[i]
|
|
|
|
|
|
|
|
if v < otherVersion {
|
|
|
|
return -1
|
|
|
|
} else if v > otherVersion {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(version) > len(other) {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
if len(version) < len(other) {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// Client is the basic type of this package. It provides methods for
|
|
|
|
// interaction with the API.
|
|
|
|
type Client struct {
|
|
|
|
SkipServerVersionCheck bool
|
|
|
|
HTTPClient *http.Client
|
|
|
|
TLSConfig *tls.Config
|
2016-09-23 20:43:03 +00:00
|
|
|
Dialer Dialer
|
2016-02-12 18:02:16 +00:00
|
|
|
|
|
|
|
endpoint string
|
|
|
|
endpointURL *url.URL
|
|
|
|
eventMonitor *eventMonitoringState
|
|
|
|
requestedAPIVersion APIVersion
|
|
|
|
serverAPIVersion APIVersion
|
|
|
|
expectedAPIVersion APIVersion
|
2016-09-23 20:43:03 +00:00
|
|
|
}
|
2016-06-21 18:11:48 +00:00
|
|
|
|
2016-09-23 20:43:03 +00:00
|
|
|
// Dialer is an interface that allows network connections to be dialed
|
|
|
|
// (net.Dialer fulfills this interface) and named pipes (a shim using
|
|
|
|
// winio.DialPipe)
|
|
|
|
type Dialer interface {
|
|
|
|
Dial(network, address string) (net.Conn, error)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewClient returns a Client instance ready for communication with the given
|
|
|
|
// server endpoint. It will use the latest remote API version available in the
|
|
|
|
// server.
|
|
|
|
func NewClient(endpoint string) (*Client, error) {
|
|
|
|
client, err := NewVersionedClient(endpoint, "")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
client.SkipServerVersionCheck = true
|
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewTLSClient returns a Client instance ready for TLS communications with the givens
|
|
|
|
// server endpoint, key and certificates . It will use the latest remote API version
|
|
|
|
// available in the server.
|
|
|
|
func NewTLSClient(endpoint string, cert, key, ca string) (*Client, error) {
|
|
|
|
client, err := NewVersionedTLSClient(endpoint, cert, key, ca, "")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
client.SkipServerVersionCheck = true
|
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewTLSClientFromBytes returns a Client instance ready for TLS communications with the givens
|
|
|
|
// server endpoint, key and certificates (passed inline to the function as opposed to being
|
|
|
|
// read from a local file). It will use the latest remote API version available in the server.
|
|
|
|
func NewTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte) (*Client, error) {
|
|
|
|
client, err := NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, "")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
client.SkipServerVersionCheck = true
|
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewVersionedClient returns a Client instance ready for communication with
|
|
|
|
// the given server endpoint, using a specific remote API version.
|
|
|
|
func NewVersionedClient(endpoint string, apiVersionString string) (*Client, error) {
|
|
|
|
u, err := parseEndpoint(endpoint, false)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var requestedAPIVersion APIVersion
|
|
|
|
if strings.Contains(apiVersionString, ".") {
|
|
|
|
requestedAPIVersion, err = NewAPIVersion(apiVersionString)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
c := &Client{
|
2017-08-10 16:19:19 +00:00
|
|
|
HTTPClient: defaultClient(),
|
2016-02-12 18:02:16 +00:00
|
|
|
Dialer: &net.Dialer{},
|
|
|
|
endpoint: endpoint,
|
|
|
|
endpointURL: u,
|
|
|
|
eventMonitor: new(eventMonitoringState),
|
|
|
|
requestedAPIVersion: requestedAPIVersion,
|
2016-09-23 20:43:03 +00:00
|
|
|
}
|
2018-11-29 22:08:16 +00:00
|
|
|
c.initializeNativeClient(defaultTransport)
|
2016-09-23 20:43:03 +00:00
|
|
|
return c, nil
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
2018-11-29 22:08:16 +00:00
|
|
|
// WithTransport replaces underlying HTTP client of Docker Client by accepting
|
|
|
|
// a function that returns pointer to a transport object.
|
|
|
|
func (c *Client) WithTransport(trFunc func() *http.Transport) {
|
|
|
|
c.initializeNativeClient(trFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewVersionnedTLSClient is like NewVersionedClient, but with ann extra n.
|
|
|
|
//
|
|
|
|
// Deprecated: Use NewVersionedTLSClient instead.
|
2016-02-12 18:02:16 +00:00
|
|
|
func NewVersionnedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) {
|
|
|
|
return NewVersionedTLSClient(endpoint, cert, key, ca, apiVersionString)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewVersionedTLSClient returns a Client instance ready for TLS communications with the givens
|
|
|
|
// server endpoint, key and certificates, using a specific remote API version.
|
|
|
|
func NewVersionedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) {
|
2017-02-15 01:34:05 +00:00
|
|
|
var certPEMBlock []byte
|
|
|
|
var keyPEMBlock []byte
|
|
|
|
var caPEMCert []byte
|
|
|
|
if _, err := os.Stat(cert); !os.IsNotExist(err) {
|
|
|
|
certPEMBlock, err = ioutil.ReadFile(cert)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2017-02-15 01:34:05 +00:00
|
|
|
if _, err := os.Stat(key); !os.IsNotExist(err) {
|
|
|
|
keyPEMBlock, err = ioutil.ReadFile(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2017-02-15 01:34:05 +00:00
|
|
|
if _, err := os.Stat(ca); !os.IsNotExist(err) {
|
|
|
|
caPEMCert, err = ioutil.ReadFile(ca)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
return NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, apiVersionString)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewClientFromEnv returns a Client instance ready for communication created from
|
2020-03-30 19:10:53 +00:00
|
|
|
// Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH,
|
|
|
|
// and DOCKER_API_VERSION.
|
2016-02-12 18:02:16 +00:00
|
|
|
//
|
|
|
|
// See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68.
|
|
|
|
// See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7.
|
2020-03-30 19:10:53 +00:00
|
|
|
// See https://github.com/moby/moby/blob/28d7dba41d0c0d9c7f0dafcc79d3c59f2b3f5dc3/client/options.go#L51
|
2016-02-12 18:02:16 +00:00
|
|
|
func NewClientFromEnv() (*Client, error) {
|
2020-03-30 19:10:53 +00:00
|
|
|
apiVersionString := os.Getenv("DOCKER_API_VERSION")
|
|
|
|
client, err := NewVersionedClientFromEnv(apiVersionString)
|
2016-02-12 18:02:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
client.SkipServerVersionCheck = apiVersionString == ""
|
2016-02-12 18:02:16 +00:00
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewVersionedClientFromEnv returns a Client instance ready for TLS communications created from
|
|
|
|
// Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH,
|
|
|
|
// and using a specific remote API version.
|
|
|
|
//
|
|
|
|
// See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68.
|
|
|
|
// See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7.
|
|
|
|
func NewVersionedClientFromEnv(apiVersionString string) (*Client, error) {
|
|
|
|
dockerEnv, err := getDockerEnv()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
dockerHost := dockerEnv.dockerHost
|
|
|
|
if dockerEnv.dockerTLSVerify {
|
|
|
|
parts := strings.SplitN(dockerEnv.dockerHost, "://", 2)
|
|
|
|
if len(parts) != 2 {
|
|
|
|
return nil, fmt.Errorf("could not split %s into two parts by ://", dockerHost)
|
|
|
|
}
|
|
|
|
cert := filepath.Join(dockerEnv.dockerCertPath, "cert.pem")
|
|
|
|
key := filepath.Join(dockerEnv.dockerCertPath, "key.pem")
|
|
|
|
ca := filepath.Join(dockerEnv.dockerCertPath, "ca.pem")
|
|
|
|
return NewVersionedTLSClient(dockerEnv.dockerHost, cert, key, ca, apiVersionString)
|
|
|
|
}
|
|
|
|
return NewVersionedClient(dockerEnv.dockerHost, apiVersionString)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewVersionedTLSClientFromBytes returns a Client instance ready for TLS communications with the givens
|
|
|
|
// server endpoint, key and certificates (passed inline to the function as opposed to being
|
|
|
|
// read from a local file), using a specific remote API version.
|
|
|
|
func NewVersionedTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte, apiVersionString string) (*Client, error) {
|
|
|
|
u, err := parseEndpoint(endpoint, true)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var requestedAPIVersion APIVersion
|
|
|
|
if strings.Contains(apiVersionString, ".") {
|
|
|
|
requestedAPIVersion, err = NewAPIVersion(apiVersionString)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2017-02-15 01:34:05 +00:00
|
|
|
tlsConfig := &tls.Config{}
|
|
|
|
if certPEMBlock != nil && keyPEMBlock != nil {
|
|
|
|
tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
tlsConfig.Certificates = []tls.Certificate{tlsCert}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
if caPEMCert == nil {
|
|
|
|
tlsConfig.InsecureSkipVerify = true
|
|
|
|
} else {
|
|
|
|
caPool := x509.NewCertPool()
|
|
|
|
if !caPool.AppendCertsFromPEM(caPEMCert) {
|
2020-03-30 19:10:53 +00:00
|
|
|
return nil, errors.New("could not add RootCA pem")
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
tlsConfig.RootCAs = caPool
|
|
|
|
}
|
2017-08-10 16:19:19 +00:00
|
|
|
tr := defaultTransport()
|
2016-02-12 18:02:16 +00:00
|
|
|
tr.TLSClientConfig = tlsConfig
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
c := &Client{
|
2016-02-12 18:02:16 +00:00
|
|
|
HTTPClient: &http.Client{Transport: tr},
|
|
|
|
TLSConfig: tlsConfig,
|
|
|
|
Dialer: &net.Dialer{},
|
|
|
|
endpoint: endpoint,
|
|
|
|
endpointURL: u,
|
|
|
|
eventMonitor: new(eventMonitoringState),
|
|
|
|
requestedAPIVersion: requestedAPIVersion,
|
2016-09-23 20:43:03 +00:00
|
|
|
}
|
2018-11-29 22:08:16 +00:00
|
|
|
c.initializeNativeClient(defaultTransport)
|
2016-09-23 20:43:03 +00:00
|
|
|
return c, nil
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
2017-11-14 23:27:57 +00:00
|
|
|
// SetTimeout takes a timeout and applies it to the HTTPClient. It should not
|
|
|
|
// be called concurrently with any other Client methods.
|
2016-06-21 18:11:48 +00:00
|
|
|
func (c *Client) SetTimeout(t time.Duration) {
|
2016-09-23 20:43:03 +00:00
|
|
|
if c.HTTPClient != nil {
|
|
|
|
c.HTTPClient.Timeout = t
|
|
|
|
}
|
2016-06-21 18:11:48 +00:00
|
|
|
}
|
|
|
|
|
2016-02-12 18:02:16 +00:00
|
|
|
func (c *Client) checkAPIVersion() error {
|
|
|
|
serverAPIVersionString, err := c.getServerAPIVersionString()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.serverAPIVersion, err = NewAPIVersion(serverAPIVersionString)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if c.requestedAPIVersion == nil {
|
|
|
|
c.expectedAPIVersion = c.serverAPIVersion
|
|
|
|
} else {
|
|
|
|
c.expectedAPIVersion = c.requestedAPIVersion
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Endpoint returns the current endpoint. It's useful for getting the endpoint
|
|
|
|
// when using functions that get this data from the environment (like
|
|
|
|
// NewClientFromEnv.
|
|
|
|
func (c *Client) Endpoint() string {
|
|
|
|
return c.endpoint
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ping pings the docker server
|
|
|
|
//
|
2017-02-15 01:34:05 +00:00
|
|
|
// See https://goo.gl/wYfgY1 for more details.
|
2016-02-12 18:02:16 +00:00
|
|
|
func (c *Client) Ping() error {
|
2020-03-30 19:10:53 +00:00
|
|
|
return c.PingWithContext(context.TODO())
|
2017-02-15 01:34:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// PingWithContext pings the docker server
|
|
|
|
// The context object can be used to cancel the ping request.
|
|
|
|
//
|
|
|
|
// See https://goo.gl/wYfgY1 for more details.
|
|
|
|
func (c *Client) PingWithContext(ctx context.Context) error {
|
2016-02-12 18:02:16 +00:00
|
|
|
path := "/_ping"
|
2020-03-30 19:10:53 +00:00
|
|
|
resp, err := c.do(http.MethodGet, path, doOptions{context: ctx})
|
2016-02-12 18:02:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return newError(resp)
|
|
|
|
}
|
|
|
|
resp.Body.Close()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) getServerAPIVersionString() (version string, err error) {
|
2020-03-30 19:10:53 +00:00
|
|
|
resp, err := c.do(http.MethodGet, "/version", doOptions{})
|
2016-02-12 18:02:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
2020-03-30 19:10:53 +00:00
|
|
|
return "", fmt.Errorf("received unexpected status %d while trying to retrieve the server version", resp.StatusCode)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
var versionResponse map[string]interface{}
|
|
|
|
if err := json.NewDecoder(resp.Body).Decode(&versionResponse); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if version, ok := (versionResponse["ApiVersion"]).(string); ok {
|
|
|
|
return version, nil
|
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type doOptions struct {
|
|
|
|
data interface{}
|
|
|
|
forceJSON bool
|
|
|
|
headers map[string]string
|
2016-09-23 20:43:03 +00:00
|
|
|
context context.Context
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) do(method, path string, doOptions doOptions) (*http.Response, error) {
|
|
|
|
var params io.Reader
|
|
|
|
if doOptions.data != nil || doOptions.forceJSON {
|
|
|
|
buf, err := json.Marshal(doOptions.data)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
params = bytes.NewBuffer(buf)
|
|
|
|
}
|
|
|
|
if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil {
|
|
|
|
err := c.checkAPIVersion()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
protocol := c.endpointURL.Scheme
|
|
|
|
var u string
|
2016-09-23 20:43:03 +00:00
|
|
|
switch protocol {
|
|
|
|
case unixProtocol, namedPipeProtocol:
|
|
|
|
u = c.getFakeNativeURL(path)
|
|
|
|
default:
|
2016-02-12 18:02:16 +00:00
|
|
|
u = c.getURL(path)
|
|
|
|
}
|
2016-06-21 18:11:48 +00:00
|
|
|
|
2016-02-12 18:02:16 +00:00
|
|
|
req, err := http.NewRequest(method, u, params)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
req.Header.Set("User-Agent", userAgent)
|
|
|
|
if doOptions.data != nil {
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
2020-03-30 19:10:53 +00:00
|
|
|
} else if method == http.MethodPost {
|
2016-02-12 18:02:16 +00:00
|
|
|
req.Header.Set("Content-Type", "plain/text")
|
|
|
|
}
|
|
|
|
|
|
|
|
for k, v := range doOptions.headers {
|
|
|
|
req.Header.Set(k, v)
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
|
|
|
|
ctx := doOptions.context
|
|
|
|
if ctx == nil {
|
|
|
|
ctx = context.Background()
|
|
|
|
}
|
|
|
|
|
2018-11-29 22:08:16 +00:00
|
|
|
resp, err := c.HTTPClient.Do(req.WithContext(ctx))
|
2016-02-12 18:02:16 +00:00
|
|
|
if err != nil {
|
|
|
|
if strings.Contains(err.Error(), "connection refused") {
|
|
|
|
return nil, ErrConnectionRefused
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
|
|
|
|
return nil, chooseError(ctx, err)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
|
|
|
|
return nil, newError(resp)
|
|
|
|
}
|
|
|
|
return resp, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type streamOptions struct {
|
|
|
|
setRawTerminal bool
|
|
|
|
rawJSONStream bool
|
|
|
|
useJSONDecoder bool
|
|
|
|
headers map[string]string
|
|
|
|
in io.Reader
|
|
|
|
stdout io.Writer
|
|
|
|
stderr io.Writer
|
2017-08-10 16:19:19 +00:00
|
|
|
reqSent chan struct{}
|
2016-05-27 10:30:04 +00:00
|
|
|
// timeout is the initial connection timeout
|
2016-02-12 18:02:16 +00:00
|
|
|
timeout time.Duration
|
2016-05-27 10:30:04 +00:00
|
|
|
// Timeout with no data is received, it's reset every time new data
|
|
|
|
// arrives
|
|
|
|
inactivityTimeout time.Duration
|
2016-09-23 20:43:03 +00:00
|
|
|
context context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
// if error in context, return that instead of generic http error
|
|
|
|
func chooseError(ctx context.Context, err error) error {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
default:
|
|
|
|
return err
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) stream(method, path string, streamOptions streamOptions) error {
|
2020-03-30 19:10:53 +00:00
|
|
|
if (method == http.MethodPost || method == http.MethodPut) && streamOptions.in == nil {
|
2016-02-12 18:02:16 +00:00
|
|
|
streamOptions.in = bytes.NewReader(nil)
|
|
|
|
}
|
|
|
|
if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil {
|
|
|
|
err := c.checkAPIVersion()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
return c.streamURL(method, c.getURL(path), streamOptions)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) streamURL(method, url string, streamOptions streamOptions) error {
|
|
|
|
if (method == http.MethodPost || method == http.MethodPut) && streamOptions.in == nil {
|
|
|
|
streamOptions.in = bytes.NewReader(nil)
|
|
|
|
}
|
|
|
|
if !c.SkipServerVersionCheck && c.expectedAPIVersion == nil {
|
|
|
|
err := c.checkAPIVersion()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
req, err := http.NewRequest(method, url, streamOptions.in)
|
2016-02-12 18:02:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
req.Header.Set("User-Agent", userAgent)
|
2020-03-30 19:10:53 +00:00
|
|
|
if method == http.MethodPost {
|
2016-02-12 18:02:16 +00:00
|
|
|
req.Header.Set("Content-Type", "plain/text")
|
|
|
|
}
|
|
|
|
for key, val := range streamOptions.headers {
|
|
|
|
req.Header.Set(key, val)
|
|
|
|
}
|
|
|
|
var resp *http.Response
|
|
|
|
protocol := c.endpointURL.Scheme
|
|
|
|
address := c.endpointURL.Path
|
|
|
|
if streamOptions.stdout == nil {
|
|
|
|
streamOptions.stdout = ioutil.Discard
|
|
|
|
}
|
|
|
|
if streamOptions.stderr == nil {
|
|
|
|
streamOptions.stderr = ioutil.Discard
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
|
|
|
|
// make a sub-context so that our active cancellation does not affect parent
|
|
|
|
ctx := streamOptions.context
|
|
|
|
if ctx == nil {
|
|
|
|
ctx = context.Background()
|
|
|
|
}
|
|
|
|
subCtx, cancelRequest := context.WithCancel(ctx)
|
|
|
|
defer cancelRequest()
|
|
|
|
|
|
|
|
if protocol == unixProtocol || protocol == namedPipeProtocol {
|
|
|
|
var dial net.Conn
|
|
|
|
dial, err = c.Dialer.Dial(protocol, address)
|
2016-02-12 18:02:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
go func() {
|
|
|
|
<-subCtx.Done()
|
|
|
|
dial.Close()
|
|
|
|
}()
|
2016-02-12 18:02:16 +00:00
|
|
|
breader := bufio.NewReader(dial)
|
|
|
|
err = req.Write(dial)
|
|
|
|
if err != nil {
|
2016-09-23 20:43:03 +00:00
|
|
|
return chooseError(subCtx, err)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ReadResponse may hang if server does not replay
|
|
|
|
if streamOptions.timeout > 0 {
|
|
|
|
dial.SetDeadline(time.Now().Add(streamOptions.timeout))
|
|
|
|
}
|
|
|
|
|
2017-08-10 16:19:19 +00:00
|
|
|
if streamOptions.reqSent != nil {
|
|
|
|
close(streamOptions.reqSent)
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
if resp, err = http.ReadResponse(breader, req); err != nil {
|
|
|
|
// Cancel timeout for future I/O operations
|
|
|
|
if streamOptions.timeout > 0 {
|
|
|
|
dial.SetDeadline(time.Time{})
|
|
|
|
}
|
|
|
|
if strings.Contains(err.Error(), "connection refused") {
|
|
|
|
return ErrConnectionRefused
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
|
|
|
|
return chooseError(subCtx, err)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
defer resp.Body.Close()
|
2016-02-12 18:02:16 +00:00
|
|
|
} else {
|
2018-11-29 22:08:16 +00:00
|
|
|
if resp, err = c.HTTPClient.Do(req.WithContext(subCtx)); err != nil {
|
2016-02-12 18:02:16 +00:00
|
|
|
if strings.Contains(err.Error(), "connection refused") {
|
|
|
|
return ErrConnectionRefused
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
return chooseError(subCtx, err)
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
defer resp.Body.Close()
|
2017-08-10 16:19:19 +00:00
|
|
|
if streamOptions.reqSent != nil {
|
|
|
|
close(streamOptions.reqSent)
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
|
|
|
|
return newError(resp)
|
|
|
|
}
|
2016-05-27 10:30:04 +00:00
|
|
|
var canceled uint32
|
|
|
|
if streamOptions.inactivityTimeout > 0 {
|
2017-02-22 00:21:13 +00:00
|
|
|
var ch chan<- struct{}
|
|
|
|
resp.Body, ch = handleInactivityTimeout(resp.Body, streamOptions.inactivityTimeout, cancelRequest, &canceled)
|
2016-05-27 10:30:04 +00:00
|
|
|
defer close(ch)
|
|
|
|
}
|
|
|
|
err = handleStreamResponse(resp, &streamOptions)
|
|
|
|
if err != nil {
|
|
|
|
if atomic.LoadUint32(&canceled) != 0 {
|
|
|
|
return ErrInactivityTimeout
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
return chooseError(subCtx, err)
|
2016-05-27 10:30:04 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleStreamResponse(resp *http.Response, streamOptions *streamOptions) error {
|
|
|
|
var err error
|
|
|
|
if !streamOptions.useJSONDecoder && resp.Header.Get("Content-Type") != "application/json" {
|
2016-02-12 18:02:16 +00:00
|
|
|
if streamOptions.setRawTerminal {
|
|
|
|
_, err = io.Copy(streamOptions.stdout, resp.Body)
|
|
|
|
} else {
|
|
|
|
_, err = stdcopy.StdCopy(streamOptions.stdout, streamOptions.stderr, resp.Body)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2016-05-27 10:30:04 +00:00
|
|
|
// if we want to get raw json stream, just copy it back to output
|
|
|
|
// without decoding it
|
|
|
|
if streamOptions.rawJSONStream {
|
|
|
|
_, err = io.Copy(streamOptions.stdout, resp.Body)
|
|
|
|
return err
|
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
if st, ok := streamOptions.stdout.(stream); ok {
|
2017-02-15 01:34:05 +00:00
|
|
|
err = jsonmessage.DisplayJSONMessagesToStream(resp.Body, st, nil)
|
|
|
|
} else {
|
|
|
|
err = jsonmessage.DisplayJSONMessagesStream(resp.Body, streamOptions.stdout, 0, false, nil)
|
2016-05-27 10:30:04 +00:00
|
|
|
}
|
2017-02-15 01:34:05 +00:00
|
|
|
return err
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
2020-03-30 19:10:53 +00:00
|
|
|
type stream interface {
|
|
|
|
io.Writer
|
|
|
|
FD() uintptr
|
|
|
|
IsTerminal() bool
|
|
|
|
}
|
|
|
|
|
2017-02-22 00:21:13 +00:00
|
|
|
type proxyReader struct {
|
|
|
|
io.ReadCloser
|
2016-05-27 10:30:04 +00:00
|
|
|
calls uint64
|
|
|
|
}
|
|
|
|
|
2017-02-22 00:21:13 +00:00
|
|
|
func (p *proxyReader) callCount() uint64 {
|
2016-05-27 10:30:04 +00:00
|
|
|
return atomic.LoadUint64(&p.calls)
|
|
|
|
}
|
|
|
|
|
2017-02-22 00:21:13 +00:00
|
|
|
func (p *proxyReader) Read(data []byte) (int, error) {
|
2016-05-27 10:30:04 +00:00
|
|
|
atomic.AddUint64(&p.calls, 1)
|
2017-02-22 00:21:13 +00:00
|
|
|
return p.ReadCloser.Read(data)
|
2016-05-27 10:30:04 +00:00
|
|
|
}
|
|
|
|
|
2017-02-22 00:21:13 +00:00
|
|
|
func handleInactivityTimeout(reader io.ReadCloser, timeout time.Duration, cancelRequest func(), canceled *uint32) (io.ReadCloser, chan<- struct{}) {
|
2016-05-27 10:30:04 +00:00
|
|
|
done := make(chan struct{})
|
2017-02-22 00:21:13 +00:00
|
|
|
proxyReader := &proxyReader{ReadCloser: reader}
|
2016-05-27 10:30:04 +00:00
|
|
|
go func() {
|
|
|
|
var lastCallCount uint64
|
|
|
|
for {
|
|
|
|
select {
|
2017-02-22 00:21:13 +00:00
|
|
|
case <-time.After(timeout):
|
2016-05-27 10:30:04 +00:00
|
|
|
case <-done:
|
|
|
|
return
|
|
|
|
}
|
2017-02-22 00:21:13 +00:00
|
|
|
curCallCount := proxyReader.callCount()
|
2016-05-27 10:30:04 +00:00
|
|
|
if curCallCount == lastCallCount {
|
|
|
|
atomic.AddUint32(canceled, 1)
|
|
|
|
cancelRequest()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
lastCallCount = curCallCount
|
|
|
|
}
|
|
|
|
}()
|
2017-02-22 00:21:13 +00:00
|
|
|
return proxyReader, done
|
2016-05-27 10:30:04 +00:00
|
|
|
}
|
|
|
|
|
2016-02-12 18:02:16 +00:00
|
|
|
type hijackOptions struct {
|
|
|
|
success chan struct{}
|
|
|
|
setRawTerminal bool
|
|
|
|
in io.Reader
|
|
|
|
stdout io.Writer
|
|
|
|
stderr io.Writer
|
|
|
|
data interface{}
|
|
|
|
}
|
|
|
|
|
2016-03-25 00:42:00 +00:00
|
|
|
// CloseWaiter is an interface with methods for closing the underlying resource
|
|
|
|
// and then waiting for it to finish processing.
|
2016-02-12 18:02:16 +00:00
|
|
|
type CloseWaiter interface {
|
|
|
|
io.Closer
|
|
|
|
Wait() error
|
|
|
|
}
|
|
|
|
|
|
|
|
type waiterFunc func() error
|
|
|
|
|
|
|
|
func (w waiterFunc) Wait() error { return w() }
|
|
|
|
|
|
|
|
type closerFunc func() error
|
|
|
|
|
|
|
|
func (c closerFunc) Close() error { return c() }
|
|
|
|
|
|
|
|
func (c *Client) hijack(method, path string, hijackOptions hijackOptions) (CloseWaiter, error) {
|
|
|
|
if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil {
|
|
|
|
err := c.checkAPIVersion()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
var params io.Reader
|
|
|
|
if hijackOptions.data != nil {
|
|
|
|
buf, err := json.Marshal(hijackOptions.data)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
params = bytes.NewBuffer(buf)
|
|
|
|
}
|
|
|
|
req, err := http.NewRequest(method, c.getURL(path), params)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-03-25 00:42:00 +00:00
|
|
|
req.Header.Set("Content-Type", "application/json")
|
2016-02-12 18:02:16 +00:00
|
|
|
req.Header.Set("Connection", "Upgrade")
|
|
|
|
req.Header.Set("Upgrade", "tcp")
|
|
|
|
protocol := c.endpointURL.Scheme
|
|
|
|
address := c.endpointURL.Path
|
2016-09-23 20:43:03 +00:00
|
|
|
if protocol != unixProtocol && protocol != namedPipeProtocol {
|
2016-02-12 18:02:16 +00:00
|
|
|
protocol = "tcp"
|
|
|
|
address = c.endpointURL.Host
|
|
|
|
}
|
|
|
|
var dial net.Conn
|
2016-09-23 20:43:03 +00:00
|
|
|
if c.TLSConfig != nil && protocol != unixProtocol && protocol != namedPipeProtocol {
|
|
|
|
netDialer, ok := c.Dialer.(*net.Dialer)
|
|
|
|
if !ok {
|
|
|
|
return nil, ErrTLSNotSupported
|
|
|
|
}
|
|
|
|
dial, err = tlsDialWithDialer(netDialer, protocol, address, c.TLSConfig)
|
2016-02-12 18:02:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
dial, err = c.Dialer.Dial(protocol, address)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-23 20:43:03 +00:00
|
|
|
errs := make(chan error, 1)
|
2016-02-12 18:02:16 +00:00
|
|
|
quit := make(chan struct{})
|
|
|
|
go func() {
|
2020-03-30 19:10:53 +00:00
|
|
|
//nolint:staticcheck
|
2016-02-12 18:02:16 +00:00
|
|
|
clientconn := httputil.NewClientConn(dial, nil)
|
|
|
|
defer clientconn.Close()
|
2020-03-30 19:10:53 +00:00
|
|
|
//nolint:bodyclose
|
2016-02-12 18:02:16 +00:00
|
|
|
clientconn.Do(req)
|
|
|
|
if hijackOptions.success != nil {
|
|
|
|
hijackOptions.success <- struct{}{}
|
|
|
|
<-hijackOptions.success
|
|
|
|
}
|
|
|
|
rwc, br := clientconn.Hijack()
|
|
|
|
defer rwc.Close()
|
|
|
|
|
|
|
|
errChanOut := make(chan error, 1)
|
2016-09-23 20:43:03 +00:00
|
|
|
errChanIn := make(chan error, 2)
|
2016-02-12 18:02:16 +00:00
|
|
|
if hijackOptions.stdout == nil && hijackOptions.stderr == nil {
|
|
|
|
close(errChanOut)
|
|
|
|
} else {
|
|
|
|
// Only copy if hijackOptions.stdout and/or hijackOptions.stderr is actually set.
|
|
|
|
// Otherwise, if the only stream you care about is stdin, your attach session
|
|
|
|
// will "hang" until the container terminates, even though you're not reading
|
|
|
|
// stdout/stderr
|
|
|
|
if hijackOptions.stdout == nil {
|
|
|
|
hijackOptions.stdout = ioutil.Discard
|
|
|
|
}
|
|
|
|
if hijackOptions.stderr == nil {
|
|
|
|
hijackOptions.stderr = ioutil.Discard
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
defer func() {
|
|
|
|
if hijackOptions.in != nil {
|
|
|
|
if closer, ok := hijackOptions.in.(io.Closer); ok {
|
|
|
|
closer.Close()
|
|
|
|
}
|
|
|
|
errChanIn <- nil
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
var err error
|
|
|
|
if hijackOptions.setRawTerminal {
|
|
|
|
_, err = io.Copy(hijackOptions.stdout, br)
|
|
|
|
} else {
|
|
|
|
_, err = stdcopy.StdCopy(hijackOptions.stdout, hijackOptions.stderr, br)
|
|
|
|
}
|
|
|
|
errChanOut <- err
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
var err error
|
|
|
|
if hijackOptions.in != nil {
|
|
|
|
_, err = io.Copy(rwc, hijackOptions.in)
|
|
|
|
}
|
|
|
|
errChanIn <- err
|
|
|
|
rwc.(interface {
|
|
|
|
CloseWrite() error
|
|
|
|
}).CloseWrite()
|
|
|
|
}()
|
|
|
|
|
|
|
|
var errIn error
|
|
|
|
select {
|
|
|
|
case errIn = <-errChanIn:
|
|
|
|
case <-quit:
|
|
|
|
}
|
|
|
|
|
|
|
|
var errOut error
|
|
|
|
select {
|
|
|
|
case errOut = <-errChanOut:
|
|
|
|
case <-quit:
|
|
|
|
}
|
|
|
|
|
|
|
|
if errIn != nil {
|
|
|
|
errs <- errIn
|
|
|
|
} else {
|
|
|
|
errs <- errOut
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return struct {
|
|
|
|
closerFunc
|
|
|
|
waiterFunc
|
|
|
|
}{
|
|
|
|
closerFunc(func() error { close(quit); return nil }),
|
|
|
|
waiterFunc(func() error { return <-errs }),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) getURL(path string) string {
|
|
|
|
urlStr := strings.TrimRight(c.endpointURL.String(), "/")
|
2016-09-23 20:43:03 +00:00
|
|
|
if c.endpointURL.Scheme == unixProtocol || c.endpointURL.Scheme == namedPipeProtocol {
|
2016-02-12 18:02:16 +00:00
|
|
|
urlStr = ""
|
|
|
|
}
|
|
|
|
if c.requestedAPIVersion != nil {
|
|
|
|
return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s%s", urlStr, path)
|
|
|
|
}
|
|
|
|
|
2020-03-30 19:10:53 +00:00
|
|
|
func (c *Client) getPath(basepath string, opts interface{}) (string, error) {
|
|
|
|
queryStr, requiredAPIVersion := queryStringVersion(opts)
|
|
|
|
return c.pathVersionCheck(basepath, queryStr, requiredAPIVersion)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) pathVersionCheck(basepath, queryStr string, requiredAPIVersion APIVersion) (string, error) {
|
|
|
|
urlStr := strings.TrimRight(c.endpointURL.String(), "/")
|
|
|
|
if c.endpointURL.Scheme == unixProtocol || c.endpointURL.Scheme == namedPipeProtocol {
|
|
|
|
urlStr = ""
|
|
|
|
}
|
|
|
|
if c.requestedAPIVersion != nil {
|
|
|
|
if c.requestedAPIVersion.GreaterThanOrEqualTo(requiredAPIVersion) {
|
|
|
|
return fmt.Sprintf("%s/v%s%s?%s", urlStr, c.requestedAPIVersion, basepath, queryStr), nil
|
|
|
|
}
|
|
|
|
return "", fmt.Errorf("API %s requires version %s, requested version %s is insufficient",
|
|
|
|
basepath, requiredAPIVersion, c.requestedAPIVersion)
|
|
|
|
}
|
|
|
|
if requiredAPIVersion != nil {
|
|
|
|
return fmt.Sprintf("%s/v%s%s?%s", urlStr, requiredAPIVersion, basepath, queryStr), nil
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s%s?%s", urlStr, basepath, queryStr), nil
|
|
|
|
}
|
|
|
|
|
2016-09-23 20:43:03 +00:00
|
|
|
// getFakeNativeURL returns the URL needed to make an HTTP request over a UNIX
|
2016-02-12 18:02:16 +00:00
|
|
|
// domain socket to the given path.
|
2016-09-23 20:43:03 +00:00
|
|
|
func (c *Client) getFakeNativeURL(path string) string {
|
2016-02-12 18:02:16 +00:00
|
|
|
u := *c.endpointURL // Copy.
|
|
|
|
|
|
|
|
// Override URL so that net/http will not complain.
|
|
|
|
u.Scheme = "http"
|
|
|
|
u.Host = "unix.sock" // Doesn't matter what this is - it's not used.
|
|
|
|
u.Path = ""
|
|
|
|
urlStr := strings.TrimRight(u.String(), "/")
|
|
|
|
if c.requestedAPIVersion != nil {
|
|
|
|
return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s%s", urlStr, path)
|
|
|
|
}
|
|
|
|
|
2020-03-30 19:10:53 +00:00
|
|
|
func queryStringVersion(opts interface{}) (string, APIVersion) {
|
2016-02-12 18:02:16 +00:00
|
|
|
if opts == nil {
|
2020-03-30 19:10:53 +00:00
|
|
|
return "", nil
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
value := reflect.ValueOf(opts)
|
|
|
|
if value.Kind() == reflect.Ptr {
|
|
|
|
value = value.Elem()
|
|
|
|
}
|
|
|
|
if value.Kind() != reflect.Struct {
|
2020-03-30 19:10:53 +00:00
|
|
|
return "", nil
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
var apiVersion APIVersion
|
2016-02-12 18:02:16 +00:00
|
|
|
items := url.Values(map[string][]string{})
|
|
|
|
for i := 0; i < value.NumField(); i++ {
|
|
|
|
field := value.Type().Field(i)
|
|
|
|
if field.PkgPath != "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
key := field.Tag.Get("qs")
|
|
|
|
if key == "" {
|
|
|
|
key = strings.ToLower(field.Name)
|
|
|
|
} else if key == "-" {
|
|
|
|
continue
|
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
if addQueryStringValue(items, key, value.Field(i)) {
|
|
|
|
verstr := field.Tag.Get("ver")
|
|
|
|
if verstr != "" {
|
|
|
|
ver, _ := NewAPIVersion(verstr)
|
|
|
|
if apiVersion == nil {
|
|
|
|
apiVersion = ver
|
|
|
|
} else if ver.GreaterThan(apiVersion) {
|
|
|
|
apiVersion = ver
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
return items.Encode(), apiVersion
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
2020-03-30 19:10:53 +00:00
|
|
|
func queryString(opts interface{}) string {
|
|
|
|
s, _ := queryStringVersion(opts)
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func addQueryStringValue(items url.Values, key string, v reflect.Value) bool {
|
2016-02-12 18:02:16 +00:00
|
|
|
switch v.Kind() {
|
|
|
|
case reflect.Bool:
|
|
|
|
if v.Bool() {
|
|
|
|
items.Add(key, "1")
|
2020-03-30 19:10:53 +00:00
|
|
|
return true
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
|
|
if v.Int() > 0 {
|
|
|
|
items.Add(key, strconv.FormatInt(v.Int(), 10))
|
2020-03-30 19:10:53 +00:00
|
|
|
return true
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2018-11-29 22:08:16 +00:00
|
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
|
|
if v.Uint() > 0 {
|
|
|
|
items.Add(key, strconv.FormatUint(v.Uint(), 10))
|
2020-03-30 19:10:53 +00:00
|
|
|
return true
|
2018-11-29 22:08:16 +00:00
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
case reflect.Float32, reflect.Float64:
|
|
|
|
if v.Float() > 0 {
|
|
|
|
items.Add(key, strconv.FormatFloat(v.Float(), 'f', -1, 64))
|
2020-03-30 19:10:53 +00:00
|
|
|
return true
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
case reflect.String:
|
|
|
|
if v.String() != "" {
|
|
|
|
items.Add(key, v.String())
|
2020-03-30 19:10:53 +00:00
|
|
|
return true
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
case reflect.Ptr:
|
|
|
|
if !v.IsNil() {
|
|
|
|
if b, err := json.Marshal(v.Interface()); err == nil {
|
|
|
|
items.Add(key, string(b))
|
2020-03-30 19:10:53 +00:00
|
|
|
return true
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
case reflect.Map:
|
|
|
|
if len(v.MapKeys()) > 0 {
|
|
|
|
if b, err := json.Marshal(v.Interface()); err == nil {
|
|
|
|
items.Add(key, string(b))
|
2020-03-30 19:10:53 +00:00
|
|
|
return true
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
case reflect.Array, reflect.Slice:
|
|
|
|
vLen := v.Len()
|
2020-03-30 19:10:53 +00:00
|
|
|
var valuesAdded int
|
2016-02-12 18:02:16 +00:00
|
|
|
if vLen > 0 {
|
|
|
|
for i := 0; i < vLen; i++ {
|
2020-03-30 19:10:53 +00:00
|
|
|
if addQueryStringValue(items, key, v.Index(i)) {
|
|
|
|
valuesAdded++
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
return valuesAdded > 0
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
2020-03-30 19:10:53 +00:00
|
|
|
return false
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Error represents failures in the API. It represents a failure from the API.
|
|
|
|
type Error struct {
|
|
|
|
Status int
|
|
|
|
Message string
|
|
|
|
}
|
|
|
|
|
|
|
|
func newError(resp *http.Response) *Error {
|
2018-11-29 22:08:16 +00:00
|
|
|
type ErrMsg struct {
|
|
|
|
Message string `json:"message"`
|
|
|
|
}
|
2016-02-12 18:02:16 +00:00
|
|
|
defer resp.Body.Close()
|
|
|
|
data, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return &Error{Status: resp.StatusCode, Message: fmt.Sprintf("cannot read body, err: %v", err)}
|
|
|
|
}
|
2018-11-29 22:08:16 +00:00
|
|
|
var emsg ErrMsg
|
|
|
|
err = json.Unmarshal(data, &emsg)
|
|
|
|
if err != nil {
|
|
|
|
return &Error{Status: resp.StatusCode, Message: string(data)}
|
|
|
|
}
|
|
|
|
return &Error{Status: resp.StatusCode, Message: emsg.Message}
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Error) Error() string {
|
|
|
|
return fmt.Sprintf("API error (%d): %s", e.Status, e.Message)
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseEndpoint(endpoint string, tls bool) (*url.URL, error) {
|
|
|
|
if endpoint != "" && !strings.Contains(endpoint, "://") {
|
|
|
|
endpoint = "tcp://" + endpoint
|
|
|
|
}
|
|
|
|
u, err := url.Parse(endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, ErrInvalidEndpoint
|
|
|
|
}
|
2016-09-23 20:43:03 +00:00
|
|
|
if tls && u.Scheme != "unix" {
|
2016-02-12 18:02:16 +00:00
|
|
|
u.Scheme = "https"
|
|
|
|
}
|
|
|
|
switch u.Scheme {
|
2016-09-23 20:43:03 +00:00
|
|
|
case unixProtocol, namedPipeProtocol:
|
2016-02-12 18:02:16 +00:00
|
|
|
return u, nil
|
|
|
|
case "http", "https", "tcp":
|
|
|
|
_, port, err := net.SplitHostPort(u.Host)
|
|
|
|
if err != nil {
|
|
|
|
if e, ok := err.(*net.AddrError); ok {
|
|
|
|
if e.Err == "missing port in address" {
|
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, ErrInvalidEndpoint
|
|
|
|
}
|
|
|
|
number, err := strconv.ParseInt(port, 10, 64)
|
|
|
|
if err == nil && number > 0 && number < 65536 {
|
|
|
|
if u.Scheme == "tcp" {
|
|
|
|
if tls {
|
|
|
|
u.Scheme = "https"
|
|
|
|
} else {
|
|
|
|
u.Scheme = "http"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
return nil, ErrInvalidEndpoint
|
|
|
|
default:
|
|
|
|
return nil, ErrInvalidEndpoint
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type dockerEnv struct {
|
|
|
|
dockerHost string
|
|
|
|
dockerTLSVerify bool
|
|
|
|
dockerCertPath string
|
|
|
|
}
|
|
|
|
|
|
|
|
func getDockerEnv() (*dockerEnv, error) {
|
|
|
|
dockerHost := os.Getenv("DOCKER_HOST")
|
|
|
|
var err error
|
|
|
|
if dockerHost == "" {
|
2020-03-30 19:10:53 +00:00
|
|
|
dockerHost = defaultHost
|
2016-02-12 18:02:16 +00:00
|
|
|
}
|
|
|
|
dockerTLSVerify := os.Getenv("DOCKER_TLS_VERIFY") != ""
|
|
|
|
var dockerCertPath string
|
|
|
|
if dockerTLSVerify {
|
|
|
|
dockerCertPath = os.Getenv("DOCKER_CERT_PATH")
|
|
|
|
if dockerCertPath == "" {
|
|
|
|
home := homedir.Get()
|
|
|
|
if home == "" {
|
|
|
|
return nil, errors.New("environment variable HOME must be set if DOCKER_CERT_PATH is not set")
|
|
|
|
}
|
|
|
|
dockerCertPath = filepath.Join(home, ".docker")
|
|
|
|
dockerCertPath, err = filepath.Abs(dockerCertPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return &dockerEnv{
|
|
|
|
dockerHost: dockerHost,
|
|
|
|
dockerTLSVerify: dockerTLSVerify,
|
|
|
|
dockerCertPath: dockerCertPath,
|
|
|
|
}, nil
|
|
|
|
}
|
2017-08-10 16:19:19 +00:00
|
|
|
|
|
|
|
// defaultTransport returns a new http.Transport with similar default values to
|
|
|
|
// http.DefaultTransport, but with idle connections and keepalives disabled.
|
|
|
|
func defaultTransport() *http.Transport {
|
|
|
|
transport := defaultPooledTransport()
|
|
|
|
transport.DisableKeepAlives = true
|
|
|
|
transport.MaxIdleConnsPerHost = -1
|
|
|
|
return transport
|
|
|
|
}
|
|
|
|
|
|
|
|
// defaultPooledTransport returns a new http.Transport with similar default
|
|
|
|
// values to http.DefaultTransport. Do not use this for transient transports as
|
|
|
|
// it can leak file descriptors over time. Only use this for transports that
|
|
|
|
// will be re-used for the same host(s).
|
|
|
|
func defaultPooledTransport() *http.Transport {
|
|
|
|
transport := &http.Transport{
|
|
|
|
Proxy: http.ProxyFromEnvironment,
|
|
|
|
DialContext: (&net.Dialer{
|
|
|
|
Timeout: 30 * time.Second,
|
|
|
|
KeepAlive: 30 * time.Second,
|
|
|
|
}).DialContext,
|
|
|
|
MaxIdleConns: 100,
|
|
|
|
IdleConnTimeout: 90 * time.Second,
|
|
|
|
TLSHandshakeTimeout: 10 * time.Second,
|
|
|
|
ExpectContinueTimeout: 1 * time.Second,
|
|
|
|
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
|
|
|
|
}
|
|
|
|
return transport
|
|
|
|
}
|
|
|
|
|
|
|
|
// defaultClient returns a new http.Client with similar default values to
|
|
|
|
// http.Client, but with a non-shared Transport, idle connections disabled, and
|
|
|
|
// keepalives disabled.
|
|
|
|
func defaultClient() *http.Client {
|
|
|
|
return &http.Client{
|
|
|
|
Transport: defaultTransport(),
|
|
|
|
}
|
|
|
|
}
|