copy.go 9.3 KB

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