copy.go 9.4 KB

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