-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathunikontainers.go
More file actions
1312 lines (1165 loc) · 38.4 KB
/
Copy pathunikontainers.go
File metadata and controls
1312 lines (1165 loc) · 38.4 KB
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023-2026, Nubificus LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package unikontainers
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"net"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"github.com/urunc-dev/urunc/pkg/network"
"github.com/urunc-dev/urunc/pkg/unikontainers/hypervisors"
"github.com/urunc-dev/urunc/pkg/unikontainers/types"
"github.com/urunc-dev/urunc/pkg/unikontainers/unikernels"
"github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
m "github.com/urunc-dev/urunc/internal/metrics"
)
const (
monitorRootfsDirName string = "monRootfs"
containerRootfsMountPath string = "/cntrRootfs"
)
var uniklog = logrus.WithField("subsystem", "unikontainers")
var ErrQueueProxy = errors.New("this a queue proxy container")
var ErrNotUnikernel = errors.New("this is not a unikernel container")
var ErrNotExistingNS = errors.New("the namespace does not exist")
// Unikontainer holds the data necessary to create, manage and delete unikernel containers
type Unikontainer struct {
State *specs.State
Spec *specs.Spec
BaseDir string
RootDir string
UruncCfg *UruncConfig
Listener *net.UnixListener
Conn *net.UnixConn
}
// New parses the bundle and creates a new Unikontainer object
func New(bundlePath string, containerID string, rootDir string, cfg *UruncConfig) (*Unikontainer, error) {
spec, err := loadSpec(bundlePath)
if err != nil {
return nil, err
}
if spec == nil || spec.Linux == nil {
return nil, fmt.Errorf("invalid OCI spec: linux section is required")
}
containerName := spec.Annotations["io.kubernetes.cri.container-name"]
if containerName == "queue-proxy" {
uniklog.Warn("This is a queue-proxy container. Adding IP env.")
configFile := filepath.Join(bundlePath, configFilename)
err = handleQueueProxy(*spec, configFile)
if err != nil {
return nil, err
}
return nil, ErrQueueProxy
}
config, err := GetUnikernelConfig(bundlePath, spec)
if err != nil {
return nil, ErrNotUnikernel
}
confMap := config.Map()
maps.Copy(confMap, cfg.Map())
containerDir := filepath.Join(rootDir, containerID)
state := &specs.State{
Version: spec.Version,
ID: containerID,
Status: "creating",
Pid: -1,
Bundle: bundlePath,
Annotations: confMap,
}
return &Unikontainer{
BaseDir: containerDir,
RootDir: rootDir,
Spec: spec,
State: state,
UruncCfg: cfg,
}, nil
}
// Get retrieves unikernel data from disk to create a Unikontainer object
func Get(containerID string, rootDir string) (*Unikontainer, error) {
u := &Unikontainer{}
containerDir := filepath.Join(rootDir, containerID)
stateFilePath := filepath.Join(containerDir, stateFilename)
state, err := loadUnikontainerState(stateFilePath)
if err != nil {
return nil, err
}
if state.Annotations[annotType] == "" {
return nil, ErrNotUnikernel
}
u.State = state
spec, err := loadSpec(state.Bundle)
if err != nil {
return nil, err
}
if spec == nil || spec.Linux == nil {
return nil, fmt.Errorf("invalid OCI spec: linux section is required")
}
u.BaseDir = containerDir
u.RootDir = rootDir
u.Spec = spec
u.UruncCfg = UruncConfigFromMap(state.Annotations)
return u, nil
}
// InitialSetup sets the Unikernel status as creating,
// creates the Unikernel base directory and
// saves the state.json file with the current Unikernel state
func (u *Unikontainer) InitialSetup() error {
bundleDir := filepath.Clean(u.State.Bundle)
rootfsDir := filepath.Clean(u.Spec.Root.Path)
rootfsDir, err := resolveAgainstBase(bundleDir, rootfsDir)
if err != nil {
uniklog.Errorf("could not resolve rootfs directory %s: %v", rootfsDir, err)
return err
}
// Ensure the container's rootfs has the correct propagation flag
// so if we unmount it later, it gets unmounted from other mount peer
// groups too. We do that regardless of the type of the container's
// rootfs (e.g. block-based, overlay) abd this is ok, because we later
// cut off all propagation from reexec.
// TODO: Move this to the shim, when we finally make it.
err = unix.Mount("", rootfsDir, "", unix.MS_SHARED|unix.MS_REC, "")
if err != nil && !errors.Is(err, unix.EINVAL) {
// An EINVAL error is fine, because it means that the
// rootfs is not really a mountpoint. This could be the case when
// using urunc directly from its cli and the rootfs is a normal
// directory
uniklog.Errorf("could not set propagation flag as shared for container's rootfs: %v", err)
return err
}
u.State.Status = specs.StateCreating
// FIXME: should we really create this base dir
err = os.MkdirAll(u.BaseDir, 0o755)
if err != nil {
return err
}
return u.saveContainerState()
}
// Create sets the Unikernel status as created,
// and saves the given PID in the provided pid file path.
// If pidFilePath is empty, it falls back to the default init.pid path.
func (u *Unikontainer) Create(pid int, pidFilePath string) error {
path := filepath.Join(u.State.Bundle, initPidFilename)
if pidFilePath != "" {
path = pidFilePath
}
err := writePidFile(path, pid)
if err != nil {
return err
}
u.State.Pid = pid
u.State.Status = specs.StateCreated
return u.saveContainerState()
}
// SetRunningState sets the Unikernel status as running,
func (u *Unikontainer) SetRunningState() error {
u.State.Status = specs.StateRunning
return u.saveContainerState()
}
func (u *Unikontainer) SetupNet() (types.NetDevParams, error) {
networkType := u.getNetworkType()
uniklog.WithField("network type", networkType).Debug("Retrieved network type")
netArgs := types.NetDevParams{}
netManager, err := network.NewNetworkManager(networkType)
if err != nil {
return netArgs, fmt.Errorf("failed to create network manager for %s type: %v", networkType, err)
}
networkInfo, err := netManager.NetworkSetup(u.Spec.Process.User.UID, u.Spec.Process.User.GID)
if err != nil {
// TODO: Handle this case better. We do not need to show an error
// since there was no network in the container. Therefore, we
// need better error handling and specifically check if the container
// di not have any network.
uniklog.Errorf("Failed to setup network :%v. Possibly due to ctr", err)
}
// if network info is nil, we didn't find eth0, so we are running with ctr
if networkInfo != nil {
netArgs.TapDev = networkInfo.TapDevice
netArgs.IP = networkInfo.EthDevice.IP
netArgs.Mask = networkInfo.EthDevice.Mask
netArgs.Gateway = networkInfo.EthDevice.DefaultGateway
// The MAC address for the guest network device is the same as the
// virtual ethernet interface inside the namespace
netArgs.MAC = networkInfo.EthDevice.MAC
netArgs.MTU = networkInfo.EthDevice.MTU
}
return netArgs, nil
}
// chooseRootfs determines the best rootfs configuration based on available options
// Priority order:
// 1. Initrd (if specified)
// 2. Explicit block device annotation (if mounted at /)
// 3. Container rootfs as block device (if MountRootfs=true and supported)
// 4. Container rootfs as shared-fs: virtiofs > 9pfs (if MountRootfs=true and supported)
// 5. No rootfs
func ChooseRootfs(bundle, specRoot string, annot map[string]string, cfg *UruncConfig) (types.RootfsParams, error) {
bundleDir := filepath.Clean(bundle)
rootfsDir := filepath.Clean(specRoot)
rootfsDir, err := resolveAgainstBase(bundleDir, rootfsDir)
if err != nil {
uniklog.Errorf("could not resolve rootfs directory %s: %v", rootfsDir, err)
return types.RootfsParams{}, err
}
if cfg == nil {
return types.RootfsParams{}, fmt.Errorf("urunc config is required for guest rootfs selection")
}
unikernelType := annot[annotType]
unikernel, err := unikernels.New(unikernelType)
if err != nil {
return types.RootfsParams{}, err
}
vmmType := annot[annotHypervisor]
vmm, err := hypervisors.NewVMM(hypervisors.VmmType(vmmType), cfg.Monitors)
if err != nil {
return types.RootfsParams{}, err
}
virtiofsdConfig := cfg.ExtraBins["virtiofsd"]
selector := &rootfsSelector{
bundle: bundleDir,
cntrRootfs: rootfsDir,
annot: annot,
unikernel: unikernel,
vmm: vmm,
vfsdPath: virtiofsdConfig.Path,
}
// Priority 1: Initrd
result, ok := selector.tryInitrd()
if ok {
return result, nil
}
// Priority 2: Explicit block annotation
result, ok = selector.tryExplicitBlock()
if ok {
return result, nil
}
// Priority 3 & 4: Container rootfs (block or shared-fs)
result, ok = selector.tryContainerRootfs()
if ok {
return switchMonRootfs(result, bundleDir)
}
if selector.shouldMountContainerRootfs() {
return types.RootfsParams{}, fmt.Errorf("can not use the container rootfs as the sandbox's guest rootfs through block or shared-fs")
}
uniklog.Info("no rootfs configured for guest")
result.MonRootfs = rootfsDir
return result, nil
}
// nolint:gocyclo
func (u *Unikontainer) Exec(metrics m.Writer) error {
metrics.Capture(m.TS15)
// container Paths
// Make sure paths are clean
bundleDir := filepath.Clean(u.State.Bundle)
rootfsDir := filepath.Clean(u.Spec.Root.Path)
rootfsDir, err := resolveAgainstBase(bundleDir, rootfsDir)
if err != nil {
uniklog.Errorf("could not resolve rootfs directory %s: %v", rootfsDir, err)
return err
}
// unikernel
unikernelType := u.State.Annotations[annotType]
unikernel, err := unikernels.New(unikernelType)
if err != nil {
return err
}
// Vmm
vmmType := u.State.Annotations[annotHypervisor]
vmm, err := hypervisors.NewVMM(hypervisors.VmmType(vmmType), u.UruncCfg.Monitors)
if err != nil {
return err
}
// unikernelParams
unikernelVersion := u.State.Annotations[annotVersion]
// ExecArgs
unikernelPath := u.State.Annotations[annotBinary]
initrdPath := u.State.Annotations[annotInitrd]
// debug
uniklog.WithFields(logrus.Fields{
"bundle directory": bundleDir,
"rootfs directory": rootfsDir,
"vmm type": vmmType,
"unikernel type": unikernelType,
"unikernel version": unikernelVersion,
"unikernel Path": unikernelPath,
"initrd Path": initrdPath,
}).Debug("Initialization values")
// ExecArgs
defaultVCPUs := u.UruncCfg.Monitors[vmmType].DefaultVCPUs
if defaultVCPUs < 1 {
defaultVCPUs = 1
}
defaultMemSizeMB := u.UruncCfg.Monitors[vmmType].DefaultMemoryMB
// ExecArgs
vmmArgs := types.ExecArgs{
ContainerID: u.State.ID,
UnikernelPath: unikernelPath,
InitrdPath: initrdPath,
Seccomp: true, // Enable Seccomp by default
MemSizeB: uint64(defaultMemSizeMB * 1024 * 1024),
VCPUs: uint(defaultVCPUs),
Environment: os.Environ(),
}
// ExecArgs
// If memory limit is set in spec, use it instead of the config default value
if u.Spec.Linux.Resources != nil && u.Spec.Linux.Resources.Memory != nil {
if u.Spec.Linux.Resources.Memory.Limit != nil {
if *u.Spec.Linux.Resources.Memory.Limit > 0 {
vmmArgs.MemSizeB = uint64(*u.Spec.Linux.Resources.Memory.Limit) // nolint:gosec
}
}
}
// ExecArgs
// Check if container is set to unconfined -- disable seccomp
if u.Spec.Linux.Seccomp == nil {
uniklog.Warn("Seccomp is disabled")
vmmArgs.Seccomp = false
}
procAttrs := types.ProcessConfig{
UID: u.Spec.Process.User.UID,
GID: u.Spec.Process.User.GID,
WorkDir: u.Spec.Process.Cwd,
}
// UnikernelParams
// populate unikernel params
unikernelParams := types.UnikernelParams{
CmdLine: u.Spec.Process.Args,
EnvVars: u.Spec.Process.Env,
Monitor: vmmType,
Version: unikernelVersion,
ProcConf: procAttrs,
}
if len(unikernelParams.CmdLine) == 0 {
unikernelParams.CmdLine = strings.Fields(u.State.Annotations[annotCmdLine])
}
// handle network
netArgs, err := u.SetupNet()
if err != nil {
uniklog.Errorf("failed to setup network: %v", err)
return err
}
metrics.Capture(m.TS16)
withTUNTAP := netArgs.IP != ""
// UnikernelParams
unikernelParams.Net = netArgs
// ExecArgs
vmmArgs.Net = netArgs
// virtiofsd config
virtiofsdConfig := u.UruncCfg.ExtraBins["virtiofsd"]
// guest rootfs
// block
// handle guest's rootfs.
// There are three options:
// 1. No rootfs for guest
// 2. Use the devmapper snapshot as a block device for the guest's rootfs
// 3. Use 9pfs to share the container's rootfs as the guest's rootfs
// By default, urunc will not set any rootfs for the guest. However,
// if the respective annotation is set then, depending on the guest
// (supports block or 9pfs), it will use the supported option. In case
// both ae supported, then the block option will be used by default.
var rootfsParams types.RootfsParams
// Read the rootfs choice written by the shim.
if rootfsParamsJSON := u.Spec.Annotations[annotRootfsParams]; rootfsParamsJSON != "" {
if err := json.Unmarshal([]byte(rootfsParamsJSON), &rootfsParams); err != nil {
return fmt.Errorf("could not decode guest rootfs params: %w", err)
}
}
// If there is no shim choice, the runtime chooses rootfs here.
if rootfsParams.MonRootfs == "" {
rootfsParams, err = ChooseRootfs(u.State.Bundle, u.Spec.Root.Path, u.State.Annotations, u.UruncCfg)
if err != nil {
uniklog.Errorf("could not choose guest rootfs: %v", err)
return err
}
}
uniklog.WithFields(logrus.Fields{
"rootfs_type": rootfsParams.Type,
"rootfs_path": rootfsParams.Path,
"mon_rootfs": rootfsParams.MonRootfs,
}).Debug("guest rootfs params")
// TODO: Add support for using both an existing
// block based snapshot of the container's rootfs
// and an auxiliary block image placed in the container's image
// Currently if a block Image is present in the container's image, then
// we will just use this image.
var rfsBuilder rootfsBuilder
switch rootfsParams.Type {
case "block":
rfsBuilder = blockRootfs{
mounts: u.Spec.Mounts,
monRootfs: rootfsParams.MonRootfs,
mountedPath: rootfsParams.MountedPath,
path: rootfsParams.Path,
kernelPath: unikernelPath,
initrdPath: initrdPath,
uruncJSONPath: uruncJSONFilename,
guestType: unikernelType,
guest: unikernel,
}
case "initrd":
rfsBuilder = initrdRootfs{
mounts: u.Spec.Mounts,
initrdHostFullPath: filepath.Join(rootfsParams.MonRootfs, rootfsParams.Path),
monRootfs: rootfsParams.MonRootfs,
}
case "virtiofs", "9pfs":
rfsBuilder = sharedfsRootfs{
mounts: u.Spec.Mounts,
monRootfs: rootfsParams.MonRootfs,
mountedPath: rootfsParams.MountedPath,
sfsType: rootfsParams.Type,
vfsdConfig: virtiofsdConfig,
sharedPath: containerRootfsMountPath,
memory: vmmArgs.MemSizeB,
}
// Update the paths of the files we need to pass in the monitor process.
vmmArgs.UnikernelPath = adjustPathsForSharedfs(vmmArgs.UnikernelPath)
vmmArgs.InitrdPath = adjustPathsForSharedfs(vmmArgs.InitrdPath)
default:
uniklog.Debug("No rootfs for guest")
rfsBuilder = noRootfs{
monRootfs: rootfsParams.MonRootfs,
annotBlockPath: u.State.Annotations[annotBlock],
annotBlockMountPoint: u.State.Annotations[annotBlockMntPoint],
}
}
if err = os.MkdirAll(rootfsParams.MonRootfs, 0o755); err != nil {
return fmt.Errorf("failed to create monitor rootfs directory %s: %w", rootfsParams.MonRootfs, err)
}
err = rfsBuilder.preSetup()
if err != nil {
return fmt.Errorf("pre setup step for rootfs failed: %w", err)
}
// Prepare Monitor rootfs
// Make sure that rootfs is mounted with the correct propagation
// flags so we can later pivot if needed.
err = prepareRoot(rootfsParams.MonRootfs, u.Spec.Linux.RootfsPropagation)
if err != nil {
return err
}
// Setup the rootfs for the monitor execution, creating necessary
// devices and the monitor's binary.
err = prepareMonRootfs(rootfsParams.MonRootfs, vmm.Path(), u.UruncCfg.Monitors[vmmType].DataPath, vmm.UsesKVM(), withTUNTAP)
if err != nil {
return err
}
err = rfsBuilder.postSetup()
if err != nil {
return fmt.Errorf("post setup step for block based rootfs failed: %w", err)
}
blockArgs, err := rfsBuilder.getBlockDevs()
if err != nil {
return fmt.Errorf("failed to get block devices to attach in sandbox: %w", err)
}
sharedfsArgs, err := rfsBuilder.getSharedDirs()
if err != nil {
uniklog.Errorf("failed to get directories to share with sandbox: %v", err)
return err
}
unikernelParams.Rootfs = rootfsParams
metrics.Capture(m.TS17)
// unikernelParams
unikernelParams.Block = blockArgs
// ExecArgs
vmmArgs.Sharedfs = sharedfsArgs
// vAccel setup
vAccelType, vsockSocketPath, rpcAddress, err := resolveVAccelConfig(u.State.Annotations[annotHypervisor], u.Spec.Annotations)
if err != nil {
if !errors.Is(err, ErrVAccelDisabled) {
uniklog.Warnf("vAccel misconfiguration: %v", err)
}
}
if vAccelType == "vsock" && err == nil {
// Remove any existing VACCEL_RPC_ADDRESS and set the new value
for i, envVar := range unikernelParams.EnvVars {
if strings.HasPrefix(envVar, "VACCEL_RPC_ADDRESS"+"=") {
unikernelParams.EnvVars = remove(unikernelParams.EnvVars, i)
break
}
}
unikernelParams.EnvVars = append(unikernelParams.EnvVars, "VACCEL_RPC_ADDRESS="+rpcAddress)
// Prepare the guest environment for vAccel vsock communication
err = prepareVSockEnvironment(rootfsParams.MonRootfs, u.State.Annotations[annotHypervisor], vsockSocketPath)
if err != nil {
uniklog.Debugf("failed to prepare all required vsock mounts: %v", err)
}
vmmArgs.VAccelType = vAccelType
vmmArgs.VSockDevPath = vsockSocketPath
vmmArgs.VSockDevID = idToGuestCID(u.State.ID)
}
// unikernel
err = unikernel.Init(unikernelParams)
if errors.Is(err, unikernels.ErrUndefinedVersion) ||
errors.Is(err, unikernels.ErrVersionParsing) {
uniklog.WithError(err).Error("an error occurred while initializing the unikernel")
} else if err != nil {
return err
}
// unikernel
// build the unikernel command
unikernelCmd, err := unikernel.CommandString()
if err != nil {
return err
}
// ExecArgs
vmmArgs.Command = unikernelCmd
// pivot
_, err = findNS(u.Spec.Linux.Namespaces, specs.MountNamespace)
// We just want to check if a mount namespace was define din the list
// Therefore, if there was no error and the mount namespace was found
// we can pivot.
withPivot := err != nil
err = changeRoot(rootfsParams.MonRootfs, withPivot)
if err != nil {
return err
}
// uid/gid
// Setup uid, gid and additional groups for the monitor process
err = setupUser(u.Spec.Process.User)
if err != nil {
return err
}
// execute hooks
// NOTE: StartContainer hooks are supposed to run right before the init of
// the container. However, in the case of a Linux-based container, the init
// of the container runs inside the sandbox. Therefore, we have to see how
// we should treat this hook, because it might refer to operations like
// ldconfig etc.
err = u.ExecuteHooks("StartContainer")
if err != nil {
return err
}
err = rfsBuilder.preStart()
if err != nil {
return err
}
uniklog.Debug("calling vmm execve")
metrics.Capture(m.TS18)
// Build the VMM command once and verify it can be constructed successfully.
// This ensures we don't report the container as started if command building fails.
execCmd, err := vmm.BuildExecCmd(vmmArgs, unikernel)
if err != nil {
uniklog.WithError(err).Error("failed to build VMM command")
return err
}
// Notify urunc start that the monitor is ready to execute.
// We send this after BuildExecCmd succeeds to avoid reporting a container
// as started when the VMM command cannot be built.
// TODO: The container can still be reported as running if the PreExec step
// (e.g., BPF/seccomp filter setup) fails after this point. We should find
// a way to handle that case as well.
err = u.SendMessage(StartSuccess)
if err != nil {
return err
}
// Perform any monitor-specific pre-exec setup (e.g., seccomp filters for HVT).
err = vmm.PreExec(vmmArgs)
if err != nil {
uniklog.WithError(err).Error("failed to perform pre-exec setup")
return err
}
// Execute the VMM using the command we built earlier.
uniklog.WithField("command", execCmd).Debug("Ready to execve VMM")
return syscall.Exec(vmm.Path(), execCmd, vmmArgs.Environment) //nolint: gosec
}
func setupUser(user specs.User) error {
runtime.LockOSThread()
// Set the user for the current go routine to exec the Monitor
AddGidsLen := len(user.AdditionalGids)
if AddGidsLen > 0 {
err := unix.Setgroups(convertUint32ToIntSlice(user.AdditionalGids, AddGidsLen))
if err != nil {
return fmt.Errorf("could not set Additional groups %v : %v", user.AdditionalGids, err)
}
}
err := unix.Setgid(int(user.GID))
if err != nil {
return fmt.Errorf("could not set gid %d: %v", user.GID, err)
}
err = unix.Setuid(int(user.UID))
if err != nil {
return fmt.Errorf("could not set uid %d: %v", user.UID, err)
}
return nil
}
// Signal sends a specified signal to container's init.
func (u *Unikontainer) Signal(signal unix.Signal) error {
vmmType := u.State.Annotations[annotHypervisor]
vmm, err := hypervisors.NewVMM(hypervisors.VmmType(vmmType), u.UruncCfg.Monitors)
if err != nil {
return err
}
return vmm.Signal(u.State.Pid, signal)
}
// Kill stops the VMM process, first by asking the VMM struct to stop
// and consequently by killing the process described in u.State.Pid
func (u *Unikontainer) Kill() error {
// Try to join the Network namespace of the monitor before killing it.
// If we kill it there might be no process inside the namespace and hence
// the namespace gets destroyed.
err := u.joinSandboxNetNs()
if err != nil {
if errors.Is(err, ErrNotExistingNS) {
// There is no network namespace to join.
// Most probably the sandbox is dead and the namespace
// has been destroyed.
uniklog.Infof("could not find sandbox's network namespace: %v", err)
return nil
}
return fmt.Errorf("failed to join sandbox netns: %v", err)
}
// get a new vmm
vmmType := u.State.Annotations[annotHypervisor]
vmm, err := hypervisors.NewVMM(hypervisors.VmmType(vmmType), u.UruncCfg.Monitors)
if err != nil {
return err
}
err = vmm.Stop(u.State.Pid)
if err != nil {
return err
}
err = network.CleanupAllUruncTaps()
if err != nil {
uniklog.Errorf("failed to cleanup tap devices: %v", err)
}
return nil
}
// Delete removes the containers base directory and its contents
func (u *Unikontainer) Delete() error {
var dirs []string
var prefPath string
if u.isRunning() {
return fmt.Errorf("cannot delete running container: %s", u.State.ID)
}
// get a monitor instance of the running monitor
vmmType := u.State.Annotations[annotHypervisor]
vmm, err := hypervisors.NewVMM(hypervisors.VmmType(vmmType), u.UruncCfg.Monitors)
if err != nil {
return err
}
// Make sure paths are clean
bundleDir := filepath.Clean(u.State.Bundle)
rootfsDir := filepath.Clean(u.Spec.Root.Path)
if !filepath.IsAbs(rootfsDir) {
rootfsDir = filepath.Join(bundleDir, rootfsDir)
}
monRootfs := filepath.Join(bundleDir, monitorRootfsDirName)
// TODO: We might not need to remove any of the directories and let
// the kernel cleanup the mounts and shim to remove directories.
// However, just to be on the safe side, we remove all the newly
// created directories from urunc. In order to check if we used the
// rootfs under the bundle directory or we create anew one, we can check
// if the monitorRootfsDirName directory exists under the bundle.
_, err = os.Stat(monRootfs)
if !os.IsNotExist(err) {
// Since there was no block defined for the unikernel
// and we created a new rootfs for the monitor, we need to
// clean it up.
dirs = append(dirs, monitorRootfsDirName)
prefPath = bundleDir
} else {
// Otherwise remove the enw directories we created inside the
// container's rootfs.
// We do not need to unmount anything here, since we rely on Linux
// to do the cleanup for us. This will happen automatically,
// when the mount namespace gets destroyed
dirs = []string{
"/lib",
"/lib64",
"/usr",
"/proc",
"/dev",
"/tmp",
}
dirs = append(dirs, vmm.Path())
prefPath = rootfsDir
}
err = rmMultipleDirs(prefPath, dirs)
if err != nil {
return err
}
return os.RemoveAll(u.BaseDir)
}
// joinSandboxNetns joins the network namespace of the sandbox
// This function should be called only from a locked thread
// (i.e. runtime. LockOSThread())
func (u Unikontainer) joinSandboxNetNs() error {
netNsPath, err := findNS(u.Spec.Linux.Namespaces, specs.NetworkNamespace)
if err != nil && !errors.Is(err, ErrNotExistingNS) {
return err
}
// In case no path was specified for the network namespace it means,
// that we had to create a new one and therefore we can join it by
// using the pid of the monitor process.
if netNsPath == "" {
netNsPath = fmt.Sprintf("/proc/%d/ns/net", u.State.Pid)
err := checkValidNsPath(netNsPath)
if err != nil {
return err
}
}
uniklog.WithFields(logrus.Fields{
"path": netNsPath,
}).Debug("Joining network namespace")
fd, err := unix.Open(netNsPath, unix.O_RDONLY|unix.O_CLOEXEC, 0)
if err != nil {
return fmt.Errorf("error opening namespace path: %w", err)
}
err = unix.Setns(int(fd), unix.CLONE_NEWNET)
if err != nil {
return fmt.Errorf("error joining namespace: %w", err)
}
uniklog.Debug("Joined network namespace")
return nil
}
// Saves current Unikernel state as baseDir/state.json for later use
func (u *Unikontainer) saveContainerState() error {
// Propagate all annotations from spec to state to solve nerdctl hooks errors.
// For more info: https://github.com/containerd/nerdctl/issues/133
for key, value := range u.Spec.Annotations {
if _, ok := u.State.Annotations[key]; !ok {
u.State.Annotations[key] = value
}
}
data, err := json.Marshal(u.State)
if err != nil {
return err
}
stateName := filepath.Join(u.BaseDir, stateFilename)
return os.WriteFile(stateName, data, 0o644) //nolint: gosec
}
// getHooksByName returns the hooks for a given lifecycle stage
func (u *Unikontainer) getHooksByName(name string) []specs.Hook {
switch name {
case "CreateRuntime":
return u.Spec.Hooks.CreateRuntime
case "CreateContainer":
return u.Spec.Hooks.CreateContainer
case "StartContainer":
return u.Spec.Hooks.StartContainer
case "Poststart":
return u.Spec.Hooks.Poststart
case "Poststop":
return u.Spec.Hooks.Poststop
default:
uniklog.Warnf("Unsupported hook %s", name)
return nil
}
}
func (u *Unikontainer) ExecuteHooks(name string) error {
if u.Spec.Hooks == nil {
return nil
}
hooks := u.getHooksByName(name)
uniklog.Debugf("Executing %d %s hooks", len(hooks), name)
s, err := json.Marshal(u.State)
if err != nil {
return err
}
// NOTE: This wrapper function provides an easy way to toggle between
// the sequential and concurrent hook execution.
// By default the hooks are executed concurrently.
// To execute hooks sequentially, change the following line to:
// if false
if true {
return u.executeHooksConcurrently(name, hooks, s)
}
return u.executeHooksSequentially(name, hooks, s)
}
// executeHooksConcurrently executes concurrently any hooks found in spec based on name:
// NOTE: It is possible that the concurrent execution of the hooks may cause
// some unknown problems down the line. Be sure to prioritize checking
// with sequential hook execution when debugging.
func (u *Unikontainer) executeHooksConcurrently(name string, hooks []specs.Hook, s []byte) error {
var (
wg sync.WaitGroup
errChan = make(chan error, len(hooks))
firstErr error
)
for i := range hooks {
uniklog.WithFields(logrus.Fields{
"id": u.State.ID,
"name": name,
"path": hooks[i].Path,
"args": hooks[i].Args,
}).Debug("Executing hook")
wg.Add(1)
go func(h specs.Hook) {
defer wg.Done()
err := executeHook(h, s)
if err != nil {
uniklog.WithFields(logrus.Fields{
"id": u.State.ID,
"name": name,
"path": h.Path,
"args": h.Args,
"error": err,
}).Error("Executing hook failed")
errChan <- err
}
}(hooks[i])
}
go func() {
wg.Wait()
close(errChan)
}()
for err := range errChan {
uniklog.WithField("error", err.Error()).Error("failed to execute hook")
if firstErr == nil {
firstErr = err
}
}
return firstErr
}
// executeHooksSequentially executes sequentially any hooks found in spec based on name:
// NOTE: This function is left on purpose to aid future debugging efforts
// in case concurrent hook execution causes unexpected errors.
func (u *Unikontainer) executeHooksSequentially(name string, hooks []specs.Hook, s []byte) error {
for i := range hooks {
uniklog.WithFields(logrus.Fields{
"id": u.State.ID,
"name": name,
"path": hooks[i].Path,
"args": hooks[i].Args,
}).Debug("Executing hook")
err := executeHook(hooks[i], s)
if err != nil {
uniklog.WithFields(logrus.Fields{
"id": u.State.ID,
"name": name,
"path": hooks[i].Path,
"args": hooks[i].Args,
"error": err,
}).Error("Executing hook failed")
return fmt.Errorf("failed to execute %s hook: %w", name, err)
}
}
return nil
}
// loadUnikontainerState returns a specs.State object containing the info
// found in stateFilePath
func loadUnikontainerState(stateFilePath string) (*specs.State, error) {
var state specs.State
data, err := os.ReadFile(stateFilePath)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &state)
if err != nil {
return nil, err
}
return &state, nil
}
// nolint:gocyclo
// FormatNsenterInfo encodes namespace info in netlink binary format
// as a io.Reader, in order to send the info to nsenter.
// The implementation is inspired from:
// https://github.com/opencontainers/runc/blob/c8737446d2f99c1b7f2fcf374a7ee5b4519b2051/libcontainer/container_linux.go#L1047
func (u *Unikontainer) FormatNsenterInfo() (rdr io.Reader, retErr error) {
r := nl.NewNetlinkRequest(int(initMsg), 0)
// Our custom messages cannot bubble up an error using returns, instead