internals.go 16 KB

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