/
container_storage.go
936 lines (784 loc) · 23.8 KB
/
container_storage.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
package mgr
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"syscall"
"github.com/alibaba/pouch/apis/opts"
"github.com/alibaba/pouch/apis/types"
"github.com/alibaba/pouch/pkg/archive"
"github.com/alibaba/pouch/pkg/errtypes"
"github.com/alibaba/pouch/pkg/log"
"github.com/alibaba/pouch/pkg/randomid"
"github.com/alibaba/pouch/pkg/system"
"github.com/alibaba/pouch/storage/quota"
volumetypes "github.com/alibaba/pouch/storage/volume/types"
"github.com/containerd/containerd/mount"
"github.com/containerd/continuity/fs"
"github.com/pkg/errors"
)
func (mgr *ContainerManager) attachVolume(ctx context.Context, name string, c *Container) (string, string, error) {
driver := volumetypes.DefaultBackend
v, err := mgr.VolumeMgr.Get(ctx, name)
if err != nil || v == nil {
opts := map[string]string{
"backend": driver,
}
if _, err := mgr.VolumeMgr.Create(ctx, name, c.HostConfig.VolumeDriver, opts, nil); err != nil {
log.With(ctx).Errorf("failed to create volume(%s), err(%v)", name, err)
return "", "", errors.Wrap(err, "failed to create volume")
}
} else {
driver = v.Driver()
}
if _, err := mgr.VolumeMgr.Attach(ctx, name, map[string]string{volumetypes.OptionRef: c.ID}); err != nil {
log.With(ctx).Errorf("failed to attach volume(%s), err(%v)", name, err)
return "", "", errors.Wrap(err, "failed to attach volume")
}
mountPath, err := mgr.VolumeMgr.Path(ctx, name)
if err != nil {
log.With(ctx).Errorf("failed to get the mount path of volume(%s), err(%v)", name, err)
return "", "", errors.Wrap(err, "failed to get volume mount path")
}
return mountPath, driver, nil
}
func (mgr *ContainerManager) generateMountPoints(ctx context.Context, c *Container) error {
var err error
if c.Config.Volumes == nil {
c.Config.Volumes = make(map[string]interface{})
}
if c.Mounts == nil {
c.Mounts = make([]*types.MountPoint, 0)
}
// define a volume map to duplicate removal
volumeSet := map[string]struct{}{}
defer func() {
if err != nil {
if err := mgr.detachVolumes(ctx, c, false); err != nil {
log.With(ctx).Errorf("failed to detach volume, err(%v)", err)
}
}
}()
// 1. read MountPoints from other containers
err = mgr.getMountPointFromContainers(ctx, c, volumeSet)
if err != nil {
return errors.Wrap(err, "failed to get mount point from containers")
}
// 2. read MountPoints from binds
err = mgr.getMountPointFromBinds(ctx, c, volumeSet)
if err != nil {
return errors.Wrap(err, "failed to get mount point from binds")
}
// 3. read MountPoints from image
err = mgr.getMountPointFromImage(ctx, c, volumeSet)
if err != nil {
return errors.Wrap(err, "failed to get mount point from image")
}
// 4. read MountPoints from Config.Volumes
err = mgr.getMountPointFromVolumes(ctx, c, volumeSet)
if err != nil {
return errors.Wrap(err, "failed to get mount point from volumes")
}
// do filepath clean
for i := range c.Mounts {
m := c.Mounts[i]
m.Source = filepath.Clean(m.Source)
m.Destination = filepath.Clean(m.Destination)
}
return nil
}
func (mgr *ContainerManager) getMountPointFromBinds(ctx context.Context, c *Container, volumeSet map[string]struct{}) error {
var err error
log.With(ctx).Debugf("bind volumes(%v)", c.HostConfig.Binds)
// parse binds
for _, b := range c.HostConfig.Binds {
var parts []string
parts, err = opts.CheckBind(b)
if err != nil {
return err
}
mode := ""
mp := new(types.MountPoint)
switch len(parts) {
case 1:
mp.Source = ""
mp.Destination = parts[0]
case 2:
mp.Source = parts[0]
mp.Destination = parts[1]
mp.Named = true
case 3:
mp.Source = parts[0]
mp.Destination = parts[1]
mode = parts[2]
mp.Named = true
default:
return errors.Errorf("unknown bind(%s)", b)
}
if opts.CheckDuplicateMountPoint(c.Mounts, mp.Destination) {
log.With(ctx).Warnf("duplicate mountpoint(%s)", mp.Destination)
continue
}
if mp.Source == "" {
mp.Source = randomid.Generate()
}
err = opts.ParseBindMode(mp, mode)
if err != nil {
log.With(ctx).Errorf("failed to parse bind mode(%s), err(%v)", mode, err)
return err
}
if !path.IsAbs(mp.Source) {
// volume bind.
name := mp.Source
if _, exist := volumeSet[name]; !exist {
_, mp.Driver, err = mgr.attachVolume(ctx, name, c)
if err != nil {
log.With(ctx).Errorf("failed to bind volume(%s), err(%v)", name, err)
return errors.Wrap(err, "failed to bind volume")
}
volumeSet[name] = struct{}{}
}
volume, err := mgr.VolumeMgr.Get(ctx, name)
if err != nil || volume == nil {
log.With(ctx).Errorf("failed to get volume(%s), err(%v)", name, err)
return errors.Wrapf(err, "failed to get volume(%s)", name)
}
mp.Driver = volume.Driver()
mp.Name = name
mp.Source, err = mgr.VolumeMgr.Path(ctx, name)
if err != nil {
return err
}
if mp.Replace != "" {
switch mp.Replace {
case "dr":
mp.Source = path.Join(mp.Source, mp.Destination)
case "rr":
mp.Source = path.Join(mp.Source, randomid.Generate())
}
mp.Name = ""
mp.Named = false
mp.Driver = ""
}
} else {
mp.CopyData = false
}
c.Mounts = append(c.Mounts, mp)
}
return nil
}
func (mgr *ContainerManager) getMountPointFromVolumes(ctx context.Context, c *Container, volumeSet map[string]struct{}) error {
var err error
// parse volumes
for dest := range c.Config.Volumes {
if opts.CheckDuplicateMountPoint(c.Mounts, dest) {
log.With(ctx).Warnf("duplicate mountpoint(%s) from volumes", dest)
continue
}
// check if volume has been created
name := randomid.Generate()
if _, exist := volumeSet[name]; exist {
continue
}
mp := new(types.MountPoint)
mp.Name = name
mp.Destination = dest
mp.Source, mp.Driver, err = mgr.attachVolume(ctx, mp.Name, c)
if err != nil {
log.With(ctx).Errorf("failed to bind volume(%s), err(%v)", mp.Name, err)
return errors.Wrap(err, "failed to bind volume")
}
err = opts.ParseBindMode(mp, "")
if err != nil {
log.With(ctx).Errorf("failed to parse mode, err(%v)", err)
return err
}
volumeSet[mp.Name] = struct{}{}
c.Mounts = append(c.Mounts, mp)
}
return nil
}
func (mgr *ContainerManager) getMountPointFromImage(ctx context.Context, c *Container, volumeSet map[string]struct{}) error {
var err error
// parse volumes from image
image, err := mgr.ImageMgr.GetImage(ctx, c.Image)
if err != nil {
return errors.Wrapf(err, "failed to get image(%s)", c.Image)
}
for dest := range image.Config.Volumes {
// check if volume has been created
name := randomid.Generate()
if _, exist := volumeSet[name]; exist {
continue
}
if opts.CheckDuplicateMountPoint(c.Mounts, dest) {
log.With(ctx).Warnf("duplicate mountpoint(%s) from image", dest)
continue
}
mp := new(types.MountPoint)
mp.Name = name
mp.Destination = dest
mp.Source, mp.Driver, err = mgr.attachVolume(ctx, mp.Name, c)
if err != nil {
log.With(ctx).Errorf("failed to bind volume(%s), err(%v)", mp.Name, err)
return errors.Wrap(err, "failed to bind volume")
}
err = opts.ParseBindMode(mp, "")
if err != nil {
log.With(ctx).Errorf("failed to parse mode, err(%v)", err)
return err
}
volumeSet[mp.Name] = struct{}{}
c.Mounts = append(c.Mounts, mp)
}
return nil
}
func (mgr *ContainerManager) getMountPointFromContainers(ctx context.Context, container *Container, volumeSet map[string]struct{}) error {
var err error
// parse volumes from other containers
for _, v := range container.HostConfig.VolumesFrom {
var containerID, mode string
containerID, mode, err = opts.ParseVolumesFrom(v)
if err != nil {
return err
}
var oldContainer *Container
oldContainer, err = mgr.Get(ctx, containerID)
if err != nil {
return err
}
for _, oldMountPoint := range oldContainer.Mounts {
if opts.CheckDuplicateMountPoint(container.Mounts, oldMountPoint.Destination) {
log.With(ctx).Warnf("duplicate mount point %s on container %s", oldMountPoint.Destination, containerID)
continue
}
mp := &types.MountPoint{
Source: oldMountPoint.Source,
Destination: oldMountPoint.Destination,
Driver: oldMountPoint.Driver,
Named: oldMountPoint.Named,
Mode: oldMountPoint.Mode,
Replace: oldMountPoint.Replace,
Propagation: oldMountPoint.Propagation,
}
if _, exist := volumeSet[oldMountPoint.Name]; len(oldMountPoint.Name) > 0 && !exist {
mp.Name = oldMountPoint.Name
mp.Source, mp.Driver, err = mgr.attachVolume(ctx, oldMountPoint.Name, container)
if err != nil {
log.With(ctx).Errorf("failed to bind volume(%s), err(%v)", oldMountPoint.Name, err)
return errors.Wrap(err, "failed to bind volume")
}
volumeSet[mp.Name] = struct{}{}
}
err = opts.ParseBindMode(mp, mode)
if err != nil {
log.With(ctx).Errorf("failed to parse volumes-from mode(%s), err(%v)", mode, err)
return err
}
// if mode has no set rw mode, so need to inherit old mountpoint rw mode.
if !(strings.Contains(mode, "ro") || strings.Contains(mode, "rw")) {
mp.RW = oldMountPoint.RW
}
// if mode has no set copy mode, so need to inherit old mountpoint copy mode.
if !strings.Contains(mode, "nocopy") {
if !strings.Contains(oldMountPoint.Mode, "nocopy") {
mp.CopyData = true
} else {
mp.CopyData = false
}
}
container.Mounts = append(container.Mounts, mp)
}
}
return nil
}
func (mgr *ContainerManager) populateVolumes(ctx context.Context, c *Container, qms []*quota.QMap) error {
// sort mounts by destination directory string shortest length.
// the reason is: there are two mounts: /home/admin and /home/admin/log,
// when do copy data with dr mode, if the data of /home/admin/log is copied first,
// it will cause /home/admin don't copy data since the destination directory is not empty.
c.Mounts = sortMountPoint(c.Mounts)
for _, mp := range c.Mounts {
if mp.Driver == "tmpfs" {
continue
}
if !mp.CopyData {
continue
}
log.With(ctx).Debugf("copying image data from (%s:%s), to volume(%s) or path(%s)",
c.ID, mp.Destination, mp.Name, mp.Source)
imagePath, err := fs.RootPath(c.MountFS, mp.Destination)
if err != nil {
return fmt.Errorf("rootpath on mountPath %s, volume %s: %w", c.MountFS, mp.Destination, err)
}
err = copyImageContent(ctx, imagePath, mp.Source, qms)
if err != nil {
log.With(ctx).Errorf("failed to copy image contents, volume[imagepath(%s), source(%s)], err(%v)", imagePath, mp.Source, err)
return errors.Wrapf(err, "failed to copy image content, image(%s), host(%s)", imagePath, mp.Source)
}
}
for _, mp := range c.Mounts {
if _, err := os.Stat(mp.Source); err != nil {
// host directory bind into container.
if !os.IsNotExist(err) {
return errors.Wrapf(err, "failed to stat %q", mp.Source)
}
// Create the host path if it doesn't exist.
if err = os.MkdirAll(mp.Source, 0755); err != nil {
return errors.Wrapf(err, "failed to mkdir %q", mp.Source)
}
}
}
return nil
}
func (mgr *ContainerManager) setMountTab(ctx context.Context, c *Container) error {
log.With(ctx).Debugf("start to set mount tab into container")
if len(c.MountFS) == 0 {
return nil
}
// set rootfs mount tab
context := "/ / ext4 rw 0 0\n"
if rootID, e := system.GetDevID(c.MountFS); e == nil {
_, _, rootFsType := quota.CheckMountpoint(rootID)
if len(rootFsType) > 0 {
context = fmt.Sprintf("/ / %s rw 0 0\n", rootFsType)
}
}
// set mount point tab
i := 1
for _, m := range c.Mounts {
if m.Source == "" || m.Destination == "" {
continue
}
finfo, err := os.Stat(m.Source)
if err != nil || !finfo.IsDir() {
continue
}
tempLine := fmt.Sprintf("/dev/v%02dd %s ext4 rw 0 0\n", i, m.Destination)
if tmpID, e := system.GetDevID(m.Source); e == nil {
_, _, fsType := quota.CheckMountpoint(tmpID)
if len(fsType) > 0 {
tempLine = fmt.Sprintf("/dev/v%02dd %s %s rw 0 0\n", i, m.Destination, fsType)
}
}
i++
context += tempLine
}
// set shm mount tab
context += "shm /dev/shm tmpfs rw 0 0\n"
// save into mtab file.
mtabPath := filepath.Join(c.MountFS, "etc/mtab")
// make directory, $BaseFS/etc/
os.MkdirAll(path.Dir(mtabPath), 0755)
// remove it before modify
os.Remove(mtabPath)
err := ioutil.WriteFile(mtabPath, []byte(context), 0644)
if err != nil {
return errors.Wrapf(err, "failed to write file(%s)", mtabPath)
}
log.With(ctx).Infof("write mtab file to (%s)", mtabPath)
return nil
}
func (mgr *ContainerManager) getDiskQuotaMountPoints(ctx context.Context, c *Container, mounted bool) ([]*types.MountPoint, error) {
var mounts []*types.MountPoint
for _, mp := range c.Mounts {
// skip volume mount or replace mode mount
if mp.Replace != "" || mp.Source == "" || mp.Destination == "" {
log.With(ctx).Debugf("skip volume mount or replace mode mount")
continue
}
// skip volume that has set size
if mp.Name != "" {
v, err := mgr.VolumeMgr.Get(ctx, mp.Name)
if err != nil {
log.With(ctx).Warnf("failed to get volume(%s)", mp.Name)
continue
}
if v.Size() != "" {
log.With(ctx).Debugf("skip volume(%s) with size", mp.Name)
continue
}
}
// skip non-directory path.
if fd, err := os.Stat(mp.Source); err != nil || !fd.IsDir() {
log.With(ctx).Debugf("skip non-directory path(%s)", mp.Source)
continue
}
mounts = append(mounts, mp)
}
// add rootfs mountpoint
rootfs, err := mgr.getRootfs(ctx, c, mounted)
if err != nil {
return nil, errors.Wrapf(err, "failed to get rootfs")
}
mounts = append(mounts, &types.MountPoint{
Source: rootfs,
Destination: "/",
})
return mounts, nil
}
func (mgr *ContainerManager) prepareQuotaMap(ctx context.Context, c *Container, mounted bool) ([]*quota.QMap, error) {
// get default quota
var (
quotas = c.Config.DiskQuota
globalQuotaID uint32
)
if quota.IsSetQuotaID(c.Config.QuotaID) {
id, err := strconv.Atoi(c.Config.QuotaID)
if err != nil {
return nil, errors.Wrapf(err, "invalid argument, QuotaID(%s)", c.Config.QuotaID)
}
// if QuotaID is < 0, it means pouchd alloc a unique quota id.
if id < 0 {
globalQuotaID, err = quota.GetNextQuotaID()
if err != nil {
return nil, errors.Wrap(err, "failed to get next quota id")
}
// update QuotaID
c.Config.QuotaID = strconv.Itoa(int(globalQuotaID))
} else {
globalQuotaID = uint32(id)
}
}
// get mount points that can set disk quota.
mounts, err := mgr.getDiskQuotaMountPoints(ctx, c, mounted)
if err != nil {
return nil, errors.Wrap(err, "failed to get mount point that can set disk quota")
}
var qms []*quota.QMap
for _, mp := range mounts {
// get quota size
var (
found bool
qm *quota.QMap
)
for exp, size := range quotas {
if strings.Contains(exp, "&") {
for _, p := range strings.Split(exp, "&") {
if p == mp.Destination {
found = true
qm = "a.QMap{
Source: mp.Source,
Destination: mp.Destination,
Expression: exp,
Size: size,
}
break
}
}
} else {
re := regexp.MustCompile(exp)
findStr := re.FindString(mp.Destination)
if findStr == mp.Destination {
qm = "a.QMap{
Source: mp.Source,
Destination: mp.Destination,
Size: size,
}
if exp != ".*" {
break
}
}
}
if found {
break
}
}
if qm != nil {
// check duplicate quota map
prev := checkDupQuotaMap(qms, qm)
if prev == nil {
// get new quota id
id := globalQuotaID
if id == 0 {
id, err = quota.GetNextQuotaID()
if err != nil {
return nil, errors.Wrap(err, "failed to get next quota id")
}
}
qm.QuotaID = id
} else {
qm.QuotaID = prev.QuotaID
}
qms = append(qms, qm)
}
}
return qms, nil
}
func checkDupQuotaMap(qms []*quota.QMap, qm *quota.QMap) *quota.QMap {
for _, prev := range qms {
if qm.Expression != "" && qm.Expression == prev.Expression {
return prev
}
}
return nil
}
func (mgr *ContainerManager) setDiskQuota(ctx context.Context, c *Container, update bool, qms []*quota.QMap) error {
var (
err error
)
// make quota effective
for _, qm := range qms {
if qm.Destination == "/" {
// set rootfs quota
_, err = quota.SetRootfsDiskQuota(qm.Source, qm.Size, qm.QuotaID, update)
if err != nil {
log.With(ctx).Warnf("failed to set rootfs quota, mountfs(%s), size(%s), quota id(%d), err(%v)",
qm.Source, qm.Size, qm.QuotaID, err)
}
} else {
err := quota.SetDiskQuota(qm.Source, qm.Size, qm.QuotaID)
if err != nil {
log.With(ctx).Warnf("failed to set disk quota, directory(%s), size(%s), quota id(%d), err(%v)",
qm.Source, qm.Size, qm.QuotaID, err)
}
}
}
return nil
}
func (mgr *ContainerManager) detachVolumes(ctx context.Context, c *Container, remove bool) error {
for _, mount := range c.Mounts {
name := mount.Name
if name == "" {
continue
}
_, err := mgr.VolumeMgr.Detach(ctx, name, map[string]string{volumetypes.OptionRef: c.ID})
if err != nil {
log.With(ctx).Warnf("failed to detach volume(%s), err(%v)", name, err)
}
if remove && !mount.Named {
if err := mgr.VolumeMgr.Remove(ctx, name); err != nil && !errtypes.IsInUse(err) {
log.With(ctx).Warnf("failed to remove volume(%s) when remove container", name)
}
}
}
return nil
}
func (mgr *ContainerManager) attachVolumes(ctx context.Context, c *Container) (err0 error) {
rollbackVolumes := make([]string, 0, len(c.Mounts))
defer func() {
if err0 != nil {
for _, name := range rollbackVolumes {
if _, err := mgr.VolumeMgr.Detach(ctx, name, map[string]string{volumetypes.OptionRef: c.ID}); err != nil {
log.With(ctx).Warnf("[rollback] failed to detach volume(%s), err(%v)", name, err)
}
}
}
}()
for _, mount := range c.Mounts {
name := mount.Name
if name == "" {
continue
}
_, err := mgr.VolumeMgr.Attach(ctx, name, map[string]string{volumetypes.OptionRef: c.ID})
if err != nil {
log.With(ctx).Warnf("failed to attach volume(%s), err(%v)", name, err)
return err
}
rollbackVolumes = append(rollbackVolumes, name)
}
return nil
}
// setMountFS is used to set mountfs directory.
func (mgr *ContainerManager) setMountFS(ctx context.Context, c *Container) {
c.MountFS = path.Join(mgr.Store.Path(c.ID), "rootfs")
}
// Mount sets the container rootfs
func (mgr *ContainerManager) Mount(ctx context.Context, c *Container) error {
mounts, err := mgr.Client.GetMounts(ctx, c.ID)
if err != nil {
return err
} else if len(mounts) != 1 {
return fmt.Errorf("failed to get snapshot %s mounts: not equals 1", c.ID)
}
if c.MountFS == "" {
mgr.setMountFS(ctx, c)
}
err = os.MkdirAll(c.MountFS, 0755)
if err != nil && !os.IsExist(err) {
return err
}
return mounts[0].Mount(c.MountFS)
}
// Unmount unsets the container rootfs
// cleanup decides whether to clean up the dir or not
func (mgr *ContainerManager) Unmount(ctx context.Context, c *Container) error {
// TODO: if umount is failed, and how to deal it.
err := mount.Unmount(c.MountFS, 0)
if err != nil {
return errors.Wrapf(err, "failed to umount mountfs(%s)", c.MountFS)
}
return os.RemoveAll(c.MountFS)
}
func (mgr *ContainerManager) initContainerStorage(ctx context.Context, c *Container) (err error) {
if err = mgr.Mount(ctx, c); err != nil {
return errors.Wrapf(err, "failed to mount mountfs(%s)", c.MountFS)
}
defer func() {
if umountErr := mgr.Unmount(ctx, c); umountErr != nil {
if err != nil {
err = errors.Wrapf(err, "failed to umount rootfs(%s), err(%v)", c.MountFS, umountErr)
} else {
err = errors.Wrapf(umountErr, "failed to umount rootfs(%s)", c.MountFS)
}
}
}()
mounted := true
// parse volume config
if err = mgr.generateMountPoints(ctx, c); err != nil {
return errors.Wrap(err, "failed to parse volume argument")
}
// prepare quota map
qms, err := mgr.prepareQuotaMap(ctx, c, mounted)
if err != nil {
return errors.Wrap(err, "failed to prepare quota maps")
}
// populate the volumes
if err = mgr.populateVolumes(ctx, c, qms); err != nil {
return errors.Wrap(err, "failed to populate volumes")
}
// try to setup container working directory
if err := mgr.SetupWorkingDirectory(ctx, c); err != nil {
return errors.Wrapf(err, "failed to setup container %s working directory", c.ID)
}
// set mount point disk quota
if err = mgr.setDiskQuota(ctx, c, false, qms); err != nil {
// just ignore failed to set disk quota
log.With(ctx).Warnf("failed to set disk quota, err(%v)", err)
}
// set volumes into /etc/mtab in container
if err = mgr.setMountTab(ctx, c); err != nil {
return errors.Wrap(err, "failed to set mount tab")
}
return nil
}
// SetupWorkingDirectory setup working directory for container
func (mgr *ContainerManager) SetupWorkingDirectory(ctx context.Context, c *Container) error {
if c.Config.WorkingDir == "" {
return nil
}
if c.MountFS == "" {
mgr.setMountFS(ctx, c)
}
workingDir := filepath.Clean(c.Config.WorkingDir)
resourcePath := c.GetResourcePath(c.MountFS, workingDir)
// TODO(ziren): not care about File mode
err := os.MkdirAll(resourcePath, 0755)
if err != nil && !os.IsExist(err) {
return err
}
return nil
}
func (mgr *ContainerManager) getRootfs(ctx context.Context, c *Container, mounted bool) (string, error) {
var (
rootfs string
err error
)
if c.IsRunningOrPaused() && c.Snapshotter != nil {
basefs, ok := c.Snapshotter.Data["MergedDir"]
if !ok || basefs == "" {
return "", fmt.Errorf("container is running, but MergedDir is missing")
}
rootfs = basefs
} else if !mounted {
if err = mgr.Mount(ctx, c); err != nil {
return "", errors.Wrapf(err, "failed to mount mountfs: (%s)", c.MountFS)
}
rootfs = c.MountFS
defer func() {
if err = mgr.Unmount(ctx, c); err != nil {
log.With(ctx).Errorf("failed to umount mountfs: (%s), err: (%v)", c.MountFS, err)
}
}()
} else {
rootfs = c.MountFS
}
return rootfs, nil
}
func sortMountPoint(mounts []*types.MountPoint) []*types.MountPoint {
sort.Slice(mounts, func(i, j int) bool {
if len(mounts[i].Destination) < len(mounts[j].Destination) {
return true
}
return false
})
return mounts
}
func copyImageContent(ctx context.Context, source, destination string, qms []*quota.QMap) error {
fi, err := os.Stat(source)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
} else if !fi.IsDir() {
return nil
}
fi, err = os.Stat(destination)
if err != nil {
if !os.IsNotExist(err) {
return err
}
// destination directory is not exist, so mkdir for it.
log.With(ctx).Warnf("(%s) is not exist", destination)
if err := os.MkdirAll(destination, 0755); err != nil && !os.IsExist(err) {
return err
}
} else if !fi.IsDir() {
return nil
}
// first set quota on volume, then copy image content to volume, or file exist in image
// can not inherit quota
for _, qm := range qms {
if qm.Source == destination {
if err := quota.SetDiskQuota(qm.Source, qm.Size, qm.QuotaID); err != nil {
log.With(ctx).Warnf("failed to set disk quota, directory(%s), size(%s), quota id(%d), err(%v)",
qm.Source, qm.Size, qm.QuotaID, err)
}
}
}
return copyExistContents(ctx, source, destination)
}
func copyExistContents(ctx context.Context, source, destination string) error {
volList, err := ioutil.ReadDir(source)
if err != nil {
return err
}
if len(volList) > 0 {
dstList, err := ioutil.ReadDir(destination)
if err != nil {
return err
}
if len(dstList) == 0 {
log.With(ctx).Debugf("copy (%s) to (%s) with tar", source, destination)
err := archive.CopyWithTar(source, destination)
if err != nil {
log.With(ctx).Errorf("copyImageContent: %v", err)
return err
}
}
}
return copyOwnership(source, destination)
}
func copyOwnership(source, destination string) error {
fi, err := os.Stat(source)
if err != nil {
return err
}
sys, ok := fi.Sys().(*syscall.Stat_t)
if !ok {
return fmt.Errorf("failed to get file %s system info", source)
}
err = os.Chown(destination, int(sys.Uid), int(sys.Gid))
if err != nil {
return err
}
return os.Chmod(destination, os.FileMode(fi.Mode()))
}