-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_utils.go
89 lines (79 loc) · 2.25 KB
/
api_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
package engine
import (
"context"
"crypto/tls"
"crypto/x509"
"io"
"net"
"net/http"
"strings"
"github.com/admpub/resty/v2"
"github.com/webx-top/echo"
"github.com/webx-top/restyclient"
)
var defaultClient = newRestyClient(nil)
func newRestyClient(client *http.Client) *resty.Client {
var c *resty.Client
if client == nil {
c = resty.New()
} else {
c = resty.NewWithClient(client)
}
c.SetRetryCount(restyclient.DefaultMaxRetryCount).
SetTimeout(restyclient.DefaultTimeout).
SetRedirectPolicy(restyclient.DefaultRedirectPolicy)
restyclient.InitRestyHook(c)
return c
}
// /var/run/docker.sock
func NewSocketClient(sockAddr string) *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", sockAddr)
},
},
}
}
func ParseSocketAddr(sockAddr string) string {
sockAddr = strings.TrimPrefix(sockAddr, `unix:`)
if !strings.HasPrefix(sockAddr, `/`) {
return `/` + sockAddr
}
maxIndex := len(sockAddr) - 1
for index, char := range sockAddr {
if char == '/' && index+1 <= maxIndex && sockAddr[index+1] != '/' {
return sockAddr[index:]
}
}
return sockAddr
}
func newCertClient(certPEMBlock, keyPEMBlock []byte) (rclient *resty.Client, err error) {
// create certificate
cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(certPEMBlock)
// Create a HTTPS client and supply the created CA pool and certificate
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
Certificates: []tls.Certificate{cert},
},
},
}
rclient = resty.NewWithClient(client)
rclient.SetRetryCount(restyclient.DefaultMaxRetryCount).
SetTimeout(restyclient.DefaultTimeout).
SetRedirectPolicy(restyclient.DefaultRedirectPolicy)
restyclient.InitRestyHook(rclient)
return
}
type ContainerExec func(ctx context.Context, containerID string, cmd []string, env []string, outWriter io.Writer, errWriter io.Writer) error
func getContainerExec() ContainerExec {
exec, _ := echo.Get(`DockerContainerExec`).(func(context.Context, string, []string, []string, io.Writer, io.Writer) error)
return exec
}