windows.go 26 KB

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