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