internals.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/backend"
  13. "github.com/docker/docker/api/types/container"
  14. "github.com/docker/docker/image"
  15. "github.com/docker/docker/pkg/idtools"
  16. "github.com/docker/docker/pkg/stringid"
  17. "github.com/docker/docker/pkg/symlink"
  18. lcUser "github.com/opencontainers/runc/libcontainer/user"
  19. "github.com/pkg/errors"
  20. )
  21. func (b *Builder) commit(dispatchState *dispatchState, comment string) error {
  22. if b.disableCommit {
  23. return nil
  24. }
  25. if !dispatchState.hasFromImage() {
  26. return errors.New("Please provide a source image with `from` prior to commit")
  27. }
  28. runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment, b.platform))
  29. hit, err := b.probeCache(dispatchState, runConfigWithCommentCmd)
  30. if err != nil || hit {
  31. return err
  32. }
  33. id, err := b.create(runConfigWithCommentCmd)
  34. if err != nil {
  35. return err
  36. }
  37. return b.commitContainer(dispatchState, id, runConfigWithCommentCmd)
  38. }
  39. func (b *Builder) commitContainer(dispatchState *dispatchState, id string, containerConfig *container.Config) error {
  40. if b.disableCommit {
  41. return nil
  42. }
  43. commitCfg := &backend.ContainerCommitConfig{
  44. ContainerCommitConfig: types.ContainerCommitConfig{
  45. Author: dispatchState.maintainer,
  46. Pause: true,
  47. // TODO: this should be done by Commit()
  48. Config: copyRunConfig(dispatchState.runConfig),
  49. },
  50. ContainerConfig: containerConfig,
  51. }
  52. // Commit the container
  53. imageID, err := b.docker.Commit(id, commitCfg)
  54. if err != nil {
  55. return err
  56. }
  57. dispatchState.imageID = imageID
  58. b.buildStages.update(imageID)
  59. return nil
  60. }
  61. func (b *Builder) exportImage(state *dispatchState, imageMount *imageMount, runConfig *container.Config) error {
  62. newLayer, err := imageMount.Layer().Commit(b.platform)
  63. if err != nil {
  64. return err
  65. }
  66. // add an image mount without an image so the layer is properly unmounted
  67. // if there is an error before we can add the full mount with image
  68. b.imageSources.Add(newImageMount(nil, newLayer))
  69. parentImage, ok := imageMount.Image().(*image.Image)
  70. if !ok {
  71. return errors.Errorf("unexpected image type")
  72. }
  73. newImage := image.NewChildImage(parentImage, image.ChildConfig{
  74. Author: state.maintainer,
  75. ContainerConfig: runConfig,
  76. DiffID: newLayer.DiffID(),
  77. Config: copyRunConfig(state.runConfig),
  78. }, parentImage.OS)
  79. // TODO: it seems strange to marshal this here instead of just passing in the
  80. // image struct
  81. config, err := newImage.MarshalJSON()
  82. if err != nil {
  83. return errors.Wrap(err, "failed to encode image config")
  84. }
  85. exportedImage, err := b.docker.CreateImage(config, state.imageID, parentImage.OS)
  86. if err != nil {
  87. return errors.Wrapf(err, "failed to export image")
  88. }
  89. state.imageID = exportedImage.ImageID()
  90. b.imageSources.Add(newImageMount(exportedImage, newLayer))
  91. b.buildStages.update(state.imageID)
  92. return nil
  93. }
  94. func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error {
  95. srcHash := getSourceHashFromInfos(inst.infos)
  96. var chownComment string
  97. if inst.chownStr != "" {
  98. chownComment = fmt.Sprintf("--chown=%s", inst.chownStr)
  99. }
  100. commentStr := fmt.Sprintf("%s %s%s in %s ", inst.cmdName, chownComment, srcHash, inst.dest)
  101. // TODO: should this have been using origPaths instead of srcHash in the comment?
  102. runConfigWithCommentCmd := copyRunConfig(
  103. state.runConfig,
  104. withCmdCommentString(commentStr, b.platform))
  105. hit, err := b.probeCache(state, runConfigWithCommentCmd)
  106. if err != nil || hit {
  107. return err
  108. }
  109. imageMount, err := b.imageSources.Get(state.imageID, true)
  110. if err != nil {
  111. return errors.Wrapf(err, "failed to get destination image %q", state.imageID)
  112. }
  113. destInfo, err := createDestInfo(state.runConfig.WorkingDir, inst, imageMount)
  114. if err != nil {
  115. return err
  116. }
  117. chownPair := b.archiver.IDMappings.RootPair()
  118. // if a chown was requested, perform the steps to get the uid, gid
  119. // translated (if necessary because of user namespaces), and replace
  120. // the root pair with the chown pair for copy operations
  121. if inst.chownStr != "" {
  122. chownPair, err = parseChownFlag(inst.chownStr, destInfo.root, b.archiver.IDMappings)
  123. if err != nil {
  124. return errors.Wrapf(err, "unable to convert uid/gid chown string to host mapping")
  125. }
  126. }
  127. opts := copyFileOptions{
  128. decompress: inst.allowLocalDecompression,
  129. archiver: b.archiver,
  130. chownPair: chownPair,
  131. }
  132. for _, info := range inst.infos {
  133. if err := performCopyForInfo(destInfo, info, opts); err != nil {
  134. return errors.Wrapf(err, "failed to copy files")
  135. }
  136. }
  137. return b.exportImage(state, imageMount, runConfigWithCommentCmd)
  138. }
  139. func parseChownFlag(chown, ctrRootPath string, idMappings *idtools.IDMappings) (idtools.IDPair, error) {
  140. var userStr, grpStr string
  141. parts := strings.Split(chown, ":")
  142. if len(parts) > 2 {
  143. return idtools.IDPair{}, errors.New("invalid chown string format: " + chown)
  144. }
  145. if len(parts) == 1 {
  146. // if no group specified, use the user spec as group as well
  147. userStr, grpStr = parts[0], parts[0]
  148. } else {
  149. userStr, grpStr = parts[0], parts[1]
  150. }
  151. passwdPath, err := symlink.FollowSymlinkInScope(filepath.Join(ctrRootPath, "etc", "passwd"), ctrRootPath)
  152. if err != nil {
  153. return idtools.IDPair{}, errors.Wrapf(err, "can't resolve /etc/passwd path in container rootfs")
  154. }
  155. groupPath, err := symlink.FollowSymlinkInScope(filepath.Join(ctrRootPath, "etc", "group"), ctrRootPath)
  156. if err != nil {
  157. return idtools.IDPair{}, errors.Wrapf(err, "can't resolve /etc/group path in container rootfs")
  158. }
  159. uid, err := lookupUser(userStr, passwdPath)
  160. if err != nil {
  161. return idtools.IDPair{}, errors.Wrapf(err, "can't find uid for user "+userStr)
  162. }
  163. gid, err := lookupGroup(grpStr, groupPath)
  164. if err != nil {
  165. return idtools.IDPair{}, errors.Wrapf(err, "can't find gid for group "+grpStr)
  166. }
  167. // convert as necessary because of user namespaces
  168. chownPair, err := idMappings.ToHost(idtools.IDPair{UID: uid, GID: gid})
  169. if err != nil {
  170. return idtools.IDPair{}, errors.Wrapf(err, "unable to convert uid/gid to host mapping")
  171. }
  172. return chownPair, nil
  173. }
  174. func lookupUser(userStr, filepath string) (int, error) {
  175. // if the string is actually a uid integer, parse to int and return
  176. // as we don't need to translate with the help of files
  177. uid, err := strconv.Atoi(userStr)
  178. if err == nil {
  179. return uid, nil
  180. }
  181. users, err := lcUser.ParsePasswdFileFilter(filepath, func(u lcUser.User) bool {
  182. return u.Name == userStr
  183. })
  184. if err != nil {
  185. return 0, err
  186. }
  187. if len(users) == 0 {
  188. return 0, errors.New("no such user: " + userStr)
  189. }
  190. return users[0].Uid, nil
  191. }
  192. func lookupGroup(groupStr, filepath string) (int, error) {
  193. // if the string is actually a gid integer, parse to int and return
  194. // as we don't need to translate with the help of files
  195. gid, err := strconv.Atoi(groupStr)
  196. if err == nil {
  197. return gid, nil
  198. }
  199. groups, err := lcUser.ParseGroupFileFilter(filepath, func(g lcUser.Group) bool {
  200. return g.Name == groupStr
  201. })
  202. if err != nil {
  203. return 0, err
  204. }
  205. if len(groups) == 0 {
  206. return 0, errors.New("no such group: " + groupStr)
  207. }
  208. return groups[0].Gid, nil
  209. }
  210. func createDestInfo(workingDir string, inst copyInstruction, imageMount *imageMount) (copyInfo, error) {
  211. // Twiddle the destination when it's a relative path - meaning, make it
  212. // relative to the WORKINGDIR
  213. dest, err := normalizeDest(workingDir, inst.dest)
  214. if err != nil {
  215. return copyInfo{}, errors.Wrapf(err, "invalid %s", inst.cmdName)
  216. }
  217. destMount, err := imageMount.Source()
  218. if err != nil {
  219. return copyInfo{}, errors.Wrapf(err, "failed to mount copy source")
  220. }
  221. return newCopyInfoFromSource(destMount, dest, ""), nil
  222. }
  223. // For backwards compat, if there's just one info then use it as the
  224. // cache look-up string, otherwise hash 'em all into one
  225. func getSourceHashFromInfos(infos []copyInfo) string {
  226. if len(infos) == 1 {
  227. return infos[0].hash
  228. }
  229. var hashs []string
  230. for _, info := range infos {
  231. hashs = append(hashs, info.hash)
  232. }
  233. return hashStringSlice("multi", hashs)
  234. }
  235. func hashStringSlice(prefix string, slice []string) string {
  236. hasher := sha256.New()
  237. hasher.Write([]byte(strings.Join(slice, ",")))
  238. return prefix + ":" + hex.EncodeToString(hasher.Sum(nil))
  239. }
  240. type runConfigModifier func(*container.Config)
  241. func copyRunConfig(runConfig *container.Config, modifiers ...runConfigModifier) *container.Config {
  242. copy := *runConfig
  243. for _, modifier := range modifiers {
  244. modifier(&copy)
  245. }
  246. return &copy
  247. }
  248. func withCmd(cmd []string) runConfigModifier {
  249. return func(runConfig *container.Config) {
  250. runConfig.Cmd = cmd
  251. }
  252. }
  253. // withCmdComment sets Cmd to a nop comment string. See withCmdCommentString for
  254. // why there are two almost identical versions of this.
  255. func withCmdComment(comment string, platform string) runConfigModifier {
  256. return func(runConfig *container.Config) {
  257. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) ", comment)
  258. }
  259. }
  260. // withCmdCommentString exists to maintain compatibility with older versions.
  261. // A few instructions (workdir, copy, add) used a nop comment that is a single arg
  262. // where as all the other instructions used a two arg comment string. This
  263. // function implements the single arg version.
  264. func withCmdCommentString(comment string, platform string) runConfigModifier {
  265. return func(runConfig *container.Config) {
  266. runConfig.Cmd = append(getShell(runConfig, platform), "#(nop) "+comment)
  267. }
  268. }
  269. func withEnv(env []string) runConfigModifier {
  270. return func(runConfig *container.Config) {
  271. runConfig.Env = env
  272. }
  273. }
  274. // withEntrypointOverride sets an entrypoint on runConfig if the command is
  275. // not empty. The entrypoint is left unmodified if command is empty.
  276. //
  277. // The dockerfile RUN instruction expect to run without an entrypoint
  278. // so the runConfig entrypoint needs to be modified accordingly. ContainerCreate
  279. // will change a []string{""} entrypoint to nil, so we probe the cache with the
  280. // nil entrypoint.
  281. func withEntrypointOverride(cmd []string, entrypoint []string) runConfigModifier {
  282. return func(runConfig *container.Config) {
  283. if len(cmd) > 0 {
  284. runConfig.Entrypoint = entrypoint
  285. }
  286. }
  287. }
  288. // getShell is a helper function which gets the right shell for prefixing the
  289. // shell-form of RUN, ENTRYPOINT and CMD instructions
  290. func getShell(c *container.Config, platform string) []string {
  291. if 0 == len(c.Shell) {
  292. return append([]string{}, defaultShellForPlatform(platform)[:]...)
  293. }
  294. return append([]string{}, c.Shell[:]...)
  295. }
  296. func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container.Config) (bool, error) {
  297. cachedID, err := b.imageProber.Probe(dispatchState.imageID, runConfig)
  298. if cachedID == "" || err != nil {
  299. return false, err
  300. }
  301. fmt.Fprint(b.Stdout, " ---> Using cache\n")
  302. dispatchState.imageID = cachedID
  303. b.buildStages.update(dispatchState.imageID)
  304. return true, nil
  305. }
  306. var defaultLogConfig = container.LogConfig{Type: "none"}
  307. func (b *Builder) probeAndCreate(dispatchState *dispatchState, runConfig *container.Config) (string, error) {
  308. if hit, err := b.probeCache(dispatchState, runConfig); err != nil || hit {
  309. return "", err
  310. }
  311. // Set a log config to override any default value set on the daemon
  312. hostConfig := &container.HostConfig{LogConfig: defaultLogConfig}
  313. container, err := b.containerManager.Create(runConfig, hostConfig, b.platform)
  314. return container.ID, err
  315. }
  316. func (b *Builder) create(runConfig *container.Config) (string, error) {
  317. hostConfig := hostConfigFromOptions(b.options)
  318. container, err := b.containerManager.Create(runConfig, hostConfig, b.platform)
  319. if err != nil {
  320. return "", err
  321. }
  322. // TODO: could this be moved into containerManager.Create() ?
  323. for _, warning := range container.Warnings {
  324. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  325. }
  326. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(container.ID))
  327. return container.ID, nil
  328. }
  329. func hostConfigFromOptions(options *types.ImageBuildOptions) *container.HostConfig {
  330. resources := container.Resources{
  331. CgroupParent: options.CgroupParent,
  332. CPUShares: options.CPUShares,
  333. CPUPeriod: options.CPUPeriod,
  334. CPUQuota: options.CPUQuota,
  335. CpusetCpus: options.CPUSetCPUs,
  336. CpusetMems: options.CPUSetMems,
  337. Memory: options.Memory,
  338. MemorySwap: options.MemorySwap,
  339. Ulimits: options.Ulimits,
  340. }
  341. return &container.HostConfig{
  342. SecurityOpt: options.SecurityOpt,
  343. Isolation: options.Isolation,
  344. ShmSize: options.ShmSize,
  345. Resources: resources,
  346. NetworkMode: container.NetworkMode(options.NetworkMode),
  347. // Set a log config to override any default value set on the daemon
  348. LogConfig: defaultLogConfig,
  349. ExtraHosts: options.ExtraHosts,
  350. }
  351. }