internals.go 17 KB

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