git_repo.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 git_repo
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "path/filepath"
  18. "strings"
  19. "k8s.io/api/core/v1"
  20. "k8s.io/apimachinery/pkg/types"
  21. "k8s.io/kubernetes/pkg/volume"
  22. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  23. "k8s.io/utils/exec"
  24. utilstrings "k8s.io/utils/strings"
  25. )
  26. // This is the primary entrypoint for volume plugins.
  27. func ProbeVolumePlugins() []volume.VolumePlugin {
  28. return []volume.VolumePlugin{&gitRepoPlugin{nil}}
  29. }
  30. type gitRepoPlugin struct {
  31. host volume.VolumeHost
  32. }
  33. var _ volume.VolumePlugin = &gitRepoPlugin{}
  34. func wrappedVolumeSpec() volume.Spec {
  35. return volume.Spec{
  36. Volume: &v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}},
  37. }
  38. }
  39. const (
  40. gitRepoPluginName = "kubernetes.io/git-repo"
  41. )
  42. func (plugin *gitRepoPlugin) Init(host volume.VolumeHost) error {
  43. plugin.host = host
  44. return nil
  45. }
  46. func (plugin *gitRepoPlugin) GetPluginName() string {
  47. return gitRepoPluginName
  48. }
  49. func (plugin *gitRepoPlugin) GetVolumeName(spec *volume.Spec) (string, error) {
  50. volumeSource, _ := getVolumeSource(spec)
  51. if volumeSource == nil {
  52. return "", fmt.Errorf("Spec does not reference a Git repo volume type")
  53. }
  54. return fmt.Sprintf(
  55. "%v:%v:%v",
  56. volumeSource.Repository,
  57. volumeSource.Revision,
  58. volumeSource.Directory), nil
  59. }
  60. func (plugin *gitRepoPlugin) CanSupport(spec *volume.Spec) bool {
  61. return spec.Volume != nil && spec.Volume.GitRepo != nil
  62. }
  63. func (plugin *gitRepoPlugin) RequiresRemount() bool {
  64. return false
  65. }
  66. func (plugin *gitRepoPlugin) SupportsMountOption() bool {
  67. return false
  68. }
  69. func (plugin *gitRepoPlugin) SupportsBulkVolumeVerification() bool {
  70. return false
  71. }
  72. func (plugin *gitRepoPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {
  73. if err := validateVolume(spec.Volume.GitRepo); err != nil {
  74. return nil, err
  75. }
  76. return &gitRepoVolumeMounter{
  77. gitRepoVolume: &gitRepoVolume{
  78. volName: spec.Name(),
  79. podUID: pod.UID,
  80. plugin: plugin,
  81. },
  82. pod: *pod,
  83. source: spec.Volume.GitRepo.Repository,
  84. revision: spec.Volume.GitRepo.Revision,
  85. target: spec.Volume.GitRepo.Directory,
  86. exec: exec.New(),
  87. opts: opts,
  88. }, nil
  89. }
  90. func (plugin *gitRepoPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
  91. return &gitRepoVolumeUnmounter{
  92. &gitRepoVolume{
  93. volName: volName,
  94. podUID: podUID,
  95. plugin: plugin,
  96. },
  97. }, nil
  98. }
  99. func (plugin *gitRepoPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
  100. gitVolume := &v1.Volume{
  101. Name: volumeName,
  102. VolumeSource: v1.VolumeSource{
  103. GitRepo: &v1.GitRepoVolumeSource{},
  104. },
  105. }
  106. return volume.NewSpecFromVolume(gitVolume), nil
  107. }
  108. // gitRepo volumes are directories which are pre-filled from a git repository.
  109. // These do not persist beyond the lifetime of a pod.
  110. type gitRepoVolume struct {
  111. volName string
  112. podUID types.UID
  113. plugin *gitRepoPlugin
  114. volume.MetricsNil
  115. }
  116. var _ volume.Volume = &gitRepoVolume{}
  117. func (gr *gitRepoVolume) GetPath() string {
  118. name := gitRepoPluginName
  119. return gr.plugin.host.GetPodVolumeDir(gr.podUID, utilstrings.EscapeQualifiedName(name), gr.volName)
  120. }
  121. // gitRepoVolumeMounter builds git repo volumes.
  122. type gitRepoVolumeMounter struct {
  123. *gitRepoVolume
  124. pod v1.Pod
  125. source string
  126. revision string
  127. target string
  128. exec exec.Interface
  129. opts volume.VolumeOptions
  130. }
  131. var _ volume.Mounter = &gitRepoVolumeMounter{}
  132. func (b *gitRepoVolumeMounter) GetAttributes() volume.Attributes {
  133. return volume.Attributes{
  134. ReadOnly: false,
  135. Managed: true,
  136. SupportsSELinux: true, // xattr change should be okay, TODO: double check
  137. }
  138. }
  139. // Checks prior to mount operations to verify that the required components (binaries, etc.)
  140. // to mount the volume are available on the underlying node.
  141. // If not, it returns an error
  142. func (b *gitRepoVolumeMounter) CanMount() error {
  143. return nil
  144. }
  145. // SetUp creates new directory and clones a git repo.
  146. func (b *gitRepoVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {
  147. return b.SetUpAt(b.GetPath(), mounterArgs)
  148. }
  149. // SetUpAt creates new directory and clones a git repo.
  150. func (b *gitRepoVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {
  151. if volumeutil.IsReady(b.getMetaDir()) {
  152. return nil
  153. }
  154. // Wrap EmptyDir, let it do the setup.
  155. wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), &b.pod, b.opts)
  156. if err != nil {
  157. return err
  158. }
  159. if err := wrapped.SetUpAt(dir, mounterArgs); err != nil {
  160. return err
  161. }
  162. args := []string{"clone", "--", b.source}
  163. if len(b.target) != 0 {
  164. args = append(args, b.target)
  165. }
  166. if output, err := b.execCommand("git", args, dir); err != nil {
  167. return fmt.Errorf("failed to exec 'git %s': %s: %v",
  168. strings.Join(args, " "), output, err)
  169. }
  170. files, err := ioutil.ReadDir(dir)
  171. if err != nil {
  172. return err
  173. }
  174. if len(b.revision) == 0 {
  175. // Done!
  176. volumeutil.SetReady(b.getMetaDir())
  177. return nil
  178. }
  179. var subdir string
  180. switch {
  181. case len(b.target) != 0 && filepath.Clean(b.target) == ".":
  182. // if target dir is '.', use the current dir
  183. subdir = filepath.Join(dir)
  184. case len(files) == 1:
  185. // if target is not '.', use the generated folder
  186. subdir = filepath.Join(dir, files[0].Name())
  187. default:
  188. // if target is not '.', but generated many files, it's wrong
  189. return fmt.Errorf("unexpected directory contents: %v", files)
  190. }
  191. if output, err := b.execCommand("git", []string{"checkout", b.revision}, subdir); err != nil {
  192. return fmt.Errorf("failed to exec 'git checkout %s': %s: %v", b.revision, output, err)
  193. }
  194. if output, err := b.execCommand("git", []string{"reset", "--hard"}, subdir); err != nil {
  195. return fmt.Errorf("failed to exec 'git reset --hard': %s: %v", output, err)
  196. }
  197. volume.SetVolumeOwnership(b, mounterArgs.FsGroup)
  198. volumeutil.SetReady(b.getMetaDir())
  199. return nil
  200. }
  201. func (b *gitRepoVolumeMounter) getMetaDir() string {
  202. return filepath.Join(b.plugin.host.GetPodPluginDir(b.podUID, utilstrings.EscapeQualifiedName(gitRepoPluginName)), b.volName)
  203. }
  204. func (b *gitRepoVolumeMounter) execCommand(command string, args []string, dir string) ([]byte, error) {
  205. cmd := b.exec.Command(command, args...)
  206. cmd.SetDir(dir)
  207. return cmd.CombinedOutput()
  208. }
  209. func validateVolume(src *v1.GitRepoVolumeSource) error {
  210. if err := validateNonFlagArgument(src.Repository, "repository"); err != nil {
  211. return err
  212. }
  213. if err := validateNonFlagArgument(src.Revision, "revision"); err != nil {
  214. return err
  215. }
  216. if err := validateNonFlagArgument(src.Directory, "directory"); err != nil {
  217. return err
  218. }
  219. return nil
  220. }
  221. // gitRepoVolumeUnmounter cleans git repo volumes.
  222. type gitRepoVolumeUnmounter struct {
  223. *gitRepoVolume
  224. }
  225. var _ volume.Unmounter = &gitRepoVolumeUnmounter{}
  226. // TearDown simply deletes everything in the directory.
  227. func (c *gitRepoVolumeUnmounter) TearDown() error {
  228. return c.TearDownAt(c.GetPath())
  229. }
  230. // TearDownAt simply deletes everything in the directory.
  231. func (c *gitRepoVolumeUnmounter) TearDownAt(dir string) error {
  232. return volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)
  233. }
  234. func getVolumeSource(spec *volume.Spec) (*v1.GitRepoVolumeSource, bool) {
  235. var readOnly bool
  236. var volumeSource *v1.GitRepoVolumeSource
  237. if spec.Volume != nil && spec.Volume.GitRepo != nil {
  238. volumeSource = spec.Volume.GitRepo
  239. readOnly = spec.ReadOnly
  240. }
  241. return volumeSource, readOnly
  242. }
  243. func validateNonFlagArgument(arg, argName string) error {
  244. if len(arg) > 0 && arg[0] == '-' {
  245. return fmt.Errorf("%q is an invalid value for %s", arg, argName)
  246. }
  247. return nil
  248. }