aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/pkg/exec.go
blob: f81318554eb4ee76b684bee5528bf167541dde01 (plain)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package pkg

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path"
	"slices"
	"strconv"
	"syscall"
	"time"

	"hakurei.app/container"
	"hakurei.app/container/check"
	"hakurei.app/container/fhs"
	"hakurei.app/container/std"
	"hakurei.app/message"
)

// AbsWork is the container pathname [CureContext.GetWorkDir] is mounted on.
var AbsWork = fhs.AbsRoot.Append("work/")

// ExecPath is a slice of [Artifact] and the [check.Absolute] pathname to make
// it available at under in the container.
type ExecPath struct {
	// Pathname in the container mount namespace.
	P *check.Absolute
	// Artifacts to mount on the pathname, must contain at least one [Artifact].
	// If there are multiple entries or W is true, P is set up as an overlay
	// mount, and entries of A must not implement [File].
	A []Artifact
	// Whether to make the mount point writable via the temp directory.
	W bool
}

// Path returns a populated [ExecPath].
func Path(pathname *check.Absolute, writable bool, a ...Artifact) ExecPath {
	return ExecPath{pathname, a, writable}
}

// MustPath is like [Path], but takes a string pathname via [check.MustAbs].
func MustPath(pathname string, writable bool, a ...Artifact) ExecPath {
	return ExecPath{check.MustAbs(pathname), a, writable}
}

const (
	// ExecTimeoutDefault replaces out of range [NewExec] timeout values.
	ExecTimeoutDefault = 15 * time.Minute
	// ExecTimeoutMax is the arbitrary upper bound of [NewExec] timeout.
	ExecTimeoutMax = 48 * time.Hour
)

// An execArtifact is an [Artifact] that produces output by running a program
// part of another [Artifact] in a [container] to produce its output.
//
// Methods of execArtifact does not modify any struct field or underlying arrays
// referred to by slices.
type execArtifact struct {
	// Caller-supplied user-facing reporting name, guaranteed to be nonzero
	// during initialisation.
	name string
	// Caller-supplied inner mount points.
	paths []ExecPath

	// Passed through to [container.Params].
	dir *check.Absolute
	// Passed through to [container.Params].
	env []string
	// Passed through to [container.Params].
	path *check.Absolute
	// Passed through to [container.Params].
	args []string

	// Duration the initial process is allowed to run. The zero value is
	// equivalent to execTimeoutDefault. This value is never encoded in Params
	// because it cannot affect outcome.
	timeout time.Duration
}

var _ fmt.Stringer = new(execArtifact)

// execNetArtifact is like execArtifact but implements [KnownChecksum] and has
// its resulting container keep the host net namespace.
type execNetArtifact struct {
	checksum Checksum

	execArtifact
}

var _ KnownChecksum = new(execNetArtifact)

// Checksum returns the caller-supplied checksum.
func (a *execNetArtifact) Checksum() Checksum { return a.checksum }

// Kind returns the hardcoded [Kind] constant.
func (a *execNetArtifact) Kind() Kind { return KindExecNet }

// Params is [Checksum] concatenated with [KindExec] params.
func (a *execNetArtifact) Params(ctx *IContext) {
	ctx.GetHash().Write(a.checksum[:])
	a.execArtifact.Params(ctx)
}

// Cure cures the [Artifact] in the container described by the caller. The
// container retains host networking.
func (a *execNetArtifact) Cure(f *FContext) error {
	return a.cure(f, true)
}

// NewExec returns a new [Artifact] that executes the program path in a
// container with specified paths bind mounted read-only in order. A private
// instance of /proc and /dev is made available to the container.
//
// The working and temporary directories are both created and mounted writable
// on [AbsWork] and [fhs.AbsTmp] respectively. If one or more paths target
// [AbsWork], the final entry is set up as a writable overlay mount on /work for
// which the upperdir is the host side work directory. In this configuration,
// the W field is ignored, and the program must avoid causing whiteout files to
// be created. Cure fails if upperdir ends up with entries other than directory,
// regular or symlink.
//
// If checksum is non-nil, the resulting [Artifact] implements [KnownChecksum]
// and its container runs in the host net namespace.
//
// The container is allowed to run for the specified duration before the initial
// process and all processes originating from it is terminated. A zero or
// negative timeout value is equivalent tp [ExecTimeoutDefault], a timeout value
// greater than [ExecTimeoutMax] is equivalent to [ExecTimeoutMax].
//
// The user-facing name is not accessible from the container and does not
// affect curing outcome. Because of this, it is omitted from parameter data
// for computing identifier.
func NewExec(
	name string,
	checksum *Checksum,
	timeout time.Duration,

	dir *check.Absolute,
	env []string,
	pathname *check.Absolute,
	args []string,

	paths ...ExecPath,
) Artifact {
	if name == "" {
		name = "exec-" + path.Base(pathname.String())
	}
	if timeout <= 0 {
		timeout = ExecTimeoutDefault
	}
	if timeout > ExecTimeoutMax {
		timeout = ExecTimeoutMax
	}
	a := execArtifact{name, paths, dir, env, pathname, args, timeout}
	if checksum == nil {
		return &a
	}
	return &execNetArtifact{*checksum, a}
}

// Kind returns the hardcoded [Kind] constant.
func (a *execArtifact) Kind() Kind { return KindExec }

// Params writes paths, executable pathname and args.
func (a *execArtifact) Params(ctx *IContext) {
	h := ctx.GetHash()

	_0, _1 := []byte{0}, []byte{1}
	for _, p := range a.paths {
		if p.W {
			h.Write(_1)
		} else {
			h.Write(_0)
		}
		if p.P != nil {
			h.Write([]byte(p.P.String()))
		} else {
			h.Write([]byte("invalid P\x00"))
		}
		h.Write(_0)
		for _, d := range p.A {
			ctx.WriteIdent(d)
		}
		h.Write(_0)
	}
	h.Write(_0)
	h.Write([]byte(a.dir.String()))
	h.Write(_0)
	for _, e := range a.env {
		h.Write([]byte(e))
	}
	h.Write(_0)
	h.Write([]byte(a.path.String()))
	h.Write(_0)
	for _, arg := range a.args {
		h.Write([]byte(arg))
	}
}

// Dependencies returns a slice of all artifacts collected from caller-supplied
// [ExecPath].
func (a *execArtifact) Dependencies() []Artifact {
	artifacts := make([][]Artifact, 0, len(a.paths))
	for _, p := range a.paths {
		artifacts = append(artifacts, p.A)
	}
	return slices.Concat(artifacts...)
}

// String returns the caller-supplied reporting name.
func (a *execArtifact) String() string { return a.name }

// Cure cures the [Artifact] in the container described by the caller.
func (a *execArtifact) Cure(f *FContext) (err error) {
	return a.cure(f, false)
}

const (
	// execWaitDelay is passed through to [container.Params].
	execWaitDelay = time.Nanosecond
)

// scanVerbose prefixes program output for a verbose [message.Msg].
func scanVerbose(
	msg message.Msg,
	done chan<- struct{},
	prefix string,
	r io.Reader,
) {
	defer close(done)
	s := bufio.NewScanner(r)
	for s.Scan() {
		msg.Verbose(prefix, s.Text())
	}
	if err := s.Err(); err != nil && !errors.Is(err, os.ErrClosed) {
		msg.Verbose("*"+prefix, err)
	}
}

// cure is like Cure but allows optional host net namespace. This is used for
// the [KnownChecksum] variant where networking is allowed.
func (a *execArtifact) cure(f *FContext, hostNet bool) (err error) {
	overlayWorkIndex := -1
	for i, p := range a.paths {
		if p.P == nil || len(p.A) == 0 {
			return os.ErrInvalid
		}
		if p.P.Is(AbsWork) {
			overlayWorkIndex = i
		}
	}

	var artifactCount int
	for _, p := range a.paths {
		artifactCount += len(p.A)
	}

	ctx, cancel := context.WithTimeout(f.Unwrap(), a.timeout)
	defer cancel()

	z := container.New(ctx, f.GetMessage())
	z.WaitDelay = execWaitDelay
	z.SeccompPresets |= std.PresetStrict
	z.ParentPerm = 0700
	z.HostNet = hostNet
	z.Hostname = "cure"
	if z.HostNet {
		z.Hostname = "cure-net"
	}
	z.Uid, z.Gid = (1<<10)-1, (1<<10)-1
	if msg := f.GetMessage(); msg.IsVerbose() {
		var stdout, stderr io.ReadCloser
		if stdout, err = z.StdoutPipe(); err != nil {
			return
		}
		if stderr, err = z.StderrPipe(); err != nil {
			_ = stdout.Close()
			return
		}
		defer func() {
			if err != nil && !errors.As(err, new(*exec.ExitError)) {
				_ = stdout.Close()
				_ = stderr.Close()
			}
		}()

		stdoutDone, stderrDone := make(chan struct{}), make(chan struct{})
		go scanVerbose(msg, stdoutDone, "("+a.name+":1)", stdout)
		go scanVerbose(msg, stderrDone, "("+a.name+":2)", stderr)
		defer func() { <-stdoutDone; <-stderrDone }()
	}

	z.Dir, z.Env, z.Path, z.Args = a.dir, a.env, a.path, a.args
	z.Grow(len(a.paths) + 4)

	temp, work := f.GetTempDir(), f.GetWorkDir()
	for i, b := range a.paths {
		layers := make([]*check.Absolute, len(b.A))
		for j, d := range b.A {
			layers[j] = f.Pathname(d)
		}

		if i == overlayWorkIndex {
			if err = os.MkdirAll(work.String(), 0700); err != nil {
				return
			}
			tempWork := temp.Append(".work")
			if err = os.MkdirAll(tempWork.String(), 0700); err != nil {
				return
			}
			z.Overlay(
				AbsWork,
				work,
				tempWork,
				layers...,
			)
			continue
		}

		if a.paths[i].W {
			tempUpper, tempWork := temp.Append(
				".upper", strconv.Itoa(i),
			), temp.Append(
				".work", strconv.Itoa(i),
			)
			if err = os.MkdirAll(tempUpper.String(), 0700); err != nil {
				return
			}
			if err = os.MkdirAll(tempWork.String(), 0700); err != nil {
				return
			}
			z.Overlay(b.P, tempUpper, tempWork, layers...)
		} else if len(layers) == 1 {
			z.Bind(layers[0], b.P, 0)
		} else {
			z.OverlayReadonly(b.P, layers...)
		}
	}
	if overlayWorkIndex < 0 {
		z.Bind(
			work,
			AbsWork,
			std.BindWritable|std.BindEnsure,
		)
	}
	z.Bind(
		f.GetTempDir(),
		fhs.AbsTmp,
		std.BindWritable|std.BindEnsure,
	)
	z.Proc(fhs.AbsProc).Dev(fhs.AbsDev, true)

	if err = z.Start(); err != nil {
		return
	}
	if err = z.Serve(); err != nil {
		return
	}
	if err = z.Wait(); err != nil {
		return
	}

	// do not allow empty directories to succeed
	for {
		err = syscall.Rmdir(work.String())
		if err != syscall.EINTR {
			break
		}
	}
	if err != nil && errors.Is(err, syscall.ENOTEMPTY) {
		err = nil
	}
	return
}