...
1
16
17 package util
18
19 import (
20 "fmt"
21 "os"
22 "path/filepath"
23 "sort"
24 "strings"
25
26 v1 "k8s.io/api/core/v1"
27 podutil "k8s.io/kubernetes/pkg/api/v1/pod"
28 )
29
30
31
32
33 func getNestedMountpoints(name, baseDir string, pod v1.Pod) ([]string, error) {
34 var retval []string
35 checkContainer := func(container *v1.Container) error {
36 var allMountPoints []string
37 var myMountPoints []string
38 for _, vol := range container.VolumeMounts {
39 cleaned := filepath.Clean(vol.MountPath)
40 allMountPoints = append(allMountPoints, cleaned)
41 if vol.Name == name {
42 myMountPoints = append(myMountPoints, cleaned)
43 }
44 }
45 sort.Strings(allMountPoints)
46 parentPrefix := ".." + string(os.PathSeparator)
47
48 for _, myMountPoint := range myMountPoints {
49 if strings.HasPrefix(myMountPoint, parentPrefix) {
50
51 return fmt.Errorf("invalid container mount point %v", myMountPoint)
52 }
53 myMPSlash := myMountPoint + string(os.PathSeparator)
54
55
56
57
58
59
60
61 prevNestedMPs := []string{}
62
63
64
65
66 for _, mp := range allMountPoints {
67 if !strings.HasPrefix(mp, myMPSlash) {
68 continue
69 }
70
71 isNested := false
72 for _, prevNestedMP := range prevNestedMPs {
73 if strings.HasPrefix(mp, prevNestedMP) {
74 isNested = true
75 break
76 }
77 }
78 if isNested {
79 continue
80 }
81
82 prevNestedMPs = append(prevNestedMPs, mp+string(os.PathSeparator))
83 retval = append(retval, mp[len(myMPSlash):])
84 }
85 }
86 return nil
87 }
88
89 var retErr error
90 podutil.VisitContainers(&pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *v1.Container, containerType podutil.ContainerType) bool {
91 retErr = checkContainer(c)
92 return retErr == nil
93 })
94 if retErr != nil {
95 return nil, retErr
96 }
97
98 return retval, nil
99 }
100
101
102 func MakeNestedMountpoints(name, baseDir string, pod v1.Pod) error {
103 dirs, err := getNestedMountpoints(name, baseDir, pod)
104 if err != nil {
105 return err
106 }
107 for _, dir := range dirs {
108 err := os.MkdirAll(filepath.Join(baseDir, dir), 0755)
109 if err != nil {
110 return fmt.Errorf("unable to create nested volume mountpoints: %v", err)
111 }
112 }
113 return nil
114 }
115
View as plain text