internals.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package dockerfile // import "github.com/docker/docker/builder/dockerfile"
  2. // internals for handling commands. Covers many areas and a lot of
  3. // non-contiguous functionality. Please read the comments.
  4. import (
  5. "context"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "fmt"
  9. "strings"
  10. "github.com/containerd/log"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/backend"
  13. "github.com/docker/docker/api/types/container"
  14. "github.com/docker/docker/builder"
  15. "github.com/docker/docker/image"
  16. "github.com/docker/docker/pkg/archive"
  17. "github.com/docker/docker/pkg/chrootarchive"
  18. "github.com/docker/docker/pkg/stringid"
  19. "github.com/docker/go-connections/nat"
  20. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  21. "github.com/pkg/errors"
  22. )
  23. func (b *Builder) getArchiver() *archive.Archiver {
  24. return chrootarchive.NewArchiver(b.idMapping)
  25. }
  26. func (b *Builder) commit(ctx context.Context, dispatchState *dispatchState, comment string) error {
  27. if b.disableCommit {
  28. return nil
  29. }
  30. if !dispatchState.hasFromImage() {
  31. return errors.New("Please provide a source image with `from` prior to commit")
  32. }
  33. runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment, dispatchState.operatingSystem))
  34. id, err := b.probeAndCreate(ctx, dispatchState, runConfigWithCommentCmd)
  35. if err != nil || id == "" {
  36. return err
  37. }
  38. return b.commitContainer(ctx, dispatchState, id, runConfigWithCommentCmd)
  39. }
  40. func (b *Builder) commitContainer(ctx context.Context, dispatchState *dispatchState, id string, containerConfig *container.Config) error {
  41. if b.disableCommit {
  42. return nil
  43. }
  44. commitCfg := backend.CommitConfig{
  45. Author: dispatchState.maintainer,
  46. // TODO: this copy should be done by Commit()
  47. Config: copyRunConfig(dispatchState.runConfig),
  48. ContainerConfig: containerConfig,
  49. ContainerID: id,
  50. }
  51. imageID, err := b.docker.CommitBuildStep(ctx, commitCfg)
  52. dispatchState.imageID = string(imageID)
  53. return err
  54. }
  55. func (b *Builder) exportImage(ctx context.Context, state *dispatchState, layer builder.RWLayer, parent builder.Image, runConfig *container.Config) error {
  56. newLayer, err := layer.Commit()
  57. if err != nil {
  58. return err
  59. }
  60. parentImage, ok := parent.(*image.Image)
  61. if !ok {
  62. return errors.Errorf("unexpected image type")
  63. }
  64. platform := &ocispec.Platform{
  65. OS: parentImage.OS,
  66. Architecture: parentImage.Architecture,
  67. Variant: parentImage.Variant,
  68. }
  69. // add an image mount without an image so the layer is properly unmounted
  70. // if there is an error before we can add the full mount with image
  71. b.imageSources.Add(newImageMount(nil, newLayer), platform)
  72. newImage := image.NewChildImage(parentImage, image.ChildConfig{
  73. Author: state.maintainer,
  74. ContainerConfig: runConfig,
  75. DiffID: newLayer.DiffID(),
  76. Config: copyRunConfig(state.runConfig),
  77. }, parentImage.OS)
  78. // TODO: it seems strange to marshal this here instead of just passing in the
  79. // image struct
  80. config, err := newImage.MarshalJSON()
  81. if err != nil {
  82. return errors.Wrap(err, "failed to encode image config")
  83. }
  84. // when writing the new image's manifest, we now need to pass in the new layer's digest.
  85. // before the containerd store work this was unnecessary since we get the layer id
  86. // from the image's RootFS ChainID -- see:
  87. // https://github.com/moby/moby/blob/8cf66ed7322fa885ef99c4c044fa23e1727301dc/image/store.go#L162
  88. // however, with the containerd store we can't do this. An alternative implementation here
  89. // without changing the signature would be to get the layer digest by walking the content store
  90. // and filtering the objects to find the layer with the DiffID we want, but that has performance
  91. // implications that should be called out/investigated
  92. exportedImage, err := b.docker.CreateImage(ctx, config, state.imageID, newLayer.ContentStoreDigest())
  93. if err != nil {
  94. return errors.Wrapf(err, "failed to export image")
  95. }
  96. state.imageID = exportedImage.ImageID()
  97. b.imageSources.Add(newImageMount(exportedImage, newLayer), platform)
  98. return nil
  99. }
  100. func (b *Builder) performCopy(ctx context.Context, req dispatchRequest, inst copyInstruction) error {
  101. state := req.state
  102. srcHash := getSourceHashFromInfos(inst.infos)
  103. var chownComment string
  104. if inst.chownStr != "" {
  105. chownComment = fmt.Sprintf("--chown=%s ", inst.chownStr)
  106. }
  107. commentStr := fmt.Sprintf("%s %s%s in %s ", inst.cmdName, chownComment, srcHash, inst.dest)
  108. // TODO: should this have been using origPaths instead of srcHash in the comment?
  109. runConfigWithCommentCmd := copyRunConfig(
  110. state.runConfig,
  111. withCmdCommentString(commentStr, state.operatingSystem))
  112. hit, err := b.probeCache(state, runConfigWithCommentCmd)
  113. if err != nil || hit {
  114. return err
  115. }
  116. imageMount, err := b.imageSources.Get(ctx, state.imageID, true, req.builder.platform)
  117. if err != nil {
  118. return errors.Wrapf(err, "failed to get destination image %q", state.imageID)
  119. }
  120. rwLayer, err := imageMount.NewRWLayer()
  121. if err != nil {
  122. return err
  123. }
  124. defer rwLayer.Release()
  125. destInfo, err := createDestInfo(state.runConfig.WorkingDir, inst, rwLayer, state.operatingSystem)
  126. if err != nil {
  127. return err
  128. }
  129. identity := b.idMapping.RootPair()
  130. // if a chown was requested, perform the steps to get the uid, gid
  131. // translated (if necessary because of user namespaces), and replace
  132. // the root pair with the chown pair for copy operations
  133. if inst.chownStr != "" {
  134. identity, err = parseChownFlag(ctx, b, state, inst.chownStr, destInfo.root, b.idMapping)
  135. if err != nil {
  136. if b.options.Platform != "windows" {
  137. return errors.Wrapf(err, "unable to convert uid/gid chown string to host mapping")
  138. }
  139. return errors.Wrapf(err, "unable to map container user account name to SID")
  140. }
  141. }
  142. for _, info := range inst.infos {
  143. opts := copyFileOptions{
  144. decompress: inst.allowLocalDecompression,
  145. archiver: b.getArchiver(),
  146. }
  147. if !inst.preserveOwnership {
  148. opts.identity = &identity
  149. }
  150. if err := performCopyForInfo(destInfo, info, opts); err != nil {
  151. return errors.Wrapf(err, "failed to copy files")
  152. }
  153. }
  154. return b.exportImage(ctx, state, rwLayer, imageMount.Image(), runConfigWithCommentCmd)
  155. }
  156. func createDestInfo(workingDir string, inst copyInstruction, rwLayer builder.RWLayer, platform string) (copyInfo, error) {
  157. // Twiddle the destination when it's a relative path - meaning, make it
  158. // relative to the WORKINGDIR
  159. dest, err := normalizeDest(workingDir, inst.dest)
  160. if err != nil {
  161. return copyInfo{}, errors.Wrapf(err, "invalid %s", inst.cmdName)
  162. }
  163. return copyInfo{root: rwLayer.Root(), path: dest}, nil
  164. }
  165. // For backwards compat, if there's just one info then use it as the
  166. // cache look-up string, otherwise hash 'em all into one
  167. func getSourceHashFromInfos(infos []copyInfo) string {
  168. if len(infos) == 1 {
  169. return infos[0].hash
  170. }
  171. var hashs []string
  172. for _, info := range infos {
  173. hashs = append(hashs, info.hash)
  174. }
  175. return hashStringSlice("multi", hashs)
  176. }
  177. func hashStringSlice(prefix string, slice []string) string {
  178. hasher := sha256.New()
  179. hasher.Write([]byte(strings.Join(slice, ",")))
  180. return prefix + ":" + hex.EncodeToString(hasher.Sum(nil))
  181. }
  182. type runConfigModifier func(*container.Config)
  183. func withCmd(cmd []string) runConfigModifier {
  184. return func(runConfig *container.Config) {
  185. runConfig.Cmd = cmd
  186. }
  187. }
  188. func withArgsEscaped(argsEscaped bool) runConfigModifier {
  189. return func(runConfig *container.Config) {
  190. runConfig.ArgsEscaped = argsEscaped
  191. }
  192. }
  193. // withCmdComment sets Cmd to a nop comment string. See withCmdCommentString for
  194. // why there are two almost identical versions of this.
  195. func withCmdComment(comment string, platform string) runConfigModifier {
  196. return func(runConfig *container.Config) {
  197. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) ", comment)
  198. }
  199. }
  200. // withCmdCommentString exists to maintain compatibility with older versions.
  201. // A few instructions (workdir, copy, add) used a nop comment that is a single arg
  202. // where as all the other instructions used a two arg comment string. This
  203. // function implements the single arg version.
  204. func withCmdCommentString(comment string, platform string) runConfigModifier {
  205. return func(runConfig *container.Config) {
  206. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) "+comment)
  207. }
  208. }
  209. func withEnv(env []string) runConfigModifier {
  210. return func(runConfig *container.Config) {
  211. runConfig.Env = env
  212. }
  213. }
  214. // withEntrypointOverride sets an entrypoint on runConfig if the command is
  215. // not empty. The entrypoint is left unmodified if command is empty.
  216. //
  217. // The dockerfile RUN instruction expect to run without an entrypoint
  218. // so the runConfig entrypoint needs to be modified accordingly. ContainerCreate
  219. // will change a []string{""} entrypoint to nil, so we probe the cache with the
  220. // nil entrypoint.
  221. func withEntrypointOverride(cmd []string, entrypoint []string) runConfigModifier {
  222. return func(runConfig *container.Config) {
  223. if len(cmd) > 0 {
  224. runConfig.Entrypoint = entrypoint
  225. }
  226. }
  227. }
  228. // withoutHealthcheck disables healthcheck.
  229. //
  230. // The dockerfile RUN instruction expect to run without healthcheck
  231. // so the runConfig Healthcheck needs to be disabled.
  232. func withoutHealthcheck() runConfigModifier {
  233. return func(runConfig *container.Config) {
  234. runConfig.Healthcheck = &container.HealthConfig{
  235. Test: []string{"NONE"},
  236. }
  237. }
  238. }
  239. func copyRunConfig(runConfig *container.Config, modifiers ...runConfigModifier) *container.Config {
  240. copy := *runConfig
  241. copy.Cmd = copyStringSlice(runConfig.Cmd)
  242. copy.Env = copyStringSlice(runConfig.Env)
  243. copy.Entrypoint = copyStringSlice(runConfig.Entrypoint)
  244. copy.OnBuild = copyStringSlice(runConfig.OnBuild)
  245. copy.Shell = copyStringSlice(runConfig.Shell)
  246. if copy.Volumes != nil {
  247. copy.Volumes = make(map[string]struct{}, len(runConfig.Volumes))
  248. for k, v := range runConfig.Volumes {
  249. copy.Volumes[k] = v
  250. }
  251. }
  252. if copy.ExposedPorts != nil {
  253. copy.ExposedPorts = make(nat.PortSet, len(runConfig.ExposedPorts))
  254. for k, v := range runConfig.ExposedPorts {
  255. copy.ExposedPorts[k] = v
  256. }
  257. }
  258. if copy.Labels != nil {
  259. copy.Labels = make(map[string]string, len(runConfig.Labels))
  260. for k, v := range runConfig.Labels {
  261. copy.Labels[k] = v
  262. }
  263. }
  264. for _, modifier := range modifiers {
  265. modifier(&copy)
  266. }
  267. return &copy
  268. }
  269. func copyStringSlice(orig []string) []string {
  270. if orig == nil {
  271. return nil
  272. }
  273. return append([]string{}, orig...)
  274. }
  275. // getShell is a helper function which gets the right shell for prefixing the
  276. // shell-form of RUN, ENTRYPOINT and CMD instructions
  277. func getShell(c *container.Config, os string) []string {
  278. if 0 == len(c.Shell) {
  279. return append([]string{}, defaultShellForOS(os)[:]...)
  280. }
  281. return append([]string{}, c.Shell[:]...)
  282. }
  283. func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container.Config) (bool, error) {
  284. cachedID, err := b.imageProber.Probe(dispatchState.imageID, runConfig)
  285. if cachedID == "" || err != nil {
  286. return false, err
  287. }
  288. fmt.Fprint(b.Stdout, " ---> Using cache\n")
  289. dispatchState.imageID = cachedID
  290. return true, nil
  291. }
  292. var defaultLogConfig = container.LogConfig{Type: "none"}
  293. func (b *Builder) probeAndCreate(ctx context.Context, dispatchState *dispatchState, runConfig *container.Config) (string, error) {
  294. if hit, err := b.probeCache(dispatchState, runConfig); err != nil || hit {
  295. return "", err
  296. }
  297. return b.create(ctx, runConfig)
  298. }
  299. func (b *Builder) create(ctx context.Context, runConfig *container.Config) (string, error) {
  300. log.G(ctx).Debugf("[BUILDER] Command to be executed: %v", runConfig.Cmd)
  301. hostConfig := hostConfigFromOptions(b.options)
  302. container, err := b.containerManager.Create(ctx, runConfig, hostConfig)
  303. if err != nil {
  304. return "", err
  305. }
  306. // TODO: could this be moved into containerManager.Create() ?
  307. for _, warning := range container.Warnings {
  308. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  309. }
  310. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(container.ID))
  311. return container.ID, nil
  312. }
  313. func hostConfigFromOptions(options *types.ImageBuildOptions) *container.HostConfig {
  314. resources := container.Resources{
  315. CgroupParent: options.CgroupParent,
  316. CPUShares: options.CPUShares,
  317. CPUPeriod: options.CPUPeriod,
  318. CPUQuota: options.CPUQuota,
  319. CpusetCpus: options.CPUSetCPUs,
  320. CpusetMems: options.CPUSetMems,
  321. Memory: options.Memory,
  322. MemorySwap: options.MemorySwap,
  323. Ulimits: options.Ulimits,
  324. }
  325. hc := &container.HostConfig{
  326. SecurityOpt: options.SecurityOpt,
  327. Isolation: options.Isolation,
  328. ShmSize: options.ShmSize,
  329. Resources: resources,
  330. NetworkMode: container.NetworkMode(options.NetworkMode),
  331. // Set a log config to override any default value set on the daemon
  332. LogConfig: defaultLogConfig,
  333. ExtraHosts: options.ExtraHosts,
  334. }
  335. return hc
  336. }