internals.go 13 KB

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