-
Notifications
You must be signed in to change notification settings - Fork 226
/
container.go
253 lines (229 loc) · 7.53 KB
/
container.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
// Copyright 2021 Google LLC
//
// 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 fnruntime
import (
"bytes"
"context"
goerrors "errors"
"fmt"
"io"
"os/exec"
"strings"
"time"
"github.com/GoogleContainerTools/kpt/internal/printer"
"github.com/GoogleContainerTools/kpt/internal/types"
fnresult "github.com/GoogleContainerTools/kpt/pkg/api/fnresult/v1"
"sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil"
)
// containerNetworkName is a type for network name used in container
type containerNetworkName string
const (
networkNameNone containerNetworkName = "none"
networkNameHost containerNetworkName = "host"
defaultLongTimeout time.Duration = 5 * time.Minute
defaultShortTimeout time.Duration = 5 * time.Second
dockerBin string = "docker"
AlwaysPull ImagePullPolicy = "always"
IfNotPresentPull ImagePullPolicy = "ifNotPresent"
NeverPull ImagePullPolicy = "never"
)
type ImagePullPolicy string
// ContainerFnPermission contains the permission of container
// function such as network access.
type ContainerFnPermission struct {
AllowNetwork bool
AllowMount bool
}
// ContainerFn implements a KRMFn which run a containerized
// KRM function
type ContainerFn struct {
Ctx context.Context
Path types.UniquePath
// Image is the container image to run
Image string
// ImagePullPolicy controls the image pulling behavior.
ImagePullPolicy ImagePullPolicy
// Container function will be killed after this timeour.
// The default value is 5 minutes.
Timeout time.Duration
Perm ContainerFnPermission
// UIDGID is the os User ID and Group ID that will be
// used to run the container in format userId:groupId.
// If it's empty, "nobody" will be used.
UIDGID string
// StorageMounts are the storage or directories to mount
// into the container
StorageMounts []runtimeutil.StorageMount
// Env is a slice of env string that will be exposed to container
Env []string
// FnResult is used to store the information about the result from
// the function.
FnResult *fnresult.Result
}
// Run runs the container function using docker runtime.
// It reads the input from the given reader and writes the output
// to the provided writer.
func (f *ContainerFn) Run(reader io.Reader, writer io.Writer) error {
// check and pull image before running to avoid polluting CLI
// output
err := f.prepareImage()
if err != nil {
return err
}
errSink := bytes.Buffer{}
cmd, cancel := f.getDockerCmd()
defer cancel()
cmd.Stdin = reader
cmd.Stdout = writer
cmd.Stderr = &errSink
if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError
if goerrors.As(err, &exitErr) {
return &ExecError{
OriginalErr: exitErr,
ExitCode: exitErr.ExitCode(),
Stderr: errSink.String(),
TruncateOutput: printer.TruncateOutput,
}
}
return fmt.Errorf("unexpected function error: %w", err)
}
if errSink.Len() > 0 {
f.FnResult.Stderr = errSink.String()
}
return nil
}
func (f *ContainerFn) getDockerCmd() (*exec.Cmd, context.CancelFunc) {
network := networkNameNone
if f.Perm.AllowNetwork {
network = networkNameHost
}
uidgid := "nobody"
if f.UIDGID != "" {
uidgid = f.UIDGID
}
args := []string{
"run", "--rm", "-i",
"-a", "STDIN", "-a", "STDOUT", "-a", "STDERR",
"--network", string(network),
"--user", uidgid,
"--security-opt=no-new-privileges",
}
if f.ImagePullPolicy == NeverPull {
args = append(args, "--pull", "never")
}
for _, storageMount := range f.StorageMounts {
args = append(args, "--mount", storageMount.String())
}
args = append(args,
NewContainerEnvFromStringSlice(f.Env).GetDockerFlags()...)
args = append(args, f.Image)
// setup container run timeout
timeout := defaultLongTimeout
if f.Timeout != 0 {
timeout = f.Timeout
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
return exec.CommandContext(ctx, dockerBin, args...), cancel
}
// NewContainerEnvFromStringSlice returns a new ContainerEnv pointer with parsing
// input envStr. envStr example: ["foo=bar", "baz"]
// using this instead of runtimeutil.NewContainerEnvFromStringSlice() to avoid
// default envs LOG_TO_STDERR
func NewContainerEnvFromStringSlice(envStr []string) *runtimeutil.ContainerEnv {
ce := &runtimeutil.ContainerEnv{
EnvVars: make(map[string]string),
}
// default envs
for _, e := range envStr {
parts := strings.SplitN(e, "=", 2)
if len(parts) == 1 {
ce.AddKey(e)
} else {
ce.AddKeyValue(parts[0], parts[1])
}
}
return ce
}
// prepareImage will check local images and pull it if it doesn't
// exist.
func (f *ContainerFn) prepareImage() error {
// If ImagePullPolicy is set to "never", we don't need to do anything here.
if f.ImagePullPolicy == NeverPull {
return nil
}
// check image existence
foundImageInLocalCache := f.checkImageExistence()
// If ImagePullPolicy is set to "ifNotPresent", we scan the local images
// first. If there is a match, we just return. This can be useful for local
// development to prevent the remote image to accidentally override the
// local image when they use the same name and tag.
if f.ImagePullPolicy == IfNotPresentPull && foundImageInLocalCache {
return nil
}
// If ImagePullPolicy is set to always (which is the default), we will try
// to pull the image regardless if the tag has been seen in the local cache.
// This can help to ensure we have the latest release for "moving tags" like
// v1 and v1.2. The performance cost is very minimal, since `docker pull`
// checks the SHA first and only pull the missing docker layer(s).
args := []string{"image", "pull", f.Image}
// setup timeout
timeout := defaultLongTimeout
if f.Timeout != 0 {
timeout = f.Timeout
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, dockerBin, args...)
output, err := cmd.CombinedOutput()
if err != nil {
return &ContainerImageError{
Image: f.Image,
Output: string(output),
}
}
return nil
}
// checkImageExistence returns true if the image does exist in
// local cache
func (f *ContainerFn) checkImageExistence() bool {
args := []string{"image", "inspect", f.Image}
ctx, cancel := context.WithTimeout(context.Background(), defaultShortTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, dockerBin, args...)
if _, err := cmd.CombinedOutput(); err == nil {
// image exists locally
return true
}
return false
}
// AddDefaultImagePathPrefix adds default gcr.io/kpt-fn/ path prefix to image if only image name is specified
func AddDefaultImagePathPrefix(image string) string {
if !strings.Contains(image, "/") {
return fmt.Sprintf("gcr.io/kpt-fn/%s", image)
}
return image
}
// ContainerImageError is an error type which will be returned when
// the container run time cannot verify docker image.
type ContainerImageError struct {
Image string
Output string
}
func (e *ContainerImageError) Error() string {
//nolint:lll
return fmt.Sprintf(
"Error: Function image %q doesn't exist remotely. If you are developing new functions locally, you can choose to set the image pull policy to ifNotPresent or never.\n%v",
e.Image, e.Output)
}