internals.go 12 KB

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