builder.go 8.6 KB

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