internals.go 8.1 KB

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