internals.go 17 KB

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