builder.go 8.6 KB

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