aboutsummaryrefslogtreecommitdiff
path: root/pkg/spec/createconfig.go
blob: 632d60b5538425fbff337e3c188bbd348c0f117e (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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
package createconfig

import (
	"encoding/json"
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
	"syscall"

	"github.com/containers/libpod/libpod"
	"github.com/containers/libpod/pkg/namespaces"
	"github.com/containers/libpod/pkg/rootless"
	"github.com/containers/storage"
	"github.com/cri-o/ocicni/pkg/ocicni"
	"github.com/docker/go-connections/nat"
	spec "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/opencontainers/runtime-tools/generate"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"golang.org/x/sys/unix"
)

type mountType string

// Type constants
const (
	bps = iota
	iops
	// TypeBind is the type for mounting host dir
	TypeBind mountType = "bind"
	// TypeVolume is the type for remote storage volumes
	// TypeVolume mountType = "volume"  // re-enable upon use
	// TypeTmpfs is the type for mounting tmpfs
	TypeTmpfs mountType = "tmpfs"
)

// CreateResourceConfig represents resource elements in CreateConfig
// structures
type CreateResourceConfig struct {
	BlkioWeight       uint16   // blkio-weight
	BlkioWeightDevice []string // blkio-weight-device
	CPUPeriod         uint64   // cpu-period
	CPUQuota          int64    // cpu-quota
	CPURtPeriod       uint64   // cpu-rt-period
	CPURtRuntime      int64    // cpu-rt-runtime
	CPUShares         uint64   // cpu-shares
	CPUs              float64  // cpus
	CPUsetCPUs        string
	CPUsetMems        string   // cpuset-mems
	DeviceReadBps     []string // device-read-bps
	DeviceReadIOps    []string // device-read-iops
	DeviceWriteBps    []string // device-write-bps
	DeviceWriteIOps   []string // device-write-iops
	DisableOomKiller  bool     // oom-kill-disable
	KernelMemory      int64    // kernel-memory
	Memory            int64    //memory
	MemoryReservation int64    // memory-reservation
	MemorySwap        int64    //memory-swap
	MemorySwappiness  int      // memory-swappiness
	OomScoreAdj       int      //oom-score-adj
	PidsLimit         int64    // pids-limit
	ShmSize           int64
	Ulimit            []string //ulimit
}

// CreateConfig is a pre OCI spec structure.  It represents user input from varlink or the CLI
type CreateConfig struct {
	Runtime            *libpod.Runtime
	Annotations        map[string]string
	Args               []string
	CapAdd             []string // cap-add
	CapDrop            []string // cap-drop
	CidFile            string
	ConmonPidFile      string
	CgroupParent       string // cgroup-parent
	Command            []string
	Detach             bool              // detach
	Devices            []string          // device
	DNSOpt             []string          //dns-opt
	DNSSearch          []string          //dns-search
	DNSServers         []string          //dns
	Entrypoint         []string          //entrypoint
	Env                map[string]string //env
	ExposedPorts       map[nat.Port]struct{}
	GroupAdd           []string // group-add
	HostAdd            []string //add-host
	Hostname           string   //hostname
	Image              string
	ImageID            string
	BuiltinImgVolumes  map[string]struct{} // volumes defined in the image config
	IDMappings         *storage.IDMappingOptions
	ImageVolumeType    string                 // how to handle the image volume, either bind, tmpfs, or ignore
	Interactive        bool                   //interactive
	IpcMode            namespaces.IpcMode     //ipc
	IP6Address         string                 //ipv6
	IPAddress          string                 //ip
	Labels             map[string]string      //label
	LinkLocalIP        []string               // link-local-ip
	LogDriver          string                 // log-driver
	LogDriverOpt       []string               // log-opt
	MacAddress         string                 //mac-address
	Name               string                 //name
	NetMode            namespaces.NetworkMode //net
	Network            string                 //network
	NetworkAlias       []string               //network-alias
	PidMode            namespaces.PidMode     //pid
	Pod                string                 //pod
	PortBindings       nat.PortMap
	Privileged         bool     //privileged
	Publish            []string //publish
	PublishAll         bool     //publish-all
	Quiet              bool     //quiet
	ReadOnlyRootfs     bool     //read-only
	Resources          CreateResourceConfig
	Rm                 bool              //rm
	StopSignal         syscall.Signal    // stop-signal
	StopTimeout        uint              // stop-timeout
	Sysctl             map[string]string //sysctl
	Systemd            bool
	Tmpfs              []string              // tmpfs
	Tty                bool                  //tty
	UsernsMode         namespaces.UsernsMode //userns
	User               string                //user
	UtsMode            namespaces.UTSMode    //uts
	Mounts             []spec.Mount          //mounts
	Volumes            []string              //volume
	VolumesFrom        []string
	WorkDir            string   //workdir
	LabelOpts          []string //SecurityOpts
	NoNewPrivs         bool     //SecurityOpts
	ApparmorProfile    string   //SecurityOpts
	SeccompProfilePath string   //SecurityOpts
	SecurityOpts       []string
	Rootfs             string
	LocalVolumes       []string //Keeps track of the built-in volumes of container used in the --volumes-from flag
	Syslog             bool     // Whether to enable syslog on exit commands
}

func u32Ptr(i int64) *uint32     { u := uint32(i); return &u }
func fmPtr(i int64) *os.FileMode { fm := os.FileMode(i); return &fm }

// CreateBlockIO returns a LinuxBlockIO struct from a CreateConfig
func (c *CreateConfig) CreateBlockIO() (*spec.LinuxBlockIO, error) {
	return c.createBlockIO()
}

// AddContainerInitBinary adds the init binary specified by path iff the
// container will run in a private PID namespace that is not shared with the
// host or another pre-existing container, where an init-like process is
// already running.
//
// Note that AddContainerInitBinary prepends "/dev/init" "--" to the command
// to execute the bind-mounted binary as PID 1.
func (c *CreateConfig) AddContainerInitBinary(path string) error {
	if path == "" {
		return fmt.Errorf("please specify a path to the container-init binary")
	}
	if !c.PidMode.IsPrivate() {
		return fmt.Errorf("cannot add init binary as PID 1 (PID namespace isn't private)")
	}
	if c.Systemd {
		return fmt.Errorf("cannot use container-init binary with systemd")
	}
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return errors.Wrap(err, "container-init binary not found on the host")
	}
	c.Command = append([]string{"/dev/init", "--"}, c.Command...)
	c.Mounts = append(c.Mounts, spec.Mount{
		Destination: "/dev/init",
		Type:        "bind",
		Source:      path,
		Options:     []string{"bind", "ro"},
	})
	return nil
}

func processOptions(options []string) []string {
	var (
		foundrw, foundro bool
		rootProp         string
	)
	options = append(options, "rbind")
	for _, opt := range options {
		switch opt {
		case "rw":
			foundrw = true
		case "ro":
			foundro = true
		case "private", "rprivate", "slave", "rslave", "shared", "rshared":
			rootProp = opt
		}
	}
	if !foundrw && !foundro {
		options = append(options, "rw")
	}
	if rootProp == "" {
		options = append(options, "rprivate")
	}
	return options
}

func (c *CreateConfig) initFSMounts() []spec.Mount {
	var mounts []spec.Mount
	for _, m := range c.Mounts {
		m.Options = processOptions(m.Options)
		if m.Type == "tmpfs" {
			m.Options = append(m.Options, "tmpcopyup")
		} else {
			mounts = append(mounts, m)
		}
	}
	return mounts
}

//GetVolumeMounts takes user provided input for bind mounts and creates Mount structs
func (c *CreateConfig) GetVolumeMounts(specMounts []spec.Mount) ([]spec.Mount, error) {
	var m []spec.Mount
	for _, i := range c.Volumes {
		var options []string
		spliti := strings.Split(i, ":")
		if len(spliti) > 2 {
			options = strings.Split(spliti[2], ",")
		}

		m = append(m, spec.Mount{
			Destination: spliti[1],
			Type:        string(TypeBind),
			Source:      spliti[0],
			Options:     processOptions(options),
		})

		logrus.Debugf("User mount %s:%s options %v", spliti[0], spliti[1], options)
	}

	// volumes from image config
	if c.ImageVolumeType != "tmpfs" {
		return m, nil
	}
	for vol := range c.BuiltinImgVolumes {
		if libpod.MountExists(specMounts, vol) {
			continue
		}
		mount := spec.Mount{
			Destination: vol,
			Type:        string(TypeTmpfs),
			Source:      string(TypeTmpfs),
			Options:     []string{"rprivate", "rw", "noexec", "nosuid", "nodev", "tmpcopyup"},
		}
		m = append(m, mount)
	}
	return m, nil
}

// GetVolumesFrom reads the create-config artifact of the container to get volumes from
// and adds it to c.Volumes of the current container.
func (c *CreateConfig) GetVolumesFrom() error {
	var options string
	for _, vol := range c.VolumesFrom {
		splitVol := strings.SplitN(vol, ":", 2)
		if len(splitVol) == 2 {
			options = splitVol[1]
		}
		ctr, err := c.Runtime.LookupContainer(splitVol[0])
		if err != nil {
			return errors.Wrapf(err, "error looking up container %q", splitVol[0])
		}
		var createArtifact CreateConfig
		artifact, err := ctr.GetArtifact("create-config")
		if err != nil {
			return errors.Wrapf(err, "error getting create-config artifact for %q", splitVol[0])
		}
		if err := json.Unmarshal(artifact, &createArtifact); err != nil {
			return err
		}

		for key := range createArtifact.BuiltinImgVolumes {
			c.LocalVolumes = append(c.LocalVolumes, key)
		}

		for _, i := range createArtifact.Volumes {
			// Volumes format is host-dir:ctr-dir[:options], so get the host and ctr dir
			// and add on the options given by the user to the flag.
			spliti := strings.SplitN(i, ":", 3)
			// Throw error if mounting volume from container with Z option (private label)
			// Override this by adding 'z' to options.
			if len(spliti) > 2 && strings.Contains(spliti[2], "Z") && !strings.Contains(options, "z") {
				return errors.Errorf("volume mounted with private option 'Z' in %q. Use option 'z' to mount in current container", ctr.ID())
			}
			if options == "" {
				// Mount the volumes with the default options
				c.Volumes = append(c.Volumes, createArtifact.Volumes...)
			} else {
				c.Volumes = append(c.Volumes, spliti[0]+":"+spliti[1]+":"+options)
			}
		}
	}
	return nil
}

//GetTmpfsMounts takes user provided input for Tmpfs mounts and creates Mount structs
func (c *CreateConfig) GetTmpfsMounts() []spec.Mount {
	var m []spec.Mount
	for _, i := range c.Tmpfs {
		// Default options if nothing passed
		options := []string{"rprivate", "rw", "noexec", "nosuid", "nodev", "size=65536k"}
		spliti := strings.Split(i, ":")
		destPath := spliti[0]
		if len(spliti) > 1 {
			options = strings.Split(spliti[1], ",")
		}
		m = append(m, spec.Mount{
			Destination: destPath,
			Type:        string(TypeTmpfs),
			Options:     options,
			Source:      string(TypeTmpfs),
		})
	}
	return m
}

func (c *CreateConfig) createExitCommand() []string {
	config := c.Runtime.GetConfig()

	cmd, _ := os.Executable()
	command := []string{cmd,
		"--root", config.StorageConfig.GraphRoot,
		"--runroot", config.StorageConfig.RunRoot,
		"--log-level", logrus.GetLevel().String(),
		"--cgroup-manager", config.CgroupManager,
		"--tmpdir", config.TmpDir,
	}
	if config.StorageConfig.GraphDriverName != "" {
		command = append(command, []string{"--storage-driver", config.StorageConfig.GraphDriverName}...)
	}
	if c.Syslog {
		command = append(command, "--syslog")
	}
	return append(command, []string{"container", "cleanup"}...)
}

// GetContainerCreateOptions takes a CreateConfig and returns a slice of CtrCreateOptions
func (c *CreateConfig) GetContainerCreateOptions(runtime *libpod.Runtime, pod *libpod.Pod) ([]libpod.CtrCreateOption, error) {
	var options []libpod.CtrCreateOption
	var portBindings []ocicni.PortMapping
	var err error

	if c.Interactive {
		options = append(options, libpod.WithStdin())
	}
	if c.Systemd && (strings.HasSuffix(c.Command[0], "init") ||
		strings.HasSuffix(c.Command[0], "systemd")) {
		options = append(options, libpod.WithSystemd())
	}
	if c.Name != "" {
		logrus.Debugf("appending name %s", c.Name)
		options = append(options, libpod.WithName(c.Name))
	}
	if c.Pod != "" || pod != nil {
		if pod == nil {
			pod, err = runtime.LookupPod(c.Pod)
			if err != nil {
				return nil, errors.Wrapf(err, "unable to add container to pod %s", c.Pod)
			}
		}
		logrus.Debugf("adding container to pod %s", c.Pod)
		options = append(options, runtime.WithPod(pod))
	}
	if len(c.PortBindings) > 0 {
		portBindings, err = c.CreatePortBindings()
		if err != nil {
			return nil, errors.Wrapf(err, "unable to create port bindings")
		}
	}

	if len(c.Volumes) != 0 {
		// Volumes consist of multiple, comma-delineated fields
		// The image spec only includes one part of that, so drop the
		// others, if they are included
		volumes := make([]string, 0, len(c.Volumes))
		for _, vol := range c.Volumes {
			volumes = append(volumes, strings.SplitN(vol, ":", 2)[0])
		}

		options = append(options, libpod.WithUserVolumes(volumes))
	}

	if len(c.LocalVolumes) != 0 {
		options = append(options, libpod.WithLocalVolumes(c.LocalVolumes))
	}

	if len(c.Command) != 0 {
		options = append(options, libpod.WithCommand(c.Command))
	}

	// Add entrypoint unconditionally
	// If it's empty it's because it was explicitly set to "" or the image
	// does not have one
	options = append(options, libpod.WithEntrypoint(c.Entrypoint))

	networks := make([]string, 0)
	userNetworks := c.NetMode.UserDefined()
	if IsPod(userNetworks) {
		userNetworks = ""
	}
	if userNetworks != "" {
		for _, netName := range strings.Split(userNetworks, ",") {
			if netName == "" {
				return nil, errors.Wrapf(err, "container networks %q invalid", networks)
			}
			networks = append(networks, netName)
		}
	}

	if IsNS(string(c.NetMode)) {
		// pass
	} else if c.NetMode.IsContainer() {
		connectedCtr, err := c.Runtime.LookupContainer(c.NetMode.Container())
		if err != nil {
			return nil, errors.Wrapf(err, "container %q not found", c.NetMode.Container())
		}
		options = append(options, libpod.WithNetNSFrom(connectedCtr))
	} else if !c.NetMode.IsHost() && !c.NetMode.IsNone() {
		isRootless := rootless.IsRootless()
		postConfigureNetNS := c.NetMode.IsSlirp4netns() || (len(c.IDMappings.UIDMap) > 0 || len(c.IDMappings.GIDMap) > 0) && !c.UsernsMode.IsHost()
		if isRootless && len(portBindings) > 0 {
			return nil, errors.New("port bindings are not yet supported by rootless containers")
		}
		options = append(options, libpod.WithNetNS(portBindings, postConfigureNetNS, string(c.NetMode), networks))
	}

	if c.PidMode.IsContainer() {
		connectedCtr, err := c.Runtime.LookupContainer(c.PidMode.Container())
		if err != nil {
			return nil, errors.Wrapf(err, "container %q not found", c.PidMode.Container())
		}

		options = append(options, libpod.WithPIDNSFrom(connectedCtr))
	}

	if c.IpcMode.IsContainer() {
		connectedCtr, err := c.Runtime.LookupContainer(c.IpcMode.Container())
		if err != nil {
			return nil, errors.Wrapf(err, "container %q not found", c.IpcMode.Container())
		}

		options = append(options, libpod.WithIPCNSFrom(connectedCtr))
	}

	if IsPod(string(c.UtsMode)) {
		options = append(options, libpod.WithUTSNSFromPod(pod))
	}
	if c.UtsMode.IsContainer() {
		connectedCtr, err := c.Runtime.LookupContainer(c.UtsMode.Container())
		if err != nil {
			return nil, errors.Wrapf(err, "container %q not found", c.UtsMode.Container())
		}

		options = append(options, libpod.WithUTSNSFrom(connectedCtr))
	}

	// TODO: MNT, USER, CGROUP
	options = append(options, libpod.WithStopSignal(c.StopSignal))
	options = append(options, libpod.WithStopTimeout(c.StopTimeout))
	if len(c.DNSSearch) > 0 {
		options = append(options, libpod.WithDNSSearch(c.DNSSearch))
	}
	if len(c.DNSServers) > 0 {
		options = append(options, libpod.WithDNS(c.DNSServers))
	}
	if len(c.DNSOpt) > 0 {
		options = append(options, libpod.WithDNSOption(c.DNSOpt))
	}
	if len(c.HostAdd) > 0 {
		options = append(options, libpod.WithHosts(c.HostAdd))
	}
	logPath := getLoggingPath(c.LogDriverOpt)
	if logPath != "" {
		options = append(options, libpod.WithLogPath(logPath))
	}
	if c.IPAddress != "" {
		ip := net.ParseIP(c.IPAddress)
		if ip == nil {
			return nil, errors.Wrapf(libpod.ErrInvalidArg, "cannot parse %s as IP address", c.IPAddress)
		} else if ip.To4() == nil {
			return nil, errors.Wrapf(libpod.ErrInvalidArg, "%s is not an IPv4 address", c.IPAddress)
		}
		options = append(options, libpod.WithStaticIP(ip))
	}

	options = append(options, libpod.WithPrivileged(c.Privileged))

	useImageVolumes := c.ImageVolumeType == "bind"
	// Gather up the options for NewContainer which consist of With... funcs
	options = append(options, libpod.WithRootFSFromImage(c.ImageID, c.Image, useImageVolumes))
	options = append(options, libpod.WithSecLabels(c.LabelOpts))
	options = append(options, libpod.WithConmonPidFile(c.ConmonPidFile))
	options = append(options, libpod.WithLabels(c.Labels))
	options = append(options, libpod.WithUser(c.User))
	if c.IpcMode.IsHost() {
		options = append(options, libpod.WithShmDir("/dev/shm"))

	} else if c.IpcMode.IsContainer() {
		ctr, err := runtime.LookupContainer(c.IpcMode.Container())
		if err != nil {
			return nil, errors.Wrapf(err, "container %q not found", c.IpcMode.Container())
		}
		options = append(options, libpod.WithShmDir(ctr.ShmDir()))
	}
	options = append(options, libpod.WithShmSize(c.Resources.ShmSize))
	options = append(options, libpod.WithGroups(c.GroupAdd))
	options = append(options, libpod.WithIDMappings(*c.IDMappings))
	if c.Rootfs != "" {
		options = append(options, libpod.WithRootFS(c.Rootfs))
	}
	// Default used if not overridden on command line

	if c.CgroupParent != "" {
		options = append(options, libpod.WithCgroupParent(c.CgroupParent))
	}
	// For a rootless container always cleanup the storage/network as they
	// run in a different namespace thus not reusable when we restart.
	if c.Detach || rootless.IsRootless() {
		options = append(options, libpod.WithExitCommand(c.createExitCommand()))
	}

	return options, nil
}

// CreatePortBindings iterates ports mappings and exposed ports into a format CNI understands
func (c *CreateConfig) CreatePortBindings() ([]ocicni.PortMapping, error) {
	return NatToOCIPortBindings(c.PortBindings)
}

// NatToOCIPortBindings iterates a nat.portmap slice and creates []ocicni portmapping slice
func NatToOCIPortBindings(ports nat.PortMap) ([]ocicni.PortMapping, error) {
	var portBindings []ocicni.PortMapping
	for containerPb, hostPb := range ports {
		var pm ocicni.PortMapping
		pm.ContainerPort = int32(containerPb.Int())
		for _, i := range hostPb {
			var hostPort int
			var err error
			pm.HostIP = i.HostIP
			if i.HostPort == "" {
				hostPort = containerPb.Int()
			} else {
				hostPort, err = strconv.Atoi(i.HostPort)
				if err != nil {
					return nil, errors.Wrapf(err, "unable to convert host port to integer")
				}
			}

			pm.HostPort = int32(hostPort)
			pm.Protocol = containerPb.Proto()
			portBindings = append(portBindings, pm)
		}
	}
	return portBindings, nil
}

// AddPrivilegedDevices iterates through host devices and adds all
// host devices to the spec
func (c *CreateConfig) AddPrivilegedDevices(g *generate.Generator) error {
	return c.addPrivilegedDevices(g)
}

func getStatFromPath(path string) (unix.Stat_t, error) {
	s := unix.Stat_t{}
	err := unix.Stat(path, &s)
	return s, err
}