context.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package builder
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "github.com/docker/docker/pkg/archive"
  13. "github.com/docker/docker/pkg/fileutils"
  14. "github.com/docker/docker/pkg/gitutils"
  15. "github.com/docker/docker/pkg/httputils"
  16. "github.com/docker/docker/pkg/ioutils"
  17. "github.com/docker/docker/pkg/progress"
  18. "github.com/docker/docker/pkg/streamformatter"
  19. )
  20. // ValidateContextDirectory checks if all the contents of the directory
  21. // can be read and returns an error if some files can't be read
  22. // symlinks which point to non-existing files don't trigger an error
  23. func ValidateContextDirectory(srcPath string, excludes []string) error {
  24. contextRoot, err := getContextRoot(srcPath)
  25. if err != nil {
  26. return err
  27. }
  28. return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
  29. if err != nil {
  30. if os.IsPermission(err) {
  31. return fmt.Errorf("can't stat '%s'", filePath)
  32. }
  33. if os.IsNotExist(err) {
  34. return nil
  35. }
  36. return err
  37. }
  38. // skip this directory/file if it's not in the path, it won't get added to the context
  39. if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
  40. return err
  41. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  42. return err
  43. } else if skip {
  44. if f.IsDir() {
  45. return filepath.SkipDir
  46. }
  47. return nil
  48. }
  49. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  50. // also skip named pipes, because they hanging on open
  51. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  52. return nil
  53. }
  54. if !f.IsDir() {
  55. currentFile, err := os.Open(filePath)
  56. if err != nil && os.IsPermission(err) {
  57. return fmt.Errorf("no permission to read from '%s'", filePath)
  58. }
  59. currentFile.Close()
  60. }
  61. return nil
  62. })
  63. }
  64. // GetContextFromReader will read the contents of the given reader as either a
  65. // Dockerfile or tar archive. Returns a tar archive used as a context and a
  66. // path to the Dockerfile inside the tar.
  67. func GetContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCloser, relDockerfile string, err error) {
  68. buf := bufio.NewReader(r)
  69. magic, err := buf.Peek(archive.HeaderSize)
  70. if err != nil && err != io.EOF {
  71. return nil, "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
  72. }
  73. if archive.IsArchive(magic) {
  74. return ioutils.NewReadCloserWrapper(buf, func() error { return r.Close() }), dockerfileName, nil
  75. }
  76. // Input should be read as a Dockerfile.
  77. tmpDir, err := ioutil.TempDir("", "docker-build-context-")
  78. if err != nil {
  79. return nil, "", fmt.Errorf("unbale to create temporary context directory: %v", err)
  80. }
  81. f, err := os.Create(filepath.Join(tmpDir, DefaultDockerfileName))
  82. if err != nil {
  83. return nil, "", err
  84. }
  85. _, err = io.Copy(f, buf)
  86. if err != nil {
  87. f.Close()
  88. return nil, "", err
  89. }
  90. if err := f.Close(); err != nil {
  91. return nil, "", err
  92. }
  93. if err := r.Close(); err != nil {
  94. return nil, "", err
  95. }
  96. tar, err := archive.Tar(tmpDir, archive.Uncompressed)
  97. if err != nil {
  98. return nil, "", err
  99. }
  100. return ioutils.NewReadCloserWrapper(tar, func() error {
  101. err := tar.Close()
  102. os.RemoveAll(tmpDir)
  103. return err
  104. }), DefaultDockerfileName, nil
  105. }
  106. // GetContextFromGitURL uses a Git URL as context for a `docker build`. The
  107. // git repo is cloned into a temporary directory used as the context directory.
  108. // Returns the absolute path to the temporary context directory, the relative
  109. // path of the dockerfile in that context directory, and a non-nil error on
  110. // success.
  111. func GetContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  112. if _, err := exec.LookPath("git"); err != nil {
  113. return "", "", fmt.Errorf("unable to find 'git': %v", err)
  114. }
  115. if absContextDir, err = gitutils.Clone(gitURL); err != nil {
  116. return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
  117. }
  118. return getDockerfileRelPath(absContextDir, dockerfileName)
  119. }
  120. // GetContextFromURL uses a remote URL as context for a `docker build`. The
  121. // remote resource is downloaded as either a Dockerfile or a tar archive.
  122. // Returns the tar archive used for the context and a path of the
  123. // dockerfile inside the tar.
  124. func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) {
  125. response, err := httputils.Download(remoteURL)
  126. if err != nil {
  127. return nil, "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
  128. }
  129. progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true)
  130. // Pass the response body through a progress reader.
  131. progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))
  132. return GetContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName)
  133. }
  134. // GetContextFromLocalDir uses the given local directory as context for a
  135. // `docker build`. Returns the absolute path to the local context directory,
  136. // the relative path of the dockerfile in that context directory, and a non-nil
  137. // error on success.
  138. func GetContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  139. // When using a local context directory, when the Dockerfile is specified
  140. // with the `-f/--file` option then it is considered relative to the
  141. // current directory and not the context directory.
  142. if dockerfileName != "" {
  143. if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
  144. return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
  145. }
  146. }
  147. return getDockerfileRelPath(localDir, dockerfileName)
  148. }
  149. // getDockerfileRelPath uses the given context directory for a `docker build`
  150. // and returns the absolute path to the context directory, the relative path of
  151. // the dockerfile in that context directory, and a non-nil error on success.
  152. func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
  153. if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
  154. return "", "", fmt.Errorf("unable to get absolute context directory of given context directory %q: %v", givenContextDir, err)
  155. }
  156. // The context dir might be a symbolic link, so follow it to the actual
  157. // target directory.
  158. //
  159. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  160. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  161. // paths (those starting with \\). This hack means that when using links
  162. // on UNC paths, they will not be followed.
  163. if !isUNC(absContextDir) {
  164. absContextDir, err = filepath.EvalSymlinks(absContextDir)
  165. if err != nil {
  166. return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
  167. }
  168. }
  169. stat, err := os.Lstat(absContextDir)
  170. if err != nil {
  171. return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
  172. }
  173. if !stat.IsDir() {
  174. return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
  175. }
  176. absDockerfile := givenDockerfile
  177. if absDockerfile == "" {
  178. // No -f/--file was specified so use the default relative to the
  179. // context directory.
  180. absDockerfile = filepath.Join(absContextDir, DefaultDockerfileName)
  181. // Just to be nice ;-) look for 'dockerfile' too but only
  182. // use it if we found it, otherwise ignore this check
  183. if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
  184. altPath := filepath.Join(absContextDir, strings.ToLower(DefaultDockerfileName))
  185. if _, err = os.Lstat(altPath); err == nil {
  186. absDockerfile = altPath
  187. }
  188. }
  189. }
  190. // If not already an absolute path, the Dockerfile path should be joined to
  191. // the base directory.
  192. if !filepath.IsAbs(absDockerfile) {
  193. absDockerfile = filepath.Join(absContextDir, absDockerfile)
  194. }
  195. // Evaluate symlinks in the path to the Dockerfile too.
  196. //
  197. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  198. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  199. // paths (those starting with \\). This hack means that when using links
  200. // on UNC paths, they will not be followed.
  201. if !isUNC(absDockerfile) {
  202. absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
  203. if err != nil {
  204. return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
  205. }
  206. }
  207. if _, err := os.Lstat(absDockerfile); err != nil {
  208. if os.IsNotExist(err) {
  209. return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
  210. }
  211. return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
  212. }
  213. if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
  214. return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
  215. }
  216. if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  217. return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
  218. }
  219. return absContextDir, relDockerfile, nil
  220. }
  221. // isUNC returns true if the path is UNC (one starting \\). It always returns
  222. // false on Linux.
  223. func isUNC(path string) bool {
  224. return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`)
  225. }