configmap.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package configmap
  14. import (
  15. "fmt"
  16. "k8s.io/klog"
  17. "k8s.io/utils/mount"
  18. utilstrings "k8s.io/utils/strings"
  19. v1 "k8s.io/api/core/v1"
  20. "k8s.io/apimachinery/pkg/api/errors"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/types"
  23. "k8s.io/kubernetes/pkg/volume"
  24. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  25. )
  26. // ProbeVolumePlugins is the entry point for plugin detection in a package.
  27. func ProbeVolumePlugins() []volume.VolumePlugin {
  28. return []volume.VolumePlugin{&configMapPlugin{}}
  29. }
  30. const (
  31. configMapPluginName = "kubernetes.io/configmap"
  32. )
  33. // configMapPlugin implements the VolumePlugin interface.
  34. type configMapPlugin struct {
  35. host volume.VolumeHost
  36. getConfigMap func(namespace, name string) (*v1.ConfigMap, error)
  37. }
  38. var _ volume.VolumePlugin = &configMapPlugin{}
  39. func getPath(uid types.UID, volName string, host volume.VolumeHost) string {
  40. return host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(configMapPluginName), volName)
  41. }
  42. func (plugin *configMapPlugin) Init(host volume.VolumeHost) error {
  43. plugin.host = host
  44. plugin.getConfigMap = host.GetConfigMapFunc()
  45. return nil
  46. }
  47. func (plugin *configMapPlugin) GetPluginName() string {
  48. return configMapPluginName
  49. }
  50. func (plugin *configMapPlugin) GetVolumeName(spec *volume.Spec) (string, error) {
  51. volumeSource, _ := getVolumeSource(spec)
  52. if volumeSource == nil {
  53. return "", fmt.Errorf("Spec does not reference a ConfigMap volume type")
  54. }
  55. return fmt.Sprintf(
  56. "%v/%v",
  57. spec.Name(),
  58. volumeSource.Name), nil
  59. }
  60. func (plugin *configMapPlugin) CanSupport(spec *volume.Spec) bool {
  61. return spec.Volume != nil && spec.Volume.ConfigMap != nil
  62. }
  63. func (plugin *configMapPlugin) RequiresRemount() bool {
  64. return true
  65. }
  66. func (plugin *configMapPlugin) SupportsMountOption() bool {
  67. return false
  68. }
  69. func (plugin *configMapPlugin) SupportsBulkVolumeVerification() bool {
  70. return false
  71. }
  72. func (plugin *configMapPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {
  73. return &configMapVolumeMounter{
  74. configMapVolume: &configMapVolume{
  75. spec.Name(),
  76. pod.UID,
  77. plugin,
  78. plugin.host.GetMounter(plugin.GetPluginName()),
  79. volume.NewCachedMetrics(volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host))),
  80. },
  81. source: *spec.Volume.ConfigMap,
  82. pod: *pod,
  83. opts: &opts,
  84. getConfigMap: plugin.getConfigMap,
  85. }, nil
  86. }
  87. func (plugin *configMapPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
  88. return &configMapVolumeUnmounter{
  89. &configMapVolume{
  90. volName,
  91. podUID,
  92. plugin,
  93. plugin.host.GetMounter(plugin.GetPluginName()),
  94. volume.NewCachedMetrics(volume.NewMetricsDu(getPath(podUID, volName, plugin.host))),
  95. },
  96. }, nil
  97. }
  98. func (plugin *configMapPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
  99. configMapVolume := &v1.Volume{
  100. Name: volumeName,
  101. VolumeSource: v1.VolumeSource{
  102. ConfigMap: &v1.ConfigMapVolumeSource{},
  103. },
  104. }
  105. return volume.NewSpecFromVolume(configMapVolume), nil
  106. }
  107. type configMapVolume struct {
  108. volName string
  109. podUID types.UID
  110. plugin *configMapPlugin
  111. mounter mount.Interface
  112. volume.MetricsProvider
  113. }
  114. var _ volume.Volume = &configMapVolume{}
  115. func (sv *configMapVolume) GetPath() string {
  116. return sv.plugin.host.GetPodVolumeDir(sv.podUID, utilstrings.EscapeQualifiedName(configMapPluginName), sv.volName)
  117. }
  118. // configMapVolumeMounter handles retrieving secrets from the API server
  119. // and placing them into the volume on the host.
  120. type configMapVolumeMounter struct {
  121. *configMapVolume
  122. source v1.ConfigMapVolumeSource
  123. pod v1.Pod
  124. opts *volume.VolumeOptions
  125. getConfigMap func(namespace, name string) (*v1.ConfigMap, error)
  126. }
  127. var _ volume.Mounter = &configMapVolumeMounter{}
  128. func (sv *configMapVolume) GetAttributes() volume.Attributes {
  129. return volume.Attributes{
  130. ReadOnly: true,
  131. Managed: true,
  132. SupportsSELinux: true,
  133. }
  134. }
  135. func wrappedVolumeSpec() volume.Spec {
  136. // This is the spec for the volume that this plugin wraps.
  137. return volume.Spec{
  138. // This should be on a tmpfs instead of the local disk; the problem is
  139. // charging the memory for the tmpfs to the right cgroup. We should make
  140. // this a tmpfs when we can do the accounting correctly.
  141. Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}},
  142. }
  143. }
  144. // Checks prior to mount operations to verify that the required components (binaries, etc.)
  145. // to mount the volume are available on the underlying node.
  146. // If not, it returns an error
  147. func (b *configMapVolumeMounter) CanMount() error {
  148. return nil
  149. }
  150. func (b *configMapVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {
  151. return b.SetUpAt(b.GetPath(), mounterArgs)
  152. }
  153. func (b *configMapVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {
  154. klog.V(3).Infof("Setting up volume %v for pod %v at %v", b.volName, b.pod.UID, dir)
  155. // Wrap EmptyDir, let it do the setup.
  156. wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), &b.pod, *b.opts)
  157. if err != nil {
  158. return err
  159. }
  160. optional := b.source.Optional != nil && *b.source.Optional
  161. configMap, err := b.getConfigMap(b.pod.Namespace, b.source.Name)
  162. if err != nil {
  163. if !(errors.IsNotFound(err) && optional) {
  164. klog.Errorf("Couldn't get configMap %v/%v: %v", b.pod.Namespace, b.source.Name, err)
  165. return err
  166. }
  167. configMap = &v1.ConfigMap{
  168. ObjectMeta: metav1.ObjectMeta{
  169. Namespace: b.pod.Namespace,
  170. Name: b.source.Name,
  171. },
  172. }
  173. }
  174. totalBytes := totalBytes(configMap)
  175. klog.V(3).Infof("Received configMap %v/%v containing (%v) pieces of data, %v total bytes",
  176. b.pod.Namespace,
  177. b.source.Name,
  178. len(configMap.Data)+len(configMap.BinaryData),
  179. totalBytes)
  180. payload, err := MakePayload(b.source.Items, configMap, b.source.DefaultMode, optional)
  181. if err != nil {
  182. return err
  183. }
  184. setupSuccess := false
  185. if err := wrapped.SetUpAt(dir, mounterArgs); err != nil {
  186. return err
  187. }
  188. if err := volumeutil.MakeNestedMountpoints(b.volName, dir, b.pod); err != nil {
  189. return err
  190. }
  191. defer func() {
  192. // Clean up directories if setup fails
  193. if !setupSuccess {
  194. unmounter, unmountCreateErr := b.plugin.NewUnmounter(b.volName, b.podUID)
  195. if unmountCreateErr != nil {
  196. klog.Errorf("error cleaning up mount %s after failure. Create unmounter failed with %v", b.volName, unmountCreateErr)
  197. return
  198. }
  199. tearDownErr := unmounter.TearDown()
  200. if tearDownErr != nil {
  201. klog.Errorf("Error tearing down volume %s with : %v", b.volName, tearDownErr)
  202. }
  203. }
  204. }()
  205. writerContext := fmt.Sprintf("pod %v/%v volume %v", b.pod.Namespace, b.pod.Name, b.volName)
  206. writer, err := volumeutil.NewAtomicWriter(dir, writerContext)
  207. if err != nil {
  208. klog.Errorf("Error creating atomic writer: %v", err)
  209. return err
  210. }
  211. err = writer.Write(payload)
  212. if err != nil {
  213. klog.Errorf("Error writing payload to dir: %v", err)
  214. return err
  215. }
  216. err = volume.SetVolumeOwnership(b, mounterArgs.FsGroup)
  217. if err != nil {
  218. klog.Errorf("Error applying volume ownership settings for group: %v", mounterArgs.FsGroup)
  219. return err
  220. }
  221. setupSuccess = true
  222. return nil
  223. }
  224. // MakePayload function is exported so that it can be called from the projection volume driver
  225. func MakePayload(mappings []v1.KeyToPath, configMap *v1.ConfigMap, defaultMode *int32, optional bool) (map[string]volumeutil.FileProjection, error) {
  226. if defaultMode == nil {
  227. return nil, fmt.Errorf("No defaultMode used, not even the default value for it")
  228. }
  229. payload := make(map[string]volumeutil.FileProjection, (len(configMap.Data) + len(configMap.BinaryData)))
  230. var fileProjection volumeutil.FileProjection
  231. if len(mappings) == 0 {
  232. for name, data := range configMap.Data {
  233. fileProjection.Data = []byte(data)
  234. fileProjection.Mode = *defaultMode
  235. payload[name] = fileProjection
  236. }
  237. for name, data := range configMap.BinaryData {
  238. fileProjection.Data = data
  239. fileProjection.Mode = *defaultMode
  240. payload[name] = fileProjection
  241. }
  242. } else {
  243. for _, ktp := range mappings {
  244. if stringData, ok := configMap.Data[ktp.Key]; ok {
  245. fileProjection.Data = []byte(stringData)
  246. } else if binaryData, ok := configMap.BinaryData[ktp.Key]; ok {
  247. fileProjection.Data = binaryData
  248. } else {
  249. if optional {
  250. continue
  251. }
  252. return nil, fmt.Errorf("configmap references non-existent config key: %s", ktp.Key)
  253. }
  254. if ktp.Mode != nil {
  255. fileProjection.Mode = *ktp.Mode
  256. } else {
  257. fileProjection.Mode = *defaultMode
  258. }
  259. payload[ktp.Path] = fileProjection
  260. }
  261. }
  262. return payload, nil
  263. }
  264. func totalBytes(configMap *v1.ConfigMap) int {
  265. totalSize := 0
  266. for _, value := range configMap.Data {
  267. totalSize += len(value)
  268. }
  269. for _, value := range configMap.BinaryData {
  270. totalSize += len(value)
  271. }
  272. return totalSize
  273. }
  274. // configMapVolumeUnmounter handles cleaning up configMap volumes.
  275. type configMapVolumeUnmounter struct {
  276. *configMapVolume
  277. }
  278. var _ volume.Unmounter = &configMapVolumeUnmounter{}
  279. func (c *configMapVolumeUnmounter) TearDown() error {
  280. return c.TearDownAt(c.GetPath())
  281. }
  282. func (c *configMapVolumeUnmounter) TearDownAt(dir string) error {
  283. return volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)
  284. }
  285. func getVolumeSource(spec *volume.Spec) (*v1.ConfigMapVolumeSource, bool) {
  286. var readOnly bool
  287. var volumeSource *v1.ConfigMapVolumeSource
  288. if spec.Volume != nil && spec.Volume.ConfigMap != nil {
  289. volumeSource = spec.Volume.ConfigMap
  290. readOnly = spec.ReadOnly
  291. }
  292. return volumeSource, readOnly
  293. }