copy.go 15 KB

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