host_path.go 14 KB

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