/
checkpoint.go
1692 lines (1494 loc) · 46.9 KB
/
checkpoint.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 container
import (
"bytes"
"context"
gocontext "context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"sync"
"syscall"
"time"
goruntime "runtime"
"github.com/cedana/cedana/utils"
"github.com/cedana/runc/libcontainer/cgroups"
"github.com/cedana/runc/libcontainer/cgroups/manager"
"github.com/cedana/runc/libcontainer/configs"
"github.com/cedana/runc/libcontainer/system"
"github.com/checkpoint-restore/go-criu/v6"
criurpc "github.com/checkpoint-restore/go-criu/v6/rpc"
containerd "github.com/containerd/containerd"
apiTasks "github.com/containerd/containerd/api/services/tasks/v1"
"github.com/containerd/containerd/api/types"
containerdTypes "github.com/containerd/containerd/api/types"
"github.com/containerd/containerd/archive"
"github.com/containerd/containerd/containers"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/diff"
"github.com/containerd/containerd/images"
"github.com/containerd/containerd/log"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/pkg/epoch"
"github.com/containerd/containerd/plugin"
"github.com/containerd/containerd/protobuf"
ptypes "github.com/containerd/containerd/protobuf/types"
"github.com/containerd/containerd/rootfs"
"github.com/containerd/containerd/runtime/linux/runctypes"
"github.com/containerd/containerd/runtime/v2/runc/options"
"github.com/containerd/typeurl/v2"
securejoin "github.com/cyphar/filepath-securejoin"
dockerTypes "github.com/docker/docker/api/types"
"github.com/docker/docker/client"
dockercli "github.com/docker/docker/client"
errdefs "github.com/containerd/errdefs"
"github.com/opencontainers/go-digest"
is "github.com/opencontainers/image-spec/specs-go"
ver "github.com/opencontainers/image-spec/specs-go"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/rs/zerolog"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/proto"
)
var (
ErrUnknown = errors.New("unknown") // used internally to represent a missed mapping.
ErrInvalidArgument = errors.New("invalid argument")
ErrNotFound = errors.New("not found")
ErrAlreadyExists = errors.New("already exists")
ErrFailedPrecondition = errors.New("failed precondition")
ErrUnavailable = errors.New("unavailable")
ErrNotImplemented = errors.New("not implemented") // represents not supported and unimplemented
)
const (
checkpointImageNameLabel = "org.opencontainers.image.ref.name"
checkpointRuntimeNameLabel = "io.containerd.checkpoint.runtime"
checkpointSnapshotterNameLabel = "io.containerd.checkpoint.snapshotter"
)
const descriptorsFilename = "descriptors.json"
const (
checkpointDateFormat = "01-02-2006-15:04:05"
checkpointNameFormat = "containerd.io/checkpoint/%s:%s"
)
type CheckpointTaskOpts func(*CheckpointTaskInfo) error
// CheckpointTaskInfo allows specific checkpoint information to be set for the task
type CheckpointTaskInfo struct {
Name string
// ParentCheckpoint is the digest of a parent checkpoint
ParentCheckpoint digest.Digest
// Options hold runtime specific settings for checkpointing a task
Options interface{}
runtime string
}
// Runtime name for the container
func (i *CheckpointTaskInfo) Runtime() string {
return i.runtime
}
type parentProcess interface {
// pid returns the pid for the running process.
pid() int
// start starts the process execution.
start() error
// send a SIGKILL to the process and wait for the exit.
terminate() error
// wait waits on the process returning the process state.
wait() (*os.ProcessState, error)
// startTime returns the process start time.
startTime() (uint64, error)
signal(os.Signal) error
externalDescriptors() []string
setExternalDescriptors(fds []string)
forwardChildLogs() chan error
}
type nonChildProcess struct {
processPid int
processStartTime uint64
fds []string
}
func (p *nonChildProcess) start() error {
return errors.New("restored process cannot be started")
}
func (p *nonChildProcess) pid() int {
return p.processPid
}
func (p *nonChildProcess) terminate() error {
return errors.New("restored process cannot be terminated")
}
func (p *nonChildProcess) wait() (*os.ProcessState, error) {
return nil, errors.New("restored process cannot be waited on")
}
func (p *nonChildProcess) startTime() (uint64, error) {
return p.processStartTime, nil
}
func (p *nonChildProcess) signal(s os.Signal) error {
proc, err := os.FindProcess(p.processPid)
if err != nil {
return err
}
return proc.Signal(s)
}
func (p *nonChildProcess) externalDescriptors() []string {
return p.fds
}
func (p *nonChildProcess) setExternalDescriptors(newFds []string) {
p.fds = newFds
}
func (p *nonChildProcess) forwardChildLogs() chan error {
return nil
}
type Status int
type containerState interface {
transition(containerState) error
destroy() error
status() Status
}
type ContainerStateJson struct {
// Version is the OCI version for the container
Version string `json:"ociVersion"`
// ID is the container ID
ID string `json:"id"`
// InitProcessPid is the init process id in the parent namespace
InitProcessPid int `json:"pid"`
// Status is the current status of the container, running, paused, ...
Status string `json:"status"`
// Bundle is the path on the filesystem to the bundle
Bundle string `json:"bundle"`
// Rootfs is a path to a directory containing the container's root filesystem.
Rootfs string `json:"rootfs"`
// Created is the unix timestamp for the creation time of the container in UTC
Created time.Time `json:"created"`
// Annotations is the user defined annotations added to the config.
Annotations map[string]string `json:"annotations,omitempty"`
// The owner of the state directory (the owner of the container).
Owner string `json:"owner"`
}
type RuncContainer struct {
Id string
StateDir string
Root string
Pid int
Config *configs.Config // standin for configs.Config from runc
CgroupManager cgroups.Manager
InitProcessStartTime uint64
InitProcess parentProcess
M sync.Mutex
CriuVersion int
Created time.Time
DockerConfig *dockerTypes.ContainerJSON
IntelRdtManager *Manager
State containerState
}
func (c *RuncContainer) saveState(s *State) (retErr error) {
tmpFile, err := os.CreateTemp(c.StateDir, "state-")
if err != nil {
return err
}
defer func() {
if retErr != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
}
}()
err = utils.WriteJSON(tmpFile, s)
if err != nil {
return err
}
err = tmpFile.Close()
if err != nil {
return err
}
stateFilePath := filepath.Join(c.StateDir, stateFilename)
return os.Rename(tmpFile.Name(), stateFilePath)
}
func (c *RuncContainer) currentState() (*State, error) {
var (
startTime uint64
externalDescriptors []string
pid = -1
)
if c.InitProcess != nil {
pid = c.InitProcess.pid()
startTime, _ = c.InitProcess.startTime()
externalDescriptors = c.InitProcess.externalDescriptors()
}
intelRdtPath := ""
if c.IntelRdtManager != nil {
intelRdtPath = c.IntelRdtManager.GetPath()
}
state := &State{
BaseState: BaseState{
ID: c.ID(),
Config: *c.Config,
InitProcessPid: pid,
InitProcessStartTime: startTime,
Created: c.Created,
},
Rootless: c.Config.RootlessEUID && c.Config.RootlessCgroups,
CgroupPaths: c.CgroupManager.GetPaths(),
IntelRdtPath: intelRdtPath,
NamespacePaths: make(map[configs.NamespaceType]string),
ExternalDescriptors: externalDescriptors,
}
if pid > 0 {
for _, ns := range c.Config.Namespaces {
state.NamespacePaths[ns.Type] = ns.GetPath(pid)
}
for _, nsType := range configs.NamespaceTypes() {
if !configs.IsNamespaceSupported(nsType) {
continue
}
if _, ok := state.NamespacePaths[nsType]; !ok {
ns := configs.Namespace{Type: nsType}
state.NamespacePaths[ns.Type] = ns.GetPath(pid)
}
}
}
return state, nil
}
func (c *RuncContainer) updateState(process parentProcess) (*State, error) {
if process != nil {
c.InitProcess = process
}
state, err := c.currentState()
if err != nil {
return nil, err
}
err = c.saveState(state)
if err != nil {
return nil, err
}
return state, nil
}
type restoredProcess struct {
cmd *exec.Cmd
processStartTime uint64
fds []string
}
func (p *restoredProcess) start() error {
return errors.New("restored process cannot be started")
}
func (p *restoredProcess) pid() int {
return p.cmd.Process.Pid
}
func (p *restoredProcess) terminate() error {
err := p.cmd.Process.Kill()
if _, werr := p.wait(); err == nil {
err = werr
}
return err
}
func (p *restoredProcess) wait() (*os.ProcessState, error) {
// TODO: how do we wait on the actual process?
// maybe use --exec-cmd in criu
err := p.cmd.Wait()
if err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
return nil, err
}
}
st := p.cmd.ProcessState
return st, nil
}
func (p *restoredProcess) startTime() (uint64, error) {
return p.processStartTime, nil
}
func (p *restoredProcess) signal(s os.Signal) error {
return p.cmd.Process.Signal(s)
}
func (p *restoredProcess) externalDescriptors() []string {
return p.fds
}
func (p *restoredProcess) setExternalDescriptors(newFds []string) {
p.fds = newFds
}
func (p *restoredProcess) forwardChildLogs() chan error {
return nil
}
func newRestoredProcess(cmd *exec.Cmd, fds []string) (*restoredProcess, error) {
var err error
pid := cmd.Process.Pid
stat, err := system.Stat(pid)
if err != nil {
return nil, err
}
return &restoredProcess{
cmd: cmd,
processStartTime: stat.StartTime,
fds: fds,
}, nil
}
func (c *RuncContainer) criuNotifications(resp *criurpc.CriuResp, process *Process, cmd *exec.Cmd, opts *CriuOpts, fds []string, oob []byte) error {
notify := resp.GetNotify()
if notify == nil {
return fmt.Errorf("invalid response: %s", resp.String())
}
script := notify.GetScript()
logrus.Debugf("notify: %s\n", script)
switch script {
case "post-dump":
f, err := os.Create(filepath.Join(c.StateDir, "checkpoint"))
if err != nil {
return err
}
f.Close()
case "network-unlock":
if err := unlockNetwork(c.Config); err != nil {
return err
}
case "network-lock":
if err := lockNetwork(c.Config); err != nil {
return err
}
case "setup-namespaces":
if c.Config.Hooks != nil {
s, err := c.currentOCIState()
if err != nil {
return nil
}
s.Pid = int(notify.GetPid())
if err := c.Config.Hooks.Run(configs.Prestart, s); err != nil {
return err
}
if err := c.Config.Hooks.Run(configs.CreateRuntime, s); err != nil {
return err
}
}
case "post-restore":
pid := notify.GetPid()
p, err := os.FindProcess(int(pid))
if err != nil {
return err
}
cmd.Process = p
r, err := newRestoredProcess(cmd, fds)
if err != nil {
return err
}
process.ops = r
if err := c.State.transition(&restoredState{
imageDir: opts.ImagesDirectory,
c: c,
}); err != nil {
return err
}
// create a timestamp indicating when the restored checkpoint was started
c.Created = time.Now().UTC()
if _, err := c.updateState(r); err != nil {
return err
}
if err := os.Remove(filepath.Join(c.StateDir, "checkpoint")); err != nil {
if !os.IsNotExist(err) {
logrus.Error(err)
}
}
case "orphan-pts-master":
scm, err := unix.ParseSocketControlMessage(oob)
if err != nil {
return err
}
fds, err := unix.ParseUnixRights(&scm[0])
if err != nil {
return err
}
master := os.NewFile(uintptr(fds[0]), "orphan-pts-master")
defer master.Close()
// While we can access console.master, using the API is a good idea.
if err := utils.SendFile(process.ConsoleSocket, master); err != nil {
return err
}
case "status-ready":
if opts.StatusFd != -1 {
// write \0 to status fd to notify that lazy page server is ready
_, err := unix.Write(opts.StatusFd, []byte{0})
if err != nil {
logrus.Warnf("can't write \\0 to status fd: %v", err)
}
_ = unix.Close(opts.StatusFd)
opts.StatusFd = -1
}
}
return nil
}
// this comes from runc, see github.com/cedana/runc
// they use an external CriuOpts struct that's populated
type VethPairName struct {
ContainerInterfaceName string
HostInterfaceName string
}
// Higher level CriuOptions that are used to turn on/off the flags passed to criu
type CriuOpts struct {
ImagesDirectory string // directory for storing image files
WorkDirectory string // directory to cd and write logs/pidfiles/stats to
ParentImage string // directory for storing parent image files in pre-dump and dump
LeaveRunning bool // leave container in running state after checkpoint
TcpEstablished bool // checkpoint/restore established TCP connections
ExternalUnixConnections bool // allow external unix connections
ShellJob bool // allow to dump and restore shell jobs
FileLocks bool // handle file locks, for safety
PreDump bool // call criu predump to perform iterative checkpoint
VethPairs []VethPairName // pass the veth to criu when restore
ManageCgroupsMode criurpc.CriuCgMode // dump or restore cgroup mode
EmptyNs uint32 // don't c/r properties for namespace from this mask
AutoDedup bool // auto deduplication for incremental dumps
LazyPages bool // restore memory pages lazily using userfaultfd
StatusFd int // fd for feedback when lazy server is ready
LsmProfile string // LSM profile used to restore the container
LsmMountContext string // LSM mount context value to use during restore
External []string // ignore external namespaces
MntnsCompatMode bool
TcpClose bool
}
type loadedState struct {
c *RuncContainer
s Status
}
func (n *loadedState) status() Status {
return n.s
}
func (n *loadedState) transition(s containerState) error {
n.c.State = s
return nil
}
// func (n *loadedState) destroy() error {
// if err := n.c.refreshState(); err != nil {
// return err
// }
// return n.c.state.destroy()
// }
func GetContainerFromRunc(containerID string, root string) *RuncContainer {
// Runc root
// root := "/var/run/runc"
// Docker root
// root := "/run/docker/runtime-runc/moby"
// Containerd root where "default" is the namespace
l := utils.GetLogger()
criu := criu.MakeCriu()
criuVersion, err := criu.GetCriuVersion()
if err != nil {
l.Fatal().Err(err).Msg("could not get criu version")
}
root = root + "/" + containerID
state, err := loadState(root)
if err != nil {
l.Fatal().Err(err).Msg("could not load state")
}
r := &nonChildProcess{
processPid: state.InitProcessPid,
processStartTime: state.InitProcessStartTime,
fds: state.ExternalDescriptors,
}
cgroupManager, err := manager.NewWithPaths(state.Config.Cgroups, state.CgroupPaths)
if err != nil {
l.Fatal().Err(err).Msg("could not create cgroup manager")
}
c := &RuncContainer{
InitProcess: r,
InitProcessStartTime: state.InitProcessStartTime,
Id: containerID,
Root: root,
CriuVersion: criuVersion,
CgroupManager: cgroupManager,
// dockerConfig: &container,
Config: &state.Config,
IntelRdtManager: NewManager(&state.Config, containerID, state.IntelRdtPath),
Pid: state.InitProcessPid,
// state: containerState,
Created: state.Created,
}
// c.state = &loadedState{c: c}
// if err := c.refreshState(); err != nil {
// return nil, err
// }
return c
}
type BaseState struct {
// ID is the container ID.
ID string `json:"id"`
// InitProcessPid is the init process id in the parent namespace.
InitProcessPid int `json:"init_process_pid"`
// InitProcessStartTime is the init process start time in clock cycles since boot time.
InitProcessStartTime uint64 `json:"init_process_start"`
// Created is the unix timestamp for the creation time of the container in UTC
Created time.Time `json:"created"`
// Config is the container's configuration.
Config configs.Config `json:"config"`
}
type State struct {
BaseState
// Platform specific fields below here
// Specified if the container was started under the rootless mode.
// Set to true if BaseState.Config.RootlessEUID && BaseState.Config.RootlessCgroups
Rootless bool `json:"rootless"`
// Paths to all the container's cgroups, as returned by (*cgroups.Manager).GetPaths
//
// For cgroup v1, a key is cgroup subsystem name, and the value is the path
// to the cgroup for this subsystem.
//
// For cgroup v2 unified hierarchy, a key is "", and the value is the unified path.
CgroupPaths map[string]string `json:"cgroup_paths"`
// NamespacePaths are filepaths to the container's namespaces. Key is the namespace type
// with the value as the path.
NamespacePaths map[configs.NamespaceType]string `json:"namespace_paths"`
// Container's standard descriptors (std{in,out,err}), needed for checkpoint and restore
ExternalDescriptors []string `json:"external_descriptors,omitempty"`
// Intel RDT "resource control" filesystem path
IntelRdtPath string `json:"intel_rdt_path"`
}
func loadState(root string) (*State, error) {
stateFilePath, err := securejoin.SecureJoin(root, "state.json")
if err != nil {
return nil, err
}
f, err := os.Open(stateFilePath)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, err
}
defer f.Close()
var state *State
if err := json.NewDecoder(f).Decode(&state); err != nil {
return nil, err
}
return state, nil
}
func newContainerdClient(ctx gocontext.Context, opts ...containerd.ClientOpt) (*containerd.Client, gocontext.Context, gocontext.CancelFunc, error) {
timeoutOpt := containerd.WithTimeout(0)
containerdEndpoint := "/run/containerd/containerd.sock"
if _, err := os.Stat(containerdEndpoint); err != nil {
containerdEndpoint = "/host/run/k3s/containerd/containerd.sock"
}
opts = append(opts, timeoutOpt)
client, err := containerd.New(containerdEndpoint, opts...)
if err != nil {
fmt.Print("failed to create client")
}
ctx, cancel := AppContext(ctx)
return client, ctx, cancel, err
}
// Pretty wacky function. "creates" a runc container from a docker container,
// basically piecing it together from information we can parse out from the docker go lib
func getContainerFromDocker(containerID string) *RuncContainer {
l := utils.GetLogger()
cli, err := dockercli.NewClientWithOpts(client.FromEnv)
if err != nil {
l.Fatal().Err(err).Msg("could not create docker client")
}
cli.NegotiateAPIVersion(gocontext.Background())
container, err := cli.ContainerInspect(gocontext.Background(), containerID)
if err != nil {
l.Fatal().Err(err).Msg("could not inspect container")
}
criu := criu.MakeCriu()
criuVersion, err := criu.GetCriuVersion()
if err != nil {
l.Fatal().Err(err).Msg("could not get criu version")
}
// need to build a config from the information we can parse out from the docker lib
// start with bare minimum
runcConf := &configs.Config{
Rootfs: container.GraphDriver.Data["MergedDir"], // does this work lol
}
// create a cgroup manager for cgroup freezing
// need c.Path, c.Parent & c.Name, c.Systemd. We can grab t his from proc/pid
var cgroupsConf *configs.Cgroup
if container.State.Pid != 0 {
cgroupPaths := []string{fmt.Sprintf("/proc/%d/cgroup", container.State.Pid)}
// assume we're in cgroup v2 unified
// for cgroup v2 unified hierarchy, there are no per-controller cgroup paths
cgroupsPaths, err := cgroups.ParseCgroupFile(cgroupPaths[0])
if err != nil {
l.Fatal().Err(err).Msg("could not parse cgroup paths")
}
path := cgroupsPaths[""]
// Splitting the string by / separator
cgroupParts := strings.Split(path, "/")
if len(cgroupParts) < 3 {
l.Fatal().Err(err).Msg("could not parse cgroup path")
}
name := cgroupParts[2]
parent := cgroupParts[1]
cgpath := "/" + parent + "/" + name
var isSystemd bool
if strings.Contains(path, ".slice") {
isSystemd = true
}
cgroupsConf = &configs.Cgroup{
Parent: parent,
Name: name,
Path: cgpath,
Systemd: isSystemd,
}
}
cgroupManager, err := manager.New(cgroupsConf)
if err != nil {
l.Fatal().Err(err).Msg("could not create cgroup manager")
}
// this is so stupid hahahaha
c := &RuncContainer{
Id: containerID,
Root: fmt.Sprintf("%s", container.Config.WorkingDir),
CriuVersion: criuVersion,
CgroupManager: cgroupManager,
DockerConfig: &container,
Config: runcConf,
Pid: container.State.Pid,
}
return c
}
// AppContext returns the context for a command. Should only be called once per
// command, near the start.
//
// This will ensure the namespace is picked up and set the timeout, if one is
// defined.
func AppContext(context gocontext.Context) (gocontext.Context, gocontext.CancelFunc) {
var (
ctx = gocontext.Background()
timeout = 0
namespace = "k8s.io"
cancel gocontext.CancelFunc
)
ctx = namespaces.WithNamespace(ctx, namespace)
if timeout > 0 {
ctx, cancel = gocontext.WithTimeout(ctx, time.Duration(timeout)*time.Second)
} else {
ctx, cancel = gocontext.WithCancel(ctx)
}
if tm, err := epoch.SourceDateEpoch(); err != nil {
log.L.WithError(err).Warn("Failed to read SOURCE_DATE_EPOCH")
} else if tm != nil {
log.L.Debugf("Using SOURCE_DATE_EPOCH: %v", tm)
ctx = epoch.WithSourceDateEpoch(ctx, tm)
}
return ctx, cancel
}
func ContainerdCheckpoint(imagePath, id string) error {
logger := utils.GetLogger()
ctx := gocontext.Background()
containerdClient, ctx, cancel, err := newContainerdClient(ctx)
if err != nil {
logger.Fatal().Err(err)
}
defer cancel()
containers, err := containerdClient.Containers(ctx)
if err != nil {
return err
}
for _, container := range containers {
fmt.Println(container.ID())
}
opts := []containerd.CheckpointOpts{
containerd.WithCheckpointRuntime,
}
opts = append(opts, containerd.WithCheckpointImage)
opts = append(opts, containerd.WithCheckpointRW)
opts = append(opts, containerd.WithCheckpointTask)
container, err := containerdClient.LoadContainer(ctx, id)
if err != nil {
return err
}
task, err := container.Task(ctx, nil)
if err != nil {
if !errdefs.IsNotFound(err) {
return err
}
}
// pause if running
if task != nil {
if err := task.Pause(ctx); err != nil {
return err
}
defer func() {
if err := task.Resume(ctx); err != nil {
fmt.Println(fmt.Errorf("error resuming task: %w", err))
}
}()
}
// checkpoint task
//checkpoint, err := task.Checkpoint(ctx, containerd.WithCheckpointImagePath(imagePath)) //checkpoint, err := runcCheckpointContainerd(ctx, containerdClient, task, WithCheckpointImagePath(""))
checkpoint, err := container.Checkpoint(ctx, "test123", opts...)
if err != nil {
return err
}
fmt.Printf("Checkpoint name: %s\n", checkpoint.Name())
// if _, err := container.Checkpoint(ctx, ref, containerdOpts...); err != nil {
// return err
// }
return nil
}
// getCheckpointPath only suitable for runc runtime now
func getCheckpointPath(runtime string, option *ptypes.Any) (string, error) {
if option == nil {
return "", nil
}
var checkpointPath string
v, err := typeurl.UnmarshalAny(option)
if err != nil {
return "", err
}
opts, ok := v.(*options.CheckpointOptions)
if !ok {
return "", fmt.Errorf("invalid task checkpoint option for %s", runtime)
}
checkpointPath = opts.ImagePath
return checkpointPath, nil
}
func localCheckpointTask(ctx gocontext.Context, client *containerd.Client, index *v1.Index, request *apiTasks.CheckpointTaskRequest, container containers.Container) (*apiTasks.CheckpointTaskResponse, error) {
// TODO BS get rid of marshal/unmarshal & CTR
v, err := typeurl.UnmarshalAny(request.Options)
if err != nil {
return &apiTasks.CheckpointTaskResponse{}, err
}
opts, ok := v.(*options.CheckpointOptions)
if !ok {
return &apiTasks.CheckpointTaskResponse{}, fmt.Errorf("invalid task checkpoint option for %s", container.Runtime.Name)
}
criuOpts := &CriuOpts{
ImagesDirectory: opts.ImagePath,
WorkDirectory: opts.WorkPath,
LeaveRunning: !opts.Exit,
TcpEstablished: opts.OpenTcp,
ExternalUnixConnections: opts.ExternalUnixSockets,
ShellJob: opts.Terminal,
FileLocks: opts.FileLocks,
StatusFd: int(3),
}
image := opts.ImagePath
checkpointImageExists := false
if image == "" {
checkpointImageExists = true
image, err = os.MkdirTemp(os.Getenv("XDG_RUNTIME_DIR"), "ctrd-checkpoint")
if err != nil {
return &apiTasks.CheckpointTaskResponse{}, err
}
criuOpts.ImagesDirectory = image
fmt.Printf("Checkpointing to %s\n", image)
defer os.RemoveAll(image)
}
root := "/run/containerd/runc/default"
// EKS
_, err = os.Stat(root)
if err != nil {
root = "/run/containerd/runc/k8s.io"
}
c := GetContainerFromRunc(container.ID, root)
err = c.RuncCheckpoint(criuOpts, c.Pid, root, c.Config)
if err != nil {
return nil, err
}
// do not commit checkpoint image if checkpoint ImagePath is passed,
// return if checkpointImageExists is false
if !checkpointImageExists {
return &apiTasks.CheckpointTaskResponse{}, nil
}
// write checkpoint to the content store
tar := archive.Diff(ctx, "", image)
cp, err := localWriteContent(ctx, client, images.MediaTypeContainerd1Checkpoint, image, tar)
if err != nil {
return nil, err
}
// close tar first after write
if err := tar.Close(); err != nil {
return &apiTasks.CheckpointTaskResponse{}, err
}
if err != nil {
return &apiTasks.CheckpointTaskResponse{}, err
}
// write the config to the content store
pbany := protobuf.FromAny(container.Spec)
data, err := proto.Marshal(pbany)
if err != nil {
return &apiTasks.CheckpointTaskResponse{}, err
}
spec := bytes.NewReader(data)
specD, err := localWriteContent(ctx, client, images.MediaTypeContainerd1CheckpointConfig, filepath.Join(image, "spec"), spec)
if err != nil {
return &apiTasks.CheckpointTaskResponse{}, err
}
return &apiTasks.CheckpointTaskResponse{
Descriptors: []*containerdTypes.Descriptor{
cp,
specD,
},
}, nil
}
func localWriteContent(ctx gocontext.Context, client *containerd.Client, mediaType, ref string, r io.Reader) (*types.Descriptor, error) {
writer, err := client.ContentStore().Writer(ctx, content.WithRef(ref), content.WithDescriptor(ocispec.Descriptor{MediaType: mediaType}))
if err != nil {
return nil, err
}
defer writer.Close()
size, err := io.Copy(writer, r)
if err != nil {
return nil, err
}
if err := writer.Commit(ctx, 0, ""); err != nil {
return nil, err
}
return &types.Descriptor{
MediaType: mediaType,
Digest: writer.Digest().String(),
Size: size,
Annotations: make(map[string]string),
}, nil
}
// WithCheckpointImagePath sets image path for checkpoint option
func WithCheckpointImagePath(path string) CheckpointTaskOpts {
return func(r *CheckpointTaskInfo) error {
if CheckRuntime(r.Runtime(), "io.containerd.runc") {
if r.Options == nil {
r.Options = &options.CheckpointOptions{}
}
opts, ok := r.Options.(*options.CheckpointOptions)
if !ok {
return errors.New("invalid v2 shim checkpoint options format")
}
opts.ImagePath = path
} else {
if r.Options == nil {
r.Options = &runctypes.CheckpointOptions{}
}
opts, ok := r.Options.(*runctypes.CheckpointOptions)
if !ok {
return errors.New("invalid v1 shim checkpoint options format")
}
opts.ImagePath = path
}
return nil
}
}
// CheckRuntime returns true if the current runtime matches the expected
// runtime. Providing various parts of the runtime schema will match those
// parts of the expected runtime
func CheckRuntime(current, expected string) bool {
cp := strings.Split(current, ".")