preload.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package control
  2. import (
  3. "compress/gzip"
  4. "context"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "regexp"
  11. "strings"
  12. "github.com/codegangsta/cli"
  13. dockerClient "github.com/docker/engine-api/client"
  14. "github.com/rancher/os/docker"
  15. "github.com/rancher/os/log"
  16. )
  17. const (
  18. userImagesPreloadDirectory = "/var/lib/rancher/preload/docker"
  19. )
  20. func preloadImagesAction(c *cli.Context) error {
  21. return PreloadImages(docker.NewDefaultClient, userImagesPreloadDirectory)
  22. }
  23. func shouldLoad(file string) bool {
  24. if strings.HasSuffix(file, ".done") {
  25. return false
  26. }
  27. if _, err := os.Stat(fmt.Sprintf("%s.done", file)); err == nil {
  28. return false
  29. }
  30. return true
  31. }
  32. func PreloadImages(clientFactory func() (dockerClient.APIClient, error), imagesDir string) error {
  33. var client dockerClient.APIClient
  34. clientInitialized := false
  35. if _, err := os.Stat(imagesDir); os.IsNotExist(err) {
  36. if err = os.MkdirAll(imagesDir, 0755); err != nil {
  37. return err
  38. }
  39. } else if err != nil {
  40. return err
  41. }
  42. files, err := ioutil.ReadDir(imagesDir)
  43. if err != nil {
  44. return err
  45. }
  46. for _, file := range files {
  47. filename := path.Join(imagesDir, file.Name())
  48. if !shouldLoad(filename) {
  49. continue
  50. }
  51. image, err := os.Open(filename)
  52. if err != nil {
  53. return err
  54. }
  55. var imageReader io.Reader
  56. imageReader = image
  57. match, err := regexp.MatchString(".t?gz$", file.Name())
  58. if err != nil {
  59. return err
  60. }
  61. if match {
  62. imageReader, err = gzip.NewReader(image)
  63. if err != nil {
  64. return err
  65. }
  66. }
  67. if !clientInitialized {
  68. client, err = clientFactory()
  69. if err != nil {
  70. return err
  71. }
  72. clientInitialized = true
  73. }
  74. log.Infof("Loading image %s", filename)
  75. if _, err = client.ImageLoad(context.Background(), imageReader, false); err != nil {
  76. return err
  77. }
  78. if err = image.Close(); err != nil {
  79. return err
  80. }
  81. doneStamp, err := os.Create(fmt.Sprintf("%s.done", filename))
  82. if err != nil {
  83. return err
  84. }
  85. if err = doneStamp.Close(); err != nil {
  86. return err
  87. }
  88. }
  89. return nil
  90. }