-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.go
198 lines (176 loc) · 5.39 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package adoc
import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
type AuthConfig struct {
UserName string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Email string `json:"email,omitempty"`
}
type RequestConfig struct {
ExtraTimeout time.Duration
}
func (auth AuthConfig) Encode() string {
var buffer bytes.Buffer
json.NewEncoder(&buffer).Encode(auth)
return base64.URLEncoding.EncodeToString(buffer.Bytes())
}
type Error struct {
StatusCode int
Status string
Message string
}
func (e Error) Error() string {
return fmt.Sprintf("%d: %s, %s", e.StatusCode, e.Status, e.Message)
}
func IsNotFound(err error) bool {
if adocErr, ok := err.(Error); ok {
return adocErr.StatusCode == 404
}
return false
}
func IsServerInternalError(err error) bool {
if adocErr, ok := err.(Error); ok {
return adocErr.StatusCode == 500
}
return false
}
const (
kDefaultApiVersion = "v1.17"
kDefaultTimeout = 30
kDefaultRWTimeout = 60
)
var apiVersions = map[string]bool{
"v1.17": true,
"v1.18": true,
}
type DockerClient struct {
daemonUrl *url.URL
httpClient *http.Client
longpollClient *http.Client
tlsConfig *tls.Config
apiVersion string
isSwarm bool
monitorLock sync.RWMutex
monitors map[int64]struct{}
}
func NewSwarmClient(swarmUrl string, tlsConfig *tls.Config, apiVersion ...string) (*DockerClient, error) {
return NewSwarmClientTimeout(swarmUrl, tlsConfig,
time.Duration(kDefaultTimeout*time.Second),
time.Duration(kDefaultRWTimeout*time.Second),
apiVersion...)
}
func NewSwarmClientTimeout(swarmUrl string, tlsConfig *tls.Config, timeout time.Duration, rwTimeout time.Duration, apiVersion ...string) (*DockerClient, error) {
docker, err := NewDockerClientTimeout(swarmUrl, tlsConfig, timeout, rwTimeout, apiVersion...)
docker.isSwarm = true
return docker, err
}
func NewDockerClient(daemonUrl string, tlsConfig *tls.Config, apiVersion ...string) (*DockerClient, error) {
return NewDockerClientTimeout(daemonUrl, tlsConfig,
time.Duration(kDefaultTimeout*time.Second),
time.Duration(kDefaultRWTimeout*time.Second),
apiVersion...)
}
func NewDockerClientTimeout(daemonUrl string, tlsConfig *tls.Config, timeout time.Duration, rwTimeout time.Duration, apiVersion ...string) (*DockerClient, error) {
u, err := url.Parse(daemonUrl)
if err != nil {
return nil, err
}
if u.Scheme == "" || u.Scheme == "tcp" {
if tlsConfig == nil {
u.Scheme = "http"
} else {
u.Scheme = "https"
}
}
copiedUrl, _ := url.Parse(u.String())
httpClient := newHttpClient(u, tlsConfig, timeout, rwTimeout)
longpollClient := newHttpClient(copiedUrl, tlsConfig, timeout, 0)
clientApiVersion := kDefaultApiVersion
if len(apiVersion) > 0 && apiVersion[0] != "" {
clientApiVersion = apiVersion[0]
if !strings.HasPrefix(clientApiVersion, "v") {
clientApiVersion = "v" + clientApiVersion
}
}
if _, checked := apiVersions[clientApiVersion]; !checked {
err = fmt.Errorf("*WARNING: Adoc haven't check out if the remote api version %s is supported, maybe not stable, but you can keep using the client anyway.", clientApiVersion)
}
return &DockerClient{
daemonUrl: u,
httpClient: httpClient,
longpollClient: longpollClient,
tlsConfig: tlsConfig,
apiVersion: clientApiVersion,
monitors: make(map[int64]struct{}),
}, err
}
type responseCallback func(resp *http.Response) error
func (client *DockerClient) sendRequestCallback(method string, path string, body []byte, headers map[string]string, callback responseCallback, rc *RequestConfig, isLongpoll ...bool) error {
b := bytes.NewBuffer(body)
urlPath := fmt.Sprintf("%s/%s/%s", client.daemonUrl.String(), client.apiVersion, path)
logger.Debugf("SendRequest %q, [%s]", method, urlPath)
req, err := http.NewRequest(method, urlPath, b)
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
if headers != nil {
for key, value := range headers {
req.Header.Add(key, value)
}
}
httpClient := client.httpClient
if len(isLongpoll) > 0 && isLongpoll[0] {
httpClient = client.longpollClient
}
if rc != nil && rc.ExtraTimeout > 0 {
httpClient = &http.Client{
Transport: httpClient.Transport,
Timeout: httpClient.Timeout + rc.ExtraTimeout,
}
}
resp, err := httpClient.Do(req)
if err != nil {
if !strings.Contains(err.Error(), "connection refused") && client.tlsConfig == nil {
return fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err)
}
return err
}
if resp.StatusCode >= 400 {
var errMsg []byte
var cbErr error
if errMsg, cbErr = ioutil.ReadAll(resp.Body); cbErr != nil {
return Error{resp.StatusCode, resp.Status, cbErr.Error()}
}
return Error{resp.StatusCode, resp.Status, strings.TrimSpace(string(errMsg))}
}
defer resp.Body.Close()
return callback(resp)
}
func (client *DockerClient) sendRequest(method string, path string, body []byte, headers map[string]string, rc *RequestConfig, isLongpoll ...bool) ([]byte, error) {
var data []byte
err := client.sendRequestCallback(method, path, body, headers, func(resp *http.Response) error {
var cbErr error
if data, cbErr = ioutil.ReadAll(resp.Body); cbErr != nil {
return cbErr
}
return nil
}, rc, isLongpoll...)
return data, err
}
var random *rand.Rand
func init() {
random = rand.New(rand.NewSource(time.Now().UnixNano()))
}