windows.go 26 KB

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