PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/pkg/volume/host_path/host_path.go

https://bitbucket.org/Jake-Qu/kubernetes-mirror
Go | 461 lines | 354 code | 65 blank | 42 comment | 62 complexity | 0434d182489b524541f97320e975b3e9 MD5 | raw file
Possible License(s): MIT, MPL-2.0-no-copyleft-exception, 0BSD, CC0-1.0, BSD-2-Clause, Apache-2.0, BSD-3-Clause
  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. if util.CheckPersistentVolumeClaimModeBlock(r.options.PVC) {
  225. return nil, fmt.Errorf("%s does not support block volume provisioning", r.plugin.GetPluginName())
  226. }
  227. fullpath := fmt.Sprintf("/tmp/hostpath_pv/%s", uuid.NewUUID())
  228. capacity := r.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
  229. pv := &v1.PersistentVolume{
  230. ObjectMeta: metav1.ObjectMeta{
  231. Name: r.options.PVName,
  232. Annotations: map[string]string{
  233. util.VolumeDynamicallyCreatedByKey: "hostpath-dynamic-provisioner",
  234. },
  235. },
  236. Spec: v1.PersistentVolumeSpec{
  237. PersistentVolumeReclaimPolicy: r.options.PersistentVolumeReclaimPolicy,
  238. AccessModes: r.options.PVC.Spec.AccessModes,
  239. Capacity: v1.ResourceList{
  240. v1.ResourceName(v1.ResourceStorage): capacity,
  241. },
  242. PersistentVolumeSource: v1.PersistentVolumeSource{
  243. HostPath: &v1.HostPathVolumeSource{
  244. Path: fullpath,
  245. },
  246. },
  247. },
  248. }
  249. if len(r.options.PVC.Spec.AccessModes) == 0 {
  250. pv.Spec.AccessModes = r.plugin.GetAccessModes()
  251. }
  252. return pv, os.MkdirAll(pv.Spec.HostPath.Path, 0750)
  253. }
  254. // hostPathDeleter deletes a hostPath PV from the cluster.
  255. // This deleter only works on a single host cluster and is for testing purposes only.
  256. type hostPathDeleter struct {
  257. name string
  258. path string
  259. host volume.VolumeHost
  260. volume.MetricsNil
  261. }
  262. func (r *hostPathDeleter) GetPath() string {
  263. return r.path
  264. }
  265. // Delete for hostPath removes the local directory so long as it is beneath /tmp/*.
  266. // THIS IS FOR TESTING AND LOCAL DEVELOPMENT ONLY! This message should scare you away from using
  267. // this deleter for anything other than development and testing.
  268. func (r *hostPathDeleter) Delete() error {
  269. regexp := regexp.MustCompile("/tmp/.+")
  270. if !regexp.MatchString(r.GetPath()) {
  271. return fmt.Errorf("host_path deleter only supports /tmp/.+ but received provided %s", r.GetPath())
  272. }
  273. return os.RemoveAll(r.GetPath())
  274. }
  275. func getVolumeSource(spec *volume.Spec) (*v1.HostPathVolumeSource, bool, error) {
  276. if spec.Volume != nil && spec.Volume.HostPath != nil {
  277. return spec.Volume.HostPath, spec.ReadOnly, nil
  278. } else if spec.PersistentVolume != nil &&
  279. spec.PersistentVolume.Spec.HostPath != nil {
  280. return spec.PersistentVolume.Spec.HostPath, spec.ReadOnly, nil
  281. }
  282. return nil, false, fmt.Errorf("Spec does not reference an HostPath volume type")
  283. }
  284. type hostPathTypeChecker interface {
  285. Exists() bool
  286. IsFile() bool
  287. MakeFile() error
  288. IsDir() bool
  289. MakeDir() error
  290. IsBlock() bool
  291. IsChar() bool
  292. IsSocket() bool
  293. GetPath() string
  294. }
  295. type fileTypeChecker struct {
  296. path string
  297. exists bool
  298. mounter mount.Interface
  299. }
  300. func (ftc *fileTypeChecker) Exists() bool {
  301. exists, err := ftc.mounter.ExistsPath(ftc.path)
  302. return exists && err == nil
  303. }
  304. func (ftc *fileTypeChecker) IsFile() bool {
  305. if !ftc.Exists() {
  306. return false
  307. }
  308. return !ftc.IsDir()
  309. }
  310. func (ftc *fileTypeChecker) MakeFile() error {
  311. return ftc.mounter.MakeFile(ftc.path)
  312. }
  313. func (ftc *fileTypeChecker) IsDir() bool {
  314. if !ftc.Exists() {
  315. return false
  316. }
  317. pathType, err := ftc.mounter.GetFileType(ftc.path)
  318. if err != nil {
  319. return false
  320. }
  321. return string(pathType) == string(v1.HostPathDirectory)
  322. }
  323. func (ftc *fileTypeChecker) MakeDir() error {
  324. return ftc.mounter.MakeDir(ftc.path)
  325. }
  326. func (ftc *fileTypeChecker) IsBlock() bool {
  327. blkDevType, err := ftc.mounter.GetFileType(ftc.path)
  328. if err != nil {
  329. return false
  330. }
  331. return string(blkDevType) == string(v1.HostPathBlockDev)
  332. }
  333. func (ftc *fileTypeChecker) IsChar() bool {
  334. charDevType, err := ftc.mounter.GetFileType(ftc.path)
  335. if err != nil {
  336. return false
  337. }
  338. return string(charDevType) == string(v1.HostPathCharDev)
  339. }
  340. func (ftc *fileTypeChecker) IsSocket() bool {
  341. socketType, err := ftc.mounter.GetFileType(ftc.path)
  342. if err != nil {
  343. return false
  344. }
  345. return string(socketType) == string(v1.HostPathSocket)
  346. }
  347. func (ftc *fileTypeChecker) GetPath() string {
  348. return ftc.path
  349. }
  350. func newFileTypeChecker(path string, mounter mount.Interface) hostPathTypeChecker {
  351. return &fileTypeChecker{path: path, mounter: mounter}
  352. }
  353. // checkType checks whether the given path is the exact pathType
  354. func checkType(path string, pathType *v1.HostPathType, mounter mount.Interface) error {
  355. return checkTypeInternal(newFileTypeChecker(path, mounter), pathType)
  356. }
  357. func checkTypeInternal(ftc hostPathTypeChecker, pathType *v1.HostPathType) error {
  358. switch *pathType {
  359. case v1.HostPathDirectoryOrCreate:
  360. if !ftc.Exists() {
  361. return ftc.MakeDir()
  362. }
  363. fallthrough
  364. case v1.HostPathDirectory:
  365. if !ftc.IsDir() {
  366. return fmt.Errorf("hostPath type check failed: %s is not a directory", ftc.GetPath())
  367. }
  368. case v1.HostPathFileOrCreate:
  369. if !ftc.Exists() {
  370. return ftc.MakeFile()
  371. }
  372. fallthrough
  373. case v1.HostPathFile:
  374. if !ftc.IsFile() {
  375. return fmt.Errorf("hostPath type check failed: %s is not a file", ftc.GetPath())
  376. }
  377. case v1.HostPathSocket:
  378. if !ftc.IsSocket() {
  379. return fmt.Errorf("hostPath type check failed: %s is not a socket file", ftc.GetPath())
  380. }
  381. case v1.HostPathCharDev:
  382. if !ftc.IsChar() {
  383. return fmt.Errorf("hostPath type check failed: %s is not a character device", ftc.GetPath())
  384. }
  385. case v1.HostPathBlockDev:
  386. if !ftc.IsBlock() {
  387. return fmt.Errorf("hostPath type check failed: %s is not a block device", ftc.GetPath())
  388. }
  389. default:
  390. return fmt.Errorf("%s is an invalid volume type", *pathType)
  391. }
  392. return nil
  393. }