copy.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. package dockerfile // import "github.com/docker/docker/builder/dockerfile"
  2. import (
  3. "archive/tar"
  4. "fmt"
  5. "io"
  6. "mime"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/docker/docker/builder"
  16. "github.com/docker/docker/builder/remotecontext"
  17. "github.com/docker/docker/pkg/archive"
  18. "github.com/docker/docker/pkg/containerfs"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/ioutils"
  21. "github.com/docker/docker/pkg/progress"
  22. "github.com/docker/docker/pkg/streamformatter"
  23. "github.com/docker/docker/pkg/system"
  24. "github.com/docker/docker/pkg/urlutil"
  25. specs "github.com/opencontainers/image-spec/specs-go/v1"
  26. "github.com/pkg/errors"
  27. )
  28. const unnamedFilename = "__unnamed__"
  29. type pathCache interface {
  30. Load(key interface{}) (value interface{}, ok bool)
  31. Store(key, value interface{})
  32. }
  33. // copyInfo is a data object which stores the metadata about each source file in
  34. // a copyInstruction
  35. type copyInfo struct {
  36. root containerfs.ContainerFS
  37. path string
  38. hash string
  39. noDecompress bool
  40. }
  41. func (c copyInfo) fullPath() (string, error) {
  42. return c.root.ResolveScopedPath(c.path, true)
  43. }
  44. func newCopyInfoFromSource(source builder.Source, path string, hash string) copyInfo {
  45. return copyInfo{root: source.Root(), path: path, hash: hash}
  46. }
  47. func newCopyInfos(copyInfos ...copyInfo) []copyInfo {
  48. return copyInfos
  49. }
  50. // copyInstruction is a fully parsed COPY or ADD command that is passed to
  51. // Builder.performCopy to copy files into the image filesystem
  52. type copyInstruction struct {
  53. cmdName string
  54. infos []copyInfo
  55. dest string
  56. chownStr string
  57. allowLocalDecompression bool
  58. preserveOwnership bool
  59. }
  60. // copier reads a raw COPY or ADD command, fetches remote sources using a downloader,
  61. // and creates a copyInstruction
  62. type copier struct {
  63. imageSource *imageMount
  64. source builder.Source
  65. pathCache pathCache
  66. download sourceDownloader
  67. platform *specs.Platform
  68. // for cleanup. TODO: having copier.cleanup() is error prone and hard to
  69. // follow. Code calling performCopy should manage the lifecycle of its params.
  70. // Copier should take override source as input, not imageMount.
  71. activeLayer builder.RWLayer
  72. tmpPaths []string
  73. }
  74. func copierFromDispatchRequest(req dispatchRequest, download sourceDownloader, imageSource *imageMount) copier {
  75. platform := req.builder.platform
  76. if platform == nil {
  77. // May be nil if not explicitly set in API/dockerfile
  78. platform = &specs.Platform{}
  79. }
  80. if platform.OS == "" {
  81. // Default to the dispatch requests operating system if not explicit in API/dockerfile
  82. platform.OS = req.state.operatingSystem
  83. }
  84. if platform.OS == "" {
  85. // This is a failsafe just in case. Shouldn't be hit.
  86. platform.OS = runtime.GOOS
  87. }
  88. return copier{
  89. source: req.source,
  90. pathCache: req.builder.pathCache,
  91. download: download,
  92. imageSource: imageSource,
  93. platform: platform,
  94. }
  95. }
  96. func (o *copier) createCopyInstruction(args []string, cmdName string) (copyInstruction, error) {
  97. inst := copyInstruction{cmdName: cmdName}
  98. last := len(args) - 1
  99. // Work in platform-specific filepath semantics
  100. // TODO: This OS switch for paths is NOT correct and should not be supported.
  101. // Maintained for backwards compatibility
  102. pathOS := runtime.GOOS
  103. if o.platform != nil {
  104. pathOS = o.platform.OS
  105. }
  106. inst.dest = fromSlash(args[last], pathOS)
  107. separator := string(separator(pathOS))
  108. infos, err := o.getCopyInfosForSourcePaths(args[0:last], inst.dest)
  109. if err != nil {
  110. return inst, errors.Wrapf(err, "%s failed", cmdName)
  111. }
  112. if len(infos) > 1 && !strings.HasSuffix(inst.dest, separator) {
  113. return inst, errors.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
  114. }
  115. inst.infos = infos
  116. return inst, nil
  117. }
  118. // getCopyInfosForSourcePaths iterates over the source files and calculate the info
  119. // needed to copy (e.g. hash value if cached)
  120. // The dest is used in case source is URL (and ends with "/")
  121. func (o *copier) getCopyInfosForSourcePaths(sources []string, dest string) ([]copyInfo, error) {
  122. var infos []copyInfo
  123. for _, orig := range sources {
  124. subinfos, err := o.getCopyInfoForSourcePath(orig, dest)
  125. if err != nil {
  126. return nil, err
  127. }
  128. infos = append(infos, subinfos...)
  129. }
  130. if len(infos) == 0 {
  131. return nil, errors.New("no source files were specified")
  132. }
  133. return infos, nil
  134. }
  135. func (o *copier) getCopyInfoForSourcePath(orig, dest string) ([]copyInfo, error) {
  136. if !urlutil.IsURL(orig) {
  137. return o.calcCopyInfo(orig, true)
  138. }
  139. remote, path, err := o.download(orig)
  140. if err != nil {
  141. return nil, err
  142. }
  143. // If path == "" then we are unable to determine filename from src
  144. // We have to make sure dest is available
  145. if path == "" {
  146. if strings.HasSuffix(dest, "/") {
  147. return nil, errors.Errorf("cannot determine filename for source %s", orig)
  148. }
  149. path = unnamedFilename
  150. }
  151. o.tmpPaths = append(o.tmpPaths, remote.Root().Path())
  152. hash, err := remote.Hash(path)
  153. ci := newCopyInfoFromSource(remote, path, hash)
  154. ci.noDecompress = true // data from http shouldn't be extracted even on ADD
  155. return newCopyInfos(ci), err
  156. }
  157. // Cleanup removes any temporary directories created as part of downloading
  158. // remote files.
  159. func (o *copier) Cleanup() {
  160. for _, path := range o.tmpPaths {
  161. os.RemoveAll(path)
  162. }
  163. o.tmpPaths = []string{}
  164. if o.activeLayer != nil {
  165. o.activeLayer.Release()
  166. o.activeLayer = nil
  167. }
  168. }
  169. // TODO: allowWildcards can probably be removed by refactoring this function further.
  170. func (o *copier) calcCopyInfo(origPath string, allowWildcards bool) ([]copyInfo, error) {
  171. imageSource := o.imageSource
  172. // TODO: do this when creating copier. Requires validateCopySourcePath
  173. // (and other below) to be aware of the difference sources. Why is it only
  174. // done on image Source?
  175. if imageSource != nil && o.activeLayer == nil {
  176. // this needs to be protected against repeated calls as wildcard copy
  177. // will call it multiple times for a single COPY
  178. var err error
  179. rwLayer, err := imageSource.NewRWLayer()
  180. if err != nil {
  181. return nil, err
  182. }
  183. o.activeLayer = rwLayer
  184. o.source, err = remotecontext.NewLazySource(rwLayer.Root())
  185. if err != nil {
  186. return nil, errors.Wrapf(err, "failed to create context for copy from %s", rwLayer.Root().Path())
  187. }
  188. }
  189. if o.source == nil {
  190. return nil, errors.Errorf("missing build context")
  191. }
  192. root := o.source.Root()
  193. if err := validateCopySourcePath(imageSource, origPath, root.OS()); err != nil {
  194. return nil, err
  195. }
  196. // Work in source OS specific filepath semantics
  197. // For LCOW, this is NOT the daemon OS.
  198. origPath = root.FromSlash(origPath)
  199. origPath = strings.TrimPrefix(origPath, string(root.Separator()))
  200. origPath = strings.TrimPrefix(origPath, "."+string(root.Separator()))
  201. // Deal with wildcards
  202. if allowWildcards && containsWildcards(origPath, root.OS()) {
  203. return o.copyWithWildcards(origPath)
  204. }
  205. if imageSource != nil && imageSource.ImageID() != "" {
  206. // return a cached copy if one exists
  207. if h, ok := o.pathCache.Load(imageSource.ImageID() + origPath); ok {
  208. return newCopyInfos(newCopyInfoFromSource(o.source, origPath, h.(string))), nil
  209. }
  210. }
  211. // Deal with the single file case
  212. copyInfo, err := copyInfoForFile(o.source, origPath)
  213. switch {
  214. case imageSource == nil && errors.Is(err, os.ErrNotExist):
  215. return nil, errors.Wrapf(err, "file not found in build context or excluded by .dockerignore")
  216. case err != nil:
  217. return nil, err
  218. case copyInfo.hash != "":
  219. o.storeInPathCache(imageSource, origPath, copyInfo.hash)
  220. return newCopyInfos(copyInfo), err
  221. }
  222. // TODO: remove, handle dirs in Hash()
  223. subfiles, err := walkSource(o.source, origPath)
  224. if err != nil {
  225. return nil, err
  226. }
  227. hash := hashStringSlice("dir", subfiles)
  228. o.storeInPathCache(imageSource, origPath, hash)
  229. return newCopyInfos(newCopyInfoFromSource(o.source, origPath, hash)), nil
  230. }
  231. func containsWildcards(name, platform string) bool {
  232. isWindows := platform == "windows"
  233. for i := 0; i < len(name); i++ {
  234. ch := name[i]
  235. if ch == '\\' && !isWindows {
  236. i++
  237. } else if ch == '*' || ch == '?' || ch == '[' {
  238. return true
  239. }
  240. }
  241. return false
  242. }
  243. func (o *copier) storeInPathCache(im *imageMount, path string, hash string) {
  244. if im != nil {
  245. o.pathCache.Store(im.ImageID()+path, hash)
  246. }
  247. }
  248. func (o *copier) copyWithWildcards(origPath string) ([]copyInfo, error) {
  249. root := o.source.Root()
  250. var copyInfos []copyInfo
  251. if err := root.Walk(root.Path(), func(path string, info os.FileInfo, err error) error {
  252. if err != nil {
  253. return err
  254. }
  255. rel, err := remotecontext.Rel(root, path)
  256. if err != nil {
  257. return err
  258. }
  259. if rel == "." {
  260. return nil
  261. }
  262. if match, _ := root.Match(origPath, rel); !match {
  263. return nil
  264. }
  265. // Note we set allowWildcards to false in case the name has
  266. // a * in it
  267. subInfos, err := o.calcCopyInfo(rel, false)
  268. if err != nil {
  269. return err
  270. }
  271. copyInfos = append(copyInfos, subInfos...)
  272. return nil
  273. }); err != nil {
  274. return nil, err
  275. }
  276. return copyInfos, nil
  277. }
  278. func copyInfoForFile(source builder.Source, path string) (copyInfo, error) {
  279. fi, err := remotecontext.StatAt(source, path)
  280. if err != nil {
  281. if errors.Is(err, os.ErrNotExist) {
  282. // return the relative path in the error, which is more user-friendly than the full path to the tmp-dir
  283. return copyInfo{}, errors.WithStack(&os.PathError{Op: "stat", Path: path, Err: os.ErrNotExist})
  284. }
  285. return copyInfo{}, err
  286. }
  287. if fi.IsDir() {
  288. return copyInfo{}, nil
  289. }
  290. hash, err := source.Hash(path)
  291. if err != nil {
  292. return copyInfo{}, err
  293. }
  294. return newCopyInfoFromSource(source, path, "file:"+hash), nil
  295. }
  296. // TODO: dedupe with copyWithWildcards()
  297. func walkSource(source builder.Source, origPath string) ([]string, error) {
  298. fp, err := remotecontext.FullPath(source, origPath)
  299. if err != nil {
  300. return nil, err
  301. }
  302. // Must be a dir
  303. var subfiles []string
  304. err = source.Root().Walk(fp, func(path string, info os.FileInfo, err error) error {
  305. if err != nil {
  306. return err
  307. }
  308. rel, err := remotecontext.Rel(source.Root(), path)
  309. if err != nil {
  310. return err
  311. }
  312. if rel == "." {
  313. return nil
  314. }
  315. hash, err := source.Hash(rel)
  316. if err != nil {
  317. return nil
  318. }
  319. // we already checked handleHash above
  320. subfiles = append(subfiles, hash)
  321. return nil
  322. })
  323. if err != nil {
  324. return nil, err
  325. }
  326. sort.Strings(subfiles)
  327. return subfiles, nil
  328. }
  329. type sourceDownloader func(string) (builder.Source, string, error)
  330. func newRemoteSourceDownloader(output, stdout io.Writer) sourceDownloader {
  331. return func(url string) (builder.Source, string, error) {
  332. return downloadSource(output, stdout, url)
  333. }
  334. }
  335. func errOnSourceDownload(_ string) (builder.Source, string, error) {
  336. return nil, "", errors.New("source can't be a URL for COPY")
  337. }
  338. func getFilenameForDownload(path string, resp *http.Response) string {
  339. // Guess filename based on source
  340. if path != "" && !strings.HasSuffix(path, "/") {
  341. if filename := filepath.Base(filepath.FromSlash(path)); filename != "" {
  342. return filename
  343. }
  344. }
  345. // Guess filename based on Content-Disposition
  346. if contentDisposition := resp.Header.Get("Content-Disposition"); contentDisposition != "" {
  347. if _, params, err := mime.ParseMediaType(contentDisposition); err == nil {
  348. if params["filename"] != "" && !strings.HasSuffix(params["filename"], "/") {
  349. if filename := filepath.Base(filepath.FromSlash(params["filename"])); filename != "" {
  350. return filename
  351. }
  352. }
  353. }
  354. }
  355. return ""
  356. }
  357. func downloadSource(output io.Writer, stdout io.Writer, srcURL string) (remote builder.Source, p string, err error) {
  358. u, err := url.Parse(srcURL)
  359. if err != nil {
  360. return
  361. }
  362. resp, err := remotecontext.GetWithStatusError(srcURL)
  363. if err != nil {
  364. return
  365. }
  366. filename := getFilenameForDownload(u.Path, resp)
  367. // Prepare file in a tmp dir
  368. tmpDir, err := ioutils.TempDir("", "docker-remote")
  369. if err != nil {
  370. return
  371. }
  372. defer func() {
  373. if err != nil {
  374. os.RemoveAll(tmpDir)
  375. }
  376. }()
  377. // If filename is empty, the returned filename will be "" but
  378. // the tmp filename will be created as "__unnamed__"
  379. tmpFileName := filename
  380. if filename == "" {
  381. tmpFileName = unnamedFilename
  382. }
  383. tmpFileName = filepath.Join(tmpDir, tmpFileName)
  384. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  385. if err != nil {
  386. return
  387. }
  388. progressOutput := streamformatter.NewJSONProgressOutput(output, true)
  389. progressReader := progress.NewProgressReader(resp.Body, progressOutput, resp.ContentLength, "", "Downloading")
  390. // Download and dump result to tmp file
  391. // TODO: add filehash directly
  392. if _, err = io.Copy(tmpFile, progressReader); err != nil {
  393. tmpFile.Close()
  394. return
  395. }
  396. // TODO: how important is this random blank line to the output?
  397. fmt.Fprintln(stdout)
  398. // Set the mtime to the Last-Modified header value if present
  399. // Otherwise just remove atime and mtime
  400. mTime := time.Time{}
  401. lastMod := resp.Header.Get("Last-Modified")
  402. if lastMod != "" {
  403. // If we can't parse it then just let it default to 'zero'
  404. // otherwise use the parsed time value
  405. if parsedMTime, err := http.ParseTime(lastMod); err == nil {
  406. mTime = parsedMTime
  407. }
  408. }
  409. tmpFile.Close()
  410. if err = system.Chtimes(tmpFileName, mTime, mTime); err != nil {
  411. return
  412. }
  413. lc, err := remotecontext.NewLazySource(containerfs.NewLocalContainerFS(tmpDir))
  414. return lc, filename, err
  415. }
  416. type copyFileOptions struct {
  417. decompress bool
  418. identity *idtools.Identity
  419. archiver Archiver
  420. }
  421. type copyEndpoint struct {
  422. driver containerfs.Driver
  423. path string
  424. }
  425. func performCopyForInfo(dest copyInfo, source copyInfo, options copyFileOptions) error {
  426. srcPath, err := source.fullPath()
  427. if err != nil {
  428. return err
  429. }
  430. destPath, err := dest.fullPath()
  431. if err != nil {
  432. return err
  433. }
  434. archiver := options.archiver
  435. srcEndpoint := &copyEndpoint{driver: source.root, path: srcPath}
  436. destEndpoint := &copyEndpoint{driver: dest.root, path: destPath}
  437. src, err := source.root.Stat(srcPath)
  438. if err != nil {
  439. return errors.Wrapf(err, "source path not found")
  440. }
  441. if src.IsDir() {
  442. return copyDirectory(archiver, srcEndpoint, destEndpoint, options.identity)
  443. }
  444. if options.decompress && isArchivePath(source.root, srcPath) && !source.noDecompress {
  445. return archiver.UntarPath(srcPath, destPath)
  446. }
  447. destExistsAsDir, err := isExistingDirectory(destEndpoint)
  448. if err != nil {
  449. return err
  450. }
  451. // dest.path must be used because destPath has already been cleaned of any
  452. // trailing slash
  453. if endsInSlash(dest.root, dest.path) || destExistsAsDir {
  454. // source.path must be used to get the correct filename when the source
  455. // is a symlink
  456. destPath = dest.root.Join(destPath, source.root.Base(source.path))
  457. destEndpoint = &copyEndpoint{driver: dest.root, path: destPath}
  458. }
  459. return copyFile(archiver, srcEndpoint, destEndpoint, options.identity)
  460. }
  461. func isArchivePath(driver containerfs.ContainerFS, path string) bool {
  462. file, err := driver.Open(path)
  463. if err != nil {
  464. return false
  465. }
  466. defer file.Close()
  467. rdr, err := archive.DecompressStream(file)
  468. if err != nil {
  469. return false
  470. }
  471. r := tar.NewReader(rdr)
  472. _, err = r.Next()
  473. return err == nil
  474. }
  475. func copyDirectory(archiver Archiver, source, dest *copyEndpoint, identity *idtools.Identity) error {
  476. destExists, err := isExistingDirectory(dest)
  477. if err != nil {
  478. return errors.Wrapf(err, "failed to query destination path")
  479. }
  480. if err := archiver.CopyWithTar(source.path, dest.path); err != nil {
  481. return errors.Wrapf(err, "failed to copy directory")
  482. }
  483. if identity != nil {
  484. // TODO: @gupta-ak. Investigate how LCOW permission mappings will work.
  485. return fixPermissions(source.path, dest.path, *identity, !destExists)
  486. }
  487. return nil
  488. }
  489. func copyFile(archiver Archiver, source, dest *copyEndpoint, identity *idtools.Identity) error {
  490. if runtime.GOOS == "windows" && dest.driver.OS() == "linux" {
  491. // LCOW
  492. if err := dest.driver.MkdirAll(dest.driver.Dir(dest.path), 0755); err != nil {
  493. return errors.Wrapf(err, "failed to create new directory")
  494. }
  495. } else {
  496. // Normal containers
  497. if identity == nil {
  498. // Use system.MkdirAll here, which is a custom version of os.MkdirAll
  499. // modified for use on Windows to handle volume GUID paths. These paths
  500. // are of the form \\?\Volume{<GUID>}\<path>. An example would be:
  501. // \\?\Volume{dae8d3ac-b9a1-11e9-88eb-e8554b2ba1db}\bin\busybox.exe
  502. if err := system.MkdirAll(filepath.Dir(dest.path), 0755); err != nil {
  503. return err
  504. }
  505. } else {
  506. if err := idtools.MkdirAllAndChownNew(filepath.Dir(dest.path), 0755, *identity); err != nil {
  507. return errors.Wrapf(err, "failed to create new directory")
  508. }
  509. }
  510. }
  511. if err := archiver.CopyFileWithTar(source.path, dest.path); err != nil {
  512. return errors.Wrapf(err, "failed to copy file")
  513. }
  514. if identity != nil {
  515. // TODO: @gupta-ak. Investigate how LCOW permission mappings will work.
  516. return fixPermissions(source.path, dest.path, *identity, false)
  517. }
  518. return nil
  519. }
  520. func endsInSlash(driver containerfs.Driver, path string) bool {
  521. return strings.HasSuffix(path, string(driver.Separator()))
  522. }
  523. // isExistingDirectory returns true if the path exists and is a directory
  524. func isExistingDirectory(point *copyEndpoint) (bool, error) {
  525. destStat, err := point.driver.Stat(point.path)
  526. switch {
  527. case errors.Is(err, os.ErrNotExist):
  528. return false, nil
  529. case err != nil:
  530. return false, err
  531. }
  532. return destStat.IsDir(), nil
  533. }