/
container.go
2150 lines (1759 loc) · 64.8 KB
/
container.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 mgr
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/alibaba/pouch/apis/opts"
"github.com/alibaba/pouch/apis/types"
"github.com/alibaba/pouch/ctrd"
daemon_config "github.com/alibaba/pouch/daemon/config"
"github.com/alibaba/pouch/daemon/containerio"
"github.com/alibaba/pouch/daemon/events"
"github.com/alibaba/pouch/daemon/logger"
"github.com/alibaba/pouch/hookplugins"
"github.com/alibaba/pouch/lxcfs"
networktypes "github.com/alibaba/pouch/network/types"
"github.com/alibaba/pouch/pkg/collect"
"github.com/alibaba/pouch/pkg/errtypes"
"github.com/alibaba/pouch/pkg/log"
"github.com/alibaba/pouch/pkg/meta"
mountutils "github.com/alibaba/pouch/pkg/mount"
"github.com/alibaba/pouch/pkg/streams"
"github.com/alibaba/pouch/pkg/utils"
volumetypes "github.com/alibaba/pouch/storage/volume/types"
"github.com/containerd/cgroups"
containerdtypes "github.com/containerd/containerd/api/types"
"github.com/containerd/containerd/mount"
"github.com/docker/go-units"
"github.com/go-openapi/strfmt"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)
// ContainerMgr as an interface defines all operations against container.
// ContainerMgr's functionality could be divided into three parts:
// 1. regular container management;
// 2. container exec management;
// 3. container network management.
// 4. container copy management
type ContainerMgr interface {
// 1. the following functions are related to regular container management
// Load containers from meta store to memory. Split used Restore feature into two function:
// Load: just load all containers information into memory, it will be called before network
// manager being initialized.
// Restore: recover all running containers, it will be called after network manager being
// initialized so that we can call network functions in the recover procedures.
Load(ctx context.Context) error
// Restore recover those alive containers.
Restore(ctx context.Context) error
// Create a new container.
Create(ctx context.Context, name string, config *types.ContainerCreateConfig) (*types.ContainerCreateResp, error)
// Get the detailed information of container.
Get(ctx context.Context, name string) (*Container, error)
// List returns the list of containers.
List(ctx context.Context, option *ContainerListOption) ([]*Container, error)
// Start a container.
Start(ctx context.Context, id string, options *types.ContainerStartOptions) error
// Stop a container.
Stop(ctx context.Context, name string, timeout int64) error
// Kill a container
Kill(ctx context.Context, name string, signal int) error
// Restart restart a running container.
Restart(ctx context.Context, name string, timeout int64) error
// Pause a container.
Pause(ctx context.Context, name string) error
// Unpause a container.
Unpause(ctx context.Context, name string) error
// Using a stream to get stats of a container.
StreamStats(ctx context.Context, name string, config *ContainerStatsConfig) error
// Stats of a container.
Stats(ctx context.Context, name string) (*containerdtypes.Metric, *cgroups.Metrics, error)
// AttachContainerIO attach stream to container IO.
AttachContainerIO(ctx context.Context, name string, cfg *streams.AttachConfig) error
// AttachCRILog attach cri log to container IO.
AttachCRILog(ctx context.Context, name string, path string) error
// Rename renames a container.
Rename(ctx context.Context, oldName string, newName string) error
// Update updates the configurations of a container.
Update(ctx context.Context, name string, config *types.UpdateConfig) error
// Upgrade upgrades a container with new image and args.
Upgrade(ctx context.Context, name string, config *types.ContainerUpgradeConfig) error
// Top lists the processes running inside of the given container
Top(ctx context.Context, name string, psArgs string) (*types.ContainerProcessList, error)
// Resize resizes the size of container tty.
Resize(ctx context.Context, name string, opts types.ResizeOptions) error
// Remove removes a container, it may be running or stopped and so on.
Remove(ctx context.Context, name string, option *types.ContainerRemoveOptions) error
// Wait stops processing until the given container is stopped.
Wait(ctx context.Context, name string) (types.ContainerWaitOKBody, error)
// 2. The following five functions is related to container exec.
// CreateExec creates exec process's environment.
CreateExec(ctx context.Context, name string, config *types.ExecCreateConfig) (string, error)
// StartExec executes a new process in container.
StartExec(ctx context.Context, execid string, cfg *streams.AttachConfig, timeout int) error
// InspectExec returns low-level information about exec command.
InspectExec(ctx context.Context, execid string) (*types.ContainerExecInspect, error)
// GetExecConfig returns execonfig of a exec process inside container.
GetExecConfig(ctx context.Context, execid string) (*ContainerExecConfig, error)
// CheckExecExist check if exec process `name` exist
CheckExecExist(ctx context.Context, name string) error
// ResizeExec resizes the size of exec process's tty.
ResizeExec(ctx context.Context, execid string, opts types.ResizeOptions) error
// 3. The following two function is related to network management.
// TODO: inconsistency, Connect/Disconnect operation is in newtork_bridge.go in upper API layer.
// Here we encapsualted them in container manager, inconsistency exists.
// Connect is used to connect a container to a network.
Connect(ctx context.Context, name string, networkIDOrName string, epConfig *types.EndpointSettings) error
// Disconnect disconnects the given container from
// given network
Disconnect(ctx context.Context, containerName, networkName string, force bool) error
// Logs is used to return log created by the container.
Logs(ctx context.Context, name string, logsOpt *types.ContainerLogsOptions) (<-chan *logger.LogMessage, bool, error)
// NewSnapshotsSyncer creates a snapshot syncer.
NewSnapshotsSyncer(snapshotStore *SnapshotStore, duration time.Duration) *SnapshotsSyncer
// CreateCheckpoint creates a checkpoint from a running container
CreateCheckpoint(ctx context.Context, name string, options *types.CheckpointCreateOptions) error
// ListCheckpoint lists checkpoints from a container
ListCheckpoint(ctx context.Context, name string, options *types.CheckpointListOptions) ([]string, error)
// DeleteCheckpoint deletes a checkpoint from a container
DeleteCheckpoint(ctx context.Context, name string, options *types.CheckpointDeleteOptions) error
// Commit commits an image from a container.
Commit(ctx context.Context, name string, options *types.ContainerCommitOptions) (*types.ContainerCommitResp, error)
// StatPath stats the dir info at the specified path in the container.
StatPath(ctx context.Context, name, path string) (stat *types.ContainerPathStat, err error)
// ArchivePath return an archive and dir info at the specified path in the container.
ArchivePath(ctx context.Context, name, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error)
// ExtractToDir extracts the given archive at the specified path in the container.
ExtractToDir(ctx context.Context, name, path string, copyUIDGID, noOverwriteDirNonDir bool, content io.Reader) error
}
// ContainerManager is the default implement of interface ContainerMgr.
type ContainerManager struct {
// Store stores containers in Backend store.
// Element operated in store must has a type of *Container.
// By default, Store will use local filesystem with json format to store containers.
Store *meta.Store
// Client is used to interact with containerd.
Client ctrd.APIClient
// NameToID stores relations between container's name and ID.
// It is used to get container ID via container name.
NameToID *collect.SafeMap
ImageMgr ImageMgr
VolumeMgr VolumeMgr
NetworkMgr NetworkMgr
IOs *containerio.Cache
ExecProcesses *collect.SafeMap
Config *daemon_config.Config
// Cache stores all containers in memory.
// Element operated in cache must have a type of *Container.
cache *collect.SafeMap
// monitor is used to handle container's event, eg: exit, stop and so on.
monitor *ContainerMonitor
containerPlugin hookplugins.ContainerPlugin
// eventsService is used to publish events generated by pouchd
eventsService *events.Events
}
// NewContainerManager creates a brand new container manager.
func NewContainerManager(ctx context.Context, store *meta.Store, cli ctrd.APIClient, imgMgr ImageMgr, volMgr VolumeMgr, cfg *daemon_config.Config, contPlugin hookplugins.ContainerPlugin, eventsService *events.Events) (*ContainerManager, error) {
mgr := &ContainerManager{
Store: store,
NameToID: collect.NewSafeMap(),
Client: cli,
ImageMgr: imgMgr,
VolumeMgr: volMgr,
IOs: containerio.NewCache(),
ExecProcesses: collect.NewSafeMap(),
cache: collect.NewSafeMap(),
Config: cfg,
monitor: NewContainerMonitor(),
containerPlugin: contPlugin,
eventsService: eventsService,
}
mgr.Client.SetExitHooks(mgr.exitedAndRelease)
mgr.Client.SetExecExitHooks(mgr.execExitedAndRelease)
mgr.Client.SetEventsHooks(mgr.publishContainerdEvent, mgr.updateContainerState)
go mgr.execProcessGC()
return mgr, nil
}
// Load containers from meta store to memory.
func (mgr *ContainerManager) Load(ctx context.Context) error {
fn := func(obj meta.Object) error {
container, ok := obj.(*Container)
if !ok {
// object has not type of Container
return nil
}
id := container.ID
// map container's name to id.
mgr.NameToID.Put(container.Name, id)
// put container into cache.
mgr.cache.Put(id, container)
return nil
}
return mgr.Store.ForEach(fn)
}
// Restore tries to recover those alive containers
func (mgr *ContainerManager) Restore(ctx context.Context) error {
// get all running containers
containers, err := mgr.List(ctx,
&ContainerListOption{
All: true,
},
)
if err != nil {
log.With(ctx).Errorf("failed to get container list when restore containers: %v", err)
return errors.Wrap(err, "failed to get container list")
}
for _, c := range containers {
id := c.Key()
ctx = log.AddFields(ctx, map[string]interface{}{"ContainerID": id})
if c.IsDead() {
log.With(ctx).Warnf("stop to load container because it is dead")
// remove meta.json for container in local disk
if err := mgr.Store.Remove(id); err != nil {
log.With(ctx).Errorf("failed to remove container from meta store, err(%v)", err)
}
continue
}
// NOTE: when pouch is restarting, we need to initialize
// container IO for the existing containers just in case that
// user tries to restart the stopped containers.
cntrio, err := mgr.initContainerIO(c)
if err != nil {
log.With(ctx).Errorf("failed to init container IO, err(%v)", err)
return err
}
if err := mgr.initLogDriverBeforeStart(c); err != nil {
log.With(ctx).Errorf("failed to init log driver, err(%v)", err)
return err
}
// recover the running or paused container.
if !c.IsRunningOrPaused() {
continue
}
log.With(ctx).Debugf("Start recover container")
// Start recover the container
err = mgr.Client.RecoverContainer(ctx, id, cntrio)
if err == nil {
continue
}
// Note(ziren): Since we got an unknown error when recover the
// container, we just log the error and continue in case we wrongly
// release the container's resources
if !strings.Contains(err.Error(), "not found") {
log.With(ctx).Errorf("failed to recover container, err(%v)", err)
// release io
cntrio.Close()
mgr.IOs.Remove(id)
continue
}
// Note(ziren) if containerd post not found error, that is mean
// container or task is not found. So we should set the container's
// status to exited and release the container's resources.
log.With(ctx).Warnf("recover container, got a notfound error, start clean the container's resources")
if err := mgr.exitedAndRelease(id, nil, nil); err != nil {
log.With(ctx).Errorf("failed to execute exited and release for container, err(%v)", err)
}
}
return nil
}
// Create checks passed in parameters and create a Container object whose status is set at Created.
func (mgr *ContainerManager) Create(ctx context.Context, name string, config *types.ContainerCreateConfig) (resp *types.ContainerCreateResp, err error) {
currentSnapshotter := ctrd.CurrentSnapshotterName(ctx)
config.Snapshotter = currentSnapshotter
if mgr.containerPlugin != nil {
log.With(ctx).Infof("invoke container pre-create hook in plugin")
if ex := mgr.containerPlugin.PreCreate(ctx, config); ex != nil {
return nil, errors.Wrapf(ex, "pre-create plugin point execute failed")
}
}
// Attention, since we support multi snapshotter, if snapshotter not changed,
// means plugin not change it, so remove value in case to effect origin logic
if config.Snapshotter == currentSnapshotter {
config.Snapshotter = ""
}
// NOTE: choose snapshotter, snapshotter can only be set
// through containerPlugin in Create function
ctx = ctrd.WithSnapshotter(ctx, config.Snapshotter)
// cleanup allocated resources when failed
cleanups := []func() error{}
defer func() {
// do cleanup
if err != nil {
log.With(ctx).Infof("start to rollback allocated resources of container %v", name)
for _, f := range cleanups {
nerr := f()
if nerr != nil {
log.With(ctx).Errorf("fail to cleanup allocated resource, error is %v", nerr)
}
}
}
}()
imgID, _, primaryRef, err := mgr.ImageMgr.CheckReference(ctx, config.Image)
if err != nil {
return nil, err
}
config.Image = primaryRef.String()
// TODO: check request validate.
if config.HostConfig == nil {
return nil, errors.Wrapf(errtypes.ErrInvalidParam, "HostConfig cannot be empty")
}
if config.NetworkingConfig == nil {
return nil, errors.Wrapf(errtypes.ErrInvalidParam, "NetworkingConfig cannot be empty")
}
// validate disk quota
if err := mgr.validateDiskQuota(config); err != nil {
return nil, errors.Wrapf(err, "invalid disk quota config")
}
id, err := mgr.generateContainerID(config.SpecificID)
if err != nil {
return nil, err
}
//put container id to cache to prevent concurrent containerCreateReq with same specific id
mgr.cache.Put(id, nil)
ctx = log.AddFields(ctx, map[string]interface{}{"ContainerID": id})
defer func() {
//clear cache
if err != nil {
mgr.cache.Remove(id)
}
}()
if name == "" {
name = mgr.generateName(id)
} else if !daemon_config.ValidNamePattern.MatchString(name) {
return nil, fmt.Errorf("Invalid container name (%s), only %s are allowed", name, daemon_config.ValidNameChars)
} else if mgr.NameToID.Get(name).Exist() {
return nil, errors.Wrapf(errtypes.ErrAlreadyExisted, "container name %s", name)
}
// set hostname.
if config.Hostname.String() == "" {
// if hostname is empty, take the part of id as the hostname
config.Hostname = strfmt.Hostname(id[:12])
}
// set container runtime
if config.HostConfig.Runtime == "" {
config.HostConfig.Runtime = mgr.Config.DefaultRuntime
}
config.HostConfig.RuntimeType, err = mgr.getRuntimeType(config.HostConfig.Runtime)
if err != nil {
return nil, errors.Wrapf(errtypes.ErrInvalidParam, "unknown runtime %s: %v", config.HostConfig.Runtime, err)
}
snapID := id
// create a snapshot with image.
if err := mgr.Client.CreateSnapshot(ctx, snapID, config.Image); err != nil {
return nil, err
}
cleanups = append(cleanups, func() error {
log.With(ctx).Infof("start to cleanup snapshot, id is %v", id)
return mgr.Client.RemoveSnapshot(ctx, id)
})
// set lxcfs binds
if config.HostConfig.EnableLxcfs && lxcfs.IsLxcfsEnabled {
config.HostConfig.Binds = append(config.HostConfig.Binds, lxcfs.LxcfsParentDir+":/var/lib/lxc:shared")
sourceDir := lxcfs.LxcfsHomeDir + "/proc/"
destDir := "/proc/"
for _, procFile := range lxcfs.LxcfsProcFiles {
bind := fmt.Sprintf("%s%s:%s%s", sourceDir, procFile, destDir, procFile)
config.HostConfig.Binds = append(config.HostConfig.Binds, bind)
}
}
// set default log driver and validate for logger driver
config.HostConfig.LogConfig = mgr.getDefaultLogConfigIfMissing(config.HostConfig.LogConfig)
// set ReadonlyPaths and MaskedPaths to nil if privileged was set.
if config.HostConfig.Privileged {
config.HostConfig.ReadonlyPaths = nil
config.HostConfig.MaskedPaths = nil
}
container := &Container{
State: &types.ContainerState{
Status: types.StatusCreated,
StartedAt: time.Time{}.UTC().Format(utils.TimeLayout),
FinishedAt: time.Time{}.UTC().Format(utils.TimeLayout),
},
ID: id,
Image: imgID.String(),
Name: name,
Config: &config.ContainerConfig,
Created: time.Now().UTC().Format(utils.TimeLayout),
HostConfig: config.HostConfig,
SnapshotID: snapID,
}
if _, err := mgr.initContainerIO(container); err != nil {
log.With(ctx).Errorf("failed to initialise IO: %v", err)
return nil, err
}
// merge image's config into container
if err := container.merge(func() (ocispec.ImageConfig, error) {
return mgr.ImageMgr.GetOCIImageConfig(ctx, config.Image)
}); err != nil {
return nil, err
}
// set container basefs, basefs is not created in pouchd, it will created
// after create options passed to containerd.
mgr.setBaseFS(ctx, container)
// init container storage module, such as: set volumes, set diskquota, set /etc/mtab, copy image's data to volume.
if err := mgr.initContainerStorage(ctx, container); err != nil {
return nil, errors.Wrapf(err, "failed to init container storage, id: (%s)", container.ID)
}
// set network settings
networkMode := config.HostConfig.NetworkMode
if networkMode == "" {
config.HostConfig.NetworkMode = "bridge"
}
container.NetworkSettings = new(types.NetworkSettings)
if len(config.NetworkingConfig.EndpointsConfig) > 0 {
container.NetworkSettings.Networks = config.NetworkingConfig.EndpointsConfig
}
if container.NetworkSettings.Networks == nil &&
!IsContainer(config.HostConfig.NetworkMode) && !IsNetNS(config.HostConfig.NetworkMode) {
container.NetworkSettings.Networks = make(map[string]*types.EndpointSettings)
container.NetworkSettings.Networks[config.HostConfig.NetworkMode] = new(types.EndpointSettings)
}
container.NetworkSettings.Ports = config.HostConfig.PortBindings
if err := parseSecurityOpts(container, config.HostConfig.SecurityOpt); err != nil {
return nil, err
}
// Get snapshot UpperDir
mounts, err := mgr.Client.GetMounts(ctx, id)
if err != nil {
return nil, err
}
if len(mounts) != 1 {
return nil, fmt.Errorf("failed to get snapshot %s mounts: not equals one", id)
}
container.SetSnapshotterMeta(mounts)
// amendContainerSettings modify container config settings to wanted
amendContainerSettings(&config.ContainerConfig, config.HostConfig)
// validate container Config
warnings, err := mgr.validateConfig(container, false)
if err != nil {
return nil, err
}
// store disk
if err := container.Write(mgr.Store); err != nil {
log.With(ctx).Errorf("failed to update meta: %v", err)
return nil, err
}
// add to collection
mgr.NameToID.Put(name, id)
mgr.cache.Put(id, container)
mgr.LogContainerEvent(ctx, container, "create")
return &types.ContainerCreateResp{
ID: id,
Name: name,
Warnings: warnings,
}, nil
}
func (mgr *ContainerManager) getDefaultLogConfigIfMissing(logConfig *types.LogConfig) *types.LogConfig {
defaultLogOpts := make(map[string]string)
for k, v := range mgr.Config.DefaultLogConfig.LogOpts {
defaultLogOpts[k] = v
}
if logConfig == nil {
defaultConfig := mgr.Config.DefaultLogConfig
defaultConfig.LogOpts = defaultLogOpts
return &defaultConfig
}
if logConfig.LogDriver == "" {
logConfig.LogDriver = mgr.Config.DefaultLogConfig.LogDriver
}
if len(logConfig.LogOpts) == 0 {
logConfig.LogOpts = defaultLogOpts
}
return logConfig
}
// Get the detailed information of container.
func (mgr *ContainerManager) Get(ctx context.Context, name string) (*Container, error) {
c, err := mgr.container(name)
if err != nil {
return nil, err
}
cID := c.ID
// get all execids belongs to this container
fn := func(v interface{}) bool {
execConfig, ok := v.(*ContainerExecConfig)
if !ok || execConfig.ContainerID != cID {
return false
}
return true
}
var execIDs []string
execProcesses := mgr.ExecProcesses.Values(fn)
for k := range execProcesses {
execIDs = append(execIDs, k)
}
c.ExecIds = execIDs
return c, nil
}
// Start a pre created Container.
func (mgr *ContainerManager) Start(ctx context.Context, id string, options *types.ContainerStartOptions) (err error) {
if id == "" {
return errors.Wrap(errtypes.ErrInvalidParam, "container ID cannot empty")
}
c, err := mgr.container(id)
if err != nil {
return err
}
ctx = log.AddFields(ctx, map[string]interface{}{"ContainerID": c.ID})
// NOTE: choose snapshotter, snapshotter can only be set
// through containerPlugin in Create function
ctx = ctrd.WithSnapshotter(ctx, c.Config.Snapshotter)
err = mgr.start(ctx, c, options)
if err == nil {
mgr.LogContainerEvent(ctx, c, "start")
}
return err
}
func (mgr *ContainerManager) start(ctx context.Context, c *Container, options *types.ContainerStartOptions) error {
// NOTE: add a big lock when start a container
c.Lock()
defer c.Unlock()
var err error
c.DetachKeys = options.DetachKeys
// check if container's status is paused
if c.State.Paused {
return fmt.Errorf("cannot start a paused container, try unpause instead")
}
// check if container's status is running
if c.State.Running {
return errors.Wrapf(errtypes.ErrNotModified, "container already started")
}
if c.State.Dead {
return fmt.Errorf("cannot start a dead container %s", c.ID)
}
attachedVolumes := map[string]struct{}{}
defer func() {
if err == nil {
return
}
// release the container resources(network and containerio)
err = mgr.releaseContainerResources(ctx, c)
if err != nil {
log.With(ctx).Errorf("failed to release container(%s) resources: %v", c.ID, err)
}
// detach the volumes
for name := range attachedVolumes {
if _, err = mgr.VolumeMgr.Detach(ctx, name, map[string]string{volumetypes.OptionRef: c.ID}); err != nil {
log.With(ctx).Errorf("failed to detach volume(%s) when start container(%s) rollback: %v", name, c.ID, err)
}
}
}()
for _, mp := range c.Mounts {
if mp.Name == "" {
continue
}
if _, err = mgr.VolumeMgr.Attach(ctx, mp.Name, map[string]string{volumetypes.OptionRef: c.ID}); err != nil {
return errors.Wrapf(err, "failed to attach volume(%s)", mp.Name)
}
attachedVolumes[mp.Name] = struct{}{}
}
if err = mgr.prepareContainerNetwork(ctx, c); err != nil {
return err
}
if err = mgr.createContainerdContainer(ctx, c, options.CheckpointDir, options.CheckpointID); err != nil {
return errors.Wrapf(err, "failed to create container(%s) on containerd", c.ID)
}
return nil
}
func (mgr *ContainerManager) prepareContainerNetwork(ctx context.Context, c *Container) error {
networkMode := c.HostConfig.NetworkMode
if IsContainer(networkMode) {
var origContainer *Container
origContainer, err := mgr.Get(ctx, strings.SplitN(networkMode, ":", 2)[1])
if err != nil {
return err
}
c.HostnamePath = origContainer.HostnamePath
c.HostsPath = origContainer.HostsPath
c.ResolvConfPath = origContainer.ResolvConfPath
c.Config.Hostname = origContainer.Config.Hostname
c.Config.Domainname = origContainer.Config.Domainname
return nil
}
// initialise host network mode
if IsHost(networkMode) {
hostname, err := os.Hostname()
if err != nil {
return err
}
c.Config.Hostname = strfmt.Hostname(hostname)
}
// build the network related path.
if err := mgr.buildNetworkRelatedPath(c); err != nil {
return err
}
// network is prepared by upper system. do nothing here.
if IsNetNS(networkMode) {
return nil
}
// initialise network endpoint
if c.NetworkSettings == nil {
return nil
}
for name, endpointSetting := range c.NetworkSettings.Networks {
endpoint := mgr.buildContainerEndpoint(ctx, c, name)
endpoint.EndpointConfig = endpointSetting
if _, err := mgr.NetworkMgr.EndpointCreate(ctx, endpoint); err != nil {
log.With(ctx).Errorf("failed to create endpoint: %v", err)
return err
}
}
sb, err := mgr.NetworkMgr.Controller().SandboxByID(c.NetworkSettings.SandboxID)
if err != nil {
// sandbox not found, maybe caused by disconnect network or no endpoint
log.With(ctx).Warnf("failed to get sandbox by id(%s), err(%v)", c.NetworkSettings.SandboxID, err)
c.NetworkSettings.Ports = types.PortMap{}
return nil
}
c.NetworkSettings.Ports = getSandboxPortMapInfo(sb)
return nil
}
// buildNetworkRelatedPath builds the network related path.
func (mgr *ContainerManager) buildNetworkRelatedPath(c *Container) error {
// set the hosts file path.
c.HostsPath = path.Join(mgr.Store.Path(c.ID), "hosts")
// set the resolv.conf file path.
c.ResolvConfPath = path.Join(mgr.Store.Path(c.ID), "resolv.conf")
// set the hostname file path.
c.HostnamePath = path.Join(mgr.Store.Path(c.ID), "hostname")
// write the hostname file, other files are filled by libnetwork.
return ioutil.WriteFile(c.HostnamePath, []byte(c.Config.Hostname+"\n"), 0644)
}
func (mgr *ContainerManager) createContainerdContainer(ctx context.Context, c *Container, checkpointDir, checkpointID string) error {
// CgroupParent from HostConfig will be first priority to use,
// then will be value from mgr.Config.CgroupParent
if c.HostConfig.CgroupParent == "" {
c.HostConfig.CgroupParent = mgr.Config.CgroupParent
}
var (
err error
prioArr []int
argsArr [][]string
)
// if creating the container by specified the rootfs, we must check
// whether the rootfs is mounted before creation
if c.RootFSProvided {
if err := mgr.ensureRootFSMounted(c.BaseFS, c.Snapshotter.Data); err != nil {
return fmt.Errorf("failed to mount container rootfs: %v", err)
}
}
if mgr.containerPlugin != nil {
// TODO: make func PreStart with no data race
prioArr, argsArr, err = mgr.containerPlugin.PreStart(ctx, c)
if err != nil {
return errors.Wrapf(err, "get pre-start hook error from container plugin")
}
}
sw := &SpecWrapper{
ctrMgr: mgr,
volMgr: mgr.VolumeMgr,
netMgr: mgr.NetworkMgr,
prioArr: prioArr,
argsArr: argsArr,
useSystemd: mgr.Config.UseSystemd(),
}
if err = createSpec(ctx, c, sw); err != nil {
return err
}
// init log driver
if err := mgr.initLogDriverBeforeStart(c); err != nil {
return errors.Wrap(err, "failed to initialize log driver")
}
// set container's LogPath
mgr.SetContainerLogPath(c)
if c.HostConfig.RuntimeType == "" {
c.HostConfig.RuntimeType = ctrd.RuntimeTypeV1
}
runtimeOptions, err := mgr.generateRuntimeOptions(c.HostConfig.Runtime)
if err != nil {
return err
}
ctrdContainer := &ctrd.Container{
ID: c.ID,
Image: c.Config.Image,
Labels: c.Config.Labels,
RuntimeType: c.HostConfig.RuntimeType,
RuntimeOptions: runtimeOptions,
Spec: sw.s,
IO: mgr.IOs.Get(c.ID),
RootFSProvided: c.RootFSProvided,
BaseFS: c.BaseFS,
UseSystemd: mgr.Config.UseSystemd(),
}
// make sure the SnapshotID got a proper value
ctrdContainer.SnapshotID = c.SnapshotKey()
if checkpointID != "" {
checkpointDir, err = mgr.getCheckpointDir(c.ID, checkpointDir, checkpointID, false)
if err != nil {
return err
}
}
if err := mgr.Client.CreateContainer(ctx, ctrdContainer, checkpointDir); err != nil {
log.With(ctx).Errorf("failed to create new containerd container: %v", err)
// TODO(ziren): markStoppedAndRelease may failed
// we should clean resources of container when start failed
_ = mgr.markStoppedAndRelease(ctx, c, nil)
return err
}
// Create containerd container success.
pid, err := mgr.Client.ContainerPID(ctx, c.ID)
if err != nil {
return errors.Wrapf(err, "failed to get PID of container %s", c.ID)
}
c.SetStatusRunning(int64(pid))
// set Snapshot MergedDir
c.Snapshotter.Data["MergedDir"] = c.BaseFS
return c.Write(mgr.Store)
}
func (mgr *ContainerManager) ensureRootFSMounted(rootfs string, snapData map[string]string) error {
if rootfs == "" || len(snapData) == 0 {
return fmt.Errorf("container rootfs or snapshotter data is empty")
}
// check if rootfs already mounted
notMounted, err := mountutils.IsLikelyNotMountPoint(rootfs)
if err != nil {
return err
}
// rootfs already mounted
if !notMounted {
return nil
}
var workDir, upperDir, lowerDir string
for _, dir := range []string{"WorkDir", "UpperDir", "LowerDir"} {
if v, ok := snapData[dir]; ok {
switch dir {
case "WorkDir":
workDir = v
case "UpperDir":
upperDir = v
case "LowerDir":
lowerDir = v
}
}
}
if workDir == "" || upperDir == "" || lowerDir == "" {
return fmt.Errorf("faile to mount overlay: one or more dirs in WorkDir, UpperDir and LowerDir are empty")
}
options := []string{
fmt.Sprintf("workdir=%s", snapData["WorkDir"]),
fmt.Sprintf("upperdir=%s", snapData["UpperDir"]),
fmt.Sprintf("lowerdir=%s", snapData["LowerDir"]),
}
mount := mount.Mount{
Type: "overlay",
Source: "overlay",
Options: options,
}
return mount.Mount(rootfs)
}
// Stop stops a running container.
func (mgr *ContainerManager) Stop(ctx context.Context, name string, timeout int64) error {
c, err := mgr.container(name)
if err != nil {
return err
}
ctx = log.AddFields(ctx, map[string]interface{}{"ContainerID": c.ID})
// NOTE: choose snapshotter, snapshotter can only be set
// through containerPlugin in Create function
ctx = ctrd.WithSnapshotter(ctx, c.Config.Snapshotter)
err = mgr.stop(ctx, c, timeout)
if err != nil {
return err
}
mgr.LogContainerEvent(ctx, c, "stop")
return nil
}
func (mgr *ContainerManager) stop(ctx context.Context, c *Container, timeout int64) error {
c.Lock()
defer c.Unlock()
if !c.IsRunningOrPaused() {
// stopping a non-running container is valid.
return nil
}
if timeout == 0 {
timeout = c.StopTimeout()
}
id := c.ID
msg, err := mgr.Client.DestroyContainer(ctx, id, timeout)
if err != nil {
return errors.Wrapf(err, "failed to destroy container %s", id)
}
return mgr.markStoppedAndRelease(ctx, c, msg)
}
// Kill kills a running container.
func (mgr *ContainerManager) Kill(ctx context.Context, name string, signal int) (err error) {
c, err := mgr.container(name)
if err != nil {
return err
}
ctx = log.AddFields(ctx, map[string]interface{}{"ContainerID": c.ID})
// NOTE: choose snapshotter, snapshotter can only be set
// through containerPlugin in Create function
ctx = ctrd.WithSnapshotter(ctx, c.Config.Snapshotter)
err = mgr.kill(ctx, c, signal)
if err != nil {
return err
}
attributes := map[string]string{
"signal": fmt.Sprintf("%d", signal),
}
mgr.LogContainerEventWithAttributes(ctx, c, "kill", attributes)
return nil
}
func (mgr *ContainerManager) kill(ctx context.Context, c *Container, signal int) error {
logrus.Debugf("Sending signal %d to %s", signal, c.ID)