PageRenderTime 29ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/pkg/volume/host_path/host_path.go

https://gitlab.com/unofficial-mirrors/kubernetes
Go | 456 lines | 350 code | 64 blank | 42 comment | 59 complexity | aac4158b1ecfd07c82f83c0fdbfe5b55 MD5 | raw file
  1. /*
  2. Copyright 2014 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 host_path
  14. import (
  15. "fmt"
  16. "os"
  17. "regexp"
  18. "k8s.io/api/core/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/types"
  21. "k8s.io/apimachinery/pkg/util/uuid"
  22. "k8s.io/kubernetes/pkg/util/mount"
  23. "k8s.io/kubernetes/pkg/volume"
  24. "k8s.io/kubernetes/pkg/volume/util"
  25. "k8s.io/kubernetes/pkg/volume/util/recyclerclient"
  26. "k8s.io/kubernetes/pkg/volume/validation"
  27. )
  28. // This is the primary entrypoint for volume plugins.
  29. // The volumeConfig arg provides the ability to configure volume behavior. It is implemented as a pointer to allow nils.
  30. // The hostPathPlugin is used to store the volumeConfig and give it, when needed, to the func that Recycles.
  31. // Tests that exercise recycling should not use this func but instead use ProbeRecyclablePlugins() to override default behavior.
  32. func ProbeVolumePlugins(volumeConfig volume.VolumeConfig) []volume.VolumePlugin {
  33. return []volume.VolumePlugin{
  34. &hostPathPlugin{
  35. host: nil,
  36. config: volumeConfig,
  37. },
  38. }
  39. }
  40. type hostPathPlugin struct {
  41. host volume.VolumeHost
  42. config volume.VolumeConfig
  43. }
  44. var _ volume.VolumePlugin = &hostPathPlugin{}
  45. var _ volume.PersistentVolumePlugin = &hostPathPlugin{}
  46. var _ volume.RecyclableVolumePlugin = &hostPathPlugin{}
  47. var _ volume.DeletableVolumePlugin = &hostPathPlugin{}
  48. var _ volume.ProvisionableVolumePlugin = &hostPathPlugin{}
  49. const (
  50. hostPathPluginName = "kubernetes.io/host-path"
  51. )
  52. func (plugin *hostPathPlugin) Init(host volume.VolumeHost) error {
  53. plugin.host = host
  54. return nil
  55. }
  56. func (plugin *hostPathPlugin) GetPluginName() string {
  57. return hostPathPluginName
  58. }
  59. func (plugin *hostPathPlugin) GetVolumeName(spec *volume.Spec) (string, error) {
  60. volumeSource, _, err := getVolumeSource(spec)
  61. if err != nil {
  62. return "", err
  63. }
  64. return volumeSource.Path, nil
  65. }
  66. func (plugin *hostPathPlugin) CanSupport(spec *volume.Spec) bool {
  67. return (spec.PersistentVolume != nil && spec.PersistentVolume.Spec.HostPath != nil) ||
  68. (spec.Volume != nil && spec.Volume.HostPath != nil)
  69. }
  70. func (plugin *hostPathPlugin) RequiresRemount() bool {
  71. return false
  72. }
  73. func (plugin *hostPathPlugin) SupportsMountOption() bool {
  74. return false
  75. }
  76. func (plugin *hostPathPlugin) SupportsBulkVolumeVerification() bool {
  77. return false
  78. }
  79. func (plugin *hostPathPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {
  80. return []v1.PersistentVolumeAccessMode{
  81. v1.ReadWriteOnce,
  82. }
  83. }
  84. func (plugin *hostPathPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {
  85. hostPathVolumeSource, readOnly, err := getVolumeSource(spec)
  86. if err != nil {
  87. return nil, err
  88. }
  89. path := hostPathVolumeSource.Path
  90. pathType := new(v1.HostPathType)
  91. if hostPathVolumeSource.Type == nil {
  92. *pathType = v1.HostPathUnset
  93. } else {
  94. pathType = hostPathVolumeSource.Type
  95. }
  96. return &hostPathMounter{
  97. hostPath: &hostPath{path: path, pathType: pathType},
  98. readOnly: readOnly,
  99. mounter: plugin.host.GetMounter(plugin.GetPluginName()),
  100. }, nil
  101. }
  102. func (plugin *hostPathPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
  103. return &hostPathUnmounter{&hostPath{
  104. path: "",
  105. }}, nil
  106. }
  107. // Recycle recycles/scrubs clean a HostPath volume.
  108. // Recycle blocks until the pod has completed or any error occurs.
  109. // HostPath recycling only works in single node clusters and is meant for testing purposes only.
  110. func (plugin *hostPathPlugin) Recycle(pvName string, spec *volume.Spec, eventRecorder recyclerclient.RecycleEventRecorder) error {
  111. if spec.PersistentVolume == nil || spec.PersistentVolume.Spec.HostPath == nil {
  112. return fmt.Errorf("spec.PersistentVolumeSource.HostPath is nil")
  113. }
  114. pod := plugin.config.RecyclerPodTemplate
  115. timeout := util.CalculateTimeoutForVolume(plugin.config.RecyclerMinimumTimeout, plugin.config.RecyclerTimeoutIncrement, spec.PersistentVolume)
  116. // overrides
  117. pod.Spec.ActiveDeadlineSeconds = &timeout
  118. pod.Spec.Volumes[0].VolumeSource = v1.VolumeSource{
  119. HostPath: &v1.HostPathVolumeSource{
  120. Path: spec.PersistentVolume.Spec.HostPath.Path,
  121. },
  122. }
  123. return recyclerclient.RecycleVolumeByWatchingPodUntilCompletion(pvName, pod, plugin.host.GetKubeClient(), eventRecorder)
  124. }
  125. func (plugin *hostPathPlugin) NewDeleter(spec *volume.Spec) (volume.Deleter, error) {
  126. return newDeleter(spec, plugin.host)
  127. }
  128. func (plugin *hostPathPlugin) NewProvisioner(options volume.VolumeOptions) (volume.Provisioner, error) {
  129. if !plugin.config.ProvisioningEnabled {
  130. return nil, fmt.Errorf("Provisioning in volume plugin %q is disabled", plugin.GetPluginName())
  131. }
  132. return newProvisioner(options, plugin.host, plugin)
  133. }
  134. func (plugin *hostPathPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
  135. hostPathVolume := &v1.Volume{
  136. Name: volumeName,
  137. VolumeSource: v1.VolumeSource{
  138. HostPath: &v1.HostPathVolumeSource{
  139. Path: volumeName,
  140. },
  141. },
  142. }
  143. return volume.NewSpecFromVolume(hostPathVolume), nil
  144. }
  145. func newDeleter(spec *volume.Spec, host volume.VolumeHost) (volume.Deleter, error) {
  146. if spec.PersistentVolume != nil && spec.PersistentVolume.Spec.HostPath == nil {
  147. return nil, fmt.Errorf("spec.PersistentVolumeSource.HostPath is nil")
  148. }
  149. path := spec.PersistentVolume.Spec.HostPath.Path
  150. return &hostPathDeleter{name: spec.Name(), path: path, host: host}, nil
  151. }
  152. func newProvisioner(options volume.VolumeOptions, host volume.VolumeHost, plugin *hostPathPlugin) (volume.Provisioner, error) {
  153. return &hostPathProvisioner{options: options, host: host, plugin: plugin}, nil
  154. }
  155. // HostPath volumes represent a bare host file or directory mount.
  156. // The direct at the specified path will be directly exposed to the container.
  157. type hostPath struct {
  158. path string
  159. pathType *v1.HostPathType
  160. volume.MetricsNil
  161. }
  162. func (hp *hostPath) GetPath() string {
  163. return hp.path
  164. }
  165. type hostPathMounter struct {
  166. *hostPath
  167. readOnly bool
  168. mounter mount.Interface
  169. }
  170. var _ volume.Mounter = &hostPathMounter{}
  171. func (b *hostPathMounter) GetAttributes() volume.Attributes {
  172. return volume.Attributes{
  173. ReadOnly: b.readOnly,
  174. Managed: false,
  175. SupportsSELinux: false,
  176. }
  177. }
  178. // Checks prior to mount operations to verify that the required components (binaries, etc.)
  179. // to mount the volume are available on the underlying node.
  180. // If not, it returns an error
  181. func (b *hostPathMounter) CanMount() error {
  182. return nil
  183. }
  184. // SetUp does nothing.
  185. func (b *hostPathMounter) SetUp(fsGroup *int64) error {
  186. err := validation.ValidatePathNoBacksteps(b.GetPath())
  187. if err != nil {
  188. return fmt.Errorf("invalid HostPath `%s`: %v", b.GetPath(), err)
  189. }
  190. if *b.pathType == v1.HostPathUnset {
  191. return nil
  192. }
  193. return checkType(b.GetPath(), b.pathType, b.mounter)
  194. }
  195. // SetUpAt does not make sense for host paths - probably programmer error.
  196. func (b *hostPathMounter) SetUpAt(dir string, fsGroup *int64) error {
  197. return fmt.Errorf("SetUpAt() does not make sense for host paths")
  198. }
  199. func (b *hostPathMounter) GetPath() string {
  200. return b.path
  201. }
  202. type hostPathUnmounter struct {
  203. *hostPath
  204. }
  205. var _ volume.Unmounter = &hostPathUnmounter{}
  206. // TearDown does nothing.
  207. func (c *hostPathUnmounter) TearDown() error {
  208. return nil
  209. }
  210. // TearDownAt does not make sense for host paths - probably programmer error.
  211. func (c *hostPathUnmounter) TearDownAt(dir string) error {
  212. return fmt.Errorf("TearDownAt() does not make sense for host paths")
  213. }
  214. // hostPathProvisioner implements a Provisioner for the HostPath plugin
  215. // This implementation is meant for testing only and only works in a single node cluster.
  216. type hostPathProvisioner struct {
  217. host volume.VolumeHost
  218. options volume.VolumeOptions
  219. plugin *hostPathPlugin
  220. }
  221. // Create for hostPath simply creates a local /tmp/hostpath_pv/%s directory as a new PersistentVolume.
  222. // This Provisioner is meant for development and testing only and WILL NOT WORK in a multi-node cluster.
  223. func (r *hostPathProvisioner) Provision() (*v1.PersistentVolume, error) {
  224. fullpath := fmt.Sprintf("/tmp/hostpath_pv/%s", uuid.NewUUID())
  225. capacity := r.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
  226. pv := &v1.PersistentVolume{
  227. ObjectMeta: metav1.ObjectMeta{
  228. Name: r.options.PVName,
  229. Annotations: map[string]string{
  230. util.VolumeDynamicallyCreatedByKey: "hostpath-dynamic-provisioner",
  231. },
  232. },
  233. Spec: v1.PersistentVolumeSpec{
  234. PersistentVolumeReclaimPolicy: r.options.PersistentVolumeReclaimPolicy,
  235. AccessModes: r.options.PVC.Spec.AccessModes,
  236. Capacity: v1.ResourceList{
  237. v1.ResourceName(v1.ResourceStorage): capacity,
  238. },
  239. PersistentVolumeSource: v1.PersistentVolumeSource{
  240. HostPath: &v1.HostPathVolumeSource{
  241. Path: fullpath,
  242. },
  243. },
  244. },
  245. }
  246. if len(r.options.PVC.Spec.AccessModes) == 0 {
  247. pv.Spec.AccessModes = r.plugin.GetAccessModes()
  248. }
  249. return pv, os.MkdirAll(pv.Spec.HostPath.Path, 0750)
  250. }
  251. // hostPathDeleter deletes a hostPath PV from the cluster.
  252. // This deleter only works on a single host cluster and is for testing purposes only.
  253. type hostPathDeleter struct {
  254. name string
  255. path string
  256. host volume.VolumeHost
  257. volume.MetricsNil
  258. }
  259. func (r *hostPathDeleter) GetPath() string {
  260. return r.path
  261. }
  262. // Delete for hostPath removes the local directory so long as it is beneath /tmp/*.
  263. // THIS IS FOR TESTING AND LOCAL DEVELOPMENT ONLY! This message should scare you away from using
  264. // this deleter for anything other than development and testing.
  265. func (r *hostPathDeleter) Delete() error {
  266. regexp := regexp.MustCompile("/tmp/.+")
  267. if !regexp.MatchString(r.GetPath()) {
  268. return fmt.Errorf("host_path deleter only supports /tmp/.+ but received provided %s", r.GetPath())
  269. }
  270. return os.RemoveAll(r.GetPath())
  271. }
  272. func getVolumeSource(spec *volume.Spec) (*v1.HostPathVolumeSource, bool, error) {
  273. if spec.Volume != nil && spec.Volume.HostPath != nil {
  274. return spec.Volume.HostPath, spec.ReadOnly, nil
  275. } else if spec.PersistentVolume != nil &&
  276. spec.PersistentVolume.Spec.HostPath != nil {
  277. return spec.PersistentVolume.Spec.HostPath, spec.ReadOnly, nil
  278. }
  279. return nil, false, fmt.Errorf("Spec does not reference an HostPath volume type")
  280. }
  281. type hostPathTypeChecker interface {
  282. Exists() bool
  283. IsFile() bool
  284. MakeFile() error
  285. IsDir() bool
  286. MakeDir() error
  287. IsBlock() bool
  288. IsChar() bool
  289. IsSocket() bool
  290. GetPath() string
  291. }
  292. type fileTypeChecker struct {
  293. path string
  294. exists bool
  295. mounter mount.Interface
  296. }
  297. func (ftc *fileTypeChecker) Exists() bool {
  298. return ftc.mounter.ExistsPath(ftc.path)
  299. }
  300. func (ftc *fileTypeChecker) IsFile() bool {
  301. if !ftc.Exists() {
  302. return false
  303. }
  304. return !ftc.IsDir()
  305. }
  306. func (ftc *fileTypeChecker) MakeFile() error {
  307. return ftc.mounter.MakeFile(ftc.path)
  308. }
  309. func (ftc *fileTypeChecker) IsDir() bool {
  310. if !ftc.Exists() {
  311. return false
  312. }
  313. pathType, err := ftc.mounter.GetFileType(ftc.path)
  314. if err != nil {
  315. return false
  316. }
  317. return string(pathType) == string(v1.HostPathDirectory)
  318. }
  319. func (ftc *fileTypeChecker) MakeDir() error {
  320. return ftc.mounter.MakeDir(ftc.path)
  321. }
  322. func (ftc *fileTypeChecker) IsBlock() bool {
  323. blkDevType, err := ftc.mounter.GetFileType(ftc.path)
  324. if err != nil {
  325. return false
  326. }
  327. return string(blkDevType) == string(v1.HostPathBlockDev)
  328. }
  329. func (ftc *fileTypeChecker) IsChar() bool {
  330. charDevType, err := ftc.mounter.GetFileType(ftc.path)
  331. if err != nil {
  332. return false
  333. }
  334. return string(charDevType) == string(v1.HostPathCharDev)
  335. }
  336. func (ftc *fileTypeChecker) IsSocket() bool {
  337. socketType, err := ftc.mounter.GetFileType(ftc.path)
  338. if err != nil {
  339. return false
  340. }
  341. return string(socketType) == string(v1.HostPathSocket)
  342. }
  343. func (ftc *fileTypeChecker) GetPath() string {
  344. return ftc.path
  345. }
  346. func newFileTypeChecker(path string, mounter mount.Interface) hostPathTypeChecker {
  347. return &fileTypeChecker{path: path, mounter: mounter}
  348. }
  349. // checkType checks whether the given path is the exact pathType
  350. func checkType(path string, pathType *v1.HostPathType, mounter mount.Interface) error {
  351. return checkTypeInternal(newFileTypeChecker(path, mounter), pathType)
  352. }
  353. func checkTypeInternal(ftc hostPathTypeChecker, pathType *v1.HostPathType) error {
  354. switch *pathType {
  355. case v1.HostPathDirectoryOrCreate:
  356. if !ftc.Exists() {
  357. return ftc.MakeDir()
  358. }
  359. fallthrough
  360. case v1.HostPathDirectory:
  361. if !ftc.IsDir() {
  362. return fmt.Errorf("hostPath type check failed: %s is not a directory", ftc.GetPath())
  363. }
  364. case v1.HostPathFileOrCreate:
  365. if !ftc.Exists() {
  366. return ftc.MakeFile()
  367. }
  368. fallthrough
  369. case v1.HostPathFile:
  370. if !ftc.IsFile() {
  371. return fmt.Errorf("hostPath type check failed: %s is not a file", ftc.GetPath())
  372. }
  373. case v1.HostPathSocket:
  374. if !ftc.IsSocket() {
  375. return fmt.Errorf("hostPath type check failed: %s is not a socket file", ftc.GetPath())
  376. }
  377. case v1.HostPathCharDev:
  378. if !ftc.IsChar() {
  379. return fmt.Errorf("hostPath type check failed: %s is not a character device", ftc.GetPath())
  380. }
  381. case v1.HostPathBlockDev:
  382. if !ftc.IsBlock() {
  383. return fmt.Errorf("hostPath type check failed: %s is not a block device", ftc.GetPath())
  384. }
  385. default:
  386. return fmt.Errorf("%s is an invalid volume type", *pathType)
  387. }
  388. return nil
  389. }