internals.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package dockerfile
  2. // internals for handling commands. Covers many areas and a lot of
  3. // non-contiguous functionality. Please read the comments.
  4. import (
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "fmt"
  8. "strings"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/backend"
  11. "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/image"
  13. "github.com/docker/docker/pkg/stringid"
  14. "github.com/pkg/errors"
  15. )
  16. func (b *Builder) commit(dispatchState *dispatchState, comment string) error {
  17. if b.disableCommit {
  18. return nil
  19. }
  20. if !dispatchState.hasFromImage() {
  21. return errors.New("Please provide a source image with `from` prior to commit")
  22. }
  23. runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment, b.platform))
  24. hit, err := b.probeCache(dispatchState, runConfigWithCommentCmd)
  25. if err != nil || hit {
  26. return err
  27. }
  28. id, err := b.create(runConfigWithCommentCmd)
  29. if err != nil {
  30. return err
  31. }
  32. return b.commitContainer(dispatchState, id, runConfigWithCommentCmd)
  33. }
  34. func (b *Builder) commitContainer(dispatchState *dispatchState, id string, containerConfig *container.Config) error {
  35. if b.disableCommit {
  36. return nil
  37. }
  38. commitCfg := &backend.ContainerCommitConfig{
  39. ContainerCommitConfig: types.ContainerCommitConfig{
  40. Author: dispatchState.maintainer,
  41. Pause: true,
  42. // TODO: this should be done by Commit()
  43. Config: copyRunConfig(dispatchState.runConfig),
  44. },
  45. ContainerConfig: containerConfig,
  46. }
  47. // Commit the container
  48. imageID, err := b.docker.Commit(id, commitCfg)
  49. if err != nil {
  50. return err
  51. }
  52. dispatchState.imageID = imageID
  53. b.buildStages.update(imageID)
  54. return nil
  55. }
  56. func (b *Builder) exportImage(state *dispatchState, imageMount *imageMount, runConfig *container.Config) error {
  57. newLayer, err := imageMount.Layer().Commit(b.platform)
  58. if err != nil {
  59. return err
  60. }
  61. // add an image mount without an image so the layer is properly unmounted
  62. // if there is an error before we can add the full mount with image
  63. b.imageSources.Add(newImageMount(nil, newLayer))
  64. parentImage, ok := imageMount.Image().(*image.Image)
  65. if !ok {
  66. return errors.Errorf("unexpected image type")
  67. }
  68. newImage := image.NewChildImage(parentImage, image.ChildConfig{
  69. Author: state.maintainer,
  70. ContainerConfig: runConfig,
  71. DiffID: newLayer.DiffID(),
  72. Config: copyRunConfig(state.runConfig),
  73. }, parentImage.OS)
  74. // TODO: it seems strange to marshal this here instead of just passing in the
  75. // image struct
  76. config, err := newImage.MarshalJSON()
  77. if err != nil {
  78. return errors.Wrap(err, "failed to encode image config")
  79. }
  80. exportedImage, err := b.docker.CreateImage(config, state.imageID, parentImage.OS)
  81. if err != nil {
  82. return errors.Wrapf(err, "failed to export image")
  83. }
  84. state.imageID = exportedImage.ImageID()
  85. b.imageSources.Add(newImageMount(exportedImage, newLayer))
  86. b.buildStages.update(state.imageID)
  87. return nil
  88. }
  89. func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error {
  90. srcHash := getSourceHashFromInfos(inst.infos)
  91. // TODO: should this have been using origPaths instead of srcHash in the comment?
  92. runConfigWithCommentCmd := copyRunConfig(
  93. state.runConfig,
  94. withCmdCommentString(fmt.Sprintf("%s %s in %s ", inst.cmdName, srcHash, inst.dest), b.platform))
  95. hit, err := b.probeCache(state, runConfigWithCommentCmd)
  96. if err != nil || hit {
  97. return err
  98. }
  99. imageMount, err := b.imageSources.Get(state.imageID, true)
  100. if err != nil {
  101. return errors.Wrapf(err, "failed to get destination image %q", state.imageID)
  102. }
  103. destInfo, err := createDestInfo(state.runConfig.WorkingDir, inst, imageMount)
  104. if err != nil {
  105. return err
  106. }
  107. opts := copyFileOptions{
  108. decompress: inst.allowLocalDecompression,
  109. archiver: b.archiver,
  110. }
  111. for _, info := range inst.infos {
  112. if err := performCopyForInfo(destInfo, info, opts); err != nil {
  113. return errors.Wrapf(err, "failed to copy files")
  114. }
  115. }
  116. return b.exportImage(state, imageMount, runConfigWithCommentCmd)
  117. }
  118. func createDestInfo(workingDir string, inst copyInstruction, imageMount *imageMount) (copyInfo, error) {
  119. // Twiddle the destination when it's a relative path - meaning, make it
  120. // relative to the WORKINGDIR
  121. dest, err := normalizeDest(workingDir, inst.dest)
  122. if err != nil {
  123. return copyInfo{}, errors.Wrapf(err, "invalid %s", inst.cmdName)
  124. }
  125. destMount, err := imageMount.Source()
  126. if err != nil {
  127. return copyInfo{}, errors.Wrapf(err, "failed to mount copy source")
  128. }
  129. return newCopyInfoFromSource(destMount, dest, ""), nil
  130. }
  131. // For backwards compat, if there's just one info then use it as the
  132. // cache look-up string, otherwise hash 'em all into one
  133. func getSourceHashFromInfos(infos []copyInfo) string {
  134. if len(infos) == 1 {
  135. return infos[0].hash
  136. }
  137. var hashs []string
  138. for _, info := range infos {
  139. hashs = append(hashs, info.hash)
  140. }
  141. return hashStringSlice("multi", hashs)
  142. }
  143. func hashStringSlice(prefix string, slice []string) string {
  144. hasher := sha256.New()
  145. hasher.Write([]byte(strings.Join(slice, ",")))
  146. return prefix + ":" + hex.EncodeToString(hasher.Sum(nil))
  147. }
  148. type runConfigModifier func(*container.Config)
  149. func copyRunConfig(runConfig *container.Config, modifiers ...runConfigModifier) *container.Config {
  150. copy := *runConfig
  151. for _, modifier := range modifiers {
  152. modifier(&copy)
  153. }
  154. return &copy
  155. }
  156. func withCmd(cmd []string) runConfigModifier {
  157. return func(runConfig *container.Config) {
  158. runConfig.Cmd = cmd
  159. }
  160. }
  161. // withCmdComment sets Cmd to a nop comment string. See withCmdCommentString for
  162. // why there are two almost identical versions of this.
  163. func withCmdComment(comment string, platform string) runConfigModifier {
  164. return func(runConfig *container.Config) {
  165. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) ", comment)
  166. }
  167. }
  168. // withCmdCommentString exists to maintain compatibility with older versions.
  169. // A few instructions (workdir, copy, add) used a nop comment that is a single arg
  170. // where as all the other instructions used a two arg comment string. This
  171. // function implements the single arg version.
  172. func withCmdCommentString(comment string, platform string) runConfigModifier {
  173. return func(runConfig *container.Config) {
  174. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) "+comment)
  175. }
  176. }
  177. func withEnv(env []string) runConfigModifier {
  178. return func(runConfig *container.Config) {
  179. runConfig.Env = env
  180. }
  181. }
  182. // withEntrypointOverride sets an entrypoint on runConfig if the command is
  183. // not empty. The entrypoint is left unmodified if command is empty.
  184. //
  185. // The dockerfile RUN instruction expect to run without an entrypoint
  186. // so the runConfig entrypoint needs to be modified accordingly. ContainerCreate
  187. // will change a []string{""} entrypoint to nil, so we probe the cache with the
  188. // nil entrypoint.
  189. func withEntrypointOverride(cmd []string, entrypoint []string) runConfigModifier {
  190. return func(runConfig *container.Config) {
  191. if len(cmd) > 0 {
  192. runConfig.Entrypoint = entrypoint
  193. }
  194. }
  195. }
  196. // getShell is a helper function which gets the right shell for prefixing the
  197. // shell-form of RUN, ENTRYPOINT and CMD instructions
  198. func getShell(c *container.Config, platform string) []string {
  199. if 0 == len(c.Shell) {
  200. return append([]string{}, defaultShellForPlatform(platform)[:]...)
  201. }
  202. return append([]string{}, c.Shell[:]...)
  203. }
  204. func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container.Config) (bool, error) {
  205. cachedID, err := b.imageProber.Probe(dispatchState.imageID, runConfig)
  206. if cachedID == "" || err != nil {
  207. return false, err
  208. }
  209. fmt.Fprint(b.Stdout, " ---> Using cache\n")
  210. dispatchState.imageID = string(cachedID)
  211. b.buildStages.update(dispatchState.imageID)
  212. return true, nil
  213. }
  214. var defaultLogConfig = container.LogConfig{Type: "none"}
  215. func (b *Builder) probeAndCreate(dispatchState *dispatchState, runConfig *container.Config) (string, error) {
  216. if hit, err := b.probeCache(dispatchState, runConfig); err != nil || hit {
  217. return "", err
  218. }
  219. // Set a log config to override any default value set on the daemon
  220. hostConfig := &container.HostConfig{LogConfig: defaultLogConfig}
  221. container, err := b.containerManager.Create(runConfig, hostConfig, b.platform)
  222. return container.ID, err
  223. }
  224. func (b *Builder) create(runConfig *container.Config) (string, error) {
  225. hostConfig := hostConfigFromOptions(b.options)
  226. container, err := b.containerManager.Create(runConfig, hostConfig, b.platform)
  227. if err != nil {
  228. return "", err
  229. }
  230. // TODO: could this be moved into containerManager.Create() ?
  231. for _, warning := range container.Warnings {
  232. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  233. }
  234. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(container.ID))
  235. return container.ID, nil
  236. }
  237. func hostConfigFromOptions(options *types.ImageBuildOptions) *container.HostConfig {
  238. resources := container.Resources{
  239. CgroupParent: options.CgroupParent,
  240. CPUShares: options.CPUShares,
  241. CPUPeriod: options.CPUPeriod,
  242. CPUQuota: options.CPUQuota,
  243. CpusetCpus: options.CPUSetCPUs,
  244. CpusetMems: options.CPUSetMems,
  245. Memory: options.Memory,
  246. MemorySwap: options.MemorySwap,
  247. Ulimits: options.Ulimits,
  248. }
  249. return &container.HostConfig{
  250. SecurityOpt: options.SecurityOpt,
  251. Isolation: options.Isolation,
  252. ShmSize: options.ShmSize,
  253. Resources: resources,
  254. NetworkMode: container.NetworkMode(options.NetworkMode),
  255. // Set a log config to override any default value set on the daemon
  256. LogConfig: defaultLogConfig,
  257. ExtraHosts: options.ExtraHosts,
  258. }
  259. }