internals.go 15 KB

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