windows.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. //+build windows
  2. package windows
  3. import (
  4. "crypto/sha512"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/Microsoft/hcsshim"
  15. "github.com/Sirupsen/logrus"
  16. "github.com/docker/docker/daemon/graphdriver"
  17. "github.com/docker/docker/pkg/archive"
  18. "github.com/docker/docker/pkg/chrootarchive"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/ioutils"
  21. "github.com/docker/docker/pkg/random"
  22. )
  23. // init registers the windows graph drivers to the register.
  24. func init() {
  25. graphdriver.Register("windowsfilter", InitFilter)
  26. graphdriver.Register("windowsdiff", InitDiff)
  27. }
  28. const (
  29. // diffDriver is an hcsshim driver type
  30. diffDriver = iota
  31. // filterDriver is an hcsshim driver type
  32. filterDriver
  33. )
  34. // Driver represents a windows graph driver.
  35. type Driver struct {
  36. // info stores the shim driver information
  37. info hcsshim.DriverInfo
  38. // Mutex protects concurrent modification to active
  39. sync.Mutex
  40. // active stores references to the activated layers
  41. active map[string]int
  42. }
  43. // InitFilter returns a new Windows storage filter driver.
  44. func InitFilter(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  45. logrus.Debugf("WindowsGraphDriver InitFilter at %s", home)
  46. d := &Driver{
  47. info: hcsshim.DriverInfo{
  48. HomeDir: home,
  49. Flavour: filterDriver,
  50. },
  51. active: make(map[string]int),
  52. }
  53. return d, nil
  54. }
  55. // InitDiff returns a new Windows differencing disk driver.
  56. func InitDiff(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  57. logrus.Debugf("WindowsGraphDriver InitDiff at %s", home)
  58. d := &Driver{
  59. info: hcsshim.DriverInfo{
  60. HomeDir: home,
  61. Flavour: diffDriver,
  62. },
  63. active: make(map[string]int),
  64. }
  65. return d, nil
  66. }
  67. // String returns the string representation of a driver.
  68. func (d *Driver) String() string {
  69. switch d.info.Flavour {
  70. case diffDriver:
  71. return "windowsdiff"
  72. case filterDriver:
  73. return "windowsfilter"
  74. default:
  75. return "Unknown driver flavour"
  76. }
  77. }
  78. // Status returns the status of the driver.
  79. func (d *Driver) Status() [][2]string {
  80. return [][2]string{
  81. {"Windows", ""},
  82. }
  83. }
  84. // Exists returns true if the given id is registered with this driver.
  85. func (d *Driver) Exists(id string) bool {
  86. rID, err := d.resolveID(id)
  87. if err != nil {
  88. return false
  89. }
  90. result, err := hcsshim.LayerExists(d.info, rID)
  91. if err != nil {
  92. return false
  93. }
  94. return result
  95. }
  96. // Create creates a new layer with the given id.
  97. func (d *Driver) Create(id, parent, mountLabel string) error {
  98. rPId, err := d.resolveID(parent)
  99. if err != nil {
  100. return err
  101. }
  102. parentChain, err := d.getLayerChain(rPId)
  103. if err != nil {
  104. return err
  105. }
  106. var layerChain []string
  107. parentIsInit := strings.HasSuffix(rPId, "-init")
  108. if !parentIsInit && rPId != "" {
  109. parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId)
  110. if err != nil {
  111. return err
  112. }
  113. layerChain = []string{parentPath}
  114. }
  115. layerChain = append(layerChain, parentChain...)
  116. if parentIsInit {
  117. if len(layerChain) == 0 {
  118. return fmt.Errorf("Cannot create a read/write layer without a parent layer.")
  119. }
  120. if err := hcsshim.CreateSandboxLayer(d.info, id, layerChain[0], layerChain); err != nil {
  121. return err
  122. }
  123. } else {
  124. if err := hcsshim.CreateLayer(d.info, id, rPId); err != nil {
  125. return err
  126. }
  127. }
  128. if _, err := os.Lstat(d.dir(parent)); err != nil {
  129. if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil {
  130. logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2)
  131. }
  132. return fmt.Errorf("Cannot create layer with missing parent %s: %s", parent, err)
  133. }
  134. if err := d.setLayerChain(id, layerChain); err != nil {
  135. if err2 := hcsshim.DestroyLayer(d.info, id); err2 != nil {
  136. logrus.Warnf("Failed to DestroyLayer %s: %s", id, err2)
  137. }
  138. return err
  139. }
  140. return nil
  141. }
  142. // dir returns the absolute path to the layer.
  143. func (d *Driver) dir(id string) string {
  144. return filepath.Join(d.info.HomeDir, filepath.Base(id))
  145. }
  146. // Remove unmounts and removes the dir information.
  147. func (d *Driver) Remove(id string) error {
  148. rID, err := d.resolveID(id)
  149. if err != nil {
  150. return err
  151. }
  152. os.RemoveAll(filepath.Join(d.info.HomeDir, "sysfile-backups", rID)) // ok to fail
  153. return hcsshim.DestroyLayer(d.info, rID)
  154. }
  155. // Get returns the rootfs path for the id. This will mount the dir at it's given path.
  156. func (d *Driver) Get(id, mountLabel string) (string, error) {
  157. logrus.Debugf("WindowsGraphDriver Get() id %s mountLabel %s", id, mountLabel)
  158. var dir string
  159. d.Lock()
  160. defer d.Unlock()
  161. rID, err := d.resolveID(id)
  162. if err != nil {
  163. return "", err
  164. }
  165. // Getting the layer paths must be done outside of the lock.
  166. layerChain, err := d.getLayerChain(rID)
  167. if err != nil {
  168. return "", err
  169. }
  170. if d.active[rID] == 0 {
  171. if err := hcsshim.ActivateLayer(d.info, rID); err != nil {
  172. return "", err
  173. }
  174. if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil {
  175. if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil {
  176. logrus.Warnf("Failed to Deactivate %s: %s", id, err)
  177. }
  178. return "", err
  179. }
  180. }
  181. mountPath, err := hcsshim.GetLayerMountPath(d.info, rID)
  182. if err != nil {
  183. if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil {
  184. logrus.Warnf("Failed to Deactivate %s: %s", id, err)
  185. }
  186. return "", err
  187. }
  188. d.active[rID]++
  189. // If the layer has a mount path, use that. Otherwise, use the
  190. // folder path.
  191. if mountPath != "" {
  192. dir = mountPath
  193. } else {
  194. dir = d.dir(id)
  195. }
  196. return dir, nil
  197. }
  198. // Put adds a new layer to the driver.
  199. func (d *Driver) Put(id string) error {
  200. logrus.Debugf("WindowsGraphDriver Put() id %s", id)
  201. rID, err := d.resolveID(id)
  202. if err != nil {
  203. return err
  204. }
  205. d.Lock()
  206. defer d.Unlock()
  207. if d.active[rID] > 1 {
  208. d.active[rID]--
  209. } else if d.active[rID] == 1 {
  210. if err := hcsshim.UnprepareLayer(d.info, rID); err != nil {
  211. return err
  212. }
  213. if err := hcsshim.DeactivateLayer(d.info, rID); err != nil {
  214. return err
  215. }
  216. delete(d.active, rID)
  217. }
  218. return nil
  219. }
  220. // Cleanup ensures the information the driver stores is properly removed.
  221. func (d *Driver) Cleanup() error {
  222. return nil
  223. }
  224. // Diff produces an archive of the changes between the specified
  225. // layer and its parent layer which may be "".
  226. func (d *Driver) Diff(id, parent string) (arch archive.Archive, err error) {
  227. rID, err := d.resolveID(id)
  228. if err != nil {
  229. return
  230. }
  231. // Getting the layer paths must be done outside of the lock.
  232. layerChain, err := d.getLayerChain(rID)
  233. if err != nil {
  234. return
  235. }
  236. d.Lock()
  237. // To support export, a layer must be activated but not prepared.
  238. if d.info.Flavour == filterDriver {
  239. if d.active[rID] == 0 {
  240. if err = hcsshim.ActivateLayer(d.info, rID); err != nil {
  241. d.Unlock()
  242. return
  243. }
  244. defer func() {
  245. if err := hcsshim.DeactivateLayer(d.info, rID); err != nil {
  246. logrus.Warnf("Failed to Deactivate %s: %s", rID, err)
  247. }
  248. }()
  249. } else {
  250. if err = hcsshim.UnprepareLayer(d.info, rID); err != nil {
  251. d.Unlock()
  252. return
  253. }
  254. defer func() {
  255. if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil {
  256. logrus.Warnf("Failed to re-PrepareLayer %s: %s", rID, err)
  257. }
  258. }()
  259. }
  260. }
  261. d.Unlock()
  262. return d.exportLayer(rID, layerChain)
  263. }
  264. // Changes produces a list of changes between the specified layer
  265. // and its parent layer. If parent is "", then all changes will be ADD changes.
  266. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  267. return nil, fmt.Errorf("The Windows graphdriver does not support Changes()")
  268. }
  269. // ApplyDiff extracts the changeset from the given diff into the
  270. // layer with the specified id and parent, returning the size of the
  271. // new layer in bytes.
  272. func (d *Driver) ApplyDiff(id, parent string, diff archive.Reader) (size int64, err error) {
  273. rPId, err := d.resolveID(parent)
  274. if err != nil {
  275. return
  276. }
  277. if d.info.Flavour == diffDriver {
  278. start := time.Now().UTC()
  279. logrus.Debugf("WindowsGraphDriver ApplyDiff: Start untar layer")
  280. destination := d.dir(id)
  281. destination = filepath.Dir(destination)
  282. if size, err = chrootarchive.ApplyUncompressedLayer(destination, diff, nil); err != nil {
  283. return
  284. }
  285. logrus.Debugf("WindowsGraphDriver ApplyDiff: Untar time: %vs", time.Now().UTC().Sub(start).Seconds())
  286. return
  287. }
  288. parentChain, err := d.getLayerChain(rPId)
  289. if err != nil {
  290. return
  291. }
  292. parentPath, err := hcsshim.GetLayerMountPath(d.info, rPId)
  293. if err != nil {
  294. return
  295. }
  296. layerChain := []string{parentPath}
  297. layerChain = append(layerChain, parentChain...)
  298. if size, err = d.importLayer(id, diff, layerChain); err != nil {
  299. return
  300. }
  301. if err = d.setLayerChain(id, layerChain); err != nil {
  302. return
  303. }
  304. return
  305. }
  306. // DiffSize calculates the changes between the specified layer
  307. // and its parent and returns the size in bytes of the changes
  308. // relative to its base filesystem directory.
  309. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  310. rPId, err := d.resolveID(parent)
  311. if err != nil {
  312. return
  313. }
  314. changes, err := d.Changes(id, rPId)
  315. if err != nil {
  316. return
  317. }
  318. layerFs, err := d.Get(id, "")
  319. if err != nil {
  320. return
  321. }
  322. defer d.Put(id)
  323. return archive.ChangesSize(layerFs, changes), nil
  324. }
  325. // CustomImageInfo is the object returned by the driver describing the base
  326. // image.
  327. type CustomImageInfo struct {
  328. ID string
  329. Name string
  330. Version string
  331. Path string
  332. Size int64
  333. CreatedTime time.Time
  334. }
  335. // GetCustomImageInfos returns the image infos for window specific
  336. // base images which should always be present.
  337. func (d *Driver) GetCustomImageInfos() ([]CustomImageInfo, error) {
  338. strData, err := hcsshim.GetSharedBaseImages()
  339. if err != nil {
  340. return nil, fmt.Errorf("Failed to restore base images: %s", err)
  341. }
  342. type customImageInfoList struct {
  343. Images []CustomImageInfo
  344. }
  345. var infoData customImageInfoList
  346. if err = json.Unmarshal([]byte(strData), &infoData); err != nil {
  347. err = fmt.Errorf("JSON unmarshal returned error=%s", err)
  348. logrus.Error(err)
  349. return nil, err
  350. }
  351. var images []CustomImageInfo
  352. for _, imageData := range infoData.Images {
  353. folderName := filepath.Base(imageData.Path)
  354. // Use crypto hash of the foldername to generate a docker style id.
  355. h := sha512.Sum384([]byte(folderName))
  356. id := fmt.Sprintf("%x", h[:32])
  357. if err := d.Create(id, "", ""); err != nil {
  358. return nil, err
  359. }
  360. // Create the alternate ID file.
  361. if err := d.setID(id, folderName); err != nil {
  362. return nil, err
  363. }
  364. imageData.ID = id
  365. images = append(images, imageData)
  366. }
  367. return images, nil
  368. }
  369. // GetMetadata returns custom driver information.
  370. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  371. m := make(map[string]string)
  372. m["dir"] = d.dir(id)
  373. return m, nil
  374. }
  375. // exportLayer generates an archive from a layer based on the given ID.
  376. func (d *Driver) exportLayer(id string, parentLayerPaths []string) (arch archive.Archive, err error) {
  377. layerFolder := d.dir(id)
  378. tempFolder := layerFolder + "-" + strconv.FormatUint(uint64(random.Rand.Uint32()), 10)
  379. if err = os.MkdirAll(tempFolder, 0755); err != nil {
  380. logrus.Errorf("Could not create %s %s", tempFolder, err)
  381. return
  382. }
  383. defer func() {
  384. if err != nil {
  385. _, folderName := filepath.Split(tempFolder)
  386. if err2 := hcsshim.DestroyLayer(d.info, folderName); err2 != nil {
  387. logrus.Warnf("Couldn't clean-up tempFolder: %s %s", tempFolder, err2)
  388. }
  389. }
  390. }()
  391. if err = hcsshim.ExportLayer(d.info, id, tempFolder, parentLayerPaths); err != nil {
  392. return
  393. }
  394. archive, err := archive.Tar(tempFolder, archive.Uncompressed)
  395. if err != nil {
  396. return
  397. }
  398. return ioutils.NewReadCloserWrapper(archive, func() error {
  399. err := archive.Close()
  400. d.Put(id)
  401. _, folderName := filepath.Split(tempFolder)
  402. if err2 := hcsshim.DestroyLayer(d.info, folderName); err2 != nil {
  403. logrus.Warnf("Couldn't clean-up tempFolder: %s %s", tempFolder, err2)
  404. }
  405. return err
  406. }), nil
  407. }
  408. // importLayer adds a new layer to the tag and graph store based on the given data.
  409. func (d *Driver) importLayer(id string, layerData archive.Reader, parentLayerPaths []string) (size int64, err error) {
  410. layerFolder := d.dir(id)
  411. tempFolder := layerFolder + "-" + strconv.FormatUint(uint64(random.Rand.Uint32()), 10)
  412. if err = os.MkdirAll(tempFolder, 0755); err != nil {
  413. logrus.Errorf("Could not create %s %s", tempFolder, err)
  414. return
  415. }
  416. defer func() {
  417. _, folderName := filepath.Split(tempFolder)
  418. if err2 := hcsshim.DestroyLayer(d.info, folderName); err2 != nil {
  419. logrus.Warnf("Couldn't clean-up tempFolder: %s %s", tempFolder, err2)
  420. }
  421. }()
  422. start := time.Now().UTC()
  423. logrus.Debugf("Start untar layer")
  424. if size, err = chrootarchive.ApplyLayer(tempFolder, layerData); err != nil {
  425. return
  426. }
  427. logrus.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds())
  428. if err = hcsshim.ImportLayer(d.info, id, tempFolder, parentLayerPaths); err != nil {
  429. return
  430. }
  431. return
  432. }
  433. // resolveID computes the layerID information based on the given id.
  434. func (d *Driver) resolveID(id string) (string, error) {
  435. content, err := ioutil.ReadFile(filepath.Join(d.dir(id), "layerID"))
  436. if os.IsNotExist(err) {
  437. return id, nil
  438. } else if err != nil {
  439. return "", err
  440. }
  441. return string(content), nil
  442. }
  443. // setID stores the layerId in disk.
  444. func (d *Driver) setID(id, altID string) error {
  445. err := ioutil.WriteFile(filepath.Join(d.dir(id), "layerId"), []byte(altID), 0600)
  446. if err != nil {
  447. return err
  448. }
  449. return nil
  450. }
  451. // getLayerChain returns the layer chain information.
  452. func (d *Driver) getLayerChain(id string) ([]string, error) {
  453. jPath := filepath.Join(d.dir(id), "layerchain.json")
  454. content, err := ioutil.ReadFile(jPath)
  455. if os.IsNotExist(err) {
  456. return nil, nil
  457. } else if err != nil {
  458. return nil, fmt.Errorf("Unable to read layerchain file - %s", err)
  459. }
  460. var layerChain []string
  461. err = json.Unmarshal(content, &layerChain)
  462. if err != nil {
  463. return nil, fmt.Errorf("Failed to unmarshall layerchain json - %s", err)
  464. }
  465. return layerChain, nil
  466. }
  467. // setLayerChain stores the layer chain information in disk.
  468. func (d *Driver) setLayerChain(id string, chain []string) error {
  469. content, err := json.Marshal(&chain)
  470. if err != nil {
  471. return fmt.Errorf("Failed to marshall layerchain json - %s", err)
  472. }
  473. jPath := filepath.Join(d.dir(id), "layerchain.json")
  474. err = ioutil.WriteFile(jPath, content, 0600)
  475. if err != nil {
  476. return fmt.Errorf("Unable to write layerchain file - %s", err)
  477. }
  478. return nil
  479. }
  480. // DiffPath returns a directory that contains files needed to construct layer diff.
  481. func (d *Driver) DiffPath(id string) (path string, release func() error, err error) {
  482. id, err = d.resolveID(id)
  483. if err != nil {
  484. return
  485. }
  486. // Getting the layer paths must be done outside of the lock.
  487. layerChain, err := d.getLayerChain(id)
  488. if err != nil {
  489. return
  490. }
  491. layerFolder := d.dir(id)
  492. tempFolder := layerFolder + "-" + strconv.FormatUint(uint64(random.Rand.Uint32()), 10)
  493. if err = os.MkdirAll(tempFolder, 0755); err != nil {
  494. logrus.Errorf("Could not create %s %s", tempFolder, err)
  495. return
  496. }
  497. defer func() {
  498. if err != nil {
  499. _, folderName := filepath.Split(tempFolder)
  500. if err2 := hcsshim.DestroyLayer(d.info, folderName); err2 != nil {
  501. logrus.Warnf("Couldn't clean-up tempFolder: %s %s", tempFolder, err2)
  502. }
  503. }
  504. }()
  505. if err = hcsshim.ExportLayer(d.info, id, tempFolder, layerChain); err != nil {
  506. return
  507. }
  508. return tempFolder, func() error {
  509. // TODO: activate layers and release here?
  510. _, folderName := filepath.Split(tempFolder)
  511. return hcsshim.DestroyLayer(d.info, folderName)
  512. }, nil
  513. }