/
docker.go
286 lines (250 loc) · 7.33 KB
/
docker.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
// Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package docker
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"github.com/ozonep/drone/pkg/runtime/engine"
"github.com/ozonep/drone/pkg/runtime/engine/docker/auth"
"github.com/ozonep/drone/pkg/runtime/engine/docker/stdcopy"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
)
type dockerEngine struct {
client client.APIClient
}
// NewEnv returns a new Engine from the environment.
func NewEnv() (engine.Engine, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return nil, err
}
return New(cli), nil
}
// Ping attempts to ping the Docker daemon. An error is returned
// if the ping attempt fails.
func Ping(ctx context.Context, engine engine.Engine) error {
eng, ok := engine.(*dockerEngine)
if !ok {
return fmt.Errorf("Not a valid Engine type")
}
_, err := eng.client.Ping(ctx)
return err
}
// New returns a new Engine using the Docker API Client.
func New(client client.APIClient) engine.Engine {
return &dockerEngine{
client: client,
}
}
func (e *dockerEngine) Setup(ctx context.Context, spec *engine.Spec) error {
if spec.Docker != nil {
// creates the default temporary (local) volumes
// that are mounted into each container step.
for _, vol := range spec.Docker.Volumes {
if vol.EmptyDir == nil {
continue
}
_, err := e.client.VolumeCreate(ctx, volume.VolumeCreateBody{
Name: vol.Metadata.UID,
Driver: "local",
Labels: spec.Metadata.Labels,
})
if err != nil {
return err
}
}
}
// creates the default pod network. All containers
// defined in the pipeline are attached to this network.
driver := "bridge"
if spec.Platform.OS == "windows" {
driver = "nat"
}
_, err := e.client.NetworkCreate(ctx, spec.Metadata.UID, types.NetworkCreate{
Driver: driver,
Labels: spec.Metadata.Labels,
})
return err
}
func (e *dockerEngine) Create(ctx context.Context, spec *engine.Spec, step *engine.Step) error {
if step.Docker == nil {
return errors.New("engine: missing docker configuration")
}
// parse the docker image name. We need to extract the
// image domain name and match to registry credentials
// stored in the .docker/config.json object.
_, domain, latest, err := parseImage(step.Docker.Image)
if err != nil {
return err
}
// create pull options with encoded authorization credentials.
pullopts := types.ImagePullOptions{}
auths, ok := engine.LookupAuth(spec, domain)
if ok {
pullopts.RegistryAuth = auth.Encode(auths.Username, auths.Password)
}
// automatically pull the latest version of the image if requested
// by the process configuration.
if step.Docker.PullPolicy == engine.PullAlways ||
(step.Docker.PullPolicy == engine.PullDefault && latest) {
// TODO(bradrydzewski) implement the PullDefault strategy to pull
// the image if the tag is :latest
rc, perr := e.client.ImagePull(ctx, step.Docker.Image, pullopts)
if perr == nil {
io.Copy(ioutil.Discard, rc)
rc.Close()
}
if perr != nil {
return perr
}
}
_, err = e.client.ContainerCreate(ctx,
toConfig(spec, step),
toHostConfig(spec, step),
toNetConfig(spec, step),
step.Metadata.UID,
)
// automatically pull and try to re-create the image if the
// failure is caused because the image does not exist.
if client.IsErrNotFound(err) && step.Docker.PullPolicy != engine.PullNever {
rc, perr := e.client.ImagePull(ctx, step.Docker.Image, pullopts)
if perr != nil {
return perr
}
io.Copy(ioutil.Discard, rc)
rc.Close()
// once the image is successfully pulled we attempt to
// re-create the container.
_, err = e.client.ContainerCreate(ctx,
toConfig(spec, step),
toHostConfig(spec, step),
toNetConfig(spec, step),
step.Metadata.UID,
)
}
if err != nil {
return err
}
copyOpts := types.CopyToContainerOptions{}
copyOpts.AllowOverwriteDirWithFile = false
for _, mount := range step.Files {
file, ok := engine.LookupFile(spec, mount.Name)
if !ok {
continue
}
tar := createTarfile(file, mount)
// TODO(bradrydzewski) this path is probably different on windows.
err := e.client.CopyToContainer(ctx, step.Metadata.UID, "/", bytes.NewReader(tar), copyOpts)
if err != nil {
return err
}
}
// use the default user-defined network if network_mode
// is not otherwise specified.
// QUESTION: is this even used?
if step.Docker.Network == "" {
for _, net := range step.Docker.Networks {
err = e.client.NetworkConnect(ctx, net, step.Metadata.UID, &network.EndpointSettings{
Aliases: []string{net},
})
if err != nil {
return nil
}
}
}
return nil
}
func (e *dockerEngine) Start(ctx context.Context, spec *engine.Spec, step *engine.Step) error {
return e.client.ContainerStart(ctx, step.Metadata.UID, types.ContainerStartOptions{})
}
func (e *dockerEngine) Wait(ctx context.Context, spec *engine.Spec, step *engine.Step) (*engine.State, error) {
wait, errc := e.client.ContainerWait(ctx, step.Metadata.UID, "")
select {
case <-wait:
case <-errc:
}
info, err := e.client.ContainerInspect(ctx, step.Metadata.UID)
if err != nil {
return nil, err
}
return &engine.State{
Exited: true,
ExitCode: info.State.ExitCode,
OOMKilled: info.State.OOMKilled,
}, nil
}
func (e *dockerEngine) Tail(ctx context.Context, spec *engine.Spec, step *engine.Step) (io.ReadCloser, error) {
opts := types.ContainerLogsOptions{
Follow: true,
ShowStdout: true,
ShowStderr: true,
Details: false,
Timestamps: false,
}
logs, err := e.client.ContainerLogs(ctx, step.Metadata.UID, opts)
if err != nil {
return nil, err
}
rc, wc := io.Pipe()
go func() {
stdcopy.StdCopy(wc, wc, logs)
logs.Close()
wc.Close()
rc.Close()
}()
return rc, nil
}
func (e *dockerEngine) Destroy(ctx context.Context, spec *engine.Spec) error {
removeOpts := types.ContainerRemoveOptions{
Force: true,
RemoveLinks: false,
RemoveVolumes: true,
}
// stop all containers
for _, step := range spec.Steps {
e.client.ContainerKill(ctx, step.Metadata.UID, "9")
}
// cleanup all containers
for _, step := range spec.Steps {
e.client.ContainerRemove(ctx, step.Metadata.UID, removeOpts)
}
// cleanup all volumes
if spec.Docker != nil {
for _, vol := range spec.Docker.Volumes {
if vol.EmptyDir == nil {
continue
}
// tempfs volumes do not have a volume entry,
// and therefore do not require removal.
if vol.EmptyDir.Medium == "memory" {
continue
}
e.client.VolumeRemove(ctx, vol.Metadata.UID, true)
}
}
// cleanup the network
e.client.NetworkRemove(ctx, spec.Metadata.UID)
// notice that we never collect or return any errors.
// this is because we silently ignore cleanup failures
// and instead ask the system admin to periodically run
// `docker prune` commands.
return nil
}