builder.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package daemonbuilder
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/docker/distribution/reference"
  11. "github.com/docker/docker/api"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/builder"
  14. "github.com/docker/docker/daemon"
  15. "github.com/docker/docker/image"
  16. "github.com/docker/docker/pkg/archive"
  17. "github.com/docker/docker/pkg/httputils"
  18. "github.com/docker/docker/pkg/idtools"
  19. "github.com/docker/docker/pkg/ioutils"
  20. "github.com/docker/docker/pkg/urlutil"
  21. "github.com/docker/docker/registry"
  22. "github.com/docker/docker/runconfig"
  23. )
  24. // Docker implements builder.Backend for the docker Daemon object.
  25. type Docker struct {
  26. *daemon.Daemon
  27. OutOld io.Writer
  28. AuthConfigs map[string]types.AuthConfig
  29. Archiver *archive.Archiver
  30. }
  31. // ensure Docker implements builder.Backend
  32. var _ builder.Backend = Docker{}
  33. // Pull tells Docker to pull image referenced by `name`.
  34. func (d Docker) Pull(name string) (builder.Image, error) {
  35. ref, err := reference.ParseNamed(name)
  36. if err != nil {
  37. return nil, err
  38. }
  39. switch ref.(type) {
  40. case reference.Tagged:
  41. case reference.Digested:
  42. default:
  43. ref, err = reference.WithTag(ref, "latest")
  44. if err != nil {
  45. return nil, err
  46. }
  47. }
  48. pullRegistryAuth := &types.AuthConfig{}
  49. if len(d.AuthConfigs) > 0 {
  50. // The request came with a full auth config file, we prefer to use that
  51. repoInfo, err := d.Daemon.RegistryService.ResolveRepository(ref)
  52. if err != nil {
  53. return nil, err
  54. }
  55. resolvedConfig := registry.ResolveAuthConfig(
  56. d.AuthConfigs,
  57. repoInfo.Index,
  58. )
  59. pullRegistryAuth = &resolvedConfig
  60. }
  61. if err := d.Daemon.PullImage(ref, nil, pullRegistryAuth, ioutils.NopWriteCloser(d.OutOld)); err != nil {
  62. return nil, err
  63. }
  64. return d.GetImage(name)
  65. }
  66. // GetImage looks up a Docker image referenced by `name`.
  67. func (d Docker) GetImage(name string) (builder.Image, error) {
  68. img, err := d.Daemon.GetImage(name)
  69. if err != nil {
  70. return nil, err
  71. }
  72. return imgWrap{img}, nil
  73. }
  74. // ContainerUpdateCmd updates Path and Args for the container with ID cID.
  75. func (d Docker) ContainerUpdateCmd(cID string, cmd []string) error {
  76. c, err := d.Daemon.GetContainer(cID)
  77. if err != nil {
  78. return err
  79. }
  80. c.Path = cmd[0]
  81. c.Args = cmd[1:]
  82. return nil
  83. }
  84. // BuilderCopy copies/extracts a source FileInfo to a destination path inside a container
  85. // specified by a container object.
  86. // TODO: make sure callers don't unnecessarily convert destPath with filepath.FromSlash (Copy does it already).
  87. // BuilderCopy should take in abstract paths (with slashes) and the implementation should convert it to OS-specific paths.
  88. func (d Docker) BuilderCopy(cID string, destPath string, src builder.FileInfo, decompress bool) error {
  89. srcPath := src.Path()
  90. destExists := true
  91. rootUID, rootGID := d.Daemon.GetRemappedUIDGID()
  92. // Work in daemon-local OS specific file paths
  93. destPath = filepath.FromSlash(destPath)
  94. c, err := d.Daemon.GetContainer(cID)
  95. if err != nil {
  96. return err
  97. }
  98. dest, err := c.GetResourcePath(destPath)
  99. if err != nil {
  100. return err
  101. }
  102. // Preserve the trailing slash
  103. // TODO: why are we appending another path separator if there was already one?
  104. if strings.HasSuffix(destPath, string(os.PathSeparator)) || destPath == "." {
  105. dest += string(os.PathSeparator)
  106. }
  107. destPath = dest
  108. destStat, err := os.Stat(destPath)
  109. if err != nil {
  110. if !os.IsNotExist(err) {
  111. logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err)
  112. return err
  113. }
  114. destExists = false
  115. }
  116. if src.IsDir() {
  117. // copy as directory
  118. if err := d.Archiver.CopyWithTar(srcPath, destPath); err != nil {
  119. return err
  120. }
  121. return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
  122. }
  123. if decompress && archive.IsArchivePath(srcPath) {
  124. // Only try to untar if it is a file and that we've been told to decompress (when ADD-ing a remote file)
  125. // First try to unpack the source as an archive
  126. // to support the untar feature we need to clean up the path a little bit
  127. // because tar is very forgiving. First we need to strip off the archive's
  128. // filename from the path but this is only added if it does not end in slash
  129. tarDest := destPath
  130. if strings.HasSuffix(tarDest, string(os.PathSeparator)) {
  131. tarDest = filepath.Dir(destPath)
  132. }
  133. // try to successfully untar the orig
  134. err := d.Archiver.UntarPath(srcPath, tarDest)
  135. if err != nil {
  136. logrus.Errorf("Couldn't untar to %s: %v", tarDest, err)
  137. }
  138. return err
  139. }
  140. // only needed for fixPermissions, but might as well put it before CopyFileWithTar
  141. if destExists && destStat.IsDir() {
  142. destPath = filepath.Join(destPath, src.Name())
  143. }
  144. if err := idtools.MkdirAllNewAs(filepath.Dir(destPath), 0755, rootUID, rootGID); err != nil {
  145. return err
  146. }
  147. if err := d.Archiver.CopyFileWithTar(srcPath, destPath); err != nil {
  148. return err
  149. }
  150. return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
  151. }
  152. // Mount mounts the root filesystem for the container.
  153. func (d Docker) Mount(cID string) error {
  154. c, err := d.Daemon.GetContainer(cID)
  155. if err != nil {
  156. return err
  157. }
  158. return d.Daemon.Mount(c)
  159. }
  160. // Unmount unmounts the root filesystem for the container.
  161. func (d Docker) Unmount(cID string) error {
  162. c, err := d.Daemon.GetContainer(cID)
  163. if err != nil {
  164. return err
  165. }
  166. d.Daemon.Unmount(c)
  167. return nil
  168. }
  169. // GetCachedImage returns a reference to a cached image whose parent equals `parent`
  170. // and runconfig equals `cfg`. A cache miss is expected to return an empty ID and a nil error.
  171. func (d Docker) GetCachedImage(imgID string, cfg *runconfig.Config) (string, error) {
  172. cache, err := d.Daemon.ImageGetCached(image.ID(imgID), cfg)
  173. if cache == nil || err != nil {
  174. return "", err
  175. }
  176. return cache.ID().String(), nil
  177. }
  178. // Following is specific to builder contexts
  179. // DetectContextFromRemoteURL returns a context and in certain cases the name of the dockerfile to be used
  180. // irrespective of user input.
  181. // progressReader is only used if remoteURL is actually a URL (not empty, and not a Git endpoint).
  182. func DetectContextFromRemoteURL(r io.ReadCloser, remoteURL string, createProgressReader func(in io.ReadCloser) io.ReadCloser) (context builder.ModifiableContext, dockerfileName string, err error) {
  183. switch {
  184. case remoteURL == "":
  185. context, err = builder.MakeTarSumContext(r)
  186. case urlutil.IsGitURL(remoteURL):
  187. context, err = builder.MakeGitContext(remoteURL)
  188. case urlutil.IsURL(remoteURL):
  189. context, err = builder.MakeRemoteContext(remoteURL, map[string]func(io.ReadCloser) (io.ReadCloser, error){
  190. httputils.MimeTypes.TextPlain: func(rc io.ReadCloser) (io.ReadCloser, error) {
  191. dockerfile, err := ioutil.ReadAll(rc)
  192. if err != nil {
  193. return nil, err
  194. }
  195. // dockerfileName is set to signal that the remote was interpreted as a single Dockerfile, in which case the caller
  196. // should use dockerfileName as the new name for the Dockerfile, irrespective of any other user input.
  197. dockerfileName = api.DefaultDockerfileName
  198. // TODO: return a context without tarsum
  199. return archive.Generate(dockerfileName, string(dockerfile))
  200. },
  201. // fallback handler (tar context)
  202. "": func(rc io.ReadCloser) (io.ReadCloser, error) {
  203. return createProgressReader(rc), nil
  204. },
  205. })
  206. default:
  207. err = fmt.Errorf("remoteURL (%s) could not be recognized as URL", remoteURL)
  208. }
  209. return
  210. }