internals.go 15 KB

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