downwardapi.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 downwardapi
  14. import (
  15. "fmt"
  16. "path/filepath"
  17. "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/types"
  19. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  20. "k8s.io/klog"
  21. "k8s.io/kubernetes/pkg/api/v1/resource"
  22. "k8s.io/kubernetes/pkg/fieldpath"
  23. "k8s.io/kubernetes/pkg/volume"
  24. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  25. utilstrings "k8s.io/utils/strings"
  26. )
  27. // ProbeVolumePlugins is the entry point for plugin detection in a package.
  28. func ProbeVolumePlugins() []volume.VolumePlugin {
  29. return []volume.VolumePlugin{&downwardAPIPlugin{}}
  30. }
  31. const (
  32. downwardAPIPluginName = "kubernetes.io/downward-api"
  33. )
  34. // downwardAPIPlugin implements the VolumePlugin interface.
  35. type downwardAPIPlugin struct {
  36. host volume.VolumeHost
  37. }
  38. var _ volume.VolumePlugin = &downwardAPIPlugin{}
  39. func getPath(uid types.UID, volName string, host volume.VolumeHost) string {
  40. return host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(downwardAPIPluginName), volName)
  41. }
  42. func wrappedVolumeSpec() volume.Spec {
  43. return volume.Spec{
  44. Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}}},
  45. }
  46. }
  47. func (plugin *downwardAPIPlugin) Init(host volume.VolumeHost) error {
  48. plugin.host = host
  49. return nil
  50. }
  51. func (plugin *downwardAPIPlugin) GetPluginName() string {
  52. return downwardAPIPluginName
  53. }
  54. func (plugin *downwardAPIPlugin) GetVolumeName(spec *volume.Spec) (string, error) {
  55. volumeSource, _ := getVolumeSource(spec)
  56. if volumeSource == nil {
  57. return "", fmt.Errorf("Spec does not reference a DownwardAPI volume type")
  58. }
  59. // Return user defined volume name, since this is an ephemeral volume type
  60. return spec.Name(), nil
  61. }
  62. func (plugin *downwardAPIPlugin) CanSupport(spec *volume.Spec) bool {
  63. return spec.Volume != nil && spec.Volume.DownwardAPI != nil
  64. }
  65. func (plugin *downwardAPIPlugin) RequiresRemount() bool {
  66. return true
  67. }
  68. func (plugin *downwardAPIPlugin) SupportsMountOption() bool {
  69. return false
  70. }
  71. func (plugin *downwardAPIPlugin) SupportsBulkVolumeVerification() bool {
  72. return false
  73. }
  74. func (plugin *downwardAPIPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {
  75. v := &downwardAPIVolume{
  76. volName: spec.Name(),
  77. items: spec.Volume.DownwardAPI.Items,
  78. pod: pod,
  79. podUID: pod.UID,
  80. plugin: plugin,
  81. MetricsProvider: volume.NewCachedMetrics(volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host))),
  82. }
  83. return &downwardAPIVolumeMounter{
  84. downwardAPIVolume: v,
  85. source: *spec.Volume.DownwardAPI,
  86. opts: &opts,
  87. }, nil
  88. }
  89. func (plugin *downwardAPIPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
  90. return &downwardAPIVolumeUnmounter{
  91. &downwardAPIVolume{
  92. volName: volName,
  93. podUID: podUID,
  94. plugin: plugin,
  95. MetricsProvider: volume.NewCachedMetrics(volume.NewMetricsDu(getPath(podUID, volName, plugin.host))),
  96. },
  97. }, nil
  98. }
  99. func (plugin *downwardAPIPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
  100. downwardAPIVolume := &v1.Volume{
  101. Name: volumeName,
  102. VolumeSource: v1.VolumeSource{
  103. DownwardAPI: &v1.DownwardAPIVolumeSource{},
  104. },
  105. }
  106. return volume.NewSpecFromVolume(downwardAPIVolume), nil
  107. }
  108. // downwardAPIVolume retrieves downward API data and placing them into the volume on the host.
  109. type downwardAPIVolume struct {
  110. volName string
  111. items []v1.DownwardAPIVolumeFile
  112. pod *v1.Pod
  113. podUID types.UID // TODO: remove this redundancy as soon NewUnmounter func will have *v1.POD and not only types.UID
  114. plugin *downwardAPIPlugin
  115. volume.MetricsProvider
  116. }
  117. // downwardAPIVolumeMounter fetches info from downward API from the pod
  118. // and dumps it in files
  119. type downwardAPIVolumeMounter struct {
  120. *downwardAPIVolume
  121. source v1.DownwardAPIVolumeSource
  122. opts *volume.VolumeOptions
  123. }
  124. // downwardAPIVolumeMounter implements volume.Mounter interface
  125. var _ volume.Mounter = &downwardAPIVolumeMounter{}
  126. // downward API volumes are always ReadOnlyManaged
  127. func (d *downwardAPIVolume) GetAttributes() volume.Attributes {
  128. return volume.Attributes{
  129. ReadOnly: true,
  130. Managed: true,
  131. SupportsSELinux: true,
  132. }
  133. }
  134. // Checks prior to mount operations to verify that the required components (binaries, etc.)
  135. // to mount the volume are available on the underlying node.
  136. // If not, it returns an error
  137. func (b *downwardAPIVolumeMounter) CanMount() error {
  138. return nil
  139. }
  140. // SetUp puts in place the volume plugin.
  141. // This function is not idempotent by design. We want the data to be refreshed periodically.
  142. // The internal sync interval of kubelet will drive the refresh of data.
  143. // TODO: Add volume specific ticker and refresh loop
  144. func (b *downwardAPIVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {
  145. return b.SetUpAt(b.GetPath(), mounterArgs)
  146. }
  147. func (b *downwardAPIVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {
  148. klog.V(3).Infof("Setting up a downwardAPI volume %v for pod %v/%v at %v", b.volName, b.pod.Namespace, b.pod.Name, dir)
  149. // Wrap EmptyDir. Here we rely on the idempotency of the wrapped plugin to avoid repeatedly mounting
  150. wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), b.pod, *b.opts)
  151. if err != nil {
  152. klog.Errorf("Couldn't setup downwardAPI volume %v for pod %v/%v: %s", b.volName, b.pod.Namespace, b.pod.Name, err.Error())
  153. return err
  154. }
  155. data, err := CollectData(b.source.Items, b.pod, b.plugin.host, b.source.DefaultMode)
  156. if err != nil {
  157. klog.Errorf("Error preparing data for downwardAPI volume %v for pod %v/%v: %s", b.volName, b.pod.Namespace, b.pod.Name, err.Error())
  158. return err
  159. }
  160. setupSuccess := false
  161. if err := wrapped.SetUpAt(dir, mounterArgs); err != nil {
  162. klog.Errorf("Unable to setup downwardAPI volume %v for pod %v/%v: %s", b.volName, b.pod.Namespace, b.pod.Name, err.Error())
  163. return err
  164. }
  165. if err := volumeutil.MakeNestedMountpoints(b.volName, dir, *b.pod); err != nil {
  166. return err
  167. }
  168. defer func() {
  169. // Clean up directories if setup fails
  170. if !setupSuccess {
  171. unmounter, unmountCreateErr := b.plugin.NewUnmounter(b.volName, b.podUID)
  172. if unmountCreateErr != nil {
  173. klog.Errorf("error cleaning up mount %s after failure. Create unmounter failed with %v", b.volName, unmountCreateErr)
  174. return
  175. }
  176. tearDownErr := unmounter.TearDown()
  177. if tearDownErr != nil {
  178. klog.Errorf("error tearing down volume %s with : %v", b.volName, tearDownErr)
  179. }
  180. }
  181. }()
  182. writerContext := fmt.Sprintf("pod %v/%v volume %v", b.pod.Namespace, b.pod.Name, b.volName)
  183. writer, err := volumeutil.NewAtomicWriter(dir, writerContext)
  184. if err != nil {
  185. klog.Errorf("Error creating atomic writer: %v", err)
  186. return err
  187. }
  188. err = writer.Write(data)
  189. if err != nil {
  190. klog.Errorf("Error writing payload to dir: %v", err)
  191. return err
  192. }
  193. err = volume.SetVolumeOwnership(b, mounterArgs.FsGroup)
  194. if err != nil {
  195. klog.Errorf("Error applying volume ownership settings for group: %v", mounterArgs.FsGroup)
  196. return err
  197. }
  198. setupSuccess = true
  199. return nil
  200. }
  201. // CollectData collects requested downwardAPI in data map.
  202. // Map's key is the requested name of file to dump
  203. // Map's value is the (sorted) content of the field to be dumped in the file.
  204. //
  205. // Note: this function is exported so that it can be called from the projection volume driver
  206. func CollectData(items []v1.DownwardAPIVolumeFile, pod *v1.Pod, host volume.VolumeHost, defaultMode *int32) (map[string]volumeutil.FileProjection, error) {
  207. if defaultMode == nil {
  208. return nil, fmt.Errorf("No defaultMode used, not even the default value for it")
  209. }
  210. errlist := []error{}
  211. data := make(map[string]volumeutil.FileProjection)
  212. for _, fileInfo := range items {
  213. var fileProjection volumeutil.FileProjection
  214. fPath := filepath.Clean(fileInfo.Path)
  215. if fileInfo.Mode != nil {
  216. fileProjection.Mode = *fileInfo.Mode
  217. } else {
  218. fileProjection.Mode = *defaultMode
  219. }
  220. if fileInfo.FieldRef != nil {
  221. // TODO: unify with Kubelet.podFieldSelectorRuntimeValue
  222. if values, err := fieldpath.ExtractFieldPathAsString(pod, fileInfo.FieldRef.FieldPath); err != nil {
  223. klog.Errorf("Unable to extract field %s: %s", fileInfo.FieldRef.FieldPath, err.Error())
  224. errlist = append(errlist, err)
  225. } else {
  226. fileProjection.Data = []byte(values)
  227. }
  228. } else if fileInfo.ResourceFieldRef != nil {
  229. containerName := fileInfo.ResourceFieldRef.ContainerName
  230. nodeAllocatable, err := host.GetNodeAllocatable()
  231. if err != nil {
  232. errlist = append(errlist, err)
  233. } else if values, err := resource.ExtractResourceValueByContainerNameAndNodeAllocatable(fileInfo.ResourceFieldRef, pod, containerName, nodeAllocatable); err != nil {
  234. klog.Errorf("Unable to extract field %s: %s", fileInfo.ResourceFieldRef.Resource, err.Error())
  235. errlist = append(errlist, err)
  236. } else {
  237. fileProjection.Data = []byte(values)
  238. }
  239. }
  240. data[fPath] = fileProjection
  241. }
  242. return data, utilerrors.NewAggregate(errlist)
  243. }
  244. func (d *downwardAPIVolume) GetPath() string {
  245. return d.plugin.host.GetPodVolumeDir(d.podUID, utilstrings.EscapeQualifiedName(downwardAPIPluginName), d.volName)
  246. }
  247. // downwardAPIVolumeCleaner handles cleaning up downwardAPI volumes
  248. type downwardAPIVolumeUnmounter struct {
  249. *downwardAPIVolume
  250. }
  251. // downwardAPIVolumeUnmounter implements volume.Unmounter interface
  252. var _ volume.Unmounter = &downwardAPIVolumeUnmounter{}
  253. func (c *downwardAPIVolumeUnmounter) TearDown() error {
  254. return c.TearDownAt(c.GetPath())
  255. }
  256. func (c *downwardAPIVolumeUnmounter) TearDownAt(dir string) error {
  257. return volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)
  258. }
  259. func getVolumeSource(spec *volume.Spec) (*v1.DownwardAPIVolumeSource, bool) {
  260. var readOnly bool
  261. var volumeSource *v1.DownwardAPIVolumeSource
  262. if spec.Volume != nil && spec.Volume.DownwardAPI != nil {
  263. volumeSource = spec.Volume.DownwardAPI
  264. readOnly = spec.ReadOnly
  265. }
  266. return volumeSource, readOnly
  267. }