-
Notifications
You must be signed in to change notification settings - Fork 151
/
custom_deploy_helpers.go
106 lines (89 loc) · 2.35 KB
/
custom_deploy_helpers.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
//go:build !wasm && !freebsd
package container
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
pack "github.com/buildpacks/pack/pkg/client"
dockertypes "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
docker "github.com/docker/docker/client"
)
type DockerClient interface {
pack.DockerClient
ImagePush(ctx context.Context, image string, options dockertypes.ImagePushOptions) (io.ReadCloser, error)
}
type CustomDockerClient struct {
*docker.Client
httpClient *http.Client
}
func NewCustomDockerClient(httpClient *http.Client) (*CustomDockerClient, error) {
dockerClient, err := docker.NewClientWithOpts(docker.FromEnv, docker.WithAPIVersionNegotiation(), docker.WithHTTPClient(httpClient))
if err != nil {
return nil, fmt.Errorf("could not connect to Docker: %w", err)
}
return &CustomDockerClient{
Client: dockerClient,
httpClient: httpClient,
}, nil
}
func (c *CustomDockerClient) ContainerAttach(_ context.Context, container string, options container.AttachOptions) (dockertypes.HijackedResponse, error) {
query := url.Values{}
if options.Stream {
query.Set("stream", "1")
}
if options.Stdin {
query.Set("stdin", "1")
}
if options.Stdout {
query.Set("stdout", "1")
}
if options.Stderr {
query.Set("stderr", "1")
}
if options.DetachKeys != "" {
query.Set("detachKeys", options.DetachKeys)
}
if options.Logs {
query.Set("logs", "1")
}
requestURL := &url.URL{
Scheme: "http",
Host: strings.TrimPrefix(c.Client.DaemonHost(), "unix://"),
Path: fmt.Sprintf("/containers/%s/attach", container),
RawQuery: query.Encode(),
}
reader, writer := net.Pipe()
go func() {
defer writer.Close()
resp, err := c.httpClient.Do(&http.Request{
Method: http.MethodPost,
Host: "docker",
URL: requestURL,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: map[string][]string{
"Content-Type": {"text/plain"},
"Connection": {"Upgrade"},
"Upgrade": {"tcp"},
},
})
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusSwitchingProtocols {
panic(fmt.Errorf("unexpected status code: %d", resp.StatusCode))
}
_, err = io.Copy(writer, resp.Body)
if err != nil {
panic(err)
}
}()
return dockertypes.NewHijackedResponse(reader, "text/plain"), nil
}