internals.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/pkg/stringid"
  13. "github.com/pkg/errors"
  14. )
  15. func (b *Builder) commit(dispatchState *dispatchState, comment string) error {
  16. if b.disableCommit {
  17. return nil
  18. }
  19. if !dispatchState.hasFromImage() {
  20. return errors.New("Please provide a source image with `from` prior to commit")
  21. }
  22. runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment))
  23. hit, err := b.probeCache(dispatchState, runConfigWithCommentCmd)
  24. if err != nil || hit {
  25. return err
  26. }
  27. id, err := b.create(runConfigWithCommentCmd)
  28. if err != nil {
  29. return err
  30. }
  31. return b.commitContainer(dispatchState, id, runConfigWithCommentCmd)
  32. }
  33. // TODO: see if any args can be dropped
  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, dispatchState.runConfig)
  54. return nil
  55. }
  56. func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error {
  57. srcHash := getSourceHashFromInfos(inst.infos)
  58. // TODO: should this have been using origPaths instead of srcHash in the comment?
  59. runConfigWithCommentCmd := copyRunConfig(
  60. state.runConfig,
  61. withCmdCommentString(fmt.Sprintf("%s %s in %s ", inst.cmdName, srcHash, inst.dest)))
  62. containerID, err := b.probeAndCreate(state, runConfigWithCommentCmd)
  63. if err != nil || containerID == "" {
  64. return err
  65. }
  66. // Twiddle the destination when it's a relative path - meaning, make it
  67. // relative to the WORKINGDIR
  68. dest, err := normaliseDest(inst.cmdName, state.runConfig.WorkingDir, inst.dest)
  69. if err != nil {
  70. return err
  71. }
  72. for _, info := range inst.infos {
  73. if err := b.docker.CopyOnBuild(containerID, dest, info.root, info.path, inst.allowLocalDecompression); err != nil {
  74. return err
  75. }
  76. }
  77. return b.commitContainer(state, containerID, runConfigWithCommentCmd)
  78. }
  79. // For backwards compat, if there's just one info then use it as the
  80. // cache look-up string, otherwise hash 'em all into one
  81. func getSourceHashFromInfos(infos []copyInfo) string {
  82. if len(infos) == 1 {
  83. return infos[0].hash
  84. }
  85. var hashs []string
  86. for _, info := range infos {
  87. hashs = append(hashs, info.hash)
  88. }
  89. return hashStringSlice("multi", hashs)
  90. }
  91. func hashStringSlice(prefix string, slice []string) string {
  92. hasher := sha256.New()
  93. hasher.Write([]byte(strings.Join(slice, ",")))
  94. return prefix + ":" + hex.EncodeToString(hasher.Sum(nil))
  95. }
  96. type runConfigModifier func(*container.Config)
  97. func copyRunConfig(runConfig *container.Config, modifiers ...runConfigModifier) *container.Config {
  98. copy := *runConfig
  99. for _, modifier := range modifiers {
  100. modifier(&copy)
  101. }
  102. return &copy
  103. }
  104. func withCmd(cmd []string) runConfigModifier {
  105. return func(runConfig *container.Config) {
  106. runConfig.Cmd = cmd
  107. }
  108. }
  109. // withCmdComment sets Cmd to a nop comment string. See withCmdCommentString for
  110. // why there are two almost identical versions of this.
  111. func withCmdComment(comment string) runConfigModifier {
  112. return func(runConfig *container.Config) {
  113. runConfig.Cmd = append(getShell(runConfig), "#(nop) ", comment)
  114. }
  115. }
  116. // withCmdCommentString exists to maintain compatibility with older versions.
  117. // A few instructions (workdir, copy, add) used a nop comment that is a single arg
  118. // where as all the other instructions used a two arg comment string. This
  119. // function implements the single arg version.
  120. func withCmdCommentString(comment string) runConfigModifier {
  121. return func(runConfig *container.Config) {
  122. runConfig.Cmd = append(getShell(runConfig), "#(nop) "+comment)
  123. }
  124. }
  125. func withEnv(env []string) runConfigModifier {
  126. return func(runConfig *container.Config) {
  127. runConfig.Env = env
  128. }
  129. }
  130. // withEntrypointOverride sets an entrypoint on runConfig if the command is
  131. // not empty. The entrypoint is left unmodified if command is empty.
  132. //
  133. // The dockerfile RUN instruction expect to run without an entrypoint
  134. // so the runConfig entrypoint needs to be modified accordingly. ContainerCreate
  135. // will change a []string{""} entrypoint to nil, so we probe the cache with the
  136. // nil entrypoint.
  137. func withEntrypointOverride(cmd []string, entrypoint []string) runConfigModifier {
  138. return func(runConfig *container.Config) {
  139. if len(cmd) > 0 {
  140. runConfig.Entrypoint = entrypoint
  141. }
  142. }
  143. }
  144. // getShell is a helper function which gets the right shell for prefixing the
  145. // shell-form of RUN, ENTRYPOINT and CMD instructions
  146. func getShell(c *container.Config) []string {
  147. if 0 == len(c.Shell) {
  148. return append([]string{}, defaultShell[:]...)
  149. }
  150. return append([]string{}, c.Shell[:]...)
  151. }
  152. func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container.Config) (bool, error) {
  153. cachedID, err := b.imageProber.Probe(dispatchState.imageID, runConfig)
  154. if cachedID == "" || err != nil {
  155. return false, err
  156. }
  157. fmt.Fprint(b.Stdout, " ---> Using cache\n")
  158. dispatchState.imageID = string(cachedID)
  159. b.buildStages.update(dispatchState.imageID, runConfig)
  160. return true, nil
  161. }
  162. var defaultLogConfig = container.LogConfig{Type: "none"}
  163. func (b *Builder) probeAndCreate(dispatchState *dispatchState, runConfig *container.Config) (string, error) {
  164. if hit, err := b.probeCache(dispatchState, runConfig); err != nil || hit {
  165. return "", err
  166. }
  167. // Set a log config to override any default value set on the daemon
  168. hostConfig := &container.HostConfig{LogConfig: defaultLogConfig}
  169. container, err := b.containerManager.Create(runConfig, hostConfig)
  170. return container.ID, err
  171. }
  172. func (b *Builder) create(runConfig *container.Config) (string, error) {
  173. hostConfig := hostConfigFromOptions(b.options)
  174. container, err := b.containerManager.Create(runConfig, hostConfig)
  175. if err != nil {
  176. return "", err
  177. }
  178. // TODO: could this be moved into containerManager.Create() ?
  179. for _, warning := range container.Warnings {
  180. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  181. }
  182. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(container.ID))
  183. return container.ID, nil
  184. }
  185. func hostConfigFromOptions(options *types.ImageBuildOptions) *container.HostConfig {
  186. resources := container.Resources{
  187. CgroupParent: options.CgroupParent,
  188. CPUShares: options.CPUShares,
  189. CPUPeriod: options.CPUPeriod,
  190. CPUQuota: options.CPUQuota,
  191. CpusetCpus: options.CPUSetCPUs,
  192. CpusetMems: options.CPUSetMems,
  193. Memory: options.Memory,
  194. MemorySwap: options.MemorySwap,
  195. Ulimits: options.Ulimits,
  196. }
  197. return &container.HostConfig{
  198. SecurityOpt: options.SecurityOpt,
  199. Isolation: options.Isolation,
  200. ShmSize: options.ShmSize,
  201. Resources: resources,
  202. NetworkMode: container.NetworkMode(options.NetworkMode),
  203. // Set a log config to override any default value set on the daemon
  204. LogConfig: defaultLogConfig,
  205. ExtraHosts: options.ExtraHosts,
  206. }
  207. }