internals.go 15 KB

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