internals.go 16 KB

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