windows.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  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. sandbox := filepath.Join(layerPath, "sandbox.vhdx")
  304. if _, statErr := os.Stat(sandbox); statErr == nil {
  305. if detachErr := vhd.DetachVhd(sandbox); detachErr != nil {
  306. return errors.Wrapf(err, "failed to detach VHD: %s", detachErr)
  307. }
  308. if renameErr := os.Rename(layerPath, tmpLayerPath); renameErr != nil && !os.IsNotExist(renameErr) {
  309. return errors.Wrapf(err, "second rename attempt following detach failed: %s", renameErr)
  310. }
  311. }
  312. }
  313. if err := hcsshim.DestroyLayer(d.info, tmpID); err != nil {
  314. logrus.Errorf("Failed to DestroyLayer %s: %s", id, err)
  315. }
  316. return nil
  317. }
  318. // GetLayerPath gets the layer path on host
  319. func (d *Driver) GetLayerPath(id string) (string, error) {
  320. return d.dir(id), nil
  321. }
  322. // Get returns the rootfs path for the id. This will mount the dir at its given path.
  323. func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) {
  324. logrus.Debugf("WindowsGraphDriver Get() id %s mountLabel %s", id, mountLabel)
  325. var dir string
  326. rID, err := d.resolveID(id)
  327. if err != nil {
  328. return nil, err
  329. }
  330. if count := d.ctr.Increment(rID); count > 1 {
  331. return containerfs.NewLocalContainerFS(d.cache[rID]), nil
  332. }
  333. // Getting the layer paths must be done outside of the lock.
  334. layerChain, err := d.getLayerChain(rID)
  335. if err != nil {
  336. d.ctr.Decrement(rID)
  337. return nil, err
  338. }
  339. if err := hcsshim.ActivateLayer(d.info, rID); err != nil {
  340. d.ctr.Decrement(rID)
  341. return nil, err
  342. }
  343. if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil {
  344. d.ctr.Decrement(rID)
  345. if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil {
  346. logrus.Warnf("Failed to Deactivate %s: %s", id, err)
  347. }
  348. return nil, err
  349. }
  350. mountPath, err := hcsshim.GetLayerMountPath(d.info, rID)
  351. if err != nil {
  352. d.ctr.Decrement(rID)
  353. if err := hcsshim.UnprepareLayer(d.info, rID); err != nil {
  354. logrus.Warnf("Failed to Unprepare %s: %s", id, err)
  355. }
  356. if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil {
  357. logrus.Warnf("Failed to Deactivate %s: %s", id, err)
  358. }
  359. return nil, err
  360. }
  361. d.cacheMu.Lock()
  362. d.cache[rID] = mountPath
  363. d.cacheMu.Unlock()
  364. // If the layer has a mount path, use that. Otherwise, use the
  365. // folder path.
  366. if mountPath != "" {
  367. dir = mountPath
  368. } else {
  369. dir = d.dir(id)
  370. }
  371. return containerfs.NewLocalContainerFS(dir), nil
  372. }
  373. // Put adds a new layer to the driver.
  374. func (d *Driver) Put(id string) error {
  375. logrus.Debugf("WindowsGraphDriver Put() id %s", id)
  376. rID, err := d.resolveID(id)
  377. if err != nil {
  378. return err
  379. }
  380. if count := d.ctr.Decrement(rID); count > 0 {
  381. return nil
  382. }
  383. d.cacheMu.Lock()
  384. _, exists := d.cache[rID]
  385. delete(d.cache, rID)
  386. d.cacheMu.Unlock()
  387. // If the cache was not populated, then the layer was left unprepared and deactivated
  388. if !exists {
  389. return nil
  390. }
  391. if err := hcsshim.UnprepareLayer(d.info, rID); err != nil {
  392. return err
  393. }
  394. return hcsshim.DeactivateLayer(d.info, rID)
  395. }
  396. // Cleanup ensures the information the driver stores is properly removed.
  397. // We use this opportunity to cleanup any -removing folders which may be
  398. // still left if the daemon was killed while it was removing a layer.
  399. func (d *Driver) Cleanup() error {
  400. items, err := ioutil.ReadDir(d.info.HomeDir)
  401. if err != nil {
  402. if os.IsNotExist(err) {
  403. return nil
  404. }
  405. return err
  406. }
  407. // Note we don't return an error below - it's possible the files
  408. // are locked. However, next time around after the daemon exits,
  409. // we likely will be able to cleanup successfully. Instead we log
  410. // warnings if there are errors.
  411. for _, item := range items {
  412. if item.IsDir() && strings.HasSuffix(item.Name(), "-removing") {
  413. if err := hcsshim.DestroyLayer(d.info, item.Name()); err != nil {
  414. logrus.Warnf("Failed to cleanup %s: %s", item.Name(), err)
  415. } else {
  416. logrus.Infof("Cleaned up %s", item.Name())
  417. }
  418. }
  419. }
  420. return nil
  421. }
  422. // Diff produces an archive of the changes between the specified
  423. // layer and its parent layer which may be "".
  424. // The layer should be mounted when calling this function
  425. func (d *Driver) Diff(id, parent string) (_ io.ReadCloser, err error) {
  426. rID, err := d.resolveID(id)
  427. if err != nil {
  428. return
  429. }
  430. layerChain, err := d.getLayerChain(rID)
  431. if err != nil {
  432. return
  433. }
  434. // this is assuming that the layer is unmounted
  435. if err := hcsshim.UnprepareLayer(d.info, rID); err != nil {
  436. return nil, err
  437. }
  438. prepare := func() {
  439. if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil {
  440. logrus.Warnf("Failed to Deactivate %s: %s", rID, err)
  441. }
  442. }
  443. arch, err := d.exportLayer(rID, layerChain)
  444. if err != nil {
  445. prepare()
  446. return
  447. }
  448. return ioutils.NewReadCloserWrapper(arch, func() error {
  449. err := arch.Close()
  450. prepare()
  451. return err
  452. }), nil
  453. }
  454. // Changes produces a list of changes between the specified layer
  455. // and its parent layer. If parent is "", then all changes will be ADD changes.
  456. // The layer should not be mounted when calling this function.
  457. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  458. rID, err := d.resolveID(id)
  459. if err != nil {
  460. return nil, err
  461. }
  462. parentChain, err := d.getLayerChain(rID)
  463. if err != nil {
  464. return nil, err
  465. }
  466. if err := hcsshim.ActivateLayer(d.info, rID); err != nil {
  467. return nil, err
  468. }
  469. defer func() {
  470. if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil {
  471. logrus.Errorf("changes() failed to DeactivateLayer %s %s: %s", id, rID, err2)
  472. }
  473. }()
  474. var changes []archive.Change
  475. err = winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error {
  476. r, err := hcsshim.NewLayerReader(d.info, id, parentChain)
  477. if err != nil {
  478. return err
  479. }
  480. defer r.Close()
  481. for {
  482. name, _, fileInfo, err := r.Next()
  483. if err == io.EOF {
  484. return nil
  485. }
  486. if err != nil {
  487. return err
  488. }
  489. name = filepath.ToSlash(name)
  490. if fileInfo == nil {
  491. changes = append(changes, archive.Change{Path: name, Kind: archive.ChangeDelete})
  492. } else {
  493. // Currently there is no way to tell between an add and a modify.
  494. changes = append(changes, archive.Change{Path: name, Kind: archive.ChangeModify})
  495. }
  496. }
  497. })
  498. if err != nil {
  499. return nil, err
  500. }
  501. return changes, nil
  502. }
  503. // ApplyDiff extracts the changeset from the given diff into the
  504. // layer with the specified id and parent, returning the size of the
  505. // new layer in bytes.
  506. // The layer should not be mounted when calling this function
  507. func (d *Driver) ApplyDiff(id, parent string, diff io.Reader) (int64, error) {
  508. var layerChain []string
  509. if parent != "" {
  510. rPId, err := d.resolveID(parent)
  511. if err != nil {
  512. return 0, err
  513. }
  514. parentChain, err := d.getLayerChain(rPId)
  515. if err != nil {
  516. return 0, err
  517. }
  518. parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId)
  519. if err != nil {
  520. return 0, err
  521. }
  522. layerChain = append(layerChain, parentPath)
  523. layerChain = append(layerChain, parentChain...)
  524. }
  525. size, err := d.importLayer(id, diff, layerChain)
  526. if err != nil {
  527. return 0, err
  528. }
  529. if err = d.setLayerChain(id, layerChain); err != nil {
  530. return 0, err
  531. }
  532. return size, nil
  533. }
  534. // DiffSize calculates the changes between the specified layer
  535. // and its parent and returns the size in bytes of the changes
  536. // relative to its base filesystem directory.
  537. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  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. m := make(map[string]string)
  556. m["dir"] = d.dir(id)
  557. return m, nil
  558. }
  559. func writeTarFromLayer(r hcsshim.LayerReader, w io.Writer) error {
  560. t := tar.NewWriter(w)
  561. for {
  562. name, size, fileInfo, err := r.Next()
  563. if err == io.EOF {
  564. break
  565. }
  566. if err != nil {
  567. return err
  568. }
  569. if fileInfo == nil {
  570. // Write a whiteout file.
  571. hdr := &tar.Header{
  572. Name: filepath.ToSlash(filepath.Join(filepath.Dir(name), archive.WhiteoutPrefix+filepath.Base(name))),
  573. }
  574. err := t.WriteHeader(hdr)
  575. if err != nil {
  576. return err
  577. }
  578. } else {
  579. err = backuptar.WriteTarFileFromBackupStream(t, r, name, size, fileInfo)
  580. if err != nil {
  581. return err
  582. }
  583. }
  584. }
  585. return t.Close()
  586. }
  587. // exportLayer generates an archive from a layer based on the given ID.
  588. func (d *Driver) exportLayer(id string, parentLayerPaths []string) (io.ReadCloser, error) {
  589. archive, w := io.Pipe()
  590. go func() {
  591. err := winio.RunWithPrivilege(winio.SeBackupPrivilege, func() error {
  592. r, err := hcsshim.NewLayerReader(d.info, id, parentLayerPaths)
  593. if err != nil {
  594. return err
  595. }
  596. err = writeTarFromLayer(r, w)
  597. cerr := r.Close()
  598. if err == nil {
  599. err = cerr
  600. }
  601. return err
  602. })
  603. w.CloseWithError(err)
  604. }()
  605. return archive, nil
  606. }
  607. // writeBackupStreamFromTarAndSaveMutatedFiles reads data from a tar stream and
  608. // writes it to a backup stream, and also saves any files that will be mutated
  609. // by the import layer process to a backup location.
  610. func writeBackupStreamFromTarAndSaveMutatedFiles(buf *bufio.Writer, w io.Writer, t *tar.Reader, hdr *tar.Header, root string) (nextHdr *tar.Header, err error) {
  611. var bcdBackup *os.File
  612. var bcdBackupWriter *winio.BackupFileWriter
  613. if backupPath, ok := mutatedFiles[hdr.Name]; ok {
  614. bcdBackup, err = os.Create(filepath.Join(root, backupPath))
  615. if err != nil {
  616. return nil, err
  617. }
  618. defer func() {
  619. cerr := bcdBackup.Close()
  620. if err == nil {
  621. err = cerr
  622. }
  623. }()
  624. bcdBackupWriter = winio.NewBackupFileWriter(bcdBackup, false)
  625. defer func() {
  626. cerr := bcdBackupWriter.Close()
  627. if err == nil {
  628. err = cerr
  629. }
  630. }()
  631. buf.Reset(io.MultiWriter(w, bcdBackupWriter))
  632. } else {
  633. buf.Reset(w)
  634. }
  635. defer func() {
  636. ferr := buf.Flush()
  637. if err == nil {
  638. err = ferr
  639. }
  640. }()
  641. return backuptar.WriteBackupStreamFromTarFile(buf, t, hdr)
  642. }
  643. func writeLayerFromTar(r io.Reader, w hcsshim.LayerWriter, root string) (int64, error) {
  644. t := tar.NewReader(r)
  645. hdr, err := t.Next()
  646. totalSize := int64(0)
  647. buf := bufio.NewWriter(nil)
  648. for err == nil {
  649. base := path.Base(hdr.Name)
  650. if strings.HasPrefix(base, archive.WhiteoutPrefix) {
  651. name := path.Join(path.Dir(hdr.Name), base[len(archive.WhiteoutPrefix):])
  652. err = w.Remove(filepath.FromSlash(name))
  653. if err != nil {
  654. return 0, err
  655. }
  656. hdr, err = t.Next()
  657. } else if hdr.Typeflag == tar.TypeLink {
  658. err = w.AddLink(filepath.FromSlash(hdr.Name), filepath.FromSlash(hdr.Linkname))
  659. if err != nil {
  660. return 0, err
  661. }
  662. hdr, err = t.Next()
  663. } else {
  664. var (
  665. name string
  666. size int64
  667. fileInfo *winio.FileBasicInfo
  668. )
  669. name, size, fileInfo, err = backuptar.FileInfoFromHeader(hdr)
  670. if err != nil {
  671. return 0, err
  672. }
  673. err = w.Add(filepath.FromSlash(name), fileInfo)
  674. if err != nil {
  675. return 0, err
  676. }
  677. hdr, err = writeBackupStreamFromTarAndSaveMutatedFiles(buf, w, t, hdr, root)
  678. totalSize += size
  679. }
  680. }
  681. if err != io.EOF {
  682. return 0, err
  683. }
  684. return totalSize, nil
  685. }
  686. // importLayer adds a new layer to the tag and graph store based on the given data.
  687. func (d *Driver) importLayer(id string, layerData io.Reader, parentLayerPaths []string) (size int64, err error) {
  688. if !noreexec {
  689. cmd := reexec.Command(append([]string{"docker-windows-write-layer", d.info.HomeDir, id}, parentLayerPaths...)...)
  690. output := bytes.NewBuffer(nil)
  691. cmd.Stdin = layerData
  692. cmd.Stdout = output
  693. cmd.Stderr = output
  694. if err = cmd.Start(); err != nil {
  695. return
  696. }
  697. if err = cmd.Wait(); err != nil {
  698. return 0, fmt.Errorf("re-exec error: %v: output: %s", err, output)
  699. }
  700. return strconv.ParseInt(output.String(), 10, 64)
  701. }
  702. return writeLayer(layerData, d.info.HomeDir, id, parentLayerPaths...)
  703. }
  704. // writeLayerReexec is the re-exec entry point for writing a layer from a tar file
  705. func writeLayerReexec() {
  706. size, err := writeLayer(os.Stdin, os.Args[1], os.Args[2], os.Args[3:]...)
  707. if err != nil {
  708. fmt.Fprint(os.Stderr, err)
  709. os.Exit(1)
  710. }
  711. fmt.Fprint(os.Stdout, size)
  712. }
  713. // writeLayer writes a layer from a tar file.
  714. func writeLayer(layerData io.Reader, home string, id string, parentLayerPaths ...string) (size int64, retErr error) {
  715. err := winio.EnableProcessPrivileges([]string{winio.SeBackupPrivilege, winio.SeRestorePrivilege})
  716. if err != nil {
  717. return 0, err
  718. }
  719. if noreexec {
  720. defer func() {
  721. if err := winio.DisableProcessPrivileges([]string{winio.SeBackupPrivilege, winio.SeRestorePrivilege}); err != nil {
  722. // This should never happen, but just in case when in debugging mode.
  723. // See https://github.com/docker/docker/pull/28002#discussion_r86259241 for rationale.
  724. panic("Failed to disabled process privileges while in non re-exec mode")
  725. }
  726. }()
  727. }
  728. info := hcsshim.DriverInfo{
  729. Flavour: filterDriver,
  730. HomeDir: home,
  731. }
  732. w, err := hcsshim.NewLayerWriter(info, id, parentLayerPaths)
  733. if err != nil {
  734. return 0, err
  735. }
  736. defer func() {
  737. if err := w.Close(); err != nil {
  738. // This error should not be discarded as a failure here
  739. // could result in an invalid layer on disk
  740. if retErr == nil {
  741. retErr = err
  742. }
  743. }
  744. }()
  745. return writeLayerFromTar(layerData, w, filepath.Join(home, id))
  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. id, err := d.resolveID(id)
  825. if err != nil {
  826. return nil, err
  827. }
  828. return &fileGetCloserWithBackupPrivileges{d.dir(id)}, nil
  829. }
  830. type storageOptions struct {
  831. size uint64
  832. }
  833. func parseStorageOpt(storageOpt map[string]string) (*storageOptions, error) {
  834. options := storageOptions{}
  835. // Read size to change the block device size per container.
  836. for key, val := range storageOpt {
  837. key := strings.ToLower(key)
  838. switch key {
  839. case "size":
  840. size, err := units.RAMInBytes(val)
  841. if err != nil {
  842. return nil, err
  843. }
  844. options.size = uint64(size)
  845. }
  846. }
  847. return &options, nil
  848. }