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