forked from docker-archive/classicswarm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
381 lines (329 loc) · 9.65 KB
/
utils.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package api
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/docker/swarm/cluster"
)
// Emit an HTTP error and log it.
func httpError(w http.ResponseWriter, err string, status int) {
log.WithField("status", status).Errorf("HTTP error: %v", err)
http.Error(w, err, status)
}
func sendJSONMessage(w io.Writer, id, status string) {
message := struct {
ID string `json:"id,omitempty"`
Status string `json:"status,omitempty"`
Progress interface{} `json:"progressDetail,omitempty"`
}{
id,
status,
struct{}{}, // this is required by the docker cli to have a proper display
}
json.NewEncoder(w).Encode(message)
}
func sendErrorJSONMessage(w io.Writer, errorCode int, errorMessage string) {
error := struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}{
errorCode,
errorMessage,
}
message := struct {
ErrorMsg string `json:"error,omitempty"`
Error interface{} `json:"errorDetail,omitempty"`
}{
errorMessage,
&error,
}
json.NewEncoder(w).Encode(message)
}
func getContainerFromVars(c *context, vars map[string]string) (string, *cluster.Container, error) {
if name, ok := vars["name"]; ok {
if container := c.cluster.Container(name); container != nil {
if !container.Engine.IsHealthy() {
return name, container, fmt.Errorf("Container %s running on unhealthy node %s", name, container.Engine.Name)
}
return name, container, nil
}
return name, nil, fmt.Errorf("No such container: %s", name)
}
if ID, ok := vars["execid"]; ok {
for _, container := range c.cluster.Containers() {
for _, execID := range container.Info.ExecIDs {
if ID == execID {
return "", container, nil
}
}
}
return "", nil, fmt.Errorf("Exec %s not found", ID)
}
return "", nil, errors.New("Not found")
}
// from https://github.com/golang/go/blob/master/src/net/http/httputil/reverseproxy.go#L82
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func proxyAsync(engine *cluster.Engine, w http.ResponseWriter, r *http.Request, callback func(*http.Response)) error {
// RequestURI may not be sent to client
r.RequestURI = ""
client, scheme, err := engine.HTTPClientAndScheme()
if err != nil {
return err
}
r.URL.Scheme = scheme
r.URL.Host = engine.Addr
log.WithFields(log.Fields{"method": r.Method, "url": r.URL}).Debug("Proxy request")
requestDone := make(chan struct{})
go func() {
defer close(requestDone)
var resp *http.Response
resp, err = client.Do(r)
if err != nil {
return
}
// cleanup
defer resp.Body.Close()
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(NewWriteFlusher(w), resp.Body)
if callback != nil {
callback(resp)
}
}()
type requestCanceler interface {
CancelRequest(*http.Request)
}
var closeNotify <-chan bool
if closeNotifier, ok := w.(http.CloseNotifier); ok {
closeNotify = closeNotifier.CloseNotify()
}
select {
case <-closeNotify:
log.WithFields(log.Fields{"method": r.Method, "url": r.URL}).Debug("user connection closed")
if rc, ok := client.Transport.(requestCanceler); ok {
rc.CancelRequest(r)
log.WithFields(log.Fields{"method": r.Method, "url": r.URL}).Debug("request cancelled")
}
// wait for request finish
<-requestDone
return err
case <-requestDone:
return err
}
}
func proxy(engine *cluster.Engine, w http.ResponseWriter, r *http.Request) error {
return proxyAsync(engine, w, r, nil)
}
type tlsClientConn struct {
*tls.Conn
rawConn net.Conn
}
func (c *tlsClientConn) CloseWrite() error {
// Go standard tls.Conn doesn't provide the CloseWrite() method so we do it
// on its underlying connection.
if cwc, ok := c.rawConn.(interface {
CloseWrite() error
}); ok {
log.Debug("Calling CloseWrite on Hijacked TLS Conn")
return cwc.CloseWrite()
}
return nil
}
// We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in
// order to return our custom tlsClientCon struct which holds both the tls.Conn
// object _and_ its underlying raw connection. The rationale for this is that
// we need to be able to close the write end of the connection when attaching,
// which tls.Conn does not provide.
func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) {
// We want the Timeout and Deadline values from dialer to cover the
// whole process: TCP connection and TLS handshake. This means that we
// also need to start our own timers now.
timeout := dialer.Timeout
if !dialer.Deadline.IsZero() {
deadlineTimeout := dialer.Deadline.Sub(time.Now())
if timeout == 0 || deadlineTimeout < timeout {
timeout = deadlineTimeout
}
}
var errChannel chan error
if timeout != 0 {
errChannel = make(chan error, 2)
time.AfterFunc(timeout, func() {
errChannel <- errors.New("")
})
}
rawConn, err := dialer.Dial(network, addr)
if err != nil {
return nil, err
}
// When we set up a TCP connection for hijack, there could be long periods
// of inactivity (a long running command with no output) that in certain
// network setups may cause ECONNTIMEOUT, leaving the client in an unknown
// state. Setting TCP KeepAlive on the socket connection will prohibit
// ECONNTIMEOUT unless the socket connection truly is broken
if tcpConn, ok := rawConn.(*net.TCPConn); ok {
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
}
colonPos := strings.LastIndex(addr, ":")
if colonPos == -1 {
colonPos = len(addr)
}
hostname := addr[:colonPos]
// If no ServerName is set, infer the ServerName
// from the hostname we're connecting to.
if config.ServerName == "" {
// Make a copy to avoid polluting argument or default.
c := &tls.Config{
Rand: config.Rand,
Time: config.Time,
Certificates: config.Certificates,
NameToCertificate: config.NameToCertificate,
GetCertificate: config.GetCertificate,
RootCAs: config.RootCAs,
NextProtos: config.NextProtos,
ServerName: config.ServerName,
ClientAuth: config.ClientAuth,
ClientCAs: config.ClientCAs,
InsecureSkipVerify: config.InsecureSkipVerify,
CipherSuites: config.CipherSuites,
PreferServerCipherSuites: config.PreferServerCipherSuites,
SessionTicketsDisabled: config.SessionTicketsDisabled,
SessionTicketKey: config.SessionTicketKey,
ClientSessionCache: config.ClientSessionCache,
MinVersion: config.MinVersion,
MaxVersion: config.MaxVersion,
CurvePreferences: config.CurvePreferences,
}
c.ServerName = hostname
config = c
}
conn := tls.Client(rawConn, config)
if timeout == 0 {
err = conn.Handshake()
} else {
go func() {
errChannel <- conn.Handshake()
}()
err = <-errChannel
}
if err != nil {
rawConn.Close()
return nil, err
}
// This is Docker difference with standard's crypto/tls package: returned a
// wrapper which holds both the TLS and raw connections.
return &tlsClientConn{conn, rawConn}, nil
}
func dialHijack(tlsConfig *tls.Config, addr string) (net.Conn, error) {
if tlsConfig == nil {
return net.Dial("tcp", addr)
}
return tlsDialWithDialer(new(net.Dialer), "tcp", addr, tlsConfig)
}
func hijack(tlsConfig *tls.Config, addr string, w http.ResponseWriter, r *http.Request) error {
if parts := strings.SplitN(addr, "://", 2); len(parts) == 2 {
addr = parts[1]
}
log.WithField("addr", addr).Debug("Proxy hijack request")
var (
d net.Conn
err error
)
d, err = dialHijack(tlsConfig, addr)
if err != nil {
return err
}
hj, ok := w.(http.Hijacker)
if !ok {
return errors.New("Docker server does not support hijacking")
}
nc, _, err := hj.Hijack()
if err != nil {
return err
}
defer nc.Close()
defer d.Close()
err = r.Write(d)
if err != nil {
return err
}
cp := func(dst io.Writer, src io.Reader, chDone chan struct{}) {
io.Copy(dst, src)
if conn, ok := dst.(interface {
CloseWrite() error
}); ok {
conn.CloseWrite()
}
close(chDone)
}
inDone := make(chan struct{})
outDone := make(chan struct{})
go cp(d, nc, inDone)
go cp(nc, d, outDone)
// 1. When stdin is done, wait for stdout always
// 2. When stdout is done, close the stream and wait for stdin to finish
//
// On 2, stdin copy should return immediately now since the out stream is closed.
// Note that we probably don't actually even need to wait here.
//
// If we don't close the stream when stdout is done, in some cases stdin will hang
select {
case <-inDone:
// wait for out to be done
<-outDone
case <-outDone:
// close the conn and wait for stdin
nc.Close()
<-inDone
}
return nil
}
func boolValue(r *http.Request, k string) bool {
s := strings.ToLower(strings.TrimSpace(r.FormValue(k)))
return !(s == "" || s == "0" || s == "no" || s == "false" || s == "none")
}
func intValueOrZero(r *http.Request, k string) int {
val, err := strconv.Atoi(r.FormValue(k))
if err != nil {
return 0
}
return val
}
func int64ValueOrZero(r *http.Request, k string) int64 {
val, err := strconv.ParseInt(r.FormValue(k), 10, 64)
if err != nil {
return 0
}
return val
}
func tagHasDigest(tag string) bool {
return strings.Contains(tag, ":")
}
// TODO(nishanttotla): There might be a better way to pass a ref string than construct it here
// getImageRef returns a string containing the registry reference given a repo and tag
func getImageRef(repo, tag string) string {
ref := repo
if tag != "" {
if tagHasDigest(tag) {
ref += "@" + tag
} else {
ref += ":" + tag
}
}
return ref
}