internals.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. "strconv"
  14. "strings"
  15. "github.com/docker/docker/api/types"
  16. "github.com/docker/docker/api/types/backend"
  17. "github.com/docker/docker/api/types/container"
  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/symlink"
  25. "github.com/docker/docker/pkg/system"
  26. "github.com/docker/go-connections/nat"
  27. lcUser "github.com/opencontainers/runc/libcontainer/user"
  28. "github.com/pkg/errors"
  29. )
  30. // Archiver defines an interface for copying files from one destination to
  31. // another using Tar/Untar.
  32. type Archiver interface {
  33. TarUntar(src, dst string) error
  34. UntarPath(src, dst string) error
  35. CopyWithTar(src, dst string) error
  36. CopyFileWithTar(src, dst string) error
  37. IDMappings() *idtools.IDMappings
  38. }
  39. // The builder will use the following interfaces if the container fs implements
  40. // these for optimized copies to and from the container.
  41. type extractor interface {
  42. ExtractArchive(src io.Reader, dst string, opts *archive.TarOptions) error
  43. }
  44. type archiver interface {
  45. ArchivePath(src string, opts *archive.TarOptions) (io.ReadCloser, error)
  46. }
  47. // helper functions to get tar/untar func
  48. func untarFunc(i interface{}) containerfs.UntarFunc {
  49. if ea, ok := i.(extractor); ok {
  50. return ea.ExtractArchive
  51. }
  52. return chrootarchive.Untar
  53. }
  54. func tarFunc(i interface{}) containerfs.TarFunc {
  55. if ap, ok := i.(archiver); ok {
  56. return ap.ArchivePath
  57. }
  58. return archive.TarWithOptions
  59. }
  60. func (b *Builder) getArchiver(src, dst containerfs.Driver) Archiver {
  61. t, u := tarFunc(src), untarFunc(dst)
  62. return &containerfs.Archiver{
  63. SrcDriver: src,
  64. DstDriver: dst,
  65. Tar: t,
  66. Untar: u,
  67. IDMappingsVar: b.idMappings,
  68. }
  69. }
  70. func (b *Builder) commit(dispatchState *dispatchState, comment string) error {
  71. if b.disableCommit {
  72. return nil
  73. }
  74. if !dispatchState.hasFromImage() {
  75. return errors.New("Please provide a source image with `from` prior to commit")
  76. }
  77. optionsPlatform := system.ParsePlatform(b.options.Platform)
  78. runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment, optionsPlatform.OS))
  79. hit, err := b.probeCache(dispatchState, runConfigWithCommentCmd)
  80. if err != nil || hit {
  81. return err
  82. }
  83. id, err := b.create(runConfigWithCommentCmd)
  84. if err != nil {
  85. return err
  86. }
  87. return b.commitContainer(dispatchState, id, runConfigWithCommentCmd)
  88. }
  89. func (b *Builder) commitContainer(dispatchState *dispatchState, id string, containerConfig *container.Config) error {
  90. if b.disableCommit {
  91. return nil
  92. }
  93. commitCfg := &backend.ContainerCommitConfig{
  94. ContainerCommitConfig: types.ContainerCommitConfig{
  95. Author: dispatchState.maintainer,
  96. Pause: true,
  97. // TODO: this should be done by Commit()
  98. Config: copyRunConfig(dispatchState.runConfig),
  99. },
  100. ContainerConfig: containerConfig,
  101. }
  102. // Commit the container
  103. imageID, err := b.docker.Commit(id, commitCfg)
  104. if err != nil {
  105. return err
  106. }
  107. dispatchState.imageID = imageID
  108. return nil
  109. }
  110. func (b *Builder) exportImage(state *dispatchState, imageMount *imageMount, runConfig *container.Config) error {
  111. newLayer, err := imageMount.Layer().Commit()
  112. if err != nil {
  113. return err
  114. }
  115. // add an image mount without an image so the layer is properly unmounted
  116. // if there is an error before we can add the full mount with image
  117. b.imageSources.Add(newImageMount(nil, newLayer))
  118. parentImage, ok := imageMount.Image().(*image.Image)
  119. if !ok {
  120. return errors.Errorf("unexpected image type")
  121. }
  122. newImage := image.NewChildImage(parentImage, image.ChildConfig{
  123. Author: state.maintainer,
  124. ContainerConfig: runConfig,
  125. DiffID: newLayer.DiffID(),
  126. Config: copyRunConfig(state.runConfig),
  127. }, parentImage.OS)
  128. // TODO: it seems strange to marshal this here instead of just passing in the
  129. // image struct
  130. config, err := newImage.MarshalJSON()
  131. if err != nil {
  132. return errors.Wrap(err, "failed to encode image config")
  133. }
  134. exportedImage, err := b.docker.CreateImage(config, state.imageID)
  135. if err != nil {
  136. return errors.Wrapf(err, "failed to export image")
  137. }
  138. state.imageID = exportedImage.ImageID()
  139. b.imageSources.Add(newImageMount(exportedImage, newLayer))
  140. return nil
  141. }
  142. func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error {
  143. srcHash := getSourceHashFromInfos(inst.infos)
  144. var chownComment string
  145. if inst.chownStr != "" {
  146. chownComment = fmt.Sprintf("--chown=%s", inst.chownStr)
  147. }
  148. commentStr := fmt.Sprintf("%s %s%s in %s ", inst.cmdName, chownComment, srcHash, inst.dest)
  149. // TODO: should this have been using origPaths instead of srcHash in the comment?
  150. optionsPlatform := system.ParsePlatform(b.options.Platform)
  151. runConfigWithCommentCmd := copyRunConfig(
  152. state.runConfig,
  153. withCmdCommentString(commentStr, optionsPlatform.OS))
  154. hit, err := b.probeCache(state, runConfigWithCommentCmd)
  155. if err != nil || hit {
  156. return err
  157. }
  158. imageMount, err := b.imageSources.Get(state.imageID, true)
  159. if err != nil {
  160. return errors.Wrapf(err, "failed to get destination image %q", state.imageID)
  161. }
  162. destInfo, err := createDestInfo(state.runConfig.WorkingDir, inst, imageMount, b.options.Platform)
  163. if err != nil {
  164. return err
  165. }
  166. chownPair := b.idMappings.RootPair()
  167. // if a chown was requested, perform the steps to get the uid, gid
  168. // translated (if necessary because of user namespaces), and replace
  169. // the root pair with the chown pair for copy operations
  170. if inst.chownStr != "" {
  171. chownPair, err = parseChownFlag(inst.chownStr, destInfo.root.Path(), b.idMappings)
  172. if err != nil {
  173. return errors.Wrapf(err, "unable to convert uid/gid chown string to host mapping")
  174. }
  175. }
  176. for _, info := range inst.infos {
  177. opts := copyFileOptions{
  178. decompress: inst.allowLocalDecompression,
  179. archiver: b.getArchiver(info.root, destInfo.root),
  180. chownPair: chownPair,
  181. }
  182. if err := performCopyForInfo(destInfo, info, opts); err != nil {
  183. return errors.Wrapf(err, "failed to copy files")
  184. }
  185. }
  186. return b.exportImage(state, imageMount, runConfigWithCommentCmd)
  187. }
  188. func parseChownFlag(chown, ctrRootPath string, idMappings *idtools.IDMappings) (idtools.IDPair, error) {
  189. var userStr, grpStr string
  190. parts := strings.Split(chown, ":")
  191. if len(parts) > 2 {
  192. return idtools.IDPair{}, errors.New("invalid chown string format: " + chown)
  193. }
  194. if len(parts) == 1 {
  195. // if no group specified, use the user spec as group as well
  196. userStr, grpStr = parts[0], parts[0]
  197. } else {
  198. userStr, grpStr = parts[0], parts[1]
  199. }
  200. passwdPath, err := symlink.FollowSymlinkInScope(filepath.Join(ctrRootPath, "etc", "passwd"), ctrRootPath)
  201. if err != nil {
  202. return idtools.IDPair{}, errors.Wrapf(err, "can't resolve /etc/passwd path in container rootfs")
  203. }
  204. groupPath, err := symlink.FollowSymlinkInScope(filepath.Join(ctrRootPath, "etc", "group"), ctrRootPath)
  205. if err != nil {
  206. return idtools.IDPair{}, errors.Wrapf(err, "can't resolve /etc/group path in container rootfs")
  207. }
  208. uid, err := lookupUser(userStr, passwdPath)
  209. if err != nil {
  210. return idtools.IDPair{}, errors.Wrapf(err, "can't find uid for user "+userStr)
  211. }
  212. gid, err := lookupGroup(grpStr, groupPath)
  213. if err != nil {
  214. return idtools.IDPair{}, errors.Wrapf(err, "can't find gid for group "+grpStr)
  215. }
  216. // convert as necessary because of user namespaces
  217. chownPair, err := idMappings.ToHost(idtools.IDPair{UID: uid, GID: gid})
  218. if err != nil {
  219. return idtools.IDPair{}, errors.Wrapf(err, "unable to convert uid/gid to host mapping")
  220. }
  221. return chownPair, nil
  222. }
  223. func lookupUser(userStr, filepath string) (int, error) {
  224. // if the string is actually a uid integer, parse to int and return
  225. // as we don't need to translate with the help of files
  226. uid, err := strconv.Atoi(userStr)
  227. if err == nil {
  228. return uid, nil
  229. }
  230. users, err := lcUser.ParsePasswdFileFilter(filepath, func(u lcUser.User) bool {
  231. return u.Name == userStr
  232. })
  233. if err != nil {
  234. return 0, err
  235. }
  236. if len(users) == 0 {
  237. return 0, errors.New("no such user: " + userStr)
  238. }
  239. return users[0].Uid, nil
  240. }
  241. func lookupGroup(groupStr, filepath string) (int, error) {
  242. // if the string is actually a gid integer, parse to int and return
  243. // as we don't need to translate with the help of files
  244. gid, err := strconv.Atoi(groupStr)
  245. if err == nil {
  246. return gid, nil
  247. }
  248. groups, err := lcUser.ParseGroupFileFilter(filepath, func(g lcUser.Group) bool {
  249. return g.Name == groupStr
  250. })
  251. if err != nil {
  252. return 0, err
  253. }
  254. if len(groups) == 0 {
  255. return 0, errors.New("no such group: " + groupStr)
  256. }
  257. return groups[0].Gid, nil
  258. }
  259. func createDestInfo(workingDir string, inst copyInstruction, imageMount *imageMount, platform string) (copyInfo, error) {
  260. // Twiddle the destination when it's a relative path - meaning, make it
  261. // relative to the WORKINGDIR
  262. dest, err := normalizeDest(workingDir, inst.dest, platform)
  263. if err != nil {
  264. return copyInfo{}, errors.Wrapf(err, "invalid %s", inst.cmdName)
  265. }
  266. destMount, err := imageMount.Source()
  267. if err != nil {
  268. return copyInfo{}, errors.Wrapf(err, "failed to mount copy source")
  269. }
  270. return newCopyInfoFromSource(destMount, dest, ""), nil
  271. }
  272. // normalizeDest normalises the destination of a COPY/ADD command in a
  273. // platform semantically consistent way.
  274. func normalizeDest(workingDir, requested string, platform string) (string, error) {
  275. dest := fromSlash(requested, platform)
  276. endsInSlash := strings.HasSuffix(dest, string(separator(platform)))
  277. if platform != "windows" {
  278. if !path.IsAbs(requested) {
  279. dest = path.Join("/", filepath.ToSlash(workingDir), dest)
  280. // Make sure we preserve any trailing slash
  281. if endsInSlash {
  282. dest += "/"
  283. }
  284. }
  285. return dest, nil
  286. }
  287. // We are guaranteed that the working directory is already consistent,
  288. // However, Windows also has, for now, the limitation that ADD/COPY can
  289. // only be done to the system drive, not any drives that might be present
  290. // as a result of a bind mount.
  291. //
  292. // So... if the path requested is Linux-style absolute (/foo or \\foo),
  293. // we assume it is the system drive. If it is a Windows-style absolute
  294. // (DRIVE:\\foo), error if DRIVE is not C. And finally, ensure we
  295. // strip any configured working directories drive letter so that it
  296. // can be subsequently legitimately converted to a Windows volume-style
  297. // pathname.
  298. // Not a typo - filepath.IsAbs, not system.IsAbs on this next check as
  299. // we only want to validate where the DriveColon part has been supplied.
  300. if filepath.IsAbs(dest) {
  301. if strings.ToUpper(string(dest[0])) != "C" {
  302. return "", fmt.Errorf("Windows does not support destinations not on the system drive (C:)")
  303. }
  304. dest = dest[2:] // Strip the drive letter
  305. }
  306. // Cannot handle relative where WorkingDir is not the system drive.
  307. if len(workingDir) > 0 {
  308. if ((len(workingDir) > 1) && !system.IsAbs(workingDir[2:])) || (len(workingDir) == 1) {
  309. return "", fmt.Errorf("Current WorkingDir %s is not platform consistent", workingDir)
  310. }
  311. if !system.IsAbs(dest) {
  312. if string(workingDir[0]) != "C" {
  313. return "", fmt.Errorf("Windows does not support relative paths when WORKDIR is not the system drive")
  314. }
  315. dest = filepath.Join(string(os.PathSeparator), workingDir[2:], dest)
  316. // Make sure we preserve any trailing slash
  317. if endsInSlash {
  318. dest += string(os.PathSeparator)
  319. }
  320. }
  321. }
  322. return dest, nil
  323. }
  324. // For backwards compat, if there's just one info then use it as the
  325. // cache look-up string, otherwise hash 'em all into one
  326. func getSourceHashFromInfos(infos []copyInfo) string {
  327. if len(infos) == 1 {
  328. return infos[0].hash
  329. }
  330. var hashs []string
  331. for _, info := range infos {
  332. hashs = append(hashs, info.hash)
  333. }
  334. return hashStringSlice("multi", hashs)
  335. }
  336. func hashStringSlice(prefix string, slice []string) string {
  337. hasher := sha256.New()
  338. hasher.Write([]byte(strings.Join(slice, ",")))
  339. return prefix + ":" + hex.EncodeToString(hasher.Sum(nil))
  340. }
  341. type runConfigModifier func(*container.Config)
  342. func withCmd(cmd []string) runConfigModifier {
  343. return func(runConfig *container.Config) {
  344. runConfig.Cmd = cmd
  345. }
  346. }
  347. // withCmdComment sets Cmd to a nop comment string. See withCmdCommentString for
  348. // why there are two almost identical versions of this.
  349. func withCmdComment(comment string, platform string) runConfigModifier {
  350. return func(runConfig *container.Config) {
  351. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) ", comment)
  352. }
  353. }
  354. // withCmdCommentString exists to maintain compatibility with older versions.
  355. // A few instructions (workdir, copy, add) used a nop comment that is a single arg
  356. // where as all the other instructions used a two arg comment string. This
  357. // function implements the single arg version.
  358. func withCmdCommentString(comment string, platform string) runConfigModifier {
  359. return func(runConfig *container.Config) {
  360. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) "+comment)
  361. }
  362. }
  363. func withEnv(env []string) runConfigModifier {
  364. return func(runConfig *container.Config) {
  365. runConfig.Env = env
  366. }
  367. }
  368. // withEntrypointOverride sets an entrypoint on runConfig if the command is
  369. // not empty. The entrypoint is left unmodified if command is empty.
  370. //
  371. // The dockerfile RUN instruction expect to run without an entrypoint
  372. // so the runConfig entrypoint needs to be modified accordingly. ContainerCreate
  373. // will change a []string{""} entrypoint to nil, so we probe the cache with the
  374. // nil entrypoint.
  375. func withEntrypointOverride(cmd []string, entrypoint []string) runConfigModifier {
  376. return func(runConfig *container.Config) {
  377. if len(cmd) > 0 {
  378. runConfig.Entrypoint = entrypoint
  379. }
  380. }
  381. }
  382. func copyRunConfig(runConfig *container.Config, modifiers ...runConfigModifier) *container.Config {
  383. copy := *runConfig
  384. copy.Cmd = copyStringSlice(runConfig.Cmd)
  385. copy.Env = copyStringSlice(runConfig.Env)
  386. copy.Entrypoint = copyStringSlice(runConfig.Entrypoint)
  387. copy.OnBuild = copyStringSlice(runConfig.OnBuild)
  388. copy.Shell = copyStringSlice(runConfig.Shell)
  389. if copy.Volumes != nil {
  390. copy.Volumes = make(map[string]struct{}, len(runConfig.Volumes))
  391. for k, v := range runConfig.Volumes {
  392. copy.Volumes[k] = v
  393. }
  394. }
  395. if copy.ExposedPorts != nil {
  396. copy.ExposedPorts = make(nat.PortSet, len(runConfig.ExposedPorts))
  397. for k, v := range runConfig.ExposedPorts {
  398. copy.ExposedPorts[k] = v
  399. }
  400. }
  401. if copy.Labels != nil {
  402. copy.Labels = make(map[string]string, len(runConfig.Labels))
  403. for k, v := range runConfig.Labels {
  404. copy.Labels[k] = v
  405. }
  406. }
  407. for _, modifier := range modifiers {
  408. modifier(&copy)
  409. }
  410. return &copy
  411. }
  412. func copyStringSlice(orig []string) []string {
  413. if orig == nil {
  414. return nil
  415. }
  416. return append([]string{}, orig...)
  417. }
  418. // getShell is a helper function which gets the right shell for prefixing the
  419. // shell-form of RUN, ENTRYPOINT and CMD instructions
  420. func getShell(c *container.Config, os string) []string {
  421. if 0 == len(c.Shell) {
  422. return append([]string{}, defaultShellForOS(os)[:]...)
  423. }
  424. return append([]string{}, c.Shell[:]...)
  425. }
  426. func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container.Config) (bool, error) {
  427. cachedID, err := b.imageProber.Probe(dispatchState.imageID, runConfig)
  428. if cachedID == "" || err != nil {
  429. return false, err
  430. }
  431. fmt.Fprint(b.Stdout, " ---> Using cache\n")
  432. dispatchState.imageID = cachedID
  433. return true, nil
  434. }
  435. var defaultLogConfig = container.LogConfig{Type: "none"}
  436. func (b *Builder) probeAndCreate(dispatchState *dispatchState, runConfig *container.Config) (string, error) {
  437. if hit, err := b.probeCache(dispatchState, runConfig); err != nil || hit {
  438. return "", err
  439. }
  440. // Set a log config to override any default value set on the daemon
  441. hostConfig := &container.HostConfig{LogConfig: defaultLogConfig}
  442. container, err := b.containerManager.Create(runConfig, hostConfig)
  443. return container.ID, err
  444. }
  445. func (b *Builder) create(runConfig *container.Config) (string, error) {
  446. hostConfig := hostConfigFromOptions(b.options)
  447. container, err := b.containerManager.Create(runConfig, hostConfig)
  448. if err != nil {
  449. return "", err
  450. }
  451. // TODO: could this be moved into containerManager.Create() ?
  452. for _, warning := range container.Warnings {
  453. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  454. }
  455. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(container.ID))
  456. return container.ID, nil
  457. }
  458. func hostConfigFromOptions(options *types.ImageBuildOptions) *container.HostConfig {
  459. resources := container.Resources{
  460. CgroupParent: options.CgroupParent,
  461. CPUShares: options.CPUShares,
  462. CPUPeriod: options.CPUPeriod,
  463. CPUQuota: options.CPUQuota,
  464. CpusetCpus: options.CPUSetCPUs,
  465. CpusetMems: options.CPUSetMems,
  466. Memory: options.Memory,
  467. MemorySwap: options.MemorySwap,
  468. Ulimits: options.Ulimits,
  469. }
  470. hc := &container.HostConfig{
  471. SecurityOpt: options.SecurityOpt,
  472. Isolation: options.Isolation,
  473. ShmSize: options.ShmSize,
  474. Resources: resources,
  475. NetworkMode: container.NetworkMode(options.NetworkMode),
  476. // Set a log config to override any default value set on the daemon
  477. LogConfig: defaultLogConfig,
  478. ExtraHosts: options.ExtraHosts,
  479. }
  480. // For WCOW, the default of 20GB hard-coded in the platform
  481. // is too small for builder scenarios where many users are
  482. // using RUN statements to install large amounts of data.
  483. // Use 127GB as that's the default size of a VHD in Hyper-V.
  484. if runtime.GOOS == "windows" && options.Platform == "windows" {
  485. hc.StorageOpt = make(map[string]string)
  486. hc.StorageOpt["size"] = "127GB"
  487. }
  488. return hc
  489. }
  490. // fromSlash works like filepath.FromSlash but with a given OS platform field
  491. func fromSlash(path, platform string) string {
  492. if platform == "windows" {
  493. return strings.Replace(path, "/", "\\", -1)
  494. }
  495. return path
  496. }
  497. // separator returns a OS path separator for the given OS platform
  498. func separator(platform string) byte {
  499. if platform == "windows" {
  500. return '\\'
  501. }
  502. return '/'
  503. }