builder.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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(&daemon.ContainerCreateConfig{
  74. Name: "",
  75. Config: cfg,
  76. HostConfig: hostCfg,
  77. AdjustCPUShares: true,
  78. })
  79. if err != nil {
  80. return nil, nil, err
  81. }
  82. container, err := d.Daemon.Get(ccr.ID)
  83. if err != nil {
  84. return nil, ccr.Warnings, err
  85. }
  86. return container, ccr.Warnings, d.Mount(container)
  87. }
  88. // Remove removes a container specified by `id`.
  89. func (d Docker) Remove(id string, cfg *daemon.ContainerRmConfig) error {
  90. return d.Daemon.ContainerRm(id, cfg)
  91. }
  92. // Commit creates a new Docker image from an existing Docker container.
  93. func (d Docker) Commit(name string, cfg *daemon.ContainerCommitConfig) (*image.Image, error) {
  94. return d.Daemon.Commit(name, cfg)
  95. }
  96. // Retain retains an image avoiding it to be removed or overwritten until a corresponding Release() call.
  97. func (d Docker) Retain(sessionID, imgID string) {
  98. d.Daemon.Graph().Retain(sessionID, imgID)
  99. }
  100. // Release releases a list of images that were retained for the time of a build.
  101. func (d Docker) Release(sessionID string, activeImages []string) {
  102. d.Daemon.Graph().Release(sessionID, activeImages...)
  103. }
  104. // Copy copies/extracts a source FileInfo to a destination path inside a container
  105. // specified by a container object.
  106. // TODO: make sure callers don't unnecessarily convert destPath with filepath.FromSlash (Copy does it already).
  107. // Copy should take in abstract paths (with slashes) and the implementation should convert it to OS-specific paths.
  108. func (d Docker) Copy(c *daemon.Container, destPath string, src builder.FileInfo, decompress bool) error {
  109. srcPath := src.Path()
  110. destExists := true
  111. rootUID, rootGID := d.Daemon.GetRemappedUIDGID()
  112. // Work in daemon-local OS specific file paths
  113. destPath = filepath.FromSlash(destPath)
  114. dest, err := c.GetResourcePath(destPath)
  115. if err != nil {
  116. return err
  117. }
  118. // Preserve the trailing slash
  119. // TODO: why are we appending another path separator if there was already one?
  120. if strings.HasSuffix(destPath, string(os.PathSeparator)) || destPath == "." {
  121. dest += string(os.PathSeparator)
  122. }
  123. destPath = dest
  124. destStat, err := os.Stat(destPath)
  125. if err != nil {
  126. if !os.IsNotExist(err) {
  127. logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err)
  128. return err
  129. }
  130. destExists = false
  131. }
  132. if src.IsDir() {
  133. // copy as directory
  134. if err := d.Archiver.CopyWithTar(srcPath, destPath); err != nil {
  135. return err
  136. }
  137. return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
  138. }
  139. if decompress {
  140. // Only try to untar if it is a file and that we've been told to decompress (when ADD-ing a remote file)
  141. // First try to unpack the source as an archive
  142. // to support the untar feature we need to clean up the path a little bit
  143. // because tar is very forgiving. First we need to strip off the archive's
  144. // filename from the path but this is only added if it does not end in slash
  145. tarDest := destPath
  146. if strings.HasSuffix(tarDest, string(os.PathSeparator)) {
  147. tarDest = filepath.Dir(destPath)
  148. }
  149. // try to successfully untar the orig
  150. if err := d.Archiver.UntarPath(srcPath, tarDest); err == nil {
  151. return nil
  152. } else if err != io.EOF {
  153. logrus.Debugf("Couldn't untar to %s: %v", tarDest, err)
  154. }
  155. }
  156. // only needed for fixPermissions, but might as well put it before CopyFileWithTar
  157. if destExists && destStat.IsDir() {
  158. destPath = filepath.Join(destPath, filepath.Base(srcPath))
  159. }
  160. if err := idtools.MkdirAllNewAs(filepath.Dir(destPath), 0755, rootUID, rootGID); err != nil {
  161. return err
  162. }
  163. if err := d.Archiver.CopyFileWithTar(srcPath, destPath); err != nil {
  164. return err
  165. }
  166. return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
  167. }
  168. // GetCachedImage returns a reference to a cached image whose parent equals `parent`
  169. // and runconfig equals `cfg`. A cache miss is expected to return an empty ID and a nil error.
  170. func (d Docker) GetCachedImage(imgID string, cfg *runconfig.Config) (string, error) {
  171. cache, err := d.Daemon.ImageGetCached(imgID, cfg)
  172. if cache == nil || err != nil {
  173. return "", err
  174. }
  175. return cache.ID, nil
  176. }
  177. // Kill stops the container execution abruptly.
  178. func (d Docker) Kill(container *daemon.Container) error {
  179. return d.Daemon.Kill(container)
  180. }
  181. // Mount mounts the root filesystem for the container.
  182. func (d Docker) Mount(c *daemon.Container) error {
  183. return d.Daemon.Mount(c)
  184. }
  185. // Unmount unmounts the root filesystem for the container.
  186. func (d Docker) Unmount(c *daemon.Container) error {
  187. return d.Daemon.Unmount(c)
  188. }
  189. // Start starts a container
  190. func (d Docker) Start(c *daemon.Container) error {
  191. return d.Daemon.Start(c)
  192. }
  193. // Following is specific to builder contexts
  194. // DetectContextFromRemoteURL returns a context and in certain cases the name of the dockerfile to be used
  195. // irrespective of user input.
  196. // progressReader is only used if remoteURL is actually a URL (not empty, and not a Git endpoint).
  197. func DetectContextFromRemoteURL(r io.ReadCloser, remoteURL string, progressReader *progressreader.Config) (context builder.ModifiableContext, dockerfileName string, err error) {
  198. switch {
  199. case remoteURL == "":
  200. context, err = builder.MakeTarSumContext(r)
  201. case urlutil.IsGitURL(remoteURL):
  202. context, err = builder.MakeGitContext(remoteURL)
  203. case urlutil.IsURL(remoteURL):
  204. context, err = builder.MakeRemoteContext(remoteURL, map[string]func(io.ReadCloser) (io.ReadCloser, error){
  205. httputils.MimeTypes.TextPlain: func(rc io.ReadCloser) (io.ReadCloser, error) {
  206. dockerfile, err := ioutil.ReadAll(rc)
  207. if err != nil {
  208. return nil, err
  209. }
  210. // dockerfileName is set to signal that the remote was interpreted as a single Dockerfile, in which case the caller
  211. // should use dockerfileName as the new name for the Dockerfile, irrespective of any other user input.
  212. dockerfileName = api.DefaultDockerfileName
  213. // TODO: return a context without tarsum
  214. return archive.Generate(dockerfileName, string(dockerfile))
  215. },
  216. // fallback handler (tar context)
  217. "": func(rc io.ReadCloser) (io.ReadCloser, error) {
  218. progressReader.In = rc
  219. return progressReader, nil
  220. },
  221. })
  222. default:
  223. err = fmt.Errorf("remoteURL (%s) could not be recognized as URL", remoteURL)
  224. }
  225. return
  226. }