internals.go 16 KB

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