this repo has no description
1package nixery
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "log/slog"
9 "os"
10 "path"
11 "runtime"
12 "sync"
13 "time"
14
15 "github.com/docker/docker/api/types/container"
16 "github.com/docker/docker/api/types/image"
17 "github.com/docker/docker/api/types/mount"
18 "github.com/docker/docker/api/types/network"
19 "github.com/docker/docker/client"
20 "github.com/docker/docker/pkg/stdcopy"
21 "gopkg.in/yaml.v3"
22 "tangled.org/core/api/tangled"
23 "tangled.org/core/log"
24 "tangled.org/core/spindle/config"
25 "tangled.org/core/spindle/engine"
26 "tangled.org/core/spindle/models"
27 "tangled.org/core/spindle/secrets"
28)
29
30const (
31 workspaceDir = "/tangled/workspace"
32 homeDir = "/tangled/home"
33)
34
35type cleanupFunc func(context.Context) error
36
37type Engine struct {
38 docker client.APIClient
39 l *slog.Logger
40 cfg *config.Config
41
42 cleanupMu sync.Mutex
43 cleanup map[string][]cleanupFunc
44}
45
46type Step struct {
47 name string
48 kind models.StepKind
49 command string
50 environment map[string]string
51}
52
53func (s Step) Name() string {
54 return s.name
55}
56
57func (s Step) Command() string {
58 return s.command
59}
60
61func (s Step) Kind() models.StepKind {
62 return s.kind
63}
64
65// setupSteps get added to start of Steps
66type setupSteps []models.Step
67
68// addStep adds a step to the beginning of the workflow's steps.
69func (ss *setupSteps) addStep(step models.Step) {
70 *ss = append(*ss, step)
71}
72
73type addlFields struct {
74 image string
75 container string
76}
77
78func (e *Engine) InitWorkflow(twf tangled.Pipeline_Workflow, tpl tangled.Pipeline) (*models.Workflow, error) {
79 swf := &models.Workflow{}
80 addl := addlFields{}
81
82 dwf := &struct {
83 Steps []struct {
84 Command string `yaml:"command"`
85 Name string `yaml:"name"`
86 Environment map[string]string `yaml:"environment"`
87 } `yaml:"steps"`
88 Dependencies map[string][]string `yaml:"dependencies"`
89 Environment map[string]string `yaml:"environment"`
90 }{}
91 err := yaml.Unmarshal([]byte(twf.Raw), &dwf)
92 if err != nil {
93 return nil, err
94 }
95
96 for _, dstep := range dwf.Steps {
97 sstep := Step{}
98 sstep.environment = dstep.Environment
99 sstep.command = dstep.Command
100 sstep.name = dstep.Name
101 sstep.kind = models.StepKindUser
102 swf.Steps = append(swf.Steps, sstep)
103 }
104 swf.Name = twf.Name
105 swf.Environment = dwf.Environment
106 addl.image = workflowImage(dwf.Dependencies, e.cfg.NixeryPipelines.Nixery)
107
108 setup := &setupSteps{}
109
110 setup.addStep(nixConfStep())
111 setup.addStep(models.BuildCloneStep(twf, *tpl.TriggerMetadata, e.cfg.Server.Dev))
112 // this step could be empty
113 if s := dependencyStep(dwf.Dependencies); s != nil {
114 setup.addStep(*s)
115 }
116
117 // append setup steps in order to the start of workflow steps
118 swf.Steps = append(*setup, swf.Steps...)
119 swf.Data = addl
120
121 return swf, nil
122}
123
124func (e *Engine) WorkflowTimeout() time.Duration {
125 workflowTimeoutStr := e.cfg.NixeryPipelines.WorkflowTimeout
126 workflowTimeout, err := time.ParseDuration(workflowTimeoutStr)
127 if err != nil {
128 e.l.Error("failed to parse workflow timeout", "error", err, "timeout", workflowTimeoutStr)
129 workflowTimeout = 5 * time.Minute
130 }
131
132 return workflowTimeout
133}
134
135func workflowImage(deps map[string][]string, nixery string) string {
136 var dependencies string
137 for reg, ds := range deps {
138 if reg == "nixpkgs" {
139 dependencies = path.Join(ds...)
140 }
141 }
142
143 // load defaults from somewhere else
144 dependencies = path.Join(dependencies, "bash", "git", "coreutils", "nix")
145
146 if runtime.GOARCH == "arm64" {
147 dependencies = path.Join("arm64", dependencies)
148 }
149
150 return path.Join(nixery, dependencies)
151}
152
153func New(ctx context.Context, cfg *config.Config) (*Engine, error) {
154 dcli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
155 if err != nil {
156 return nil, err
157 }
158
159 l := log.FromContext(ctx).With("component", "spindle")
160
161 e := &Engine{
162 docker: dcli,
163 l: l,
164 cfg: cfg,
165 }
166
167 e.cleanup = make(map[string][]cleanupFunc)
168
169 return e, nil
170}
171
172func (e *Engine) SetupWorkflow(ctx context.Context, wid models.WorkflowId, wf *models.Workflow) error {
173 e.l.Info("setting up workflow", "workflow", wid)
174
175 _, err := e.docker.NetworkCreate(ctx, networkName(wid), network.CreateOptions{
176 Driver: "bridge",
177 })
178 if err != nil {
179 return err
180 }
181 e.registerCleanup(wid, func(ctx context.Context) error {
182 return e.docker.NetworkRemove(ctx, networkName(wid))
183 })
184
185 addl := wf.Data.(addlFields)
186
187 reader, err := e.docker.ImagePull(ctx, addl.image, image.PullOptions{})
188 if err != nil {
189 e.l.Error("pipeline image pull failed!", "image", addl.image, "workflowId", wid, "error", err.Error())
190
191 return fmt.Errorf("pulling image: %w", err)
192 }
193 defer reader.Close()
194 io.Copy(os.Stdout, reader)
195
196 resp, err := e.docker.ContainerCreate(ctx, &container.Config{
197 Image: addl.image,
198 Cmd: []string{"cat"},
199 OpenStdin: true, // so cat stays alive :3
200 Tty: false,
201 Hostname: "spindle",
202 WorkingDir: workspaceDir,
203 Labels: map[string]string{
204 "sh.tangled.pipeline/workflow_id": wid.String(),
205 },
206 // TODO(winter): investigate whether environment variables passed here
207 // get propagated to ContainerExec processes
208 }, &container.HostConfig{
209 Mounts: []mount.Mount{
210 {
211 Type: mount.TypeTmpfs,
212 Target: "/tmp",
213 ReadOnly: false,
214 TmpfsOptions: &mount.TmpfsOptions{
215 Mode: 0o1777, // world-writeable sticky bit
216 Options: [][]string{
217 {"exec"},
218 },
219 },
220 },
221 },
222 ReadonlyRootfs: false,
223 CapDrop: []string{"ALL"},
224 CapAdd: []string{"CAP_DAC_OVERRIDE", "CAP_CHOWN", "CAP_FOWNER", "CAP_SETUID", "CAP_SETGID"},
225 SecurityOpt: []string{"no-new-privileges"},
226 ExtraHosts: []string{"host.docker.internal:host-gateway"},
227 }, nil, nil, "")
228 if err != nil {
229 return fmt.Errorf("creating container: %w", err)
230 }
231 e.registerCleanup(wid, func(ctx context.Context) error {
232 err = e.docker.ContainerStop(ctx, resp.ID, container.StopOptions{})
233 if err != nil {
234 return err
235 }
236
237 return e.docker.ContainerRemove(ctx, resp.ID, container.RemoveOptions{
238 RemoveVolumes: true,
239 RemoveLinks: false,
240 Force: false,
241 })
242 })
243
244 err = e.docker.ContainerStart(ctx, resp.ID, container.StartOptions{})
245 if err != nil {
246 return fmt.Errorf("starting container: %w", err)
247 }
248
249 mkExecResp, err := e.docker.ContainerExecCreate(ctx, resp.ID, container.ExecOptions{
250 Cmd: []string{"mkdir", "-p", workspaceDir, homeDir},
251 AttachStdout: true, // NOTE(winter): pretty sure this will make it so that when stdout read is done below, mkdir is done. maybe??
252 AttachStderr: true, // for good measure, backed up by docker/cli ("If -d is not set, attach to everything by default")
253 })
254 if err != nil {
255 return err
256 }
257
258 // This actually *starts* the command. Thanks, Docker!
259 execResp, err := e.docker.ContainerExecAttach(ctx, mkExecResp.ID, container.ExecAttachOptions{})
260 if err != nil {
261 return err
262 }
263 defer execResp.Close()
264
265 // This is apparently best way to wait for the command to complete.
266 _, err = io.ReadAll(execResp.Reader)
267 if err != nil {
268 return err
269 }
270
271 execInspectResp, err := e.docker.ContainerExecInspect(ctx, mkExecResp.ID)
272 if err != nil {
273 return err
274 }
275
276 if execInspectResp.ExitCode != 0 {
277 return fmt.Errorf("mkdir exited with exit code %d", execInspectResp.ExitCode)
278 } else if execInspectResp.Running {
279 return errors.New("mkdir is somehow still running??")
280 }
281
282 addl.container = resp.ID
283 wf.Data = addl
284
285 return nil
286}
287
288func (e *Engine) RunStep(ctx context.Context, wid models.WorkflowId, w *models.Workflow, idx int, secrets []secrets.UnlockedSecret, wfLogger *models.WorkflowLogger) error {
289 addl := w.Data.(addlFields)
290 workflowEnvs := ConstructEnvs(w.Environment)
291 // TODO(winter): should SetupWorkflow also have secret access?
292 // IMO yes, but probably worth thinking on.
293 for _, s := range secrets {
294 workflowEnvs.AddEnv(s.Key, s.Value)
295 }
296
297 step := w.Steps[idx].(Step)
298
299 select {
300 case <-ctx.Done():
301 return ctx.Err()
302 default:
303 }
304
305 envs := append(EnvVars(nil), workflowEnvs...)
306 for k, v := range step.environment {
307 envs.AddEnv(k, v)
308 }
309 envs.AddEnv("HOME", homeDir)
310
311 mkExecResp, err := e.docker.ContainerExecCreate(ctx, addl.container, container.ExecOptions{
312 Cmd: []string{"bash", "-c", step.Command()},
313 AttachStdout: true,
314 AttachStderr: true,
315 Env: envs,
316 })
317 if err != nil {
318 return fmt.Errorf("creating exec: %w", err)
319 }
320
321 // start tailing logs in background
322 tailDone := make(chan error, 1)
323 go func() {
324 tailDone <- e.tailStep(ctx, wfLogger, mkExecResp.ID, wid, idx, step)
325 }()
326
327 select {
328 case <-tailDone:
329
330 case <-ctx.Done():
331 // cleanup will be handled by DestroyWorkflow, since
332 // Docker doesn't provide an API to kill an exec run
333 // (sure, we could grab the PID and kill it ourselves,
334 // but that's wasted effort)
335 e.l.Warn("step timed out", "step", step.Name())
336
337 <-tailDone
338
339 return engine.ErrTimedOut
340 }
341
342 select {
343 case <-ctx.Done():
344 return ctx.Err()
345 default:
346 }
347
348 execInspectResp, err := e.docker.ContainerExecInspect(ctx, mkExecResp.ID)
349 if err != nil {
350 return err
351 }
352
353 if execInspectResp.ExitCode != 0 {
354 inspectResp, err := e.docker.ContainerInspect(ctx, addl.container)
355 if err != nil {
356 return err
357 }
358
359 e.l.Error("workflow failed!", "workflow_id", wid.String(), "exit_code", execInspectResp.ExitCode, "oom_killed", inspectResp.State.OOMKilled)
360
361 if inspectResp.State.OOMKilled {
362 return ErrOOMKilled
363 }
364 return engine.ErrWorkflowFailed
365 }
366
367 return nil
368}
369
370func (e *Engine) tailStep(ctx context.Context, wfLogger *models.WorkflowLogger, execID string, wid models.WorkflowId, stepIdx int, step models.Step) error {
371 if wfLogger == nil {
372 return nil
373 }
374
375 // This actually *starts* the command. Thanks, Docker!
376 logs, err := e.docker.ContainerExecAttach(ctx, execID, container.ExecAttachOptions{})
377 if err != nil {
378 return err
379 }
380 defer logs.Close()
381
382 _, err = stdcopy.StdCopy(
383 wfLogger.DataWriter(stepIdx, "stdout"),
384 wfLogger.DataWriter(stepIdx, "stderr"),
385 logs.Reader,
386 )
387 if err != nil && err != io.EOF && !errors.Is(err, context.DeadlineExceeded) {
388 return fmt.Errorf("failed to copy logs: %w", err)
389 }
390
391 return nil
392}
393
394func (e *Engine) DestroyWorkflow(ctx context.Context, wid models.WorkflowId) error {
395 e.cleanupMu.Lock()
396 key := wid.String()
397
398 fns := e.cleanup[key]
399 delete(e.cleanup, key)
400 e.cleanupMu.Unlock()
401
402 for _, fn := range fns {
403 if err := fn(ctx); err != nil {
404 e.l.Error("failed to cleanup workflow resource", "workflowId", wid, "error", err)
405 }
406 }
407 return nil
408}
409
410func (e *Engine) registerCleanup(wid models.WorkflowId, fn cleanupFunc) {
411 e.cleanupMu.Lock()
412 defer e.cleanupMu.Unlock()
413
414 key := wid.String()
415 e.cleanup[key] = append(e.cleanup[key], fn)
416}
417
418func networkName(wid models.WorkflowId) string {
419 return fmt.Sprintf("workflow-network-%s", wid)
420}