internals.go 17 KB

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