This repository has been archived by the owner on Oct 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
runtime_docker.go
225 lines (189 loc) · 7.95 KB
/
runtime_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
package main
import (
"context"
"fmt"
"io"
"net"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/docker/errdefs"
"github.com/docker/go-connections/nat"
"github.com/crossplane/crossplane-runtime/pkg/errors"
pkgv1beta1 "github.com/crossplane/crossplane/apis/pkg/v1beta1"
)
// Annotations that can be used to configure the Docker runtime.
const (
// AnnotationKeyRuntimeDockerCleanup configures how a Function's Docker
// container should be cleaned up once rendering is done.
AnnotationKeyRuntimeDockerCleanup = "xrender.crossplane.io/runtime-docker-cleanup"
// AnnotationKeyRuntimeDockerImage overrides the Docker image that will be
// used to run the Function. By default xrender assumes the Function package
// (i.e. spec.package) can be used to run the Function.
AnnotationKeyRuntimeDockerImage = "xrender.crossplane.io/runtime-docker-image"
)
// DockerCleanup specifies what Docker should do with a Function container after
// it has been run.
type DockerCleanup string
// Supported AnnotationKeyRuntimeDockerCleanup values.
const (
// AnnotationValueRuntimeDockerCleanupStop is the default. It stops the
// container once rendering is done.
AnnotationValueRuntimeDockerCleanupStop DockerCleanup = "Stop"
// AnnotationValueRuntimeDockerCleanupOrphan leaves the container running
// once rendering is done.
AnnotationValueRuntimeDockerCleanupOrphan DockerCleanup = "Orphan"
AnnotationValueRuntimeDockerCleanupDefault = AnnotationValueRuntimeDockerCleanupStop
)
// AnnotationKeyRuntimeDockerPullPolicy can be added to a Function to control how its runtime
// image is pulled.
const AnnotationKeyRuntimeDockerPullPolicy = "xrender.crossplane.io/runtime-docker-pull-policy"
// DockerPullPolicy can be added to a Function to control how its runtime image
// is pulled by Docker.
type DockerPullPolicy string
// Supported pull policies.
const (
// Always pull the image.
AnnotationValueRuntimeDockerPullPolicyAlways DockerPullPolicy = "Always"
// Never pull the image.
AnnotationValueRuntimeDockerPullPolicyNever DockerPullPolicy = "Never"
// Pull the image if it's not present.
AnnotationValueRuntimeDockerPullPolicyIfNotPresent DockerPullPolicy = "IfNotPresent"
AnnotationValueRuntimeDockerPullPolicyDefault DockerPullPolicy = AnnotationValueRuntimeDockerPullPolicyIfNotPresent
)
// RuntimeDocker uses a Docker daemon to run a Function.
type RuntimeDocker struct {
// Image to run
Image string
// Stop container once rendering is done
Stop bool
// PullPolicy controls how the runtime image is pulled.
PullPolicy DockerPullPolicy
}
// GetDockerPullPolicy extracts PullPolicy configuration from the supplied
// Function.
func GetDockerPullPolicy(fn pkgv1beta1.Function) (DockerPullPolicy, error) {
switch p := DockerPullPolicy(fn.GetAnnotations()[AnnotationKeyRuntimeDockerPullPolicy]); p {
case AnnotationValueRuntimeDockerPullPolicyAlways, AnnotationValueRuntimeDockerPullPolicyNever, AnnotationValueRuntimeDockerPullPolicyIfNotPresent:
return p, nil
case "":
return AnnotationValueRuntimeDockerPullPolicyDefault, nil
default:
return "", errors.Errorf("unsupported %q annotation value %q (unknown pull policy)", AnnotationKeyRuntimeDockerPullPolicy, p)
}
}
// GetDockerCleanup extracts Cleanup configuration from the supplied Function.
func GetDockerCleanup(fn pkgv1beta1.Function) (DockerCleanup, error) {
switch c := DockerCleanup(fn.GetAnnotations()[AnnotationKeyRuntimeDockerCleanup]); c {
case AnnotationValueRuntimeDockerCleanupStop, AnnotationValueRuntimeDockerCleanupOrphan:
return c, nil
case "":
return AnnotationValueRuntimeDockerCleanupDefault, nil
default:
return "", errors.Errorf("unsupported %q annotation value %q (unknown cleanup policy)", AnnotationKeyRuntimeDockerCleanup, c)
}
}
// GetRuntimeDocker extracts RuntimeDocker configuration from the supplied
// Function.
func GetRuntimeDocker(fn pkgv1beta1.Function) (*RuntimeDocker, error) {
cleanup, err := GetDockerCleanup(fn)
if err != nil {
return nil, errors.Wrapf(err, "cannot get cleanup policy for Function %q", fn.GetName())
}
// TODO(negz): Pull package in case it has a different controller image? I
// hope in most cases Functions will use 'fat' packages, and it's possible
// to manually override with an annotation so maybe not worth it.
pullPolicy, err := GetDockerPullPolicy(fn)
if err != nil {
return nil, errors.Wrapf(err, "cannot get pull policy for Function %q", fn.GetName())
}
r := &RuntimeDocker{
Image: fn.Spec.Package,
Stop: cleanup == AnnotationValueRuntimeDockerCleanupStop,
PullPolicy: pullPolicy,
}
if i := fn.GetAnnotations()[AnnotationKeyRuntimeDockerImage]; i != "" {
r.Image = i
}
return r, nil
}
var _ Runtime = &RuntimeDocker{}
// Start a Function as a Docker container.
func (r *RuntimeDocker) Start(ctx context.Context) (RuntimeContext, error) { //nolint:gocyclo // TODO(phisco): Refactor to break this up a bit, not so easy.
c, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return RuntimeContext{}, errors.Wrap(err, "cannot create Docker client using environment variables")
}
// Find a random, available port. There's a chance of a race here, where
// something else binds to the port before we start our container.
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
return RuntimeContext{}, errors.Wrap(err, "cannot get available TCP port")
}
addr := lis.Addr().String()
_ = lis.Close()
spec := fmt.Sprintf("%s:9443/tcp", addr)
expose, bind, err := nat.ParsePortSpecs([]string{spec})
if err != nil {
return RuntimeContext{}, errors.Wrapf(err, "cannot parse Docker port spec %q", spec)
}
cfg := &container.Config{
Image: r.Image,
Cmd: []string{"--insecure"},
ExposedPorts: expose,
}
hcfg := &container.HostConfig{
PortBindings: bind,
}
if r.PullPolicy == AnnotationValueRuntimeDockerPullPolicyAlways {
err = PullImage(ctx, c, r.Image)
if err != nil {
return RuntimeContext{}, errors.Wrapf(err, "cannot pull Docker image %q", r.Image)
}
}
// TODO(negz): Set a container name? Presumably unique across runs.
rsp, err := c.ContainerCreate(ctx, cfg, hcfg, nil, nil, "")
if err != nil {
if !errdefs.IsNotFound(err) || r.PullPolicy == AnnotationValueRuntimeDockerPullPolicyNever {
return RuntimeContext{}, errors.Wrap(err, "cannot create Docker container")
}
// The image was not found, but we're allowed to pull it.
err = PullImage(ctx, c, r.Image)
if err != nil {
return RuntimeContext{}, errors.Wrapf(err, "cannot pull Docker image %q", r.Image)
}
rsp, err = c.ContainerCreate(ctx, cfg, hcfg, nil, nil, "")
if err != nil {
return RuntimeContext{}, errors.Wrap(err, "cannot create Docker container")
}
}
if err := c.ContainerStart(ctx, rsp.ID, types.ContainerStartOptions{}); err != nil {
return RuntimeContext{}, errors.Wrap(err, "cannot start Docker container")
}
stop := func(_ context.Context) error {
// TODO(negz): Maybe log to stderr that we're leaving the container running?
return nil
}
if r.Stop {
stop = func(ctx context.Context) error {
err := c.ContainerStop(ctx, rsp.ID, container.StopOptions{})
return errors.Wrap(err, "cannot stop Docker container")
}
}
return RuntimeContext{Target: addr, Stop: stop}, nil
}
// PullImage pulls the supplied image using the supplied client. It blocks until
// the image has either finished pulling or hit an error.
func PullImage(ctx context.Context, c *client.Client, image string) error {
out, err := c.ImagePull(ctx, image, types.ImagePullOptions{})
if err != nil {
return err
}
defer out.Close() //nolint:errcheck // TODO(negz): Can this error?
// Each line read from out is a JSON object containing the status of the
// pull - similar to the progress bars you'd see if running docker pull. It
// seems that consuming all of this output is the best way to block until
// the image is actually pulled before we try to run it.
_, err = io.Copy(io.Discard, out)
return err
}