git_repo.go 8.0 KB

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