/
runtime_oci.go
1546 lines (1358 loc) · 42.1 KB
/
runtime_oci.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
package oci
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
metadata "github.com/checkpoint-restore/checkpointctl/lib"
conmonconfig "github.com/containers/conmon/runner/config"
"github.com/containers/podman/v4/pkg/checkpoint/crutils"
"github.com/containers/podman/v4/pkg/criu"
"github.com/containers/storage/pkg/pools"
"github.com/cri-o/cri-o/internal/config/cgmgr"
"github.com/cri-o/cri-o/internal/log"
"github.com/cri-o/cri-o/pkg/config"
"github.com/cri-o/cri-o/server/metrics"
"github.com/cri-o/cri-o/utils"
"github.com/cri-o/cri-o/utils/cmdrunner"
"github.com/fsnotify/fsnotify"
json "github.com/json-iterator/go"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
"golang.org/x/sys/unix"
kwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/remotecommand"
types "k8s.io/cri-api/pkg/apis/runtime/v1"
kclock "k8s.io/utils/clock"
utilexec "k8s.io/utils/exec"
)
const (
// RuntimeTypeOCI is the type representing the RuntimeOCI implementation.
RuntimeTypeOCI = "oci"
// Command line flag used to specify the run root directory
rootFlag = "--root"
// Configuration for the stop loop exponential backoff manager.
stopInitialBackoff = 20 * time.Millisecond
stopMaximumBackoff = 2 * time.Minute
stopResetBackoff = 5 * time.Minute
stopBackoffFactor = 2.0
stopBackoffJitter = 1.25
// When to start the blocked process reminder and
// how frequently the reminder should be shown.
stopProcessBlockedInterval = stopMaximumBackoff / 2
// Used to delay periodic process liveness check. Part of the
// container stop loop where a goroutine wakes up on a regular
// basis to check whether a given PID (process) continues to
// run. This allows to short-circuit stop logic if the process
// has already been terminated.
stopProcessWatchSleep = 100 * time.Millisecond
)
// runtimeOCI is the Runtime interface implementation relying on conmon to
// interact with the container runtime.
type runtimeOCI struct {
*Runtime
root string
handler *config.RuntimeHandler
}
// newRuntimeOCI creates a new runtimeOCI instance
func newRuntimeOCI(r *Runtime, handler *config.RuntimeHandler) RuntimeImpl {
runRoot := config.DefaultRuntimeRoot
if handler.RuntimeRoot != "" {
runRoot = handler.RuntimeRoot
}
return &runtimeOCI{
Runtime: r,
root: runRoot,
handler: handler,
}
}
// syncInfo is used to return data from monitor process to daemon
type syncInfo struct {
Pid int `json:"pid"`
Message string `json:"message,omitempty"`
}
// exitCodeInfo is used to return the monitored process exit code to the daemon
type exitCodeInfo struct {
ExitCode int32 `json:"exit_code"`
Message string `json:"message,omitempty"`
}
// CreateContainer creates a container.
func (r *runtimeOCI) CreateContainer(ctx context.Context, c *Container, cgroupParent string, restore bool) (retErr error) {
ctx, span := log.StartSpan(ctx)
defer span.End()
if c.Spoofed() {
return nil
}
var stderrBuf bytes.Buffer
parentPipe, childPipe, err := newPipe()
if err != nil {
return fmt.Errorf("error creating socket pair: %w", err)
}
childStartPipe, parentStartPipe, err := newPipe()
if err != nil {
return fmt.Errorf("error creating socket pair: %w", err)
}
defer parentPipe.Close()
defer parentStartPipe.Close()
args := []string{
"-b", c.bundlePath,
"-c", c.ID(),
"--exit-dir", r.config.ContainerExitsDir,
"-l", c.logPath,
"--log-level", logrus.GetLevel().String(),
"-n", c.name,
"-P", c.conmonPidFilePath(),
"-p", filepath.Join(c.bundlePath, "pidfile"),
"--persist-dir", c.dir,
"-r", c.RuntimePathForPlatform(r),
"--runtime-arg", fmt.Sprintf("%s=%s", rootFlag, r.root),
"--socket-dir-path", r.config.ContainerAttachSocketDir,
"--syslog",
"-u", c.ID(),
}
if r.config.CgroupManager().IsSystemd() {
args = append(args, "-s")
}
if r.config.LogSizeMax >= 0 {
args = append(args, "--log-size-max", strconv.FormatInt(r.config.LogSizeMax, 10))
}
if r.config.LogToJournald {
args = append(args, "--log-path", "journald:")
}
if r.config.NoPivot {
args = append(args, "--no-pivot")
}
if c.terminal {
args = append(args, "-t")
} else if c.stdin {
if !c.stdinOnce {
args = append(args, "--leave-stdin-open")
}
args = append(args, "-i")
}
if restore {
log.Debugf(ctx, "Restore is true %v", restore)
args = append(args, "--restore", c.CheckpointPath())
if c.Spec().Process.SelinuxLabel != "" {
args = append(
args,
"--runtime-opt",
fmt.Sprintf(
"--lsm-profile=selinux:%s",
c.Spec().Process.SelinuxLabel,
),
)
}
if c.Spec().Linux.MountLabel != "" {
args = append(
args,
"--runtime-opt",
fmt.Sprintf(
"--lsm-mount-context=%s",
c.Spec().Linux.MountLabel,
),
)
}
}
log.WithFields(ctx, logrus.Fields{
"args": args,
}).Debugf("running conmon: %s", r.handler.MonitorPath)
cmd := cmdrunner.Command(r.handler.MonitorPath, args...) // nolint: gosec
cmd.Dir = c.bundlePath
cmd.SysProcAttr = sysProcAttrPlatform()
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if c.terminal {
cmd.Stderr = &stderrBuf
}
cmd.ExtraFiles = append(cmd.ExtraFiles, childPipe, childStartPipe)
// 0, 1 and 2 are stdin, stdout and stderr
cmd.Env = r.handler.MonitorEnv
cmd.Env = append(cmd.Env,
fmt.Sprintf("_OCI_SYNCPIPE=%d", 3),
fmt.Sprintf("_OCI_STARTPIPE=%d", 4))
if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found {
cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v))
}
if restore {
// The CRIU binary is usually in /usr/sbin/criu
if v, found := os.LookupEnv("PATH"); found {
cmd.Env = append(cmd.Env, fmt.Sprintf("PATH=%s", v))
}
}
err = cmd.Start()
if err != nil {
childPipe.Close()
childStartPipe.Close()
return err
}
// We don't need childPipe on the parent side
childPipe.Close()
childStartPipe.Close()
// Create new scope to reduce cleanup code.
if err := func() (retErr error) {
defer func() {
if retErr != nil {
// We need to always kill and wait on this process.
// Failing to do so will cause us to leak a zombie.
killErr := cmd.Process.Kill()
waitErr := cmd.Wait()
if killErr != nil {
retErr = fmt.Errorf("failed to kill %+v after failing with: %w", killErr, retErr)
}
// Per https://pkg.go.dev/os#ProcessState.ExitCode, the exit code is -1 when the process died because
// of a signal. We expect this in this case, as we've just killed it with a signal. Don't append the
// error in this case to reduce noise.
if exitErr, ok := waitErr.(*exec.ExitError); !ok || exitErr.ExitCode() != -1 {
retErr = fmt.Errorf("failed to wait %+v after failing with: %w", waitErr, retErr)
}
}
}()
// Platform specific container setup
if !c.Spoofed() {
if err := r.createContainerPlatform(c, cgroupParent, cmd.Process.Pid); err != nil {
return err
}
}
/* We set the cgroup, now the child can start creating children */
someData := []byte{0}
_, err = parentStartPipe.Write(someData)
return err
}(); err != nil {
return err
}
defer func() {
if retErr != nil {
if err := os.Remove(c.logPath); err != nil {
log.Warnf(ctx, "Failed to remove log path %s after failing to create container: %v", c.logPath, err)
}
}
}()
/* Wait for initial setup and fork, and reap child */
err = cmd.Wait()
if err != nil {
return err
}
// We will delete all container resources if creation fails
defer func() {
if retErr != nil {
if err := r.DeleteContainer(ctx, c); err != nil {
log.Warnf(ctx, "Unable to delete container %s: %v", c.ID(), err)
}
}
}()
// Wait to get container pid from conmon
type syncStruct struct {
si *syncInfo
err error
}
ch := make(chan syncStruct, 1)
go func() {
defer close(ch)
var si *syncInfo
if err = json.NewDecoder(parentPipe).Decode(&si); err != nil {
ch <- syncStruct{err: err}
return
}
ch <- syncStruct{si: si}
}()
var pid int
select {
case ss := <-ch:
if ss.err != nil {
return fmt.Errorf("error reading container (probably exited) json message: %w", ss.err)
}
log.Debugf(ctx, "Received container pid: %d", ss.si.Pid)
pid = ss.si.Pid
if ss.si.Pid == -1 {
if ss.si.Message != "" {
if restore {
log.Errorf(ctx, "Container restore error: %s", ss.si.Message)
return fmt.Errorf("container restore failed: %s", ss.si.Message)
}
log.Errorf(ctx, "Container creation error: %s", ss.si.Message)
return fmt.Errorf("container create failed: %s", ss.si.Message)
}
log.Errorf(ctx, "Container creation failed")
return fmt.Errorf("container create failed")
}
case <-time.After(ContainerCreateTimeout):
log.Errorf(ctx, "Container creation timeout (%v)", ContainerCreateTimeout)
return fmt.Errorf("create container timeout")
}
// Now we know the container has started, save the pid to verify against future calls.
if err := c.state.SetInitPid(pid); err != nil {
return err
}
return nil
}
// StartContainer starts a container.
func (r *runtimeOCI) StartContainer(ctx context.Context, c *Container) error {
_, span := log.StartSpan(ctx)
defer span.End()
c.opLock.Lock()
defer c.opLock.Unlock()
if c.Spoofed() {
return nil
}
if _, err := r.runtimeCmd("start", c.ID()); err != nil {
return err
}
c.state.Started = time.Now()
return nil
}
func prepareExec() (pidFileName string, parentPipe, childPipe *os.File, _ error) {
var err error
parentPipe, childPipe, err = os.Pipe()
if err != nil {
return "", nil, nil, err
}
pidFile, err := os.CreateTemp("", "pidfile")
if err != nil {
parentPipe.Close()
childPipe.Close()
return "", nil, nil, err
}
pidFile.Close()
pidFileName = pidFile.Name()
return pidFileName, parentPipe, childPipe, nil
}
func parseLog(ctx context.Context, l []byte) (stdout, stderr []byte) {
ctx, span := log.StartSpan(ctx)
defer span.End()
// Split the log on newlines, which is what separates entries.
lines := bytes.SplitAfter(l, []byte{'\n'})
for _, line := range lines {
// Ignore empty lines.
if len(line) == 0 {
continue
}
// The format of log lines is "DATE pipe LogTag REST".
parts := bytes.SplitN(line, []byte{' '}, 4)
if len(parts) < 4 {
// Ignore the line if it's formatted incorrectly, but complain
// about it so it can be debugged.
log.Warnf(ctx, "Hit invalid log format: %q", string(line))
continue
}
pipe := string(parts[1])
content := parts[3]
linetype := string(parts[2])
if linetype == "P" {
contentLen := len(content)
if contentLen > 0 && content[contentLen-1] == '\n' {
content = content[:contentLen-1]
}
}
switch pipe {
case "stdout":
stdout = append(stdout, content...)
case "stderr":
stderr = append(stderr, content...)
default:
// Complain about unknown pipes.
log.Warnf(ctx, "Hit invalid log format [unknown pipe %s]: %q", pipe, string(line))
continue
}
}
return stdout, stderr
}
// ExecContainer prepares a streaming endpoint to execute a command in the container.
func (r *runtimeOCI) ExecContainer(ctx context.Context, c *Container, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resizeChan <-chan remotecommand.TerminalSize) error {
_, span := log.StartSpan(ctx)
defer span.End()
if c.Spoofed() {
return nil
}
processFile, err := prepareProcessExec(c, cmd, tty)
if err != nil {
return err
}
defer os.RemoveAll(processFile)
args := r.defaultRuntimeArgs()
args = append(args, "exec", "--process", processFile, c.ID())
execCmd := cmdrunner.CommandContext(ctx, c.RuntimePathForPlatform(r), args...) // nolint: gosec
if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found {
execCmd.Env = append(execCmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v))
}
var cmdErr, copyError error
if tty {
execCmd.WaitDelay = 30 * time.Second
cmdErr = ttyCmd(execCmd, stdin, stdout, resizeChan, c)
} else {
var r, w *os.File
if stdin != nil {
// Use an os.Pipe here as it returns true *os.File objects.
// This way, if you run 'kubectl exec <pod> -i bash' (no tty) and type 'exit',
// the call below to execCmd.Run() can unblock because its Stdin is the read half
// of the pipe.
r, w, err = os.Pipe()
if err != nil {
return err
}
u := c.Spec().Process.User
// Change the owner for the pipe to the user in the container
if err := unix.Fchown(int(r.Fd()), int(u.UID), int(u.GID)); err != nil {
return err
}
execCmd.Stdin = r
go func() {
_, copyError = pools.Copy(w, stdin)
w.Close()
}()
}
if stdout != nil {
execCmd.Stdout = stdout
}
if stderr != nil {
execCmd.Stderr = stderr
}
if err := execCmd.Start(); err != nil {
return err
}
pid := execCmd.Process.Pid
if err := c.AddExecPID(pid, true); err != nil {
return err
}
defer c.DeleteExecPID(pid)
// The read side of the pipe should be closed after the container process has been started.
if r != nil {
if err := r.Close(); err != nil {
if waitErr := execCmd.Wait(); waitErr != nil {
return fmt.Errorf("%v: %w", waitErr, err)
}
return err
}
}
cmdErr = execCmd.Wait()
}
if copyError != nil {
return copyError
}
if exitErr, ok := cmdErr.(*exec.ExitError); ok {
return &utilexec.ExitErrorWrapper{ExitError: exitErr}
}
return cmdErr
}
// ExecSyncContainer execs a command in a container and returns it's stdout, stderr and return code.
func (r *runtimeOCI) ExecSyncContainer(ctx context.Context, c *Container, command []string, timeout int64) (*types.ExecSyncResponse, error) {
ctx, span := log.StartSpan(ctx)
defer span.End()
if c.Spoofed() {
return nil, nil
}
pidFile, parentPipe, childPipe, err := prepareExec()
if err != nil {
return nil, &ExecSyncError{
ExitCode: -1,
Err: err,
}
}
childStartPipe, parentStartPipe, err := newPipe()
if err != nil {
return nil, &ExecSyncError{
ExitCode: -1,
Err: err,
}
}
defer parentPipe.Close()
defer parentStartPipe.Close()
defer func() {
if e := os.Remove(pidFile); e != nil {
log.Warnf(ctx, "Could not remove temporary PID file %s", pidFile)
}
}()
logFile, err := os.CreateTemp("", "crio-log-"+c.ID())
if err != nil {
return nil, &ExecSyncError{
ExitCode: -1,
Err: err,
}
}
logFile.Close()
logPath := logFile.Name()
defer func() {
os.RemoveAll(logPath)
}()
args := []string{
"-c", c.ID(),
"-n", c.name,
"-r", c.RuntimePathForPlatform(r),
"-p", pidFile,
"-e",
"-l", logPath,
"--socket-dir-path", r.config.ContainerAttachSocketDir,
"--log-level", logrus.GetLevel().String(),
}
if r.config.ConmonSupportsSync() {
args = append(args, "--sync")
}
if r.config.ConmonSupportsLogGlobalSizeMax() {
args = append(args, "--log-global-size-max", strconv.Itoa(maxExecSyncSize))
}
if c.terminal {
args = append(args, "-t")
}
if timeout > 0 {
args = append(args, "-T", strconv.FormatInt(timeout, 10))
}
if r.config.CgroupManager().IsSystemd() {
args = append(args, "-s")
}
processFile, err := prepareProcessExec(c, command, c.terminal)
if err != nil {
return nil, &ExecSyncError{
ExitCode: -1,
Err: err,
}
}
defer os.RemoveAll(processFile)
args = append(args,
"--exec-process-spec", processFile,
"--runtime-arg", fmt.Sprintf("%s=%s", rootFlag, r.root))
var cmd *exec.Cmd
if r.handler.MonitorExecCgroup == config.MonitorExecCgroupDefault || r.config.InfraCtrCPUSet == "" { // nolint: gocritic
cmd = cmdrunner.Command(r.handler.MonitorPath, args...) // nolint: gosec
} else if r.handler.MonitorExecCgroup == config.MonitorExecCgroupContainer {
cmd = exec.Command(r.handler.MonitorPath, args...) // nolint: gosec
} else {
msg := fmt.Sprintf("Unsupported monitor_exec_cgroup value: %s", r.handler.MonitorExecCgroup)
return &types.ExecSyncResponse{
Stderr: []byte(msg),
ExitCode: -1,
}, nil
}
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
cmd.ExtraFiles = append(cmd.ExtraFiles, childPipe, childStartPipe)
// 0, 1 and 2 are stdin, stdout and stderr
cmd.Env = r.handler.MonitorEnv
cmd.Env = append(cmd.Env,
fmt.Sprintf("_OCI_SYNCPIPE=%d", 3),
fmt.Sprintf("_OCI_STARTPIPE=%d", 4))
if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found {
cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v))
}
err = cmd.Start()
if err != nil {
childPipe.Close()
childStartPipe.Close()
return nil, &ExecSyncError{
Stdout: stdoutBuf,
Stderr: stderrBuf,
ExitCode: -1,
Err: err,
}
}
// We don't need childPipe on the parent side
childPipe.Close()
childStartPipe.Close()
// Create new scope to reduce cleanup code.
if err := func() (retErr error) {
defer func() {
if retErr != nil {
// We need to always kill and wait on this process.
// Failing to do so will cause us to leak a zombie.
killErr := cmd.Process.Kill()
waitErr := cmd.Wait()
if killErr != nil {
retErr = fmt.Errorf("failed to kill %+v after failing with: %w", killErr, retErr)
}
// Per https://pkg.go.dev/os#ProcessState.ExitCode, the exit code is -1 when the process died because
// of a signal. We expect this in this case, as we've just killed it with a signal. Don't append the
// error in this case to reduce noise.
if exitErr, ok := waitErr.(*exec.ExitError); !ok || exitErr.ExitCode() != -1 {
retErr = fmt.Errorf("failed to wait %+v after failing with: %w", waitErr, retErr)
}
}
}()
// A neat trick we can do is register the exec PID before we send info down the start pipe.
// Doing so guarantees we can short circuit the exec process if the container is stopping already.
if err := c.AddExecPID(cmd.Process.Pid, false); err != nil {
return err
}
if r.handler.MonitorExecCgroup == config.MonitorExecCgroupContainer && r.config.InfraCtrCPUSet != "" {
// Update the exec's cgroup
containerPid, _, err := c.pid()
if err != nil {
return err
}
err = cgmgr.MoveProcessToContainerCgroup(containerPid, cmd.Process.Pid)
if err != nil {
return err
}
}
// Unblock children
someData := []byte{0}
_, err = parentStartPipe.Write(someData)
if err != nil {
return err
}
return nil
}(); err != nil {
return nil, &ExecSyncError{
Stdout: stdoutBuf,
Stderr: stderrBuf,
ExitCode: -1,
Err: err,
}
}
// defer in case the Pid is changed after Wait()
pid := cmd.Process.Pid
// first, wait till the command is done
waitErr := cmd.Wait()
c.DeleteExecPID(pid)
// regardless of what is in waitErr
// we should attempt to decode the output of the parent pipe
// this allows us to catch TimedOutMessage, which will cause waitErr to not be nil
var ec *exitCodeInfo
decodeErr := json.NewDecoder(parentPipe).Decode(&ec)
if decodeErr == nil {
log.Debugf(ctx, "Received container exit code: %v, message: %s", ec.ExitCode, ec.Message)
// When we timeout the command in conmon then we should return
// an ExecSyncResponse with a non-zero exit code because
// the prober code in the kubelet checks for it. If we return
// a custom error, then the probes transition into Unknown status
// and the container isn't restarted as expected.
if ec.ExitCode == -1 && ec.Message == conmonconfig.TimedOutMessage {
return &types.ExecSyncResponse{
Stderr: []byte(conmonconfig.TimedOutMessage),
ExitCode: -1,
}, nil
}
}
if waitErr != nil {
// if we aren't a ExitError, some I/O problems probably occurred
if _, ok := waitErr.(*exec.ExitError); !ok {
return nil, &ExecSyncError{
Stdout: stdoutBuf,
Stderr: stderrBuf,
ExitCode: -1,
Err: waitErr,
}
}
}
if decodeErr != nil {
return nil, &ExecSyncError{
Stdout: stdoutBuf,
Stderr: stderrBuf,
ExitCode: -1,
Err: decodeErr,
}
}
if ec.ExitCode == -1 {
return nil, &ExecSyncError{
Stdout: stdoutBuf,
Stderr: stderrBuf,
ExitCode: -1,
Err: errors.New(ec.Message),
}
}
// The actual logged output is not the same as stdoutBuf and stderrBuf,
// which are used for getting error information. For the actual
// ExecSyncResponse we have to read the logfile.
// XXX: Currently runC dups the same console over both stdout and stderr,
// so we can't differentiate between the two.
logBytes, err := TruncateAndReadFile(ctx, logPath, maxExecSyncSize)
if err != nil {
return nil, &ExecSyncError{
Stdout: stdoutBuf,
Stderr: stderrBuf,
ExitCode: -1,
Err: err,
}
}
// We have to parse the log output into {stdout, stderr} buffers.
stdoutBytes, stderrBytes := parseLog(ctx, logBytes)
return &types.ExecSyncResponse{
Stdout: stdoutBytes,
Stderr: stderrBytes,
ExitCode: ec.ExitCode,
}, nil
}
func TruncateAndReadFile(ctx context.Context, path string, size int64) ([]byte, error) {
ctx, span := log.StartSpan(ctx)
defer span.End()
info, err := os.Stat(path)
if err != nil {
return nil, err
}
if info.Size() > size {
log.Errorf(ctx, "Exec sync output in file %s has size %d which is longer than expected size of %d", path, info.Size(), size)
if err := os.Truncate(path, size); err != nil {
return nil, err
}
}
return os.ReadFile(path)
}
// UpdateContainer updates container resources
func (r *runtimeOCI) UpdateContainer(ctx context.Context, c *Container, res *rspec.LinuxResources) error {
_, span := log.StartSpan(ctx)
defer span.End()
c.opLock.Lock()
defer c.opLock.Unlock()
if c.Spoofed() {
return nil
}
cmd := cmdrunner.Command(c.RuntimePathForPlatform(r), rootFlag, r.root, "update", "--resources", "-", c.ID()) // nolint: gosec
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found {
cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v))
}
jsonResources, err := json.Marshal(res)
if err != nil {
return err
}
cmd.Stdin = bytes.NewReader(jsonResources)
if err := cmd.Run(); err != nil {
return fmt.Errorf("updating resources for container %q failed: %v %v: %w", c.ID(), stderr.String(), stdout.String(), err)
}
return nil
}
// StopContainer stops a container. Timeout is given in seconds.
func (r *runtimeOCI) StopContainer(ctx context.Context, c *Container, timeout int64) (retErr error) {
ctx, span := log.StartSpan(ctx)
defer span.End()
if c.Spoofed() {
c.state.Status = ContainerStateStopped
c.state.Finished = time.Now()
return nil
}
if err := c.ShouldBeStopped(); err != nil {
if errors.Is(err, ErrContainerStopped) {
err = nil
}
return err
}
// The initial container process either doesn't exist, or isn't ours.
if err := c.Living(); err != nil {
c.state.Finished = time.Now()
return nil
}
if c.SetAsStopping() {
// The API is due to be deprecated. However, the replacement is completely broken, see:
// https://github.com/kubernetes/kubernetes/issues/118638
go r.StopLoopForContainer(c,
kwait.NewExponentialBackoffManager( //nolint:staticcheck // Ignore deprecated function warning.
stopInitialBackoff,
stopMaximumBackoff,
stopResetBackoff,
stopBackoffFactor,
stopBackoffJitter,
&kclock.RealClock{},
),
)
}
c.WaitOnStopTimeout(ctx, timeout)
return nil
}
func (r *runtimeOCI) StopLoopForContainer(c *Container, bm kwait.BackoffManager) {
ctx := context.Background()
ctx, span := log.StartSpan(ctx)
defer span.End()
startTime := time.Now()
go c.KillExecPIDs()
// Allow for SIGINT to correctly interrupt the stop loop, especially
// when CRI-O is run directly in the foreground in the terminal.
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
c.opLock.Lock()
// Begin the actual kill.
if _, err := r.runtimeCmd("kill", c.ID(), c.GetStopSignal()); err != nil {
if err := c.Living(); err != nil {
// The initial container process either doesn't exist, or isn't ours.
// Set state accordingly.
c.state.Finished = time.Now()
c.opLock.Unlock()
c.SetAsDoneStopping()
return
}
}
done := make(chan struct{})
go func() {
for {
if err := c.Living(); err != nil {
// The initial container process either doesn't exist, or isn't ours.
if !errors.Is(err, ErrNotFound) {
log.Warnf(ctx, "Failed to find process for container %s: %v", c.ID(), err)
}
close(done)
return
}
// The PID is still active and belongs to the container, continue to wait.
time.Sleep(stopProcessWatchSleep)
}
}()
// Operate in terms of targetTime, so that we can pause in the middle of the operation
// to catch a new timeout (and possibly ignore that new timeout if it's not correct to
// take a new one).
targetTime := time.Now().AddDate(+1, 0, 0) // A year from this one.
blockedTimer := time.AfterFunc(stopProcessBlockedInterval, func() {
if state, err := c.ProcessState(); err == nil && state == "D" {
log.Errorf(ctx,
"Detected process (%d) blocked in uninterruptible sleep for more than %d seconds for container %s",
c.state.InitPid, int(time.Since(startTime)/time.Second), c.ID(),
)
}
})
defer blockedTimer.Stop()
// Do not start the stuck process reminder immediately.
blockedTimer.Stop()
// We cannot use ExponentialBackoff() here as its stop conditions are not flexible enough.
kwait.BackoffUntil(func() {
select {
case newTimeout := <-c.stopTimeoutChan:
// If a new timeout comes in, interrupt the old one, and start a new one.
newTargetTime := time.Now().Add(time.Duration(newTimeout) * time.Second)
// But, only if it's an earlier one.
if newTargetTime.Before(targetTime) {
targetTime = newTargetTime
}
case <-time.After(time.Until(targetTime)):
log.Warnf(ctx, "Stopping container %s with stop signal timed out. Killing...", c.ID())
if _, err := r.runtimeCmd("kill", c.ID(), "KILL"); err != nil {
log.Errorf(ctx, "Killing container %v failed: %v", c.ID(), err)
}
if err := c.Living(); err != nil {
stop()
}
// Reschedule the timer so that the periodic reminder can continue.
blockedTimer.Reset(stopProcessBlockedInterval)
case <-done:
stop()
}
}, bm, true, ctx.Done())
c.state.Finished = time.Now()
c.opLock.Unlock()
c.SetAsDoneStopping()
}
// DeleteContainer deletes a container.
func (r *runtimeOCI) DeleteContainer(ctx context.Context, c *Container) error {
_, span := log.StartSpan(ctx)
defer span.End()
c.opLock.Lock()
defer c.opLock.Unlock()
if c.Spoofed() {
return nil
}
_, err := r.runtimeCmd("delete", "--force", c.ID())
return err
}
func updateContainerStatusFromExitFile(c *Container) error {
exitFilePath := c.exitFilePath()
fi, err := os.Stat(exitFilePath)
if err != nil {
return fmt.Errorf("failed to find container exit file for %s: %w", c.ID(), err)
}
c.state.Finished, err = getFinishedTime(fi)
if err != nil {
return fmt.Errorf("failed to get finished time: %w", err)
}
statusCodeStr, err := os.ReadFile(exitFilePath)
if err != nil {
return fmt.Errorf("failed to read exit file: %w", err)
}
statusCode, err := strconv.ParseInt(string(statusCodeStr), 10, 32)
if err != nil {
return fmt.Errorf("status code conversion failed: %w", err)
}
c.state.ExitCode = utils.Int32Ptr(int32(statusCode))
return nil
}