aboutsummaryrefslogtreecommitdiffhomepage
path: root/container/params.go
blob: a48eabafc1369c1d1e1d9be83e41c6e253ab0080 (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
package container

import (
	"encoding/gob"
	"errors"
	"os"
	"strconv"
	"syscall"
)

// Setup appends the read end of a pipe for setup params transmission and returns its fd.
func Setup(extraFiles *[]*os.File) (int, *gob.Encoder, error) {
	if r, w, err := os.Pipe(); err != nil {
		return -1, nil, err
	} else {
		fd := 3 + len(*extraFiles)
		*extraFiles = append(*extraFiles, r)
		return fd, gob.NewEncoder(w), nil
	}
}

var (
	ErrReceiveEnv = errors.New("environment variable not set")
)

// Receive retrieves setup fd from the environment and receives params.
func Receive(key string, e any, fdp *uintptr) (func() error, error) {
	var setup *os.File

	if s, ok := os.LookupEnv(key); !ok {
		return nil, ErrReceiveEnv
	} else {
		if fd, err := strconv.Atoi(s); err != nil {
			return nil, optionalErrorUnwrap(err)
		} else {
			setup = os.NewFile(uintptr(fd), "setup")
			if setup == nil {
				return nil, syscall.EDOM
			}
			if fdp != nil {
				*fdp = setup.Fd()
			}
		}
	}

	return setup.Close, gob.NewDecoder(setup).Decode(e)
}