forked from kata-containers/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
1826 lines (1502 loc) · 51.5 KB
/
grpc.go
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) 2017-2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
gpb "github.com/gogo/protobuf/types"
"github.com/kata-containers/agent/pkg/types"
pb "github.com/kata-containers/agent/protocols/grpc"
"github.com/opencontainers/runc/libcontainer"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runc/libcontainer/seccomp"
"github.com/opencontainers/runc/libcontainer/specconv"
"github.com/opencontainers/runc/libcontainer/utils"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
"golang.org/x/sys/unix"
"google.golang.org/grpc/codes"
grpcStatus "google.golang.org/grpc/status"
)
type agentGRPC struct {
sandbox *sandbox
version string
}
// CPU and Memory hotplug
const (
cpuRegexpPattern = "cpu[0-9]*"
memRegexpPattern = "memory[0-9]*"
libcontainerPath = "/run/libcontainer"
)
var (
sysfsCPUOnlinePath = "/sys/devices/system/cpu"
sysfsMemOnlinePath = "/sys/devices/system/memory"
sysfsMemoryBlockSizePath = "/sys/devices/system/memory/block_size_bytes"
sysfsMemoryHotplugProbePath = "/sys/devices/system/memory/probe"
sysfsAcpiMemoryHotplugPath = "/sys/firmware/acpi/hotplug/memory/enabled"
sysfsConnectedCPUsPath = filepath.Join(sysfsCPUOnlinePath, "online")
containersRootfsPath = "/run"
// set when StartTracing() is called.
startTracingCalled = false
// set when StopTracing() is called.
stopTracingCalled = false
modprobePath = "/sbin/modprobe"
)
type onlineResource struct {
sysfsOnlinePath string
regexpPattern string
}
type cookie map[string]bool
var emptyResp = &gpb.Empty{}
const onlineCPUMemWaitTime = 100 * time.Millisecond
var onlineCPUMaxTries = uint32(100)
const cpusetMode = 0644
// handleError will log the specified error if wait is false
func handleError(wait bool, err error) error {
if !wait {
agentLog.WithError(err).Error()
}
return err
}
// Online resources, nbResources specifies the maximum number of resources to online.
// If nbResources is <= 0 then there is no limit and all resources are connected.
// Returns the number of resources connected.
func onlineResources(resource onlineResource, nbResources int32) (uint32, error) {
files, err := ioutil.ReadDir(resource.sysfsOnlinePath)
if err != nil {
return 0, err
}
var count uint32
for _, file := range files {
matched, err := regexp.MatchString(resource.regexpPattern, file.Name())
if err != nil {
return count, err
}
if !matched {
continue
}
onlinePath := filepath.Join(resource.sysfsOnlinePath, file.Name(), "online")
status, err := ioutil.ReadFile(onlinePath)
if err != nil {
// resource cold plugged
continue
}
if strings.Trim(string(status), "\n\t ") == "0" {
if err := ioutil.WriteFile(onlinePath, []byte("1"), 0600); err != nil {
agentLog.WithField("online-path", onlinePath).WithError(err).Errorf("Could not online resource")
continue
}
count++
if nbResources > 0 && count == uint32(nbResources) {
return count, nil
}
}
}
return count, nil
}
func onlineCPUResources(nbCpus uint32) error {
resource := onlineResource{
sysfsOnlinePath: sysfsCPUOnlinePath,
regexpPattern: cpuRegexpPattern,
}
var count uint32
for i := uint32(0); i < onlineCPUMaxTries; i++ {
r, err := onlineResources(resource, int32(nbCpus-count))
if err != nil {
return err
}
count += r
if count == nbCpus {
return nil
}
time.Sleep(onlineCPUMemWaitTime)
}
return fmt.Errorf("only %d of %d were connected", count, nbCpus)
}
func onlineMemResources() error {
resource := onlineResource{
sysfsOnlinePath: sysfsMemOnlinePath,
regexpPattern: memRegexpPattern,
}
_, err := onlineResources(resource, -1)
return err
}
// updates a cpuset cgroups path visiting each sub-directory in cgroupPath parent and writing
// the maximal set of cpus in cpuset.cpus file, finally the cgroupPath is updated with the requsted
//value.
// cookies are used for performance reasons in order to
// don't update a cgroup twice.
func updateCpusetPath(cgroupPath string, newCpuset string, cookies cookie) error {
// Each cpuset cgroup parent MUST BE updated with the actual number of vCPUs.
//Start to update from cgroup system root.
cgroupParentPath := cgroupCpusetPath
cpusetGuest, err := getCpusetGuest()
if err != nil {
return err
}
// Update parents with max set of current cpus
//Iterate all parent dirs in order.
//This is needed to ensure the cgroup parent has cpus on needed needed
//by the request.
cgroupsParentPaths := strings.Split(filepath.Dir(cgroupPath), "/")
for _, path := range cgroupsParentPaths {
// Skip if empty.
if path == "" {
continue
}
cgroupParentPath = filepath.Join(cgroupParentPath, path)
// check if the cgroup was already updated.
if cookies[cgroupParentPath] {
agentLog.WithField("path", cgroupParentPath).Debug("cpuset cgroup already updated")
continue
}
cpusetCpusParentPath := filepath.Join(cgroupParentPath, "cpuset.cpus")
agentLog.WithField("path", cpusetCpusParentPath).Debug("updating cpuset parent cgroup")
if err := ioutil.WriteFile(cpusetCpusParentPath, []byte(cpusetGuest), cpusetMode); err != nil {
return fmt.Errorf("Could not update parent cpuset cgroup (%s) cpuset:'%s': %v", cpusetCpusParentPath, cpusetGuest, err)
}
// add cgroup path to the cookies.
cookies[cgroupParentPath] = true
}
// Finally update group path with requested value.
cpusetCpusPath := filepath.Join(cgroupCpusetPath, cgroupPath, "cpuset.cpus")
agentLog.WithField("path", cpusetCpusPath).Debug("updating cpuset cgroup")
if err := ioutil.WriteFile(cpusetCpusPath, []byte(newCpuset), cpusetMode); err != nil {
return fmt.Errorf("Could not update parent cpuset cgroup (%s) cpuset:'%s': %v", cpusetCpusPath, cpusetGuest, err)
}
return nil
}
func (a *agentGRPC) onlineCPUMem(req *pb.OnlineCPUMemRequest) error {
if req.NbCpus == 0 && req.CpuOnly {
return handleError(req.Wait, fmt.Errorf("requested number of CPUs '%d' must be greater than 0", req.NbCpus))
}
// we are going to update the containers of the sandbox, we have to lock it
a.sandbox.Lock()
defer a.sandbox.Unlock()
if req.NbCpus > 0 {
agentLog.WithField("vcpus-to-connect", req.NbCpus).Debug("connecting vCPUs")
if err := onlineCPUResources(req.NbCpus); err != nil {
return handleError(req.Wait, err)
}
}
if !req.CpuOnly {
if err := onlineMemResources(); err != nil {
return handleError(req.Wait, err)
}
}
// At this point all CPUs have been connected, we need to know
// the actual range of CPUs
connectedCpus, err := getCpusetGuest()
if err != nil {
return handleError(req.Wait, fmt.Errorf("Could not get the actual range of connected CPUs: %v", err))
}
agentLog.WithField("range-of-vcpus", connectedCpus).Debug("connecting vCPUs")
cookies := make(cookie)
// Now that we know the actual range of connected CPUs, we need to iterate over
// all containers an update each cpuset cgroup. This is not required in docker
// containers since they don't hot add/remove CPUs.
for _, c := range a.sandbox.containers {
agentLog.WithField("container", c.container.ID()).Debug("updating cpuset cgroup")
contConfig := c.container.Config()
cgroupPath := contConfig.Cgroups.Path
// In order to avoid issues updating the container cpuset cgroup, its cpuset cgroup *parents*
// MUST BE updated, otherwise we'll get next errors:
// - write /sys/fs/cgroup/cpuset/XXXXX/cpuset.cpus: permission denied
// - write /sys/fs/cgroup/cpuset/XXXXX/cpuset.cpus: device or resource busy
// NOTE: updating container cpuset cgroup *parents* won't affect container cpuset cgroup, for example if container cpuset cgroup has "0"
// and its cpuset cgroup *parents* have "0-5", the container will be able to use only the CPU 0.
// cpuset assinged containers are not updated, only we update its parents.
if contConfig.Cgroups.Resources.CpusetCpus != "" {
agentLog.WithField("cpuset", contConfig.Cgroups.Resources.CpusetCpus).Debug("updating container cpuset cgroup parents")
// remove container cgroup directory
cgroupPath = filepath.Dir(cgroupPath)
}
if err := updateCpusetPath(cgroupPath, connectedCpus, cookies); err != nil {
return handleError(req.Wait, err)
}
}
return nil
}
func setConsoleCarriageReturn(fd int) error {
termios, err := unix.IoctlGetTermios(fd, unix.TCGETS)
if err != nil {
return err
}
termios.Oflag |= unix.ONLCR
return unix.IoctlSetTermios(fd, unix.TCSETS, termios)
}
func buildProcess(agentProcess *pb.Process, procID string, init bool) (*process, error) {
user := agentProcess.User.Username
if user == "" {
// We can specify the user and the group separated by ":"
user = fmt.Sprintf("%d:%d", agentProcess.User.UID, agentProcess.User.GID)
}
additionalGids := []string{}
for _, gid := range agentProcess.User.AdditionalGids {
additionalGids = append(additionalGids, fmt.Sprintf("%d", gid))
}
proc := &process{
id: procID,
process: libcontainer.Process{
Cwd: agentProcess.Cwd,
Args: agentProcess.Args,
Env: agentProcess.Env,
User: user,
AdditionalGroups: additionalGids,
Init: init,
},
}
if agentProcess.Terminal {
parentSock, childSock, err := utils.NewSockPair("console")
if err != nil {
return nil, err
}
proc.process.ConsoleSocket = childSock
proc.consoleSock = parentSock
epoller, err := newEpoller()
if err != nil {
return nil, err
}
proc.epoller = epoller
return proc, nil
}
rStdin, wStdin, err := os.Pipe()
if err != nil {
return nil, err
}
rStdout, wStdout, err := createExtendedPipe()
if err != nil {
return nil, err
}
rStderr, wStderr, err := createExtendedPipe()
if err != nil {
return nil, err
}
proc.process.Stdin = rStdin
proc.process.Stdout = wStdout
proc.process.Stderr = wStderr
proc.stdin = wStdin
proc.stdout = rStdout
proc.stderr = rStderr
return proc, nil
}
func (a *agentGRPC) Check(ctx context.Context, req *pb.CheckRequest) (*pb.HealthCheckResponse, error) {
return &pb.HealthCheckResponse{Status: pb.HealthCheckResponse_SERVING}, nil
}
func (a *agentGRPC) Version(ctx context.Context, req *pb.CheckRequest) (*pb.VersionCheckResponse, error) {
return &pb.VersionCheckResponse{
GrpcVersion: pb.APIVersion,
AgentVersion: a.version,
}, nil
}
func (a *agentGRPC) getContainer(cid string) (*container, error) {
if !a.sandbox.running {
return nil, grpcStatus.Error(codes.FailedPrecondition, "Sandbox not started")
}
ctr, err := a.sandbox.getContainer(cid)
if err != nil {
return nil, err
}
return ctr, nil
}
// Shared function between CreateContainer and ExecProcess, because those expect
// a process to be run.
func (a *agentGRPC) execProcess(ctr *container, proc *process, createContainer bool) (err error) {
if ctr == nil {
return grpcStatus.Error(codes.InvalidArgument, "Container cannot be nil")
}
if proc == nil {
return grpcStatus.Error(codes.InvalidArgument, "Process cannot be nil")
}
// This lock is very important to avoid any race with reaper.reap().
// Indeed, if we don't lock this here, we could potentially get the
// SIGCHLD signal before the channel has been created, meaning we will
// miss the opportunity to get the exit code, leading WaitProcess() to
// wait forever on the new channel.
// This lock has to be taken before we run the new process.
a.sandbox.subreaper.lock()
defer a.sandbox.subreaper.unlock()
if createContainer {
err = ctr.container.Start(&proc.process)
} else {
err = ctr.container.Run(&(proc.process))
}
if err != nil {
return grpcStatus.Errorf(codes.Internal, "Could not run process: %v", err)
}
// Get process PID
pid, err := proc.process.Pid()
if err != nil {
return err
}
proc.exitCodeCh = make(chan int, 1)
// Create process channel to allow WaitProcess to wait on it.
// This channel is buffered so that reaper.reap() will not
// block until WaitProcess listen onto this channel.
a.sandbox.subreaper.setExitCodeCh(pid, proc.exitCodeCh)
return nil
}
// Shared function between CreateContainer and ExecProcess, because those expect
// the console to be properly setup after the process has been started.
func (a *agentGRPC) postExecProcess(ctr *container, proc *process) error {
if ctr == nil {
return grpcStatus.Error(codes.InvalidArgument, "Container cannot be nil")
}
if proc == nil {
return grpcStatus.Error(codes.InvalidArgument, "Process cannot be nil")
}
defer proc.closePostStartFDs()
// Setup terminal if enabled.
if proc.consoleSock != nil {
termMaster, err := utils.RecvFd(proc.consoleSock)
if err != nil {
return err
}
if err := setConsoleCarriageReturn(int(termMaster.Fd())); err != nil {
return err
}
proc.termMaster = termMaster
// Get process PID
pid, err := proc.process.Pid()
if err != nil {
return err
}
a.sandbox.subreaper.setEpoller(pid, proc.epoller)
if err = proc.epoller.add(proc.termMaster); err != nil {
return err
}
}
ctr.setProcess(proc)
return nil
}
// This function updates the container namespaces configuration based on the
// sandbox information. When the sandbox is created, it can be setup in a way
// that all containers will share some specific namespaces. This is the agent
// responsibility to create those namespaces so that they can be shared across
// several containers.
// If the sandbox has not been setup to share namespaces, then we assume all
// containers will be started in their own new namespace.
// The value of a.sandbox.sharedPidNs.path will always override the namespace
// path set by the spec, since we will always ignore it. Indeed, it makes no
// sense to rely on the namespace path provided by the host since namespaces
// are different inside the guest.
func (a *agentGRPC) updateContainerConfigNamespaces(config *configs.Config, ctr *container) {
var ipcNs, utsNs bool
for idx, ns := range config.Namespaces {
if ns.Type == configs.NEWIPC {
config.Namespaces[idx].Path = a.sandbox.sharedIPCNs.path
ipcNs = true
}
if ns.Type == configs.NEWUTS {
config.Namespaces[idx].Path = a.sandbox.sharedUTSNs.path
utsNs = true
}
}
if !ipcNs {
newIPCNs := configs.Namespace{
Type: configs.NEWIPC,
Path: a.sandbox.sharedIPCNs.path,
}
config.Namespaces = append(config.Namespaces, newIPCNs)
}
if !utsNs {
newUTSNs := configs.Namespace{
Type: configs.NEWUTS,
Path: a.sandbox.sharedUTSNs.path,
}
config.Namespaces = append(config.Namespaces, newUTSNs)
}
// Update PID namespace.
var pidNsPath string
// Use shared pid ns if useSandboxPidns has been set in either
// the CreateSandbox request or CreateContainer request.
// Else set this to empty string so that a new pid namespace is
// created for the container.
if ctr.useSandboxPidNs || a.sandbox.sandboxPidNs {
pidNsPath = a.sandbox.sharedPidNs.path
} else {
pidNsPath = ""
}
newPidNs := configs.Namespace{
Type: configs.NEWPID,
Path: pidNsPath,
}
config.Namespaces = append(config.Namespaces, newPidNs)
}
func (a *agentGRPC) updateContainerConfigPrivileges(spec *specs.Spec, config *configs.Config) error {
if spec == nil || spec.Process == nil {
// Don't throw an error in case the Spec does not contain any
// information about NoNewPrivileges.
return nil
}
// Add the value for NoNewPrivileges option.
config.NoNewPrivileges = spec.Process.NoNewPrivileges
return nil
}
func (a *agentGRPC) updateContainerConfig(spec *specs.Spec, config *configs.Config, ctr *container) error {
a.updateContainerConfigNamespaces(config, ctr)
return a.updateContainerConfigPrivileges(spec, config)
}
// rollbackFailingContainerCreation rolls back important steps that might have
// been performed before the container creation failed.
// - Destroy the container created by libcontainer
// - Delete the container from the agent internal map
// - Unmount all mounts related to this container
func (a *agentGRPC) rollbackFailingContainerCreation(ctr *container) {
if ctr.container != nil {
ctr.container.Destroy()
}
a.sandbox.deleteContainer(ctr.id)
if err := removeMounts(ctr.mounts); err != nil {
agentLog.WithError(err).Error("rollback failed removeMounts()")
}
}
func (a *agentGRPC) finishCreateContainer(ctr *container, req *pb.CreateContainerRequest, config *configs.Config) (resp *gpb.Empty, err error) {
containerPath := filepath.Join(libcontainerPath, a.sandbox.id)
factory, err := libcontainer.New(containerPath, libcontainer.Cgroupfs)
if err != nil {
return emptyResp, err
}
ctr.container, err = factory.Create(req.ContainerId, config)
if err != nil {
return emptyResp, err
}
ctr.config = *config
ctr.initProcess, err = buildProcess(req.OCI.Process, req.ExecId, true)
if err != nil {
return emptyResp, err
}
if err = a.execProcess(ctr, ctr.initProcess, true); err != nil {
return emptyResp, err
}
// Make sure add Container to Sandbox, before call updateSharedPidNs
a.sandbox.setContainer(ctr.ctx, req.ContainerId, ctr)
if err := a.updateSharedPidNs(ctr); err != nil {
return emptyResp, err
}
return emptyResp, a.postExecProcess(ctr, ctr.initProcess)
}
func (a *agentGRPC) CreateContainer(ctx context.Context, req *pb.CreateContainerRequest) (resp *gpb.Empty, err error) {
if err := a.createContainerChecks(req); err != nil {
return emptyResp, err
}
// re-scan PCI bus
// looking for hidden devices
if err = rescanPciBus(); err != nil {
agentLog.WithError(err).Warn("Could not rescan PCI bus")
}
// Some devices need some extra processing (the ones invoked with
// --device for instance), and that's what this call is doing. It
// updates the devices listed in the OCI spec, so that they actually
// match real devices inside the VM. This step is necessary since we
// cannot predict everything from the caller.
if err = addDevices(ctx, req.Devices, req.OCI, a.sandbox); err != nil {
return emptyResp, err
}
// Both rootfs and volumes (invoked with --volume for instance) will
// be processed the same way. The idea is to always mount any provided
// storage to the specified MountPoint, so that it will match what's
// inside oci.Mounts.
// After all those storages have been processed, no matter the order
// here, the agent will rely on libcontainer (using the oci.Mounts
// list) to bind mount all of them inside the container.
mountList, err := addStorages(ctx, req.Storages, a.sandbox)
if err != nil {
return emptyResp, err
}
ctr := &container{
id: req.ContainerId,
processes: make(map[string]*process),
mounts: mountList,
useSandboxPidNs: req.SandboxPidns,
ctx: ctx,
}
// In case the container creation failed, make sure we cleanup
// properly by rolling back the actions previously performed.
defer func() {
if err != nil {
a.rollbackFailingContainerCreation(ctr)
}
}()
// Convert the spec to an actual OCI specification structure.
ociSpec, err := pb.GRPCtoOCI(req.OCI)
if err != nil {
return emptyResp, err
}
if err := a.handleCPUSet(ociSpec); err != nil {
return emptyResp, err
}
if err := a.applyNetworkSysctls(ociSpec); err != nil {
return emptyResp, err
}
if a.sandbox.guestHooksPresent {
// Add any custom OCI hooks to the spec
a.sandbox.addGuestHooks(ociSpec)
// write the OCI spec to a file so that hooks can read it
err = writeSpecToFile(ociSpec)
if err != nil {
return emptyResp, err
}
// Change cwd because libcontainer assumes the bundle path is the cwd:
// https://github.com/opencontainers/runc/blob/v1.0.0-rc5/libcontainer/specconv/spec_linux.go#L157
oldcwd, err := changeToBundlePath(ociSpec)
if err != nil {
return emptyResp, err
}
defer os.Chdir(oldcwd)
}
// Convert the OCI specification into a libcontainer configuration.
config, err := specconv.CreateLibcontainerConfig(&specconv.CreateOpts{
CgroupName: req.ContainerId,
NoNewKeyring: true,
Spec: ociSpec,
NoPivotRoot: a.sandbox.noPivotRoot,
})
if err != nil {
return emptyResp, err
}
// apply rlimits
config.Rlimits = posixRlimitsToRlimits(ociSpec.Process.Rlimits)
// Update libcontainer configuration for specific cases not handled
// by the specconv converter.
if err = a.updateContainerConfig(ociSpec, config, ctr); err != nil {
return emptyResp, err
}
return a.finishCreateContainer(ctr, req, config)
}
// Path overridden in unit tests
var procSysDir = "/proc/sys"
// writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
// For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
func writeSystemProperty(key, value string) error {
keyPath := strings.Replace(key, ".", "/", -1)
return ioutil.WriteFile(filepath.Join(procSysDir, keyPath), []byte(value), 0644)
}
func isNetworkSysctl(sysctl string) bool {
return strings.HasPrefix(sysctl, "net.")
}
// libcontainer checks if the container is running in a separate network namespace
// before applying the network related sysctls. If it sees that the network namespace of the container
// is the same as the "host", it errors out. Since we do no create a new net namespace inside the guest,
// libcontainer would error out while verifying network sysctls. To overcome this, we dont pass
// network sysctls to libcontainer, we instead have the agent directly apply them. All other namespaced
// sysctls are applied by libcontainer.
func (a *agentGRPC) applyNetworkSysctls(ociSpec *specs.Spec) error {
sysctls := ociSpec.Linux.Sysctl
for key, value := range sysctls {
if isNetworkSysctl(key) {
if err := writeSystemProperty(key, value); err != nil {
return err
}
delete(sysctls, key)
}
}
ociSpec.Linux.Sysctl = sysctls
return nil
}
func (a *agentGRPC) handleCPUSet(ociSpec *specs.Spec) error {
if ociSpec.Linux.Resources.CPU != nil && ociSpec.Linux.Resources.CPU.Cpus != "" {
availableCpuset, err := getAvailableCpusetList(ociSpec.Linux.Resources.CPU.Cpus)
if err != nil {
return err
}
ociSpec.Linux.Resources.CPU.Cpus = availableCpuset
}
return nil
}
func posixRlimitsToRlimits(posixRlimits []specs.POSIXRlimit) []configs.Rlimit {
var rlimits []configs.Rlimit
rlimitsMap := map[string]int{
"RLIMIT_CPU": unix.RLIMIT_CPU, // 0x0
"RLIMIT_FSIZE": unix.RLIMIT_FSIZE, // 0x1
"RLIMIT_DATA": unix.RLIMIT_DATA, // 0x2
"RLIMIT_STACK": unix.RLIMIT_STACK, // 0x3
"RLIMIT_CORE": unix.RLIMIT_CORE, // 0x4
"RLIMIT_RSS": unix.RLIMIT_RSS, // 0x5
"RLIMIT_NPROC": unix.RLIMIT_NPROC, // 0x6
"RLIMIT_NOFILE": unix.RLIMIT_NOFILE, // 0x7
"RLIMIT_MEMLOCK": unix.RLIMIT_MEMLOCK, // 0x8
"RLIMIT_AS": unix.RLIMIT_AS, // 0x9
"RLIMIT_LOCKS": unix.RLIMIT_LOCKS, // 0xa
"RLIMIT_SIGPENDING": unix.RLIMIT_SIGPENDING, // 0xb
"RLIMIT_MSGQUEUE": unix.RLIMIT_MSGQUEUE, // 0xc
"RLIMIT_NICE": unix.RLIMIT_NICE, // 0xd
"RLIMIT_RTPRIO": unix.RLIMIT_RTPRIO, // 0xe
"RLIMIT_RTTIME": unix.RLIMIT_RTTIME, // 0xf
}
for _, l := range posixRlimits {
limit, ok := rlimitsMap[l.Type]
if !ok {
agentLog.WithField("rlimit", l.Type).Warnf("Unknown rlimit")
continue
}
rl := configs.Rlimit{
Type: limit,
Hard: l.Hard,
Soft: l.Soft,
}
rlimits = append(rlimits, rl)
}
return rlimits
}
func (a *agentGRPC) createContainerChecks(req *pb.CreateContainerRequest) (err error) {
if !a.sandbox.running {
return grpcStatus.Error(codes.FailedPrecondition, "Sandbox not started, impossible to run a new container")
}
if _, err = a.sandbox.getContainer(req.ContainerId); err == nil {
return grpcStatus.Errorf(codes.AlreadyExists, "Container %s already exists, impossible to create", req.ContainerId)
}
if a.pidNsExists(req.OCI) {
return grpcStatus.Errorf(codes.FailedPrecondition, "Unexpected PID namespace received for container %s, should have been cleared out", req.ContainerId)
}
return nil
}
func (a *agentGRPC) pidNsExists(grpcSpec *pb.Spec) bool {
if grpcSpec.Linux != nil {
for _, n := range grpcSpec.Linux.Namespaces {
if n.Type == string(configs.NEWPID) {
return true
}
}
}
return false
}
func (a *agentGRPC) updateSharedPidNs(ctr *container) error {
// Populate the shared pid path only if this is an infra container and
// SandboxPidns has not been passed in the CreateSandbox request.
// This means a separate pause process has not been created. We treat the
// first container created as the infra container in that case
// and use its pid namespace in case pid namespace needs to be shared.
if !a.sandbox.sandboxPidNs && len(a.sandbox.containers) == 1 {
pid, err := ctr.initProcess.process.Pid()
if err != nil {
return err
}
a.sandbox.sharedPidNs.path = fmt.Sprintf("/proc/%d/ns/pid", pid)
}
return nil
}
func (a *agentGRPC) StartContainer(ctx context.Context, req *pb.StartContainerRequest) (*gpb.Empty, error) {
ctr, err := a.getContainer(req.ContainerId)
if err != nil {
return emptyResp, err
}
status, err := ctr.container.Status()
if err != nil {
return nil, err
}
if status != libcontainer.Created {
return nil, grpcStatus.Errorf(codes.FailedPrecondition, "Container %s status %s, should be %s", req.ContainerId, status.String(), libcontainer.Created.String())
}
if err := ctr.container.Exec(); err != nil {
return emptyResp, err
}
// Add the container to the OOM event monitor
oomCh, err := ctr.container.NotifyOOM()
if err != nil {
return emptyResp, err
}
a.sandbox.runOOMEventMonitor(oomCh, req.ContainerId)
return emptyResp, nil
}
func (a *agentGRPC) ExecProcess(ctx context.Context, req *pb.ExecProcessRequest) (*gpb.Empty, error) {
ctr, err := a.getContainer(req.ContainerId)
if err != nil {
return emptyResp, err
}
status, err := ctr.container.Status()
if err != nil {
return nil, err
}
if status == libcontainer.Stopped {
return nil, grpcStatus.Errorf(codes.FailedPrecondition, "Cannot exec in stopped container %s", req.ContainerId)
}
proc, err := buildProcess(req.Process, req.ExecId, false)
if err != nil {
return emptyResp, err
}
if err := a.execProcess(ctr, proc, false); err != nil {
return emptyResp, err
}
return emptyResp, a.postExecProcess(ctr, proc)
}
func (a *agentGRPC) SignalProcess(ctx context.Context, req *pb.SignalProcessRequest) (*gpb.Empty, error) {
if !a.sandbox.running {
return emptyResp, grpcStatus.Error(codes.FailedPrecondition, "Sandbox not started, impossible to signal the container")
}
ctr, err := a.sandbox.getContainer(req.ContainerId)
if err != nil {
return emptyResp, grpcStatus.Errorf(codes.FailedPrecondition, "Could not signal process %s: %v", req.ExecId, err)
}
status, err := ctr.container.Status()
if err != nil {
return emptyResp, err
}
signal := syscall.Signal(req.Signal)
if status == libcontainer.Stopped {
agentLog.WithFields(logrus.Fields{
"containerID": req.ContainerId,
"signal": signal.String(),
}).Info("discarding signal as container stopped")
return emptyResp, nil
}
// If the exec ID provided is empty, let's apply the signal to all
// processes inside the container.
// If the process is the container process, let's use the container
// API for that.
// Frozen processes are thawed when `all` is true, allowing them to receive and process signals.
if req.ExecId == "" || status == libcontainer.Paused {
return emptyResp, ctr.container.Signal(signal, true)
} else if ctr.initProcess.id == req.ExecId {
pid, err := ctr.initProcess.process.Pid()
if err != nil {
return emptyResp, err
}
// For container initProcess, if it hasn't installed handler for "SIGTERM" signal,
// it will ignore the "SIGTERM" signal sent to it, thus send it "SIGKILL" signal
// instead of "SIGTERM" to terminate it.
if signal == syscall.SIGTERM && !isSignalHandled(pid, syscall.SIGTERM) {
signal = syscall.SIGKILL
}
return emptyResp, ctr.container.Signal(signal, false)
}
proc, err := ctr.getProcess(req.ExecId)
if err != nil {
return emptyResp, grpcStatus.Errorf(grpcStatus.Convert(err).Code(), "Could not signal process: %v", err)
}
if err := proc.process.Signal(signal); err != nil {
return emptyResp, err
}
return emptyResp, nil
}
// Check is the container process installed the
// handler for specific signal.
func isSignalHandled(pid int, signum syscall.Signal) bool {
var sigMask uint64 = 1 << (uint(signum) - 1)
procFile := fmt.Sprintf("/proc/%d/status", pid)
file, err := os.Open(procFile)
if err != nil {
agentLog.WithField("procFile", procFile).Warn("Open proc file failed")
return false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "SigCgt:") {
maskSlice := strings.Split(line, ":")
if len(maskSlice) != 2 {
agentLog.WithField("procFile", procFile).Warn("Parse the SigCgt field failed")
return false
}
sigCgtStr := strings.TrimSpace(maskSlice[1])
sigCgtMask, err := strconv.ParseUint(sigCgtStr, 16, 64)
if err != nil {
agentLog.WithField("sigCgt", sigCgtStr).Warn("parse the SigCgt to hex failed")
return false
}
return (sigCgtMask & sigMask) == sigMask
}
}
return false
}
func (a *agentGRPC) WaitProcess(ctx context.Context, req *pb.WaitProcessRequest) (*pb.WaitProcessResponse, error) {
proc, ctr, err := a.sandbox.getProcess(req.ContainerId, req.ExecId)
if err != nil {
return &pb.WaitProcessResponse{}, err
}
defer proc.Do(func() {
proc.closePostExitFDs()
ctr.deleteProcess(proc.id)