downwardapi.go 10 KB

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