windows.go 26 KB

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