copy.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. package dockerfile
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/url"
  7. "os"
  8. "path/filepath"
  9. "sort"
  10. "strings"
  11. "time"
  12. "github.com/docker/docker/builder"
  13. "github.com/docker/docker/builder/remotecontext"
  14. "github.com/docker/docker/pkg/archive"
  15. "github.com/docker/docker/pkg/idtools"
  16. "github.com/docker/docker/pkg/ioutils"
  17. "github.com/docker/docker/pkg/progress"
  18. "github.com/docker/docker/pkg/streamformatter"
  19. "github.com/docker/docker/pkg/symlink"
  20. "github.com/docker/docker/pkg/system"
  21. "github.com/docker/docker/pkg/urlutil"
  22. "github.com/pkg/errors"
  23. )
  24. type pathCache interface {
  25. Load(key interface{}) (value interface{}, ok bool)
  26. Store(key, value interface{})
  27. }
  28. // copyInfo is a data object which stores the metadata about each source file in
  29. // a copyInstruction
  30. type copyInfo struct {
  31. root string
  32. path string
  33. hash string
  34. }
  35. func (c copyInfo) fullPath() (string, error) {
  36. return symlink.FollowSymlinkInScope(filepath.Join(c.root, c.path), c.root)
  37. }
  38. func newCopyInfoFromSource(source builder.Source, path string, hash string) copyInfo {
  39. return copyInfo{root: source.Root(), path: path, hash: hash}
  40. }
  41. func newCopyInfos(copyInfos ...copyInfo) []copyInfo {
  42. return copyInfos
  43. }
  44. // copyInstruction is a fully parsed COPY or ADD command that is passed to
  45. // Builder.performCopy to copy files into the image filesystem
  46. type copyInstruction struct {
  47. cmdName string
  48. infos []copyInfo
  49. dest string
  50. allowLocalDecompression bool
  51. }
  52. // copier reads a raw COPY or ADD command, fetches remote sources using a downloader,
  53. // and creates a copyInstruction
  54. type copier struct {
  55. imageSource *imageMount
  56. source builder.Source
  57. pathCache pathCache
  58. download sourceDownloader
  59. tmpPaths []string
  60. }
  61. func copierFromDispatchRequest(req dispatchRequest, download sourceDownloader, imageSource *imageMount) copier {
  62. return copier{
  63. source: req.source,
  64. pathCache: req.builder.pathCache,
  65. download: download,
  66. imageSource: imageSource,
  67. }
  68. }
  69. func (o *copier) createCopyInstruction(args []string, cmdName string) (copyInstruction, error) {
  70. inst := copyInstruction{cmdName: cmdName}
  71. last := len(args) - 1
  72. // Work in daemon-specific filepath semantics
  73. inst.dest = filepath.FromSlash(args[last])
  74. infos, err := o.getCopyInfosForSourcePaths(args[0:last])
  75. if err != nil {
  76. return inst, errors.Wrapf(err, "%s failed", cmdName)
  77. }
  78. if len(infos) > 1 && !strings.HasSuffix(inst.dest, string(os.PathSeparator)) {
  79. return inst, errors.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
  80. }
  81. inst.infos = infos
  82. return inst, nil
  83. }
  84. // getCopyInfosForSourcePaths iterates over the source files and calculate the info
  85. // needed to copy (e.g. hash value if cached)
  86. func (o *copier) getCopyInfosForSourcePaths(sources []string) ([]copyInfo, error) {
  87. var infos []copyInfo
  88. for _, orig := range sources {
  89. subinfos, err := o.getCopyInfoForSourcePath(orig)
  90. if err != nil {
  91. return nil, err
  92. }
  93. infos = append(infos, subinfos...)
  94. }
  95. if len(infos) == 0 {
  96. return nil, errors.New("no source files were specified")
  97. }
  98. return infos, nil
  99. }
  100. func (o *copier) getCopyInfoForSourcePath(orig string) ([]copyInfo, error) {
  101. if !urlutil.IsURL(orig) {
  102. return o.calcCopyInfo(orig, true)
  103. }
  104. remote, path, err := o.download(orig)
  105. if err != nil {
  106. return nil, err
  107. }
  108. o.tmpPaths = append(o.tmpPaths, remote.Root())
  109. hash, err := remote.Hash(path)
  110. return newCopyInfos(newCopyInfoFromSource(remote, path, hash)), err
  111. }
  112. // Cleanup removes any temporary directories created as part of downloading
  113. // remote files.
  114. func (o *copier) Cleanup() {
  115. for _, path := range o.tmpPaths {
  116. os.RemoveAll(path)
  117. }
  118. o.tmpPaths = []string{}
  119. }
  120. // TODO: allowWildcards can probably be removed by refactoring this function further.
  121. func (o *copier) calcCopyInfo(origPath string, allowWildcards bool) ([]copyInfo, error) {
  122. imageSource := o.imageSource
  123. if err := validateCopySourcePath(imageSource, origPath); err != nil {
  124. return nil, err
  125. }
  126. // Work in daemon-specific OS filepath semantics
  127. origPath = filepath.FromSlash(origPath)
  128. origPath = strings.TrimPrefix(origPath, string(os.PathSeparator))
  129. origPath = strings.TrimPrefix(origPath, "."+string(os.PathSeparator))
  130. // TODO: do this when creating copier. Requires validateCopySourcePath
  131. // (and other below) to be aware of the difference sources. Why is it only
  132. // done on image Source?
  133. if imageSource != nil {
  134. var err error
  135. o.source, err = imageSource.Source()
  136. if err != nil {
  137. return nil, errors.Wrapf(err, "failed to copy from %s", imageSource.ImageID())
  138. }
  139. }
  140. if o.source == nil {
  141. return nil, errors.Errorf("missing build context")
  142. }
  143. // Deal with wildcards
  144. if allowWildcards && containsWildcards(origPath) {
  145. return o.copyWithWildcards(origPath)
  146. }
  147. if imageSource != nil && imageSource.ImageID() != "" {
  148. // return a cached copy if one exists
  149. if h, ok := o.pathCache.Load(imageSource.ImageID() + origPath); ok {
  150. return newCopyInfos(newCopyInfoFromSource(o.source, origPath, h.(string))), nil
  151. }
  152. }
  153. // Deal with the single file case
  154. copyInfo, err := copyInfoForFile(o.source, origPath)
  155. switch {
  156. case err != nil:
  157. return nil, err
  158. case copyInfo.hash != "":
  159. o.storeInPathCache(imageSource, origPath, copyInfo.hash)
  160. return newCopyInfos(copyInfo), err
  161. }
  162. // TODO: remove, handle dirs in Hash()
  163. subfiles, err := walkSource(o.source, origPath)
  164. if err != nil {
  165. return nil, err
  166. }
  167. hash := hashStringSlice("dir", subfiles)
  168. o.storeInPathCache(imageSource, origPath, hash)
  169. return newCopyInfos(newCopyInfoFromSource(o.source, origPath, hash)), nil
  170. }
  171. func (o *copier) storeInPathCache(im *imageMount, path string, hash string) {
  172. if im != nil {
  173. o.pathCache.Store(im.ImageID()+path, hash)
  174. }
  175. }
  176. func (o *copier) copyWithWildcards(origPath string) ([]copyInfo, error) {
  177. var copyInfos []copyInfo
  178. if err := filepath.Walk(o.source.Root(), func(path string, info os.FileInfo, err error) error {
  179. if err != nil {
  180. return err
  181. }
  182. rel, err := remotecontext.Rel(o.source.Root(), path)
  183. if err != nil {
  184. return err
  185. }
  186. if rel == "." {
  187. return nil
  188. }
  189. if match, _ := filepath.Match(origPath, rel); !match {
  190. return nil
  191. }
  192. // Note we set allowWildcards to false in case the name has
  193. // a * in it
  194. subInfos, err := o.calcCopyInfo(rel, false)
  195. if err != nil {
  196. return err
  197. }
  198. copyInfos = append(copyInfos, subInfos...)
  199. return nil
  200. }); err != nil {
  201. return nil, err
  202. }
  203. return copyInfos, nil
  204. }
  205. func copyInfoForFile(source builder.Source, path string) (copyInfo, error) {
  206. fi, err := remotecontext.StatAt(source, path)
  207. if err != nil {
  208. return copyInfo{}, err
  209. }
  210. if fi.IsDir() {
  211. return copyInfo{}, nil
  212. }
  213. hash, err := source.Hash(path)
  214. if err != nil {
  215. return copyInfo{}, err
  216. }
  217. return newCopyInfoFromSource(source, path, "file:"+hash), nil
  218. }
  219. // TODO: dedupe with copyWithWildcards()
  220. func walkSource(source builder.Source, origPath string) ([]string, error) {
  221. fp, err := remotecontext.FullPath(source, origPath)
  222. if err != nil {
  223. return nil, err
  224. }
  225. // Must be a dir
  226. var subfiles []string
  227. err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
  228. if err != nil {
  229. return err
  230. }
  231. rel, err := remotecontext.Rel(source.Root(), path)
  232. if err != nil {
  233. return err
  234. }
  235. if rel == "." {
  236. return nil
  237. }
  238. hash, err := source.Hash(rel)
  239. if err != nil {
  240. return nil
  241. }
  242. // we already checked handleHash above
  243. subfiles = append(subfiles, hash)
  244. return nil
  245. })
  246. if err != nil {
  247. return nil, err
  248. }
  249. sort.Strings(subfiles)
  250. return subfiles, nil
  251. }
  252. type sourceDownloader func(string) (builder.Source, string, error)
  253. func newRemoteSourceDownloader(output, stdout io.Writer) sourceDownloader {
  254. return func(url string) (builder.Source, string, error) {
  255. return downloadSource(output, stdout, url)
  256. }
  257. }
  258. func errOnSourceDownload(_ string) (builder.Source, string, error) {
  259. return nil, "", errors.New("source can't be a URL for COPY")
  260. }
  261. func downloadSource(output io.Writer, stdout io.Writer, srcURL string) (remote builder.Source, p string, err error) {
  262. u, err := url.Parse(srcURL)
  263. if err != nil {
  264. return
  265. }
  266. filename := filepath.Base(filepath.FromSlash(u.Path)) // Ensure in platform semantics
  267. if filename == "" {
  268. err = errors.Errorf("cannot determine filename from url: %s", u)
  269. return
  270. }
  271. resp, err := remotecontext.GetWithStatusError(srcURL)
  272. if err != nil {
  273. return
  274. }
  275. // Prepare file in a tmp dir
  276. tmpDir, err := ioutils.TempDir("", "docker-remote")
  277. if err != nil {
  278. return
  279. }
  280. defer func() {
  281. if err != nil {
  282. os.RemoveAll(tmpDir)
  283. }
  284. }()
  285. tmpFileName := filepath.Join(tmpDir, filename)
  286. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  287. if err != nil {
  288. return
  289. }
  290. progressOutput := streamformatter.NewJSONProgressOutput(output, true)
  291. progressReader := progress.NewProgressReader(resp.Body, progressOutput, resp.ContentLength, "", "Downloading")
  292. // Download and dump result to tmp file
  293. // TODO: add filehash directly
  294. if _, err = io.Copy(tmpFile, progressReader); err != nil {
  295. tmpFile.Close()
  296. return
  297. }
  298. // TODO: how important is this random blank line to the output?
  299. fmt.Fprintln(stdout)
  300. // Set the mtime to the Last-Modified header value if present
  301. // Otherwise just remove atime and mtime
  302. mTime := time.Time{}
  303. lastMod := resp.Header.Get("Last-Modified")
  304. if lastMod != "" {
  305. // If we can't parse it then just let it default to 'zero'
  306. // otherwise use the parsed time value
  307. if parsedMTime, err := http.ParseTime(lastMod); err == nil {
  308. mTime = parsedMTime
  309. }
  310. }
  311. tmpFile.Close()
  312. if err = system.Chtimes(tmpFileName, mTime, mTime); err != nil {
  313. return
  314. }
  315. lc, err := remotecontext.NewLazySource(tmpDir)
  316. return lc, filename, err
  317. }
  318. type copyFileOptions struct {
  319. decompress bool
  320. archiver *archive.Archiver
  321. }
  322. func performCopyForInfo(dest copyInfo, source copyInfo, options copyFileOptions) error {
  323. srcPath, err := source.fullPath()
  324. if err != nil {
  325. return err
  326. }
  327. destPath, err := dest.fullPath()
  328. if err != nil {
  329. return err
  330. }
  331. archiver := options.archiver
  332. src, err := os.Stat(srcPath)
  333. if err != nil {
  334. return errors.Wrapf(err, "source path not found")
  335. }
  336. if src.IsDir() {
  337. return copyDirectory(archiver, srcPath, destPath)
  338. }
  339. if options.decompress && archive.IsArchivePath(srcPath) {
  340. return archiver.UntarPath(srcPath, destPath)
  341. }
  342. destExistsAsDir, err := isExistingDirectory(destPath)
  343. if err != nil {
  344. return err
  345. }
  346. // dest.path must be used because destPath has already been cleaned of any
  347. // trailing slash
  348. if endsInSlash(dest.path) || destExistsAsDir {
  349. // source.path must be used to get the correct filename when the source
  350. // is a symlink
  351. destPath = filepath.Join(destPath, filepath.Base(source.path))
  352. }
  353. return copyFile(archiver, srcPath, destPath)
  354. }
  355. func copyDirectory(archiver *archive.Archiver, source, dest string) error {
  356. if err := archiver.CopyWithTar(source, dest); err != nil {
  357. return errors.Wrapf(err, "failed to copy directory")
  358. }
  359. return fixPermissions(source, dest, archiver.IDMappings.RootPair())
  360. }
  361. func copyFile(archiver *archive.Archiver, source, dest string) error {
  362. rootIDs := archiver.IDMappings.RootPair()
  363. if err := idtools.MkdirAllAndChownNew(filepath.Dir(dest), 0755, rootIDs); err != nil {
  364. return errors.Wrapf(err, "failed to create new directory")
  365. }
  366. if err := archiver.CopyFileWithTar(source, dest); err != nil {
  367. return errors.Wrapf(err, "failed to copy file")
  368. }
  369. return fixPermissions(source, dest, rootIDs)
  370. }
  371. func endsInSlash(path string) bool {
  372. return strings.HasSuffix(path, string(os.PathSeparator))
  373. }
  374. // isExistingDirectory returns true if the path exists and is a directory
  375. func isExistingDirectory(path string) (bool, error) {
  376. destStat, err := os.Stat(path)
  377. switch {
  378. case os.IsNotExist(err):
  379. return false, nil
  380. case err != nil:
  381. return false, err
  382. }
  383. return destStat.IsDir(), nil
  384. }