internals.go 15 KB

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