internals.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. "runtime"
  13. "strings"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/api/types/backend"
  16. "github.com/docker/docker/api/types/container"
  17. "github.com/docker/docker/builder"
  18. "github.com/docker/docker/image"
  19. "github.com/docker/docker/pkg/archive"
  20. "github.com/docker/docker/pkg/chrootarchive"
  21. "github.com/docker/docker/pkg/containerfs"
  22. "github.com/docker/docker/pkg/idtools"
  23. "github.com/docker/docker/pkg/stringid"
  24. "github.com/docker/docker/pkg/system"
  25. "github.com/docker/go-connections/nat"
  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. IDMappings() *idtools.IDMappings
  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. IDMappingsVar: b.idMappings,
  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. // add an image mount without an image so the layer is properly unmounted
  104. // if there is an error before we can add the full mount with image
  105. b.imageSources.Add(newImageMount(nil, newLayer))
  106. parentImage, ok := parent.(*image.Image)
  107. if !ok {
  108. return errors.Errorf("unexpected image type")
  109. }
  110. newImage := image.NewChildImage(parentImage, image.ChildConfig{
  111. Author: state.maintainer,
  112. ContainerConfig: runConfig,
  113. DiffID: newLayer.DiffID(),
  114. Config: copyRunConfig(state.runConfig),
  115. }, parentImage.OS)
  116. // TODO: it seems strange to marshal this here instead of just passing in the
  117. // image struct
  118. config, err := newImage.MarshalJSON()
  119. if err != nil {
  120. return errors.Wrap(err, "failed to encode image config")
  121. }
  122. exportedImage, err := b.docker.CreateImage(config, state.imageID)
  123. if err != nil {
  124. return errors.Wrapf(err, "failed to export image")
  125. }
  126. state.imageID = exportedImage.ImageID()
  127. b.imageSources.Add(newImageMount(exportedImage, newLayer))
  128. return nil
  129. }
  130. func (b *Builder) performCopy(req dispatchRequest, inst copyInstruction) error {
  131. state := req.state
  132. srcHash := getSourceHashFromInfos(inst.infos)
  133. var chownComment string
  134. if inst.chownStr != "" {
  135. chownComment = fmt.Sprintf("--chown=%s", inst.chownStr)
  136. }
  137. commentStr := fmt.Sprintf("%s %s%s in %s ", inst.cmdName, chownComment, srcHash, inst.dest)
  138. // TODO: should this have been using origPaths instead of srcHash in the comment?
  139. runConfigWithCommentCmd := copyRunConfig(
  140. state.runConfig,
  141. withCmdCommentString(commentStr, state.operatingSystem))
  142. hit, err := b.probeCache(state, runConfigWithCommentCmd)
  143. if err != nil || hit {
  144. return err
  145. }
  146. imageMount, err := b.imageSources.Get(state.imageID, true, req.builder.options.Platform)
  147. if err != nil {
  148. return errors.Wrapf(err, "failed to get destination image %q", state.imageID)
  149. }
  150. rwLayer, err := imageMount.NewRWLayer()
  151. if err != nil {
  152. return err
  153. }
  154. defer rwLayer.Release()
  155. destInfo, err := createDestInfo(state.runConfig.WorkingDir, inst, rwLayer, state.operatingSystem)
  156. if err != nil {
  157. return err
  158. }
  159. chownPair := b.idMappings.RootPair()
  160. // if a chown was requested, perform the steps to get the uid, gid
  161. // translated (if necessary because of user namespaces), and replace
  162. // the root pair with the chown pair for copy operations
  163. if inst.chownStr != "" {
  164. chownPair, err = parseChownFlag(inst.chownStr, destInfo.root.Path(), b.idMappings)
  165. if err != nil {
  166. return errors.Wrapf(err, "unable to convert uid/gid chown string to host mapping")
  167. }
  168. }
  169. for _, info := range inst.infos {
  170. opts := copyFileOptions{
  171. decompress: inst.allowLocalDecompression,
  172. archiver: b.getArchiver(info.root, destInfo.root),
  173. chownPair: chownPair,
  174. }
  175. if err := performCopyForInfo(destInfo, info, opts); err != nil {
  176. return errors.Wrapf(err, "failed to copy files")
  177. }
  178. }
  179. return b.exportImage(state, rwLayer, imageMount.Image(), runConfigWithCommentCmd)
  180. }
  181. func createDestInfo(workingDir string, inst copyInstruction, rwLayer builder.RWLayer, platform string) (copyInfo, error) {
  182. // Twiddle the destination when it's a relative path - meaning, make it
  183. // relative to the WORKINGDIR
  184. dest, err := normalizeDest(workingDir, inst.dest, platform)
  185. if err != nil {
  186. return copyInfo{}, errors.Wrapf(err, "invalid %s", inst.cmdName)
  187. }
  188. return copyInfo{root: rwLayer.Root(), path: dest}, nil
  189. }
  190. // normalizeDest normalises the destination of a COPY/ADD command in a
  191. // platform semantically consistent way.
  192. func normalizeDest(workingDir, requested string, platform string) (string, error) {
  193. dest := fromSlash(requested, platform)
  194. endsInSlash := strings.HasSuffix(dest, string(separator(platform)))
  195. if platform != "windows" {
  196. if !path.IsAbs(requested) {
  197. dest = path.Join("/", filepath.ToSlash(workingDir), dest)
  198. // Make sure we preserve any trailing slash
  199. if endsInSlash {
  200. dest += "/"
  201. }
  202. }
  203. return dest, nil
  204. }
  205. // We are guaranteed that the working directory is already consistent,
  206. // However, Windows also has, for now, the limitation that ADD/COPY can
  207. // only be done to the system drive, not any drives that might be present
  208. // as a result of a bind mount.
  209. //
  210. // So... if the path requested is Linux-style absolute (/foo or \\foo),
  211. // we assume it is the system drive. If it is a Windows-style absolute
  212. // (DRIVE:\\foo), error if DRIVE is not C. And finally, ensure we
  213. // strip any configured working directories drive letter so that it
  214. // can be subsequently legitimately converted to a Windows volume-style
  215. // pathname.
  216. // Not a typo - filepath.IsAbs, not system.IsAbs on this next check as
  217. // we only want to validate where the DriveColon part has been supplied.
  218. if filepath.IsAbs(dest) {
  219. if strings.ToUpper(string(dest[0])) != "C" {
  220. return "", fmt.Errorf("Windows does not support destinations not on the system drive (C:)")
  221. }
  222. dest = dest[2:] // Strip the drive letter
  223. }
  224. // Cannot handle relative where WorkingDir is not the system drive.
  225. if len(workingDir) > 0 {
  226. if ((len(workingDir) > 1) && !system.IsAbs(workingDir[2:])) || (len(workingDir) == 1) {
  227. return "", fmt.Errorf("Current WorkingDir %s is not platform consistent", workingDir)
  228. }
  229. if !system.IsAbs(dest) {
  230. if string(workingDir[0]) != "C" {
  231. return "", fmt.Errorf("Windows does not support relative paths when WORKDIR is not the system drive")
  232. }
  233. dest = filepath.Join(string(os.PathSeparator), workingDir[2:], dest)
  234. // Make sure we preserve any trailing slash
  235. if endsInSlash {
  236. dest += string(os.PathSeparator)
  237. }
  238. }
  239. }
  240. return dest, nil
  241. }
  242. // For backwards compat, if there's just one info then use it as the
  243. // cache look-up string, otherwise hash 'em all into one
  244. func getSourceHashFromInfos(infos []copyInfo) string {
  245. if len(infos) == 1 {
  246. return infos[0].hash
  247. }
  248. var hashs []string
  249. for _, info := range infos {
  250. hashs = append(hashs, info.hash)
  251. }
  252. return hashStringSlice("multi", hashs)
  253. }
  254. func hashStringSlice(prefix string, slice []string) string {
  255. hasher := sha256.New()
  256. hasher.Write([]byte(strings.Join(slice, ",")))
  257. return prefix + ":" + hex.EncodeToString(hasher.Sum(nil))
  258. }
  259. type runConfigModifier func(*container.Config)
  260. func withCmd(cmd []string) runConfigModifier {
  261. return func(runConfig *container.Config) {
  262. runConfig.Cmd = cmd
  263. }
  264. }
  265. // withCmdComment sets Cmd to a nop comment string. See withCmdCommentString for
  266. // why there are two almost identical versions of this.
  267. func withCmdComment(comment string, platform string) runConfigModifier {
  268. return func(runConfig *container.Config) {
  269. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) ", comment)
  270. }
  271. }
  272. // withCmdCommentString exists to maintain compatibility with older versions.
  273. // A few instructions (workdir, copy, add) used a nop comment that is a single arg
  274. // where as all the other instructions used a two arg comment string. This
  275. // function implements the single arg version.
  276. func withCmdCommentString(comment string, platform string) runConfigModifier {
  277. return func(runConfig *container.Config) {
  278. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) "+comment)
  279. }
  280. }
  281. func withEnv(env []string) runConfigModifier {
  282. return func(runConfig *container.Config) {
  283. runConfig.Env = env
  284. }
  285. }
  286. // withEntrypointOverride sets an entrypoint on runConfig if the command is
  287. // not empty. The entrypoint is left unmodified if command is empty.
  288. //
  289. // The dockerfile RUN instruction expect to run without an entrypoint
  290. // so the runConfig entrypoint needs to be modified accordingly. ContainerCreate
  291. // will change a []string{""} entrypoint to nil, so we probe the cache with the
  292. // nil entrypoint.
  293. func withEntrypointOverride(cmd []string, entrypoint []string) runConfigModifier {
  294. return func(runConfig *container.Config) {
  295. if len(cmd) > 0 {
  296. runConfig.Entrypoint = entrypoint
  297. }
  298. }
  299. }
  300. func copyRunConfig(runConfig *container.Config, modifiers ...runConfigModifier) *container.Config {
  301. copy := *runConfig
  302. copy.Cmd = copyStringSlice(runConfig.Cmd)
  303. copy.Env = copyStringSlice(runConfig.Env)
  304. copy.Entrypoint = copyStringSlice(runConfig.Entrypoint)
  305. copy.OnBuild = copyStringSlice(runConfig.OnBuild)
  306. copy.Shell = copyStringSlice(runConfig.Shell)
  307. if copy.Volumes != nil {
  308. copy.Volumes = make(map[string]struct{}, len(runConfig.Volumes))
  309. for k, v := range runConfig.Volumes {
  310. copy.Volumes[k] = v
  311. }
  312. }
  313. if copy.ExposedPorts != nil {
  314. copy.ExposedPorts = make(nat.PortSet, len(runConfig.ExposedPorts))
  315. for k, v := range runConfig.ExposedPorts {
  316. copy.ExposedPorts[k] = v
  317. }
  318. }
  319. if copy.Labels != nil {
  320. copy.Labels = make(map[string]string, len(runConfig.Labels))
  321. for k, v := range runConfig.Labels {
  322. copy.Labels[k] = v
  323. }
  324. }
  325. for _, modifier := range modifiers {
  326. modifier(&copy)
  327. }
  328. return &copy
  329. }
  330. func copyStringSlice(orig []string) []string {
  331. if orig == nil {
  332. return nil
  333. }
  334. return append([]string{}, orig...)
  335. }
  336. // getShell is a helper function which gets the right shell for prefixing the
  337. // shell-form of RUN, ENTRYPOINT and CMD instructions
  338. func getShell(c *container.Config, os string) []string {
  339. if 0 == len(c.Shell) {
  340. return append([]string{}, defaultShellForOS(os)[:]...)
  341. }
  342. return append([]string{}, c.Shell[:]...)
  343. }
  344. func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container.Config) (bool, error) {
  345. cachedID, err := b.imageProber.Probe(dispatchState.imageID, runConfig)
  346. if cachedID == "" || err != nil {
  347. return false, err
  348. }
  349. fmt.Fprint(b.Stdout, " ---> Using cache\n")
  350. dispatchState.imageID = cachedID
  351. return true, nil
  352. }
  353. var defaultLogConfig = container.LogConfig{Type: "none"}
  354. func (b *Builder) probeAndCreate(dispatchState *dispatchState, runConfig *container.Config) (string, error) {
  355. if hit, err := b.probeCache(dispatchState, runConfig); err != nil || hit {
  356. return "", err
  357. }
  358. return b.create(runConfig)
  359. }
  360. func (b *Builder) create(runConfig *container.Config) (string, error) {
  361. logrus.Debugf("[BUILDER] Command to be executed: %v", runConfig.Cmd)
  362. hostConfig := hostConfigFromOptions(b.options)
  363. container, err := b.containerManager.Create(runConfig, hostConfig)
  364. if err != nil {
  365. return "", err
  366. }
  367. // TODO: could this be moved into containerManager.Create() ?
  368. for _, warning := range container.Warnings {
  369. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  370. }
  371. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(container.ID))
  372. return container.ID, nil
  373. }
  374. func hostConfigFromOptions(options *types.ImageBuildOptions) *container.HostConfig {
  375. resources := container.Resources{
  376. CgroupParent: options.CgroupParent,
  377. CPUShares: options.CPUShares,
  378. CPUPeriod: options.CPUPeriod,
  379. CPUQuota: options.CPUQuota,
  380. CpusetCpus: options.CPUSetCPUs,
  381. CpusetMems: options.CPUSetMems,
  382. Memory: options.Memory,
  383. MemorySwap: options.MemorySwap,
  384. Ulimits: options.Ulimits,
  385. }
  386. hc := &container.HostConfig{
  387. SecurityOpt: options.SecurityOpt,
  388. Isolation: options.Isolation,
  389. ShmSize: options.ShmSize,
  390. Resources: resources,
  391. NetworkMode: container.NetworkMode(options.NetworkMode),
  392. // Set a log config to override any default value set on the daemon
  393. LogConfig: defaultLogConfig,
  394. ExtraHosts: options.ExtraHosts,
  395. }
  396. // For WCOW, the default of 20GB hard-coded in the platform
  397. // is too small for builder scenarios where many users are
  398. // using RUN statements to install large amounts of data.
  399. // Use 127GB as that's the default size of a VHD in Hyper-V.
  400. if runtime.GOOS == "windows" && options.Platform != nil && options.Platform.OS == "windows" {
  401. hc.StorageOpt = make(map[string]string)
  402. hc.StorageOpt["size"] = "127GB"
  403. }
  404. return hc
  405. }
  406. // fromSlash works like filepath.FromSlash but with a given OS platform field
  407. func fromSlash(path, platform string) string {
  408. if platform == "windows" {
  409. return strings.Replace(path, "/", "\\", -1)
  410. }
  411. return path
  412. }
  413. // separator returns a OS path separator for the given OS platform
  414. func separator(platform string) byte {
  415. if platform == "windows" {
  416. return '\\'
  417. }
  418. return '/'
  419. }