configmap.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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/api/core/v1"
  17. "k8s.io/apimachinery/pkg/api/errors"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/apimachinery/pkg/types"
  20. "k8s.io/klog"
  21. "k8s.io/kubernetes/pkg/util/mount"
  22. "k8s.io/kubernetes/pkg/volume"
  23. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  24. utilstrings "k8s.io/utils/strings"
  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) IsMigratedToCSI() bool {
  64. return false
  65. }
  66. func (plugin *configMapPlugin) RequiresRemount() bool {
  67. return true
  68. }
  69. func (plugin *configMapPlugin) SupportsMountOption() bool {
  70. return false
  71. }
  72. func (plugin *configMapPlugin) SupportsBulkVolumeVerification() bool {
  73. return false
  74. }
  75. func (plugin *configMapPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {
  76. return &configMapVolumeMounter{
  77. configMapVolume: &configMapVolume{
  78. spec.Name(),
  79. pod.UID,
  80. plugin,
  81. plugin.host.GetMounter(plugin.GetPluginName()),
  82. volume.NewCachedMetrics(volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host))),
  83. },
  84. source: *spec.Volume.ConfigMap,
  85. pod: *pod,
  86. opts: &opts,
  87. getConfigMap: plugin.getConfigMap,
  88. }, nil
  89. }
  90. func (plugin *configMapPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
  91. return &configMapVolumeUnmounter{
  92. &configMapVolume{
  93. volName,
  94. podUID,
  95. plugin,
  96. plugin.host.GetMounter(plugin.GetPluginName()),
  97. volume.NewCachedMetrics(volume.NewMetricsDu(getPath(podUID, volName, plugin.host))),
  98. },
  99. }, nil
  100. }
  101. func (plugin *configMapPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
  102. configMapVolume := &v1.Volume{
  103. Name: volumeName,
  104. VolumeSource: v1.VolumeSource{
  105. ConfigMap: &v1.ConfigMapVolumeSource{},
  106. },
  107. }
  108. return volume.NewSpecFromVolume(configMapVolume), nil
  109. }
  110. type configMapVolume struct {
  111. volName string
  112. podUID types.UID
  113. plugin *configMapPlugin
  114. mounter mount.Interface
  115. volume.MetricsProvider
  116. }
  117. var _ volume.Volume = &configMapVolume{}
  118. func (sv *configMapVolume) GetPath() string {
  119. return sv.plugin.host.GetPodVolumeDir(sv.podUID, utilstrings.EscapeQualifiedName(configMapPluginName), sv.volName)
  120. }
  121. // configMapVolumeMounter handles retrieving secrets from the API server
  122. // and placing them into the volume on the host.
  123. type configMapVolumeMounter struct {
  124. *configMapVolume
  125. source v1.ConfigMapVolumeSource
  126. pod v1.Pod
  127. opts *volume.VolumeOptions
  128. getConfigMap func(namespace, name string) (*v1.ConfigMap, error)
  129. }
  130. var _ volume.Mounter = &configMapVolumeMounter{}
  131. func (sv *configMapVolume) GetAttributes() volume.Attributes {
  132. return volume.Attributes{
  133. ReadOnly: true,
  134. Managed: true,
  135. SupportsSELinux: true,
  136. }
  137. }
  138. func wrappedVolumeSpec() volume.Spec {
  139. // This is the spec for the volume that this plugin wraps.
  140. return volume.Spec{
  141. // This should be on a tmpfs instead of the local disk; the problem is
  142. // charging the memory for the tmpfs to the right cgroup. We should make
  143. // this a tmpfs when we can do the accounting correctly.
  144. Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}},
  145. }
  146. }
  147. // Checks prior to mount operations to verify that the required components (binaries, etc.)
  148. // to mount the volume are available on the underlying node.
  149. // If not, it returns an error
  150. func (b *configMapVolumeMounter) CanMount() error {
  151. return nil
  152. }
  153. func (b *configMapVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {
  154. return b.SetUpAt(b.GetPath(), mounterArgs)
  155. }
  156. func (b *configMapVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {
  157. klog.V(3).Infof("Setting up volume %v for pod %v at %v", b.volName, b.pod.UID, dir)
  158. // Wrap EmptyDir, let it do the setup.
  159. wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), &b.pod, *b.opts)
  160. if err != nil {
  161. return err
  162. }
  163. optional := b.source.Optional != nil && *b.source.Optional
  164. configMap, err := b.getConfigMap(b.pod.Namespace, b.source.Name)
  165. if err != nil {
  166. if !(errors.IsNotFound(err) && optional) {
  167. klog.Errorf("Couldn't get configMap %v/%v: %v", b.pod.Namespace, b.source.Name, err)
  168. return err
  169. }
  170. configMap = &v1.ConfigMap{
  171. ObjectMeta: metav1.ObjectMeta{
  172. Namespace: b.pod.Namespace,
  173. Name: b.source.Name,
  174. },
  175. }
  176. }
  177. totalBytes := totalBytes(configMap)
  178. klog.V(3).Infof("Received configMap %v/%v containing (%v) pieces of data, %v total bytes",
  179. b.pod.Namespace,
  180. b.source.Name,
  181. len(configMap.Data)+len(configMap.BinaryData),
  182. totalBytes)
  183. payload, err := MakePayload(b.source.Items, configMap, b.source.DefaultMode, optional)
  184. if err != nil {
  185. return err
  186. }
  187. setupSuccess := false
  188. if err := wrapped.SetUpAt(dir, mounterArgs); err != nil {
  189. return err
  190. }
  191. if err := volumeutil.MakeNestedMountpoints(b.volName, dir, b.pod); err != nil {
  192. return err
  193. }
  194. defer func() {
  195. // Clean up directories if setup fails
  196. if !setupSuccess {
  197. unmounter, unmountCreateErr := b.plugin.NewUnmounter(b.volName, b.podUID)
  198. if unmountCreateErr != nil {
  199. klog.Errorf("error cleaning up mount %s after failure. Create unmounter failed with %v", b.volName, unmountCreateErr)
  200. return
  201. }
  202. tearDownErr := unmounter.TearDown()
  203. if tearDownErr != nil {
  204. klog.Errorf("Error tearing down volume %s with : %v", b.volName, tearDownErr)
  205. }
  206. }
  207. }()
  208. writerContext := fmt.Sprintf("pod %v/%v volume %v", b.pod.Namespace, b.pod.Name, b.volName)
  209. writer, err := volumeutil.NewAtomicWriter(dir, writerContext)
  210. if err != nil {
  211. klog.Errorf("Error creating atomic writer: %v", err)
  212. return err
  213. }
  214. err = writer.Write(payload)
  215. if err != nil {
  216. klog.Errorf("Error writing payload to dir: %v", err)
  217. return err
  218. }
  219. err = volume.SetVolumeOwnership(b, mounterArgs.FsGroup)
  220. if err != nil {
  221. klog.Errorf("Error applying volume ownership settings for group: %v", mounterArgs.FsGroup)
  222. return err
  223. }
  224. setupSuccess = true
  225. return nil
  226. }
  227. // MakePayload function is exported so that it can be called from the projection volume driver
  228. func MakePayload(mappings []v1.KeyToPath, configMap *v1.ConfigMap, defaultMode *int32, optional bool) (map[string]volumeutil.FileProjection, error) {
  229. if defaultMode == nil {
  230. return nil, fmt.Errorf("No defaultMode used, not even the default value for it")
  231. }
  232. payload := make(map[string]volumeutil.FileProjection, (len(configMap.Data) + len(configMap.BinaryData)))
  233. var fileProjection volumeutil.FileProjection
  234. if len(mappings) == 0 {
  235. for name, data := range configMap.Data {
  236. fileProjection.Data = []byte(data)
  237. fileProjection.Mode = *defaultMode
  238. payload[name] = fileProjection
  239. }
  240. for name, data := range configMap.BinaryData {
  241. fileProjection.Data = data
  242. fileProjection.Mode = *defaultMode
  243. payload[name] = fileProjection
  244. }
  245. } else {
  246. for _, ktp := range mappings {
  247. if stringData, ok := configMap.Data[ktp.Key]; ok {
  248. fileProjection.Data = []byte(stringData)
  249. } else if binaryData, ok := configMap.BinaryData[ktp.Key]; ok {
  250. fileProjection.Data = binaryData
  251. } else {
  252. if optional {
  253. continue
  254. }
  255. return nil, fmt.Errorf("configmap references non-existent config key: %s", ktp.Key)
  256. }
  257. if ktp.Mode != nil {
  258. fileProjection.Mode = *ktp.Mode
  259. } else {
  260. fileProjection.Mode = *defaultMode
  261. }
  262. payload[ktp.Path] = fileProjection
  263. }
  264. }
  265. return payload, nil
  266. }
  267. func totalBytes(configMap *v1.ConfigMap) int {
  268. totalSize := 0
  269. for _, value := range configMap.Data {
  270. totalSize += len(value)
  271. }
  272. for _, value := range configMap.BinaryData {
  273. totalSize += len(value)
  274. }
  275. return totalSize
  276. }
  277. // configMapVolumeUnmounter handles cleaning up configMap volumes.
  278. type configMapVolumeUnmounter struct {
  279. *configMapVolume
  280. }
  281. var _ volume.Unmounter = &configMapVolumeUnmounter{}
  282. func (c *configMapVolumeUnmounter) TearDown() error {
  283. return c.TearDownAt(c.GetPath())
  284. }
  285. func (c *configMapVolumeUnmounter) TearDownAt(dir string) error {
  286. return volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)
  287. }
  288. func getVolumeSource(spec *volume.Spec) (*v1.ConfigMapVolumeSource, bool) {
  289. var readOnly bool
  290. var volumeSource *v1.ConfigMapVolumeSource
  291. if spec.Volume != nil && spec.Volume.ConfigMap != nil {
  292. volumeSource = spec.Volume.ConfigMap
  293. readOnly = spec.ReadOnly
  294. }
  295. return volumeSource, readOnly
  296. }