github.com/jwhonce/docker@v0.6.7-0.20190327063223-da823cf3a5a3/daemon/graphdriver/windows/windows.go (about) 1 //+build windows 2 3 package windows // import "github.com/docker/docker/daemon/graphdriver/windows" 4 5 import ( 6 "bufio" 7 "bytes" 8 "encoding/json" 9 "fmt" 10 "io" 11 "io/ioutil" 12 "os" 13 "path" 14 "path/filepath" 15 "strconv" 16 "strings" 17 "sync" 18 "syscall" 19 "time" 20 "unsafe" 21 22 "github.com/Microsoft/go-winio" 23 "github.com/Microsoft/go-winio/archive/tar" 24 "github.com/Microsoft/go-winio/backuptar" 25 "github.com/Microsoft/go-winio/vhd" 26 "github.com/Microsoft/hcsshim" 27 "github.com/docker/docker/daemon/graphdriver" 28 "github.com/docker/docker/pkg/archive" 29 "github.com/docker/docker/pkg/containerfs" 30 "github.com/docker/docker/pkg/idtools" 31 "github.com/docker/docker/pkg/ioutils" 32 "github.com/docker/docker/pkg/longpath" 33 "github.com/docker/docker/pkg/reexec" 34 "github.com/docker/docker/pkg/system" 35 units "github.com/docker/go-units" 36 "github.com/pkg/errors" 37 "github.com/sirupsen/logrus" 38 "golang.org/x/sys/windows" 39 ) 40 41 // filterDriver is an HCSShim driver type for the Windows Filter driver. 42 const filterDriver = 1 43 44 var ( 45 // mutatedFiles is a list of files that are mutated by the import process 46 // and must be backed up and restored. 47 mutatedFiles = map[string]string{ 48 "UtilityVM/Files/EFI/Microsoft/Boot/BCD": "bcd.bak", 49 "UtilityVM/Files/EFI/Microsoft/Boot/BCD.LOG": "bcd.log.bak", 50 "UtilityVM/Files/EFI/Microsoft/Boot/BCD.LOG1": "bcd.log1.bak", 51 "UtilityVM/Files/EFI/Microsoft/Boot/BCD.LOG2": "bcd.log2.bak", 52 } 53 noreexec = false 54 ) 55 56 // init registers the windows graph drivers to the register. 57 func init() { 58 graphdriver.Register("windowsfilter", InitFilter) 59 // DOCKER_WINDOWSFILTER_NOREEXEC allows for inline processing which makes 60 // debugging issues in the re-exec codepath significantly easier. 61 if os.Getenv("DOCKER_WINDOWSFILTER_NOREEXEC") != "" { 62 logrus.Warnf("WindowsGraphDriver is set to not re-exec. This is intended for debugging purposes only.") 63 noreexec = true 64 } else { 65 reexec.Register("docker-windows-write-layer", writeLayerReexec) 66 } 67 } 68 69 type checker struct { 70 } 71 72 func (c *checker) IsMounted(path string) bool { 73 return false 74 } 75 76 // Driver represents a windows graph driver. 77 type Driver struct { 78 // info stores the shim driver information 79 info hcsshim.DriverInfo 80 ctr *graphdriver.RefCounter 81 // it is safe for windows to use a cache here because it does not support 82 // restoring containers when the daemon dies. 83 cacheMu sync.Mutex 84 cache map[string]string 85 } 86 87 // InitFilter returns a new Windows storage filter driver. 88 func InitFilter(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) { 89 logrus.Debugf("WindowsGraphDriver InitFilter at %s", home) 90 91 fsType, err := getFileSystemType(string(home[0])) 92 if err != nil { 93 return nil, err 94 } 95 if strings.ToLower(fsType) == "refs" { 96 return nil, fmt.Errorf("%s is on an ReFS volume - ReFS volumes are not supported", home) 97 } 98 99 if err := idtools.MkdirAllAndChown(home, 0700, idtools.Identity{UID: 0, GID: 0}); err != nil { 100 return nil, fmt.Errorf("windowsfilter failed to create '%s': %v", home, err) 101 } 102 103 d := &Driver{ 104 info: hcsshim.DriverInfo{ 105 HomeDir: home, 106 Flavour: filterDriver, 107 }, 108 cache: make(map[string]string), 109 ctr: graphdriver.NewRefCounter(&checker{}), 110 } 111 return d, nil 112 } 113 114 // win32FromHresult is a helper function to get the win32 error code from an HRESULT 115 func win32FromHresult(hr uintptr) uintptr { 116 if hr&0x1fff0000 == 0x00070000 { 117 return hr & 0xffff 118 } 119 return hr 120 } 121 122 // getFileSystemType obtains the type of a file system through GetVolumeInformation 123 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364993(v=vs.85).aspx 124 func getFileSystemType(drive string) (fsType string, hr error) { 125 var ( 126 modkernel32 = windows.NewLazySystemDLL("kernel32.dll") 127 procGetVolumeInformation = modkernel32.NewProc("GetVolumeInformationW") 128 buf = make([]uint16, 255) 129 size = windows.MAX_PATH + 1 130 ) 131 if len(drive) != 1 { 132 hr = errors.New("getFileSystemType must be called with a drive letter") 133 return 134 } 135 drive += `:\` 136 n := uintptr(unsafe.Pointer(nil)) 137 r0, _, _ := syscall.Syscall9(procGetVolumeInformation.Addr(), 8, uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(drive))), n, n, n, n, n, uintptr(unsafe.Pointer(&buf[0])), uintptr(size), 0) 138 if int32(r0) < 0 { 139 hr = syscall.Errno(win32FromHresult(r0)) 140 } 141 fsType = windows.UTF16ToString(buf) 142 return 143 } 144 145 // String returns the string representation of a driver. This should match 146 // the name the graph driver has been registered with. 147 func (d *Driver) String() string { 148 return "windowsfilter" 149 } 150 151 // Status returns the status of the driver. 152 func (d *Driver) Status() [][2]string { 153 return [][2]string{ 154 {"Windows", ""}, 155 } 156 } 157 158 // Exists returns true if the given id is registered with this driver. 159 func (d *Driver) Exists(id string) bool { 160 rID, err := d.resolveID(id) 161 if err != nil { 162 return false 163 } 164 result, err := hcsshim.LayerExists(d.info, rID) 165 if err != nil { 166 return false 167 } 168 return result 169 } 170 171 // CreateReadWrite creates a layer that is writable for use as a container 172 // file system. 173 func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error { 174 if opts != nil { 175 return d.create(id, parent, opts.MountLabel, false, opts.StorageOpt) 176 } 177 return d.create(id, parent, "", false, nil) 178 } 179 180 // Create creates a new read-only layer with the given id. 181 func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { 182 if opts != nil { 183 return d.create(id, parent, opts.MountLabel, true, opts.StorageOpt) 184 } 185 return d.create(id, parent, "", true, nil) 186 } 187 188 func (d *Driver) create(id, parent, mountLabel string, readOnly bool, storageOpt map[string]string) error { 189 rPId, err := d.resolveID(parent) 190 if err != nil { 191 return err 192 } 193 194 parentChain, err := d.getLayerChain(rPId) 195 if err != nil { 196 return err 197 } 198 199 var layerChain []string 200 201 if rPId != "" { 202 parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId) 203 if err != nil { 204 return err 205 } 206 if _, err := os.Stat(filepath.Join(parentPath, "Files")); err == nil { 207 // This is a legitimate parent layer (not the empty "-init" layer), 208 // so include it in the layer chain. 209 layerChain = []string{parentPath} 210 } 211 } 212 213 layerChain = append(layerChain, parentChain...) 214 215 if readOnly { 216 if err := hcsshim.CreateLayer(d.info, id, rPId); err != nil { 217 return err 218 } 219 } else { 220 var parentPath string 221 if len(layerChain) != 0 { 222 parentPath = layerChain[0] 223 } 224 225 if err := hcsshim.CreateSandboxLayer(d.info, id, parentPath, layerChain); err != nil { 226 return err 227 } 228 229 storageOptions, err := parseStorageOpt(storageOpt) 230 if err != nil { 231 return fmt.Errorf("Failed to parse storage options - %s", err) 232 } 233 234 if storageOptions.size != 0 { 235 if err := hcsshim.ExpandSandboxSize(d.info, id, storageOptions.size); err != nil { 236 return err 237 } 238 } 239 } 240 241 if _, err := os.Lstat(d.dir(parent)); err != nil { 242 if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil { 243 logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2) 244 } 245 return fmt.Errorf("Cannot create layer with missing parent %s: %s", parent, err) 246 } 247 248 if err := d.setLayerChain(id, layerChain); err != nil { 249 if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil { 250 logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2) 251 } 252 return err 253 } 254 255 return nil 256 } 257 258 // dir returns the absolute path to the layer. 259 func (d *Driver) dir(id string) string { 260 return filepath.Join(d.info.HomeDir, filepath.Base(id)) 261 } 262 263 // Remove unmounts and removes the dir information. 264 func (d *Driver) Remove(id string) error { 265 rID, err := d.resolveID(id) 266 if err != nil { 267 return err 268 } 269 270 // This retry loop is due to a bug in Windows (Internal bug #9432268) 271 // if GetContainers fails with ErrVmcomputeOperationInvalidState 272 // it is a transient error. Retry until it succeeds. 273 var computeSystems []hcsshim.ContainerProperties 274 retryCount := 0 275 osv := system.GetOSVersion() 276 for { 277 // Get and terminate any template VMs that are currently using the layer. 278 // Note: It is unfortunate that we end up in the graphdrivers Remove() call 279 // for both containers and images, but the logic for template VMs is only 280 // needed for images - specifically we are looking to see if a base layer 281 // is in use by a template VM as a result of having started a Hyper-V 282 // container at some point. 283 // 284 // We have a retry loop for ErrVmcomputeOperationInvalidState and 285 // ErrVmcomputeOperationAccessIsDenied as there is a race condition 286 // in RS1 and RS2 building during enumeration when a silo is going away 287 // for example under it, in HCS. AccessIsDenied added to fix 30278. 288 // 289 // TODO @jhowardmsft - For RS3, we can remove the retries. Also consider 290 // using platform APIs (if available) to get this more succinctly. Also 291 // consider enhancing the Remove() interface to have context of why 292 // the remove is being called - that could improve efficiency by not 293 // enumerating compute systems during a remove of a container as it's 294 // not required. 295 computeSystems, err = hcsshim.GetContainers(hcsshim.ComputeSystemQuery{}) 296 if err != nil { 297 if (osv.Build < 15139) && 298 ((err == hcsshim.ErrVmcomputeOperationInvalidState) || (err == hcsshim.ErrVmcomputeOperationAccessIsDenied)) { 299 if retryCount >= 500 { 300 break 301 } 302 retryCount++ 303 time.Sleep(10 * time.Millisecond) 304 continue 305 } 306 return err 307 } 308 break 309 } 310 311 for _, computeSystem := range computeSystems { 312 if strings.Contains(computeSystem.RuntimeImagePath, id) && computeSystem.IsRuntimeTemplate { 313 container, err := hcsshim.OpenContainer(computeSystem.ID) 314 if err != nil { 315 return err 316 } 317 defer container.Close() 318 err = container.Terminate() 319 if hcsshim.IsPending(err) { 320 err = container.Wait() 321 } else if hcsshim.IsAlreadyStopped(err) { 322 err = nil 323 } 324 325 if err != nil { 326 return err 327 } 328 } 329 } 330 331 layerPath := filepath.Join(d.info.HomeDir, rID) 332 tmpID := fmt.Sprintf("%s-removing", rID) 333 tmpLayerPath := filepath.Join(d.info.HomeDir, tmpID) 334 if err := os.Rename(layerPath, tmpLayerPath); err != nil && !os.IsNotExist(err) { 335 if !os.IsPermission(err) { 336 return err 337 } 338 // If permission denied, it's possible that the scratch is still mounted, an 339 // artifact after a hard daemon crash for example. Worth a shot to try detaching it 340 // before retrying the rename. 341 if detachErr := vhd.DetachVhd(filepath.Join(layerPath, "sandbox.vhdx")); detachErr != nil { 342 return errors.Wrapf(err, "failed to detach VHD: %s", detachErr) 343 } 344 if renameErr := os.Rename(layerPath, tmpLayerPath); renameErr != nil && !os.IsNotExist(renameErr) { 345 return errors.Wrapf(err, "second rename attempt following detach failed: %s", renameErr) 346 } 347 } 348 if err := hcsshim.DestroyLayer(d.info, tmpID); err != nil { 349 logrus.Errorf("Failed to DestroyLayer %s: %s", id, err) 350 } 351 352 return nil 353 } 354 355 // GetLayerPath gets the layer path on host 356 func (d *Driver) GetLayerPath(id string) (string, error) { 357 return d.dir(id), nil 358 } 359 360 // Get returns the rootfs path for the id. This will mount the dir at its given path. 361 func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { 362 logrus.Debugf("WindowsGraphDriver Get() id %s mountLabel %s", id, mountLabel) 363 var dir string 364 365 rID, err := d.resolveID(id) 366 if err != nil { 367 return nil, err 368 } 369 if count := d.ctr.Increment(rID); count > 1 { 370 return containerfs.NewLocalContainerFS(d.cache[rID]), nil 371 } 372 373 // Getting the layer paths must be done outside of the lock. 374 layerChain, err := d.getLayerChain(rID) 375 if err != nil { 376 d.ctr.Decrement(rID) 377 return nil, err 378 } 379 380 if err := hcsshim.ActivateLayer(d.info, rID); err != nil { 381 d.ctr.Decrement(rID) 382 return nil, err 383 } 384 if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { 385 d.ctr.Decrement(rID) 386 if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { 387 logrus.Warnf("Failed to Deactivate %s: %s", id, err) 388 } 389 return nil, err 390 } 391 392 mountPath, err := hcsshim.GetLayerMountPath(d.info, rID) 393 if err != nil { 394 d.ctr.Decrement(rID) 395 if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { 396 logrus.Warnf("Failed to Unprepare %s: %s", id, err) 397 } 398 if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { 399 logrus.Warnf("Failed to Deactivate %s: %s", id, err) 400 } 401 return nil, err 402 } 403 d.cacheMu.Lock() 404 d.cache[rID] = mountPath 405 d.cacheMu.Unlock() 406 407 // If the layer has a mount path, use that. Otherwise, use the 408 // folder path. 409 if mountPath != "" { 410 dir = mountPath 411 } else { 412 dir = d.dir(id) 413 } 414 415 return containerfs.NewLocalContainerFS(dir), nil 416 } 417 418 // Put adds a new layer to the driver. 419 func (d *Driver) Put(id string) error { 420 logrus.Debugf("WindowsGraphDriver Put() id %s", id) 421 422 rID, err := d.resolveID(id) 423 if err != nil { 424 return err 425 } 426 if count := d.ctr.Decrement(rID); count > 0 { 427 return nil 428 } 429 d.cacheMu.Lock() 430 _, exists := d.cache[rID] 431 delete(d.cache, rID) 432 d.cacheMu.Unlock() 433 434 // If the cache was not populated, then the layer was left unprepared and deactivated 435 if !exists { 436 return nil 437 } 438 439 if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { 440 return err 441 } 442 return hcsshim.DeactivateLayer(d.info, rID) 443 } 444 445 // Cleanup ensures the information the driver stores is properly removed. 446 // We use this opportunity to cleanup any -removing folders which may be 447 // still left if the daemon was killed while it was removing a layer. 448 func (d *Driver) Cleanup() error { 449 items, err := ioutil.ReadDir(d.info.HomeDir) 450 if err != nil { 451 if os.IsNotExist(err) { 452 return nil 453 } 454 return err 455 } 456 457 // Note we don't return an error below - it's possible the files 458 // are locked. However, next time around after the daemon exits, 459 // we likely will be able to cleanup successfully. Instead we log 460 // warnings if there are errors. 461 for _, item := range items { 462 if item.IsDir() && strings.HasSuffix(item.Name(), "-removing") { 463 if err := hcsshim.DestroyLayer(d.info, item.Name()); err != nil { 464 logrus.Warnf("Failed to cleanup %s: %s", item.Name(), err) 465 } else { 466 logrus.Infof("Cleaned up %s", item.Name()) 467 } 468 } 469 } 470 471 return nil 472 } 473 474 // Diff produces an archive of the changes between the specified 475 // layer and its parent layer which may be "". 476 // The layer should be mounted when calling this function 477 func (d *Driver) Diff(id, parent string) (_ io.ReadCloser, err error) { 478 rID, err := d.resolveID(id) 479 if err != nil { 480 return 481 } 482 483 layerChain, err := d.getLayerChain(rID) 484 if err != nil { 485 return 486 } 487 488 // this is assuming that the layer is unmounted 489 if err := hcsshim.UnprepareLayer(d.info, rID); err != nil { 490 return nil, err 491 } 492 prepare := func() { 493 if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { 494 logrus.Warnf("Failed to Deactivate %s: %s", rID, err) 495 } 496 } 497 498 arch, err := d.exportLayer(rID, layerChain) 499 if err != nil { 500 prepare() 501 return 502 } 503 return ioutils.NewReadCloserWrapper(arch, func() error { 504 err := arch.Close() 505 prepare() 506 return err 507 }), nil 508 } 509 510 // Changes produces a list of changes between the specified layer 511 // and its parent layer. If parent is "", then all changes will be ADD changes. 512 // The layer should not be mounted when calling this function. 513 func (d *Driver) Changes(id, parent string) ([]archive.Change, error) { 514 rID, err := d.resolveID(id) 515 if err != nil { 516 return nil, err 517 } 518 parentChain, err := d.getLayerChain(rID) 519 if err != nil { 520 return nil, err 521 } 522 523 if err := hcsshim.ActivateLayer(d.info, rID); err != nil { 524 return nil, err 525 } 526 defer func() { 527 if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { 528 logrus.Errorf("changes() failed to DeactivateLayer %s %s: %s", id, rID, err2) 529 } 530 }() 531 532 var changes []archive.Change 533 err = winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error { 534 r, err := hcsshim.NewLayerReader(d.info, id, parentChain) 535 if err != nil { 536 return err 537 } 538 defer r.Close() 539 540 for { 541 name, _, fileInfo, err := r.Next() 542 if err == io.EOF { 543 return nil 544 } 545 if err != nil { 546 return err 547 } 548 name = filepath.ToSlash(name) 549 if fileInfo == nil { 550 changes = append(changes, archive.Change{Path: name, Kind: archive.ChangeDelete}) 551 } else { 552 // Currently there is no way to tell between an add and a modify. 553 changes = append(changes, archive.Change{Path: name, Kind: archive.ChangeModify}) 554 } 555 } 556 }) 557 if err != nil { 558 return nil, err 559 } 560 561 return changes, nil 562 } 563 564 // ApplyDiff extracts the changeset from the given diff into the 565 // layer with the specified id and parent, returning the size of the 566 // new layer in bytes. 567 // The layer should not be mounted when calling this function 568 func (d *Driver) ApplyDiff(id, parent string, diff io.Reader) (int64, error) { 569 var layerChain []string 570 if parent != "" { 571 rPId, err := d.resolveID(parent) 572 if err != nil { 573 return 0, err 574 } 575 parentChain, err := d.getLayerChain(rPId) 576 if err != nil { 577 return 0, err 578 } 579 parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId) 580 if err != nil { 581 return 0, err 582 } 583 layerChain = append(layerChain, parentPath) 584 layerChain = append(layerChain, parentChain...) 585 } 586 587 size, err := d.importLayer(id, diff, layerChain) 588 if err != nil { 589 return 0, err 590 } 591 592 if err = d.setLayerChain(id, layerChain); err != nil { 593 return 0, err 594 } 595 596 return size, nil 597 } 598 599 // DiffSize calculates the changes between the specified layer 600 // and its parent and returns the size in bytes of the changes 601 // relative to its base filesystem directory. 602 func (d *Driver) DiffSize(id, parent string) (size int64, err error) { 603 rPId, err := d.resolveID(parent) 604 if err != nil { 605 return 606 } 607 608 changes, err := d.Changes(id, rPId) 609 if err != nil { 610 return 611 } 612 613 layerFs, err := d.Get(id, "") 614 if err != nil { 615 return 616 } 617 defer d.Put(id) 618 619 return archive.ChangesSize(layerFs.Path(), changes), nil 620 } 621 622 // GetMetadata returns custom driver information. 623 func (d *Driver) GetMetadata(id string) (map[string]string, error) { 624 m := make(map[string]string) 625 m["dir"] = d.dir(id) 626 return m, nil 627 } 628 629 func writeTarFromLayer(r hcsshim.LayerReader, w io.Writer) error { 630 t := tar.NewWriter(w) 631 for { 632 name, size, fileInfo, err := r.Next() 633 if err == io.EOF { 634 break 635 } 636 if err != nil { 637 return err 638 } 639 if fileInfo == nil { 640 // Write a whiteout file. 641 hdr := &tar.Header{ 642 Name: filepath.ToSlash(filepath.Join(filepath.Dir(name), archive.WhiteoutPrefix+filepath.Base(name))), 643 } 644 err := t.WriteHeader(hdr) 645 if err != nil { 646 return err 647 } 648 } else { 649 err = backuptar.WriteTarFileFromBackupStream(t, r, name, size, fileInfo) 650 if err != nil { 651 return err 652 } 653 } 654 } 655 return t.Close() 656 } 657 658 // exportLayer generates an archive from a layer based on the given ID. 659 func (d *Driver) exportLayer(id string, parentLayerPaths []string) (io.ReadCloser, error) { 660 archive, w := io.Pipe() 661 go func() { 662 err := winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error { 663 r, err := hcsshim.NewLayerReader(d.info, id, parentLayerPaths) 664 if err != nil { 665 return err 666 } 667 668 err = writeTarFromLayer(r, w) 669 cerr := r.Close() 670 if err == nil { 671 err = cerr 672 } 673 return err 674 }) 675 w.CloseWithError(err) 676 }() 677 678 return archive, nil 679 } 680 681 // writeBackupStreamFromTarAndSaveMutatedFiles reads data from a tar stream and 682 // writes it to a backup stream, and also saves any files that will be mutated 683 // by the import layer process to a backup location. 684 func writeBackupStreamFromTarAndSaveMutatedFiles(buf *bufio.Writer, w io.Writer, t *tar.Reader, hdr *tar.Header, root string) (nextHdr *tar.Header, err error) { 685 var bcdBackup *os.File 686 var bcdBackupWriter *winio.BackupFileWriter 687 if backupPath, ok := mutatedFiles[hdr.Name]; ok { 688 bcdBackup, err = os.Create(filepath.Join(root, backupPath)) 689 if err != nil { 690 return nil, err 691 } 692 defer func() { 693 cerr := bcdBackup.Close() 694 if err == nil { 695 err = cerr 696 } 697 }() 698 699 bcdBackupWriter = winio.NewBackupFileWriter(bcdBackup, false) 700 defer func() { 701 cerr := bcdBackupWriter.Close() 702 if err == nil { 703 err = cerr 704 } 705 }() 706 707 buf.Reset(io.MultiWriter(w, bcdBackupWriter)) 708 } else { 709 buf.Reset(w) 710 } 711 712 defer func() { 713 ferr := buf.Flush() 714 if err == nil { 715 err = ferr 716 } 717 }() 718 719 return backuptar.WriteBackupStreamFromTarFile(buf, t, hdr) 720 } 721 722 func writeLayerFromTar(r io.Reader, w hcsshim.LayerWriter, root string) (int64, error) { 723 t := tar.NewReader(r) 724 hdr, err := t.Next() 725 totalSize := int64(0) 726 buf := bufio.NewWriter(nil) 727 for err == nil { 728 base := path.Base(hdr.Name) 729 if strings.HasPrefix(base, archive.WhiteoutPrefix) { 730 name := path.Join(path.Dir(hdr.Name), base[len(archive.WhiteoutPrefix):]) 731 err = w.Remove(filepath.FromSlash(name)) 732 if err != nil { 733 return 0, err 734 } 735 hdr, err = t.Next() 736 } else if hdr.Typeflag == tar.TypeLink { 737 err = w.AddLink(filepath.FromSlash(hdr.Name), filepath.FromSlash(hdr.Linkname)) 738 if err != nil { 739 return 0, err 740 } 741 hdr, err = t.Next() 742 } else { 743 var ( 744 name string 745 size int64 746 fileInfo *winio.FileBasicInfo 747 ) 748 name, size, fileInfo, err = backuptar.FileInfoFromHeader(hdr) 749 if err != nil { 750 return 0, err 751 } 752 err = w.Add(filepath.FromSlash(name), fileInfo) 753 if err != nil { 754 return 0, err 755 } 756 hdr, err = writeBackupStreamFromTarAndSaveMutatedFiles(buf, w, t, hdr, root) 757 totalSize += size 758 } 759 } 760 if err != io.EOF { 761 return 0, err 762 } 763 return totalSize, nil 764 } 765 766 // importLayer adds a new layer to the tag and graph store based on the given data. 767 func (d *Driver) importLayer(id string, layerData io.Reader, parentLayerPaths []string) (size int64, err error) { 768 if !noreexec { 769 cmd := reexec.Command(append([]string{"docker-windows-write-layer", d.info.HomeDir, id}, parentLayerPaths...)...) 770 output := bytes.NewBuffer(nil) 771 cmd.Stdin = layerData 772 cmd.Stdout = output 773 cmd.Stderr = output 774 775 if err = cmd.Start(); err != nil { 776 return 777 } 778 779 if err = cmd.Wait(); err != nil { 780 return 0, fmt.Errorf("re-exec error: %v: output: %s", err, output) 781 } 782 783 return strconv.ParseInt(output.String(), 10, 64) 784 } 785 return writeLayer(layerData, d.info.HomeDir, id, parentLayerPaths...) 786 } 787 788 // writeLayerReexec is the re-exec entry point for writing a layer from a tar file 789 func writeLayerReexec() { 790 size, err := writeLayer(os.Stdin, os.Args[1], os.Args[2], os.Args[3:]...) 791 if err != nil { 792 fmt.Fprint(os.Stderr, err) 793 os.Exit(1) 794 } 795 fmt.Fprint(os.Stdout, size) 796 } 797 798 // writeLayer writes a layer from a tar file. 799 func writeLayer(layerData io.Reader, home string, id string, parentLayerPaths ...string) (size int64, retErr error) { 800 err := winio.EnableProcessPrivileges([]string{winio.SeBackupPrivilege, winio.SeRestorePrivilege}) 801 if err != nil { 802 return 0, err 803 } 804 if noreexec { 805 defer func() { 806 if err := winio.DisableProcessPrivileges([]string{winio.SeBackupPrivilege, winio.SeRestorePrivilege}); err != nil { 807 // This should never happen, but just in case when in debugging mode. 808 // See https://github.com/docker/docker/pull/28002#discussion_r86259241 for rationale. 809 panic("Failed to disabled process privileges while in non re-exec mode") 810 } 811 }() 812 } 813 814 info := hcsshim.DriverInfo{ 815 Flavour: filterDriver, 816 HomeDir: home, 817 } 818 819 w, err := hcsshim.NewLayerWriter(info, id, parentLayerPaths) 820 if err != nil { 821 return 0, err 822 } 823 824 defer func() { 825 if err := w.Close(); err != nil { 826 // This error should not be discarded as a failure here 827 // could result in an invalid layer on disk 828 if retErr == nil { 829 retErr = err 830 } 831 } 832 }() 833 834 return writeLayerFromTar(layerData, w, filepath.Join(home, id)) 835 } 836 837 // resolveID computes the layerID information based on the given id. 838 func (d *Driver) resolveID(id string) (string, error) { 839 content, err := ioutil.ReadFile(filepath.Join(d.dir(id), "layerID")) 840 if os.IsNotExist(err) { 841 return id, nil 842 } else if err != nil { 843 return "", err 844 } 845 return string(content), nil 846 } 847 848 // setID stores the layerId in disk. 849 func (d *Driver) setID(id, altID string) error { 850 return ioutil.WriteFile(filepath.Join(d.dir(id), "layerId"), []byte(altID), 0600) 851 } 852 853 // getLayerChain returns the layer chain information. 854 func (d *Driver) getLayerChain(id string) ([]string, error) { 855 jPath := filepath.Join(d.dir(id), "layerchain.json") 856 content, err := ioutil.ReadFile(jPath) 857 if os.IsNotExist(err) { 858 return nil, nil 859 } else if err != nil { 860 return nil, fmt.Errorf("Unable to read layerchain file - %s", err) 861 } 862 863 var layerChain []string 864 err = json.Unmarshal(content, &layerChain) 865 if err != nil { 866 return nil, fmt.Errorf("Failed to unmarshall layerchain json - %s", err) 867 } 868 869 return layerChain, nil 870 } 871 872 // setLayerChain stores the layer chain information in disk. 873 func (d *Driver) setLayerChain(id string, chain []string) error { 874 content, err := json.Marshal(&chain) 875 if err != nil { 876 return fmt.Errorf("Failed to marshall layerchain json - %s", err) 877 } 878 879 jPath := filepath.Join(d.dir(id), "layerchain.json") 880 err = ioutil.WriteFile(jPath, content, 0600) 881 if err != nil { 882 return fmt.Errorf("Unable to write layerchain file - %s", err) 883 } 884 885 return nil 886 } 887 888 type fileGetCloserWithBackupPrivileges struct { 889 path string 890 } 891 892 func (fg *fileGetCloserWithBackupPrivileges) Get(filename string) (io.ReadCloser, error) { 893 if backupPath, ok := mutatedFiles[filename]; ok { 894 return os.Open(filepath.Join(fg.path, backupPath)) 895 } 896 897 var f *os.File 898 // Open the file while holding the Windows backup privilege. This ensures that the 899 // file can be opened even if the caller does not actually have access to it according 900 // to the security descriptor. Also use sequential file access to avoid depleting the 901 // standby list - Microsoft VSO Bug Tracker #9900466 902 err := winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error { 903 path := longpath.AddPrefix(filepath.Join(fg.path, filename)) 904 p, err := windows.UTF16FromString(path) 905 if err != nil { 906 return err 907 } 908 const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN 909 h, err := windows.CreateFile(&p[0], windows.GENERIC_READ, windows.FILE_SHARE_READ, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS|fileFlagSequentialScan, 0) 910 if err != nil { 911 return &os.PathError{Op: "open", Path: path, Err: err} 912 } 913 f = os.NewFile(uintptr(h), path) 914 return nil 915 }) 916 return f, err 917 } 918 919 func (fg *fileGetCloserWithBackupPrivileges) Close() error { 920 return nil 921 } 922 923 // DiffGetter returns a FileGetCloser that can read files from the directory that 924 // contains files for the layer differences. Used for direct access for tar-split. 925 func (d *Driver) DiffGetter(id string) (graphdriver.FileGetCloser, error) { 926 id, err := d.resolveID(id) 927 if err != nil { 928 return nil, err 929 } 930 931 return &fileGetCloserWithBackupPrivileges{d.dir(id)}, nil 932 } 933 934 type storageOptions struct { 935 size uint64 936 } 937 938 func parseStorageOpt(storageOpt map[string]string) (*storageOptions, error) { 939 options := storageOptions{} 940 941 // Read size to change the block device size per container. 942 for key, val := range storageOpt { 943 key := strings.ToLower(key) 944 switch key { 945 case "size": 946 size, err := units.RAMInBytes(val) 947 if err != nil { 948 return nil, err 949 } 950 options.size = uint64(size) 951 } 952 } 953 return &options, nil 954 }