internals.go 16 KB

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