forked from kata-containers/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.go
1560 lines (1276 loc) · 38 KB
/
agent.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"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/gogo/protobuf/proto"
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
"github.com/kata-containers/agent/pkg/uevent"
pb "github.com/kata-containers/agent/protocols/grpc"
"github.com/mdlayher/vsock"
"github.com/opencontainers/runc/libcontainer"
"github.com/opencontainers/runc/libcontainer/configs"
_ "github.com/opencontainers/runc/libcontainer/nsenter"
"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"
"google.golang.org/grpc/codes"
grpcStatus "google.golang.org/grpc/status"
)
const (
procCgroups = "/proc/cgroups"
bashPath = "/bin/bash"
shPath = "/bin/sh"
debugConsolePath = "/dev/console"
)
var (
// List of shells that are tried (in order) to setup a debug console
supportedShells = []string{bashPath, shPath}
meminfo = "/proc/meminfo"
// cgroup fs is mounted at /sys/fs when systemd is the init process
sysfsDir = "/sys"
cgroupPath = sysfsDir + "/fs/cgroup"
cgroupCpusetPath = cgroupPath + "/cpuset"
cgroupMemoryPath = cgroupPath + "/memory"
cgroupMemoryUseHierarchyPath = cgroupMemoryPath + "/memory.use_hierarchy"
cgroupMemoryUseHierarchyMode = os.FileMode(0400)
// Set by the build
seccompSupport string
// Set to the context that should be used for tracing gRPC calls.
grpcContext context.Context
rootContext context.Context
)
var initRootfsMounts = []initMount{
{"proc", "proc", "/proc", []string{"nosuid", "nodev", "noexec"}},
{"sysfs", "sysfs", sysfsDir, []string{"nosuid", "nodev", "noexec"}},
{"devtmpfs", "dev", "/dev", []string{"nosuid"}},
{"tmpfs", "tmpfs", "/dev/shm", []string{"nosuid", "nodev"}},
{"devpts", "devpts", "/dev/pts", []string{"nosuid", "noexec"}},
{"tmpfs", "tmpfs", "/run", []string{"nosuid", "nodev"}},
}
type process struct {
sync.RWMutex
id string
process libcontainer.Process
stdin *os.File
stdout *os.File
stderr *os.File
consoleSock *os.File
termMaster *os.File
epoller *epoller
exitCodeCh chan int
sync.Once
stdinClosed bool
}
type container struct {
sync.RWMutex
id string
initProcess *process
container libcontainer.Container
config configs.Config
processes map[string]*process
mounts []string
useSandboxPidNs bool
ctx context.Context
}
type sandboxStorage struct {
refCount int
}
type sandbox struct {
sync.RWMutex
ctx context.Context
id string
hostname string
containers map[string]*container
channel channel
network network
wg sync.WaitGroup
sharedPidNs namespace
mounts []string
subreaper reaper
server *grpc.Server
pciDeviceMap map[string]string
deviceWatchers map[string](chan string)
sharedUTSNs namespace
sharedIPCNs namespace
guestHooks *specs.Hooks
guestHooksPresent bool
running bool
noPivotRoot bool
enableGrpcTrace bool
sandboxPidNs bool
storages map[string]*sandboxStorage
stopServer chan struct{}
}
var agentFields = logrus.Fields{
"name": agentName,
"pid": os.Getpid(),
"source": "agent",
}
var agentLog = logrus.WithFields(agentFields)
// version is the agent version. This variable is populated at build time.
var version = "unknown"
var debug = false
// tracing enables opentracing support
var tracing = false
// Associate agent traces with runtime traces. This can only be enabled using
// the traceModeFlag.
var collatedTrace = false
// if true, coredump when an internal error occurs or a fatal signal is received
var crashOnError = false
// if true, a shell (bash or sh) is started only if it's available in the rootfs.
var debugConsole = false
// Specify a vsock port where logs are written.
var logsVSockPort = uint32(0)
// Specify a vsock port where debug console is attached.
var debugConsoleVSockPort = uint32(0)
// Timeout waiting for a device to be hotplugged
var hotplugTimeout = 3 * time.Second
// commType is used to denote the communication channel type used.
type commType int
const (
// virtio-serial channel
serialCh commType = iota
// vsock channel
vsockCh
// channel type not passed explicitly
unknownCh
)
var commCh = unknownCh
// This is the list of file descriptors we can properly close after the process
// has been started. When the new process is exec(), those file descriptors are
// duplicated and it is our responsibility to close them since we have opened
// them.
func (p *process) closePostStartFDs() {
if p.process.Stdin != nil {
p.process.Stdin.(*os.File).Close()
}
if p.process.Stdout != nil {
p.process.Stdout.(*os.File).Close()
}
if p.process.Stderr != nil {
p.process.Stderr.(*os.File).Close()
}
if p.process.ConsoleSocket != nil {
p.process.ConsoleSocket.Close()
}
if p.consoleSock != nil {
p.consoleSock.Close()
}
}
// This is the list of file descriptors we can properly close after the process
// has exited. These are the remaining file descriptors that we have opened and
// are no longer needed.
func (p *process) closePostExitFDs() {
if p.termMaster != nil {
p.termMaster.Close()
}
if p.stdin != nil {
p.stdin.Close()
}
if p.stdout != nil {
p.stdout.Close()
}
if p.stderr != nil {
p.stderr.Close()
}
if p.epoller != nil {
p.epoller.sockR.Close()
}
}
func (c *container) trace(name string) (*agentSpan, context.Context) {
if c.ctx == nil {
agentLog.WithField("type", "bug").Error("trace called before context set")
c.ctx = context.Background()
}
return trace(c.ctx, "container", name)
}
func (c *container) setProcess(process *process) {
c.Lock()
c.processes[process.id] = process
c.Unlock()
}
func (c *container) deleteProcess(execID string) {
span, _ := c.trace("deleteProcess")
span.setTag("exec-id", execID)
defer span.finish()
c.Lock()
delete(c.processes, execID)
c.Unlock()
}
func (c *container) removeContainer() error {
span, _ := c.trace("removeContainer")
defer span.finish()
// This will terminates all processes related to this container, and
// destroy the container right after. But this will error in case the
// container in not in the right state.
if err := c.container.Destroy(); err != nil {
return err
}
return removeMounts(c.mounts)
}
func (c *container) getProcess(execID string) (*process, error) {
c.RLock()
defer c.RUnlock()
proc, exist := c.processes[execID]
if !exist {
return nil, grpcStatus.Errorf(codes.NotFound, "Process %s not found (container %s)", execID, c.id)
}
return proc, nil
}
func (s *sandbox) trace(name string) (*agentSpan, context.Context) {
if s.ctx == nil {
agentLog.WithField("type", "bug").Error("trace called before context set")
s.ctx = context.Background()
}
span, ctx := trace(s.ctx, "sandbox", name)
span.setTag("sandbox", s.id)
return span, ctx
}
// setSandboxStorage sets the sandbox level reference
// counter for the sandbox storage.
// This method also returns a boolean to let
// callers know if the storage already existed or not.
// It will return true if storage is new.
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
func (s *sandbox) setSandboxStorage(path string) bool {
if _, ok := s.storages[path]; !ok {
sbs := &sandboxStorage{refCount: 1}
s.storages[path] = sbs
return true
}
sbs := s.storages[path]
sbs.refCount++
return false
}
// scanGuestHooks will search the given guestHookPath
// for any OCI hooks
func (s *sandbox) scanGuestHooks(guestHookPath string) {
span, _ := s.trace("scanGuestHooks")
span.setTag("guest-hook-path", guestHookPath)
defer span.finish()
fieldLogger := agentLog.WithField("oci-hook-path", guestHookPath)
fieldLogger.Info("Scanning guest filesystem for OCI hooks")
s.guestHooks.Prestart = findHooks(guestHookPath, "prestart")
s.guestHooks.Poststart = findHooks(guestHookPath, "poststart")
s.guestHooks.Poststop = findHooks(guestHookPath, "poststop")
if len(s.guestHooks.Prestart) > 0 || len(s.guestHooks.Poststart) > 0 || len(s.guestHooks.Poststop) > 0 {
s.guestHooksPresent = true
} else {
fieldLogger.Warn("Guest hooks were requested but none were found")
}
}
// addGuestHooks will add any guest OCI hooks that were
// found to the OCI spec
func (s *sandbox) addGuestHooks(spec *specs.Spec) {
span, _ := s.trace("addGuestHooks")
defer span.finish()
if spec == nil {
return
}
if spec.Hooks == nil {
spec.Hooks = &specs.Hooks{}
}
spec.Hooks.Prestart = append(spec.Hooks.Prestart, s.guestHooks.Prestart...)
spec.Hooks.Poststart = append(spec.Hooks.Poststart, s.guestHooks.Poststart...)
spec.Hooks.Poststop = append(spec.Hooks.Poststop, s.guestHooks.Poststop...)
}
// unSetSandboxStorage will decrement the sandbox storage
// reference counter. If there aren't any containers using
// that sandbox storage, this method will remove the
// storage reference from the sandbox and return 'true, nil' to
// let the caller know that they can clean up the storage
// related directories by calling removeSandboxStorage
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
func (s *sandbox) unSetSandboxStorage(path string) (bool, error) {
span, _ := s.trace("unSetSandboxStorage")
span.setTag("path", path)
defer span.finish()
if sbs, ok := s.storages[path]; ok {
sbs.refCount--
// If this sandbox storage is not used by any container
// then remove it's reference
if sbs.refCount < 1 {
delete(s.storages, path)
return true, nil
}
return false, nil
}
return false, grpcStatus.Errorf(codes.NotFound, "Sandbox storage with path %s not found", path)
}
// removeSandboxStorage removes the sandbox storage if no
// containers are using that storage.
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
func (s *sandbox) removeSandboxStorage(path string) error {
span, _ := s.trace("removeSandboxStorage")
span.setTag("path", path)
defer span.finish()
err := removeMounts([]string{path})
if err != nil {
return grpcStatus.Errorf(codes.Unknown, "Unable to unmount sandbox storage path %s: %v", path, err)
}
err = os.RemoveAll(path)
if err != nil {
return grpcStatus.Errorf(codes.Unknown, "Unable to delete sandbox storage path %s: %v", path, err)
}
return nil
}
// unsetAndRemoveSandboxStorage unsets the storage from sandbox
// and if there are no containers using this storage it will
// remove it from the sandbox.
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
func (s *sandbox) unsetAndRemoveSandboxStorage(path string) error {
span, _ := s.trace("unsetAndRemoveSandboxStorage")
span.setTag("path", path)
defer span.finish()
removeSbs, err := s.unSetSandboxStorage(path)
if err != nil {
return err
}
if removeSbs {
if err := s.removeSandboxStorage(path); err != nil {
return err
}
}
return nil
}
func (s *sandbox) getContainer(id string) (*container, error) {
s.RLock()
defer s.RUnlock()
ctr, exist := s.containers[id]
if !exist {
return nil, grpcStatus.Errorf(codes.NotFound, "Container %s not found", id)
}
return ctr, nil
}
func (s *sandbox) setContainer(ctx context.Context, id string, ctr *container) {
// Update the context. This is required since the function is called
// from by gRPC functions meaning we must use the latest context
// available.
s.ctx = ctx
span, _ := s.trace("setContainer")
span.setTag("id", id)
span.setTag("container", ctr.id)
defer span.finish()
s.Lock()
s.containers[id] = ctr
s.Unlock()
}
func (s *sandbox) deleteContainer(id string) {
span, _ := s.trace("deleteContainer")
span.setTag("container", id)
defer span.finish()
s.Lock()
// Find the sandbox storage used by this container
ctr, exist := s.containers[id]
if !exist {
agentLog.WithField("container-id", id).Debug("Container doesn't exist")
} else {
// Let's go over the mounts used by this container
for _, k := range ctr.mounts {
// Check if this mount is used from sandbox storage
if _, ok := s.storages[k]; ok {
if err := s.unsetAndRemoveSandboxStorage(k); err != nil {
agentLog.WithError(err).Error()
}
}
}
}
delete(s.containers, id)
s.Unlock()
}
func (s *sandbox) getProcess(cid, execID string) (*process, *container, error) {
if !s.running {
return nil, nil, grpcStatus.Error(codes.FailedPrecondition, "Sandbox not started")
}
ctr, err := s.getContainer(cid)
if err != nil {
return nil, nil, err
}
// A container being in stopped state is not a valid reason for not
// accepting a call to getProcess(). Indeed, we want to make sure a
// shim can connect after the process has already terminated. Some
// processes have a very short lifetime and the shim might end up
// calling into WaitProcess() after this happened. This does not mean
// we cannot retrieve the output and the exit code from the shim.
proc, err := ctr.getProcess(execID)
if err != nil {
return nil, nil, err
}
return proc, ctr, nil
}
func (s *sandbox) readStdio(cid, execID string, length int, stdout bool) ([]byte, error) {
proc, _, err := s.getProcess(cid, execID)
if err != nil {
return nil, err
}
var file *os.File
if proc.termMaster != nil {
// The process's epoller's run() will return a file descriptor of the process's
// terminal or one end of its exited pipe. If it returns its terminal, it means
// there is data needed to be read out or it has been closed; if it returns the
// process's exited pipe, it means the process has exited and there is no data
// needed to be read out in its terminal, thus following read on it will read out
// "EOF" to terminate this process's io since the other end of this pipe has been
// closed in reap().
file, err = proc.epoller.run()
if err != nil {
return nil, err
}
} else {
if stdout {
file = proc.stdout
} else {
file = proc.stderr
}
}
buf := make([]byte, length)
bytesRead, err := file.Read(buf)
if err != nil {
return nil, err
}
return buf[:bytesRead], nil
}
func (s *sandbox) setupSharedNamespaces(ctx context.Context) error {
span, _ := trace(ctx, "sandbox", "setupSharedNamespaces")
defer span.finish()
// Set up shared IPC namespace
ns, err := setupPersistentNs(nsTypeIPC)
if err != nil {
return err
}
s.sharedIPCNs = *ns
// Set up shared UTS namespace
ns, err = setupPersistentNs(nsTypeUTS)
if err != nil {
return err
}
s.sharedUTSNs = *ns
return nil
}
func (s *sandbox) unmountSharedNamespaces() error {
span, _ := s.trace("unmountSharedNamespaces")
defer span.finish()
if err := unix.Unmount(s.sharedIPCNs.path, unix.MNT_DETACH); err != nil {
return err
}
return unix.Unmount(s.sharedUTSNs.path, unix.MNT_DETACH)
}
// setupSharedPidNs will reexec this binary in order to execute the C routine
// defined into pause.go file. The pauseBinArg is very important since that is
// the flag allowing the C function to determine it should run the "pause".
// This pause binary will ensure that we always have the init process of the
// new PID namespace running into the namespace, preventing the namespace to
// be destroyed if other processes are terminated.
func (s *sandbox) setupSharedPidNs() error {
span, _ := s.trace("setupSharedPidNs")
defer span.finish()
cmd := &exec.Cmd{
Path: selfBinPath,
Env: []string{fmt.Sprintf("%s=%s", pauseBinKey, pauseBinValue)},
}
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWPID,
}
exitCodeCh, err := s.subreaper.start(cmd)
if err != nil {
return err
}
// Save info about this namespace inside sandbox structure.
s.sharedPidNs = namespace{
path: fmt.Sprintf("/proc/%d/ns/pid", cmd.Process.Pid),
init: cmd.Process,
exitCodeCh: exitCodeCh,
}
return nil
}
func (s *sandbox) teardownSharedPidNs() error {
span, _ := s.trace("teardownSharedPidNs")
defer span.finish()
if !s.sandboxPidNs {
// We are not in a case where we have created a pause process.
// Simply clear out the sharedPidNs path.
s.sharedPidNs.path = ""
return nil
}
// Terminates the "init" process of the PID namespace.
if err := s.sharedPidNs.init.Kill(); err != nil {
return err
}
// Using helper function wait() to deal with the subreaper.
osProcess := (*reaperOSProcess)(s.sharedPidNs.init)
if _, err := s.subreaper.wait(s.sharedPidNs.exitCodeCh, osProcess); err != nil {
return err
}
// Empty the sandbox structure.
s.sharedPidNs = namespace{}
return nil
}
func (s *sandbox) waitForStopServer() {
span, _ := s.trace("waitForStopServer")
defer span.finish()
fieldLogger := agentLog.WithField("subsystem", "stopserverwatcher")
fieldLogger.Info("Waiting for stopServer signal...")
// Wait for DestroySandbox() to signal this thread about the need to
// stop the server.
<-s.stopServer
fieldLogger.Info("stopServer signal received")
if s.server == nil {
fieldLogger.Info("No server initialized, nothing to stop")
return
}
defer fieldLogger.Info("gRPC server stopped")
// Try to gracefully stop the server for a minute
timeout := time.Minute
done := make(chan struct{})
go func() {
s.server.GracefulStop()
close(done)
}()
select {
case <-done:
s.server = nil
return
case <-time.After(timeout):
fieldLogger.WithField("timeout", timeout).Warn("Could not gracefully stop the server")
}
fieldLogger.Info("Force stopping the server now")
span.setTag("forced", true)
s.stopGRPC()
}
func (s *sandbox) listenToUdevEvents() {
fieldLogger := agentLog.WithField("subsystem", "udevlistener")
uEvHandler, err := uevent.NewHandler()
if err != nil {
fieldLogger.Warnf("Error starting uevent listening loop %s", err)
return
}
defer uEvHandler.Close()
fieldLogger.Infof("Started listening for uevents")
for {
uEv, err := uEvHandler.Read()
if err != nil {
fieldLogger.Error(err)
continue
}
// We only care about add event
if uEv.Action != "add" {
continue
}
span, _ := trace(rootContext, "udev", "udev event")
span.setTag("udev-action", uEv.Action)
span.setTag("udev-name", uEv.DevName)
span.setTag("udev-path", uEv.DevPath)
span.setTag("udev-subsystem", uEv.SubSystem)
span.setTag("udev-seqno", uEv.SeqNum)
fieldLogger = fieldLogger.WithFields(logrus.Fields{
"uevent-action": uEv.Action,
"uevent-devpath": uEv.DevPath,
"uevent-subsystem": uEv.SubSystem,
"uevent-seqnum": uEv.SeqNum,
"uevent-devname": uEv.DevName,
})
fieldLogger.Infof("Received add uevent")
// Check if device hotplug event results in a device node being created.
if uEv.DevName != "" && strings.HasPrefix(uEv.DevPath, rootBusPath) {
// Lock is needed to safey read and modify the pciDeviceMap and deviceWatchers.
// This makes sure that watchers do not access the map while it is being updated.
s.Lock()
// Add the device node name to the pci device map.
s.pciDeviceMap[uEv.DevPath] = uEv.DevName
// Notify watchers that are interested in the udev event.
// Close the channel after watcher has been notified.
for devAddress, ch := range s.deviceWatchers {
if ch == nil {
continue
}
fieldLogger.Infof("Got a wait channel for device %s", devAddress)
// blk driver case
if strings.HasPrefix(uEv.DevPath, filepath.Join(rootBusPath, devAddress)) {
goto OUT
}
if strings.Contains(uEv.DevPath, devAddress) {
// scsi driver case
if strings.HasSuffix(devAddress, scsiBlockSuffix) {
goto OUT
}
// blk-ccw driver case
if strings.HasSuffix(devAddress, blkCCWSuffix) {
goto OUT
}
}
continue
OUT:
ch <- uEv.DevName
close(ch)
delete(s.deviceWatchers, devAddress)
}
s.Unlock()
} else if onlinePath := filepath.Join(sysfsDir, uEv.DevPath, "online"); strings.HasPrefix(onlinePath, sysfsMemOnlinePath) {
// Check memory hotplug and online if possible
if err := ioutil.WriteFile(onlinePath, []byte("1"), 0600); err != nil {
fieldLogger.WithError(err).Error("failed online device")
}
}
span.finish()
}
}
// This loop is meant to be run inside a separate Go routine.
func (s *sandbox) signalHandlerLoop(sigCh chan os.Signal, errCh chan error) {
// Lock OS thread as subreaper is a thread local capability
// and is not inherited by children created by fork(2) and clone(2).
runtime.LockOSThread()
// Set agent as subreaper
err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, uintptr(1), 0, 0, 0)
if err != nil {
errCh <- err
return
}
close(errCh)
for sig := range sigCh {
logger := agentLog.WithField("signal", sig)
if sig == unix.SIGCHLD {
if err := s.subreaper.reap(); err != nil {
logger.WithError(err).Error("failed to reap")
continue
}
}
nativeSignal, ok := sig.(syscall.Signal)
if !ok {
err := errors.New("unknown signal")
logger.WithError(err).Error("failed to handle signal")
continue
}
if fatalSignal(nativeSignal) {
logger.Error("received fatal signal")
die(s.ctx)
}
if debug && nonFatalSignal(nativeSignal) {
logger.Debug("handling signal")
backtrace()
continue
}
logger.Info("ignoring unexpected signal")
}
}
func (s *sandbox) setupSignalHandler() error {
span, _ := s.trace("setupSignalHandler")
defer span.finish()
sigCh := make(chan os.Signal, 512)
signal.Notify(sigCh, unix.SIGCHLD)
for _, sig := range handledSignals() {
signal.Notify(sigCh, sig)
}
errCh := make(chan error, 1)
go s.signalHandlerLoop(sigCh, errCh)
return <-errCh
}
// getMemory returns a string containing the total amount of memory reported
// by the kernel. The string includes a suffix denoting the units the memory
// is measured in.
func getMemory() (string, error) {
bytes, err := ioutil.ReadFile(meminfo)
if err != nil {
return "", err
}
lines := string(bytes)
for _, line := range strings.Split(lines, "\n") {
if !strings.HasPrefix(line, "MemTotal") {
continue
}
expectedFields := 2
fields := strings.Split(line, ":")
count := len(fields)
if count != expectedFields {
return "", fmt.Errorf("expected %d fields, got %d in line %q", expectedFields, count, line)
}
if fields[1] == "" {
return "", fmt.Errorf("cannot determine total memory from line %q", line)
}
memTotal := strings.TrimSpace(fields[1])
if memTotal == "" {
return "", fmt.Errorf("cannot determine total memory from line %q", line)
}
return memTotal, nil
}
return "", fmt.Errorf("no lines in file %q", meminfo)
}
func getAnnounceFields() (logrus.Fields, error) {
var deviceHandlers []string
var storageHandlers []string
for handler := range deviceHandlerList {
deviceHandlers = append(deviceHandlers, handler)
}
for handler := range storageHandlerList {
storageHandlers = append(storageHandlers, handler)
}
memTotal, err := getMemory()
if err != nil {
return logrus.Fields{}, err
}
return logrus.Fields{
"version": version,
"device-handlers": strings.Join(deviceHandlers, ","),
"storage-handlers": strings.Join(storageHandlers, ","),
"system-memory": memTotal,
}, nil
}
// formatFields converts logrus Fields (containing arbitrary types) into a string slice.
func formatFields(fields logrus.Fields) []string {
var results []string
for k, v := range fields {
value, ok := v.(string)
if !ok {
// convert non-string value into a string
value = fmt.Sprint(v)
}
results = append(results, fmt.Sprintf("%s=%q", k, value))
}
return results
}
// announce logs details of the agents version and capabilities.
func announce() error {
announceFields, err := getAnnounceFields()
if err != nil {
return err
}
if os.Getpid() == 1 {
fields := formatFields(agentFields)
extraFields := formatFields(announceFields)
fields = append(fields, extraFields...)
fmt.Printf("announce: %s\n", strings.Join(fields, ","))
} else {
agentLog.WithFields(announceFields).Info("announce")
}
return nil
}
func logsToVPort() {
l, err := vsock.Listen(logsVSockPort)
if err != nil {
// no body listening
return
}
c, err := l.Accept()
if err != nil {
l.Close()
// no connection
return
}
r, w := io.Pipe()
agentLog.Logger.Out = w
io.Copy(c, r)
w.Close()
r.Close()
c.Close()
l.Close()
}
func (s *sandbox) initLogger(ctx context.Context) error {
agentLog.Logger.Formatter = &logrus.TextFormatter{DisableColors: true, TimestampFormat: time.RFC3339Nano}
config := newConfig(defaultLogLevel)
if err := config.getConfig(kernelCmdlineFile); err != nil {
agentLog.WithError(err).Warn("Failed to get config from kernel cmdline")
}
agentLog.Logger.SetLevel(config.logLevel)
agentLog = agentLog.WithField("debug_console", debugConsole)
if logsVSockPort != 0 {
go func() {
// save original logger's output to restore it when there
// is no process reading the logs in the host
out := agentLog.Logger.Out
for {
select {
case <-ctx.Done():
// stop the thread
return
default:
logsToVPort()