/
container_command_executor.go
311 lines (282 loc) · 9.29 KB
/
container_command_executor.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package runner
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/aws/codecatalyst-runner-cli/command-runner/internal/containers/types"
"github.com/aws/codecatalyst-runner-cli/command-runner/internal/fs"
"github.com/aws/codecatalyst-runner-cli/command-runner/pkg/common"
"github.com/opencontainers/selinux/go-selinux"
"github.com/rs/zerolog/log"
)
type containerCommandExecutor struct {
Container types.Container
ReuseContainers bool
CloseExecutors []common.Executor
mceDir string
ctx context.Context
}
type newContainerCommandExecutorParams struct {
*EnvironmentConfiguration
ID string
Image string
Entrypoint Command
ContainerService types.ContainerService
}
const containerSourceDir = "/codecatalyst/output/src"
func newContainerCommandExecutor(ctx context.Context, params *newContainerCommandExecutorParams) (commandExecutor, error) {
containerName := fmt.Sprintf("codecatalyst-%s", regexp.MustCompile(`[^a-zA-Z0-9_.-]`).ReplaceAllString(params.ID, "_"))
containerName = strings.ToLower(containerName)
var imagePrep common.Executor
var image string
platform := ""
if i, found := strings.CutPrefix(params.Image, "docker://"); found {
// pull image from registry
image = i
} else {
// local docker build
dockerfilePath := params.Image
if !filepath.IsAbs(dockerfilePath) {
dockerfilePath = filepath.Join(params.WorkingDir, params.Image)
}
_, err := os.Stat(dockerfilePath)
if err != nil {
return nil, err
}
image = fmt.Sprintf("%s:%s", containerName, "latest")
exists, err := params.ContainerService.ImageExistsLocally(ctx, image, platform)
log.Ctx(ctx).Debug().Msgf("%s exists? %v", image, exists)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("unable to check for local image")
}
if params.Reuse && exists {
imagePrep = func(ctx context.Context) error { return nil }
} else {
imagePrep = params.ContainerService.BuildImage(types.BuildImageInput{
ContextDir: filepath.Dir(dockerfilePath),
Dockerfile: filepath.Base(dockerfilePath),
ImageTag: image,
Platform: platform,
}).TraceRegion("image-build")
}
}
env, containerDefaultDir, err := setupEnvironmentVariables(params.Env)
if err != nil {
return nil, err
}
mceDir, err := setupMceDir(env, containerDefaultDir)
if err != nil {
return nil, err
}
binds := []string{
fmt.Sprintf("%s:%s", "/var/run/docker.sock", "/var/run/docker.sock"),
fmt.Sprintf("%s:%s", mceDir, "/tmp/mce"),
}
for _, filemap := range params.FileMaps {
srcPath := resolvePath(filemap.SourcePath, params.WorkingDir)
targetPath := resolvePath(filemap.TargetPath, containerSourceDir)
if filemap.Type == FileMapTypeBind {
binds = append(binds,
fmt.Sprintf(
"%s:%s%s",
srcPath,
targetPath,
bindModifiers(),
),
)
}
}
log.Ctx(ctx).Debug().Msgf("Container binds: %#v", binds)
log.Ctx(ctx).Debug().Msgf("Container env: %#v", env)
actionContainer := params.ContainerService.NewContainer(types.NewContainerInput{
Image: image,
Name: containerName,
Stdout: params.Stdout,
Stderr: params.Stderr,
Env: env,
WorkingDir: containerDefaultDir,
Binds: binds,
Entrypoint: params.Entrypoint,
})
copyExecutors, closeExecutors, err := setupCopyAndCloseExecutors(actionContainer, params.WorkingDir, params.FileMaps)
if err != nil {
return nil, err
}
if imagePrep == nil {
imagePrep = actionContainer.Pull(true).TraceRegion("image-pull")
}
if err := common.NewPipelineExecutor(
imagePrep,
actionContainer.Remove().IfBool(!params.Reuse),
actionContainer.Create(nil, nil).TraceRegion("container-create"),
common.NewPipelineExecutor(copyExecutors...).TraceRegion("container-copy"),
actionContainer.Start(false).TraceRegion("container-start"),
)(ctx); err != nil {
return nil, fmt.Errorf("unable to create container executor: %w", err)
}
return &containerCommandExecutor{
Container: actionContainer,
ReuseContainers: params.Reuse,
CloseExecutors: closeExecutors,
mceDir: mceDir,
ctx: ctx,
}, nil
}
func (cce *containerCommandExecutor) Close(isError bool) error {
var err error
if !isError {
err = common.NewPipelineExecutor(cce.CloseExecutors...).TraceRegion("close-executors")(cce.ctx)
}
if !cce.ReuseContainers {
if err := cce.Container.Remove()(context.Background()); err != nil {
log.Ctx(cce.ctx).Error().Err(err).Msg("error removing container")
}
}
if err := os.RemoveAll(cce.mceDir); err != nil {
log.Ctx(cce.ctx).Error().Err(err).Msg("error removing temp mce directory")
}
return err
}
func (cce *containerCommandExecutor) ExecuteCommand(ctx context.Context, command Command) error {
script := fmt.Sprintf(`cd $(cat /tmp/mce/tmp/dir.txt)
set -a
. /tmp/mce/tmp/env.sh
while read line; do
env "$line" > /dev/null
done < /tmp/mce/tmp/init.env
%s
CODEBUILD_LAST_EXIT=$?
export -p > /tmp/mce/tmp/env.sh
pwd > /tmp/mce/tmp/dir.txt
exit $CODEBUILD_LAST_EXIT`, strings.Join(command, " "))
log.Ctx(ctx).Debug().Msgf("script: %s", script)
scriptName := fmt.Sprintf("script-%d.sh", time.Now().UnixNano())
if err := os.WriteFile(filepath.Join(cce.mceDir, "tmp", scriptName), []byte(script), 00755); err != nil /* #nosec G306 */ {
return err
}
return cce.Container.Exec([]string{"/bin/sh", fmt.Sprintf("/tmp/mce/tmp/%s", scriptName)}, nil, "", "")(ctx)
}
func bindModifiers() string {
var bindModifiers string
if runtime.GOOS == "darwin" {
bindModifiers = ":consistent"
}
if selinux.GetEnabled() {
bindModifiers = ":z"
}
return bindModifiers
}
func resolvePath(path string, basePath string) string {
p := path
if !filepath.IsAbs(p) {
absBasePath, err := filepath.Abs(basePath)
if err != nil {
log.Fatal().Err(err)
}
p = fmt.Sprintf("%s/%s", absBasePath, p)
}
return p
}
func clean(dir string) common.Executor {
return func(ctx context.Context) error {
if err := os.RemoveAll(dir); err != nil {
return err
}
return os.MkdirAll(dir, 0755)
}
}
func setupMceDir(env []string, containerDefaultDir string) (string, error) {
mceDir, err := os.MkdirTemp(fs.TmpDir(), "mce")
if err != nil {
return "", err
}
if err := os.MkdirAll(filepath.Join(mceDir, "tmp"), 0755); err != nil {
return "", fmt.Errorf("unable to create tmp dir: %w", err)
}
if err := os.WriteFile(filepath.Join(mceDir, "tmp", "init.env"), []byte(strings.Join(env, "\n")), 00777); err != nil /* #nosec G306 */ {
return "", err
}
if err := os.WriteFile(filepath.Join(mceDir, "tmp", "env.sh"), []byte(""), 00666); err != nil /* #nosec G306 */ {
return "", err
}
if err := os.WriteFile(filepath.Join(mceDir, "tmp", "dir.txt"), []byte(containerDefaultDir), 00666); err != nil /* #nosec G306 */ {
return "", err
}
envout := `. /tmp/mce/tmp/env.sh
env -0 | while IFS='=' read -r -d '' n v; do printf "::set-output name=%s::%s\n" "$n" "$v"; done`
if err := os.WriteFile(filepath.Join(mceDir, "tmp", "envout.sh"), []byte(envout), 00755); err != nil /* #nosec G306 */ {
return "", err
}
return mceDir, nil
}
func setupCopyAndCloseExecutors(actionContainer types.Container, workingDir string, filemaps []*FileMap) ([]common.Executor, []common.Executor, error) {
copyExecutors := []common.Executor{}
closeExecutors := []common.Executor{
actionContainer.Exec([]string{"/bin/bash", "/tmp/mce/tmp/envout.sh"}, nil, "", "/"),
}
for _, filemap := range filemaps {
switch filemap.Type {
case FileMapTypeBind:
continue
case FileMapTypeCopyOut:
srcPath := resolvePath(filemap.SourcePath, containerSourceDir)
closeExecutors = append(
closeExecutors,
actionContainer.Exec([]string{"mkdir", "-p", "/extract"}, nil, "", "/"),
actionContainer.Exec([]string{"/bin/sh", "-c", fmt.Sprintf("cp -a %s /extract || echo 'nothing to cache' > /dev/null 2>&1", srcPath)}, nil, "", "/"),
)
if !strings.HasSuffix(srcPath, "/.") {
closeExecutors = append(closeExecutors, clean(filemap.TargetPath))
}
closeExecutors = append(
closeExecutors,
actionContainer.CopyOut(filemap.TargetPath, "/extract/."),
actionContainer.Exec([]string{"rm", "-rf", "/extract"}, nil, "", "/"),
)
case FileMapTypeCopyIn:
copyExecutors = append(
copyExecutors,
actionContainer.CopyIn(
resolvePath(filemap.TargetPath, containerSourceDir),
resolvePath(filemap.SourcePath, workingDir),
false,
),
)
case FileMapTypeCopyInWithGitignore:
copyExecutors = append(
copyExecutors,
actionContainer.CopyIn(
resolvePath(filemap.TargetPath, containerSourceDir),
resolvePath(filemap.SourcePath, workingDir),
true,
),
)
default:
return nil, nil, fmt.Errorf("unknown filemap Type")
}
}
return copyExecutors, closeExecutors, nil
}
func setupEnvironmentVariables(env map[string]string) ([]string, string, error) {
var containerDefaultDir string
envVars := make([]string, 0)
for k, v := range env {
if strings.HasPrefix(k, "CATALYST_SOURCE_DIR_") {
v = resolvePath(v, containerSourceDir)
if k == "CATALYST_SOURCE_DIR_WorkflowSource" || containerDefaultDir == "" {
containerDefaultDir = v
}
}
envVars = append(envVars, fmt.Sprintf("%s=%s", k, v))
}
if containerDefaultDir == "" {
return nil, "", fmt.Errorf("input source or artifact is required")
}
envVars = append(envVars, fmt.Sprintf("CATALYST_DEFAULT_DIR=%s", containerDefaultDir))
return envVars, containerDefaultDir, nil
}