dispatchers.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. package dockerfile // import "github.com/docker/docker/builder/dockerfile"
  2. // This file contains the dispatchers for each command. Note that
  3. // `nullDispatch` is not actually a command, but support for commands we parse
  4. // but do nothing with.
  5. //
  6. // See evaluator.go for a higher level discussion of the whole evaluator
  7. // package.
  8. import (
  9. "bytes"
  10. "fmt"
  11. "runtime"
  12. "sort"
  13. "strings"
  14. "github.com/containerd/containerd/platforms"
  15. "github.com/docker/docker/api"
  16. "github.com/docker/docker/api/types/container"
  17. "github.com/docker/docker/api/types/strslice"
  18. "github.com/docker/docker/builder"
  19. "github.com/docker/docker/errdefs"
  20. "github.com/docker/docker/image"
  21. "github.com/docker/docker/pkg/jsonmessage"
  22. "github.com/docker/docker/pkg/signal"
  23. "github.com/docker/docker/pkg/system"
  24. "github.com/docker/go-connections/nat"
  25. "github.com/moby/buildkit/frontend/dockerfile/instructions"
  26. "github.com/moby/buildkit/frontend/dockerfile/parser"
  27. "github.com/moby/buildkit/frontend/dockerfile/shell"
  28. specs "github.com/opencontainers/image-spec/specs-go/v1"
  29. "github.com/pkg/errors"
  30. )
  31. // ENV foo bar
  32. //
  33. // Sets the environment variable foo to bar, also makes interpolation
  34. // in the dockerfile available from the next statement on via ${foo}.
  35. //
  36. func dispatchEnv(d dispatchRequest, c *instructions.EnvCommand) error {
  37. runConfig := d.state.runConfig
  38. commitMessage := bytes.NewBufferString("ENV")
  39. for _, e := range c.Env {
  40. name := e.Key
  41. newVar := e.String()
  42. commitMessage.WriteString(" " + newVar)
  43. gotOne := false
  44. for i, envVar := range runConfig.Env {
  45. envParts := strings.SplitN(envVar, "=", 2)
  46. compareFrom := envParts[0]
  47. if shell.EqualEnvKeys(compareFrom, name) {
  48. runConfig.Env[i] = newVar
  49. gotOne = true
  50. break
  51. }
  52. }
  53. if !gotOne {
  54. runConfig.Env = append(runConfig.Env, newVar)
  55. }
  56. }
  57. return d.builder.commit(d.state, commitMessage.String())
  58. }
  59. // MAINTAINER some text <maybe@an.email.address>
  60. //
  61. // Sets the maintainer metadata.
  62. func dispatchMaintainer(d dispatchRequest, c *instructions.MaintainerCommand) error {
  63. d.state.maintainer = c.Maintainer
  64. return d.builder.commit(d.state, "MAINTAINER "+c.Maintainer)
  65. }
  66. // LABEL some json data describing the image
  67. //
  68. // Sets the Label variable foo to bar,
  69. //
  70. func dispatchLabel(d dispatchRequest, c *instructions.LabelCommand) error {
  71. if d.state.runConfig.Labels == nil {
  72. d.state.runConfig.Labels = make(map[string]string)
  73. }
  74. commitStr := "LABEL"
  75. for _, v := range c.Labels {
  76. d.state.runConfig.Labels[v.Key] = v.Value
  77. commitStr += " " + v.String()
  78. }
  79. return d.builder.commit(d.state, commitStr)
  80. }
  81. // ADD foo /path
  82. //
  83. // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
  84. // exist here. If you do not wish to have this automatic handling, use COPY.
  85. //
  86. func dispatchAdd(d dispatchRequest, c *instructions.AddCommand) error {
  87. downloader := newRemoteSourceDownloader(d.builder.Output, d.builder.Stdout)
  88. copier := copierFromDispatchRequest(d, downloader, nil)
  89. defer copier.Cleanup()
  90. copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "ADD")
  91. if err != nil {
  92. return err
  93. }
  94. copyInstruction.chownStr = c.Chown
  95. copyInstruction.allowLocalDecompression = true
  96. return d.builder.performCopy(d, copyInstruction)
  97. }
  98. // COPY foo /path
  99. //
  100. // Same as 'ADD' but without the tar and remote url handling.
  101. //
  102. func dispatchCopy(d dispatchRequest, c *instructions.CopyCommand) error {
  103. var im *imageMount
  104. var err error
  105. if c.From != "" {
  106. im, err = d.getImageMount(c.From)
  107. if err != nil {
  108. return errors.Wrapf(err, "invalid from flag value %s", c.From)
  109. }
  110. }
  111. copier := copierFromDispatchRequest(d, errOnSourceDownload, im)
  112. defer copier.Cleanup()
  113. copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "COPY")
  114. if err != nil {
  115. return err
  116. }
  117. copyInstruction.chownStr = c.Chown
  118. return d.builder.performCopy(d, copyInstruction)
  119. }
  120. func (d *dispatchRequest) getImageMount(imageRefOrID string) (*imageMount, error) {
  121. if imageRefOrID == "" {
  122. // TODO: this could return the source in the default case as well?
  123. return nil, nil
  124. }
  125. var localOnly bool
  126. stage, err := d.stages.get(imageRefOrID)
  127. if err != nil {
  128. return nil, err
  129. }
  130. if stage != nil {
  131. imageRefOrID = stage.Image
  132. localOnly = true
  133. }
  134. return d.builder.imageSources.Get(imageRefOrID, localOnly, d.builder.options.Platform)
  135. }
  136. // FROM [--platform=platform] imagename[:tag | @digest] [AS build-stage-name]
  137. //
  138. func initializeStage(d dispatchRequest, cmd *instructions.Stage) error {
  139. d.builder.imageProber.Reset()
  140. var platform *specs.Platform
  141. if v := cmd.Platform; v != "" {
  142. v, err := d.getExpandedString(d.shlex, v)
  143. if err != nil {
  144. return errors.Wrapf(err, "failed to process arguments for platform %s", v)
  145. }
  146. p, err := platforms.Parse(v)
  147. if err != nil {
  148. return errors.Wrapf(err, "failed to parse platform %s", v)
  149. }
  150. platform = &p
  151. }
  152. image, err := d.getFromImage(d.shlex, cmd.BaseName, platform)
  153. if err != nil {
  154. return err
  155. }
  156. state := d.state
  157. if err := state.beginStage(cmd.Name, image); err != nil {
  158. return err
  159. }
  160. if len(state.runConfig.OnBuild) > 0 {
  161. triggers := state.runConfig.OnBuild
  162. state.runConfig.OnBuild = nil
  163. return dispatchTriggeredOnBuild(d, triggers)
  164. }
  165. return nil
  166. }
  167. func dispatchTriggeredOnBuild(d dispatchRequest, triggers []string) error {
  168. fmt.Fprintf(d.builder.Stdout, "# Executing %d build trigger", len(triggers))
  169. if len(triggers) > 1 {
  170. fmt.Fprint(d.builder.Stdout, "s")
  171. }
  172. fmt.Fprintln(d.builder.Stdout)
  173. for _, trigger := range triggers {
  174. d.state.updateRunConfig()
  175. ast, err := parser.Parse(strings.NewReader(trigger))
  176. if err != nil {
  177. return err
  178. }
  179. if len(ast.AST.Children) != 1 {
  180. return errors.New("onbuild trigger should be a single expression")
  181. }
  182. cmd, err := instructions.ParseCommand(ast.AST.Children[0])
  183. if err != nil {
  184. if instructions.IsUnknownInstruction(err) {
  185. buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
  186. }
  187. return err
  188. }
  189. err = dispatch(d, cmd)
  190. if err != nil {
  191. return err
  192. }
  193. }
  194. return nil
  195. }
  196. func (d *dispatchRequest) getExpandedString(shlex *shell.Lex, str string) (string, error) {
  197. substitutionArgs := []string{}
  198. for key, value := range d.state.buildArgs.GetAllMeta() {
  199. substitutionArgs = append(substitutionArgs, key+"="+value)
  200. }
  201. name, err := shlex.ProcessWord(str, substitutionArgs)
  202. if err != nil {
  203. return "", err
  204. }
  205. return name, nil
  206. }
  207. func (d *dispatchRequest) getImageOrStage(name string, platform *specs.Platform) (builder.Image, error) {
  208. var localOnly bool
  209. if im, ok := d.stages.getByName(name); ok {
  210. name = im.Image
  211. localOnly = true
  212. }
  213. if platform == nil {
  214. platform = d.builder.options.Platform
  215. }
  216. // Windows cannot support a container with no base image unless it is LCOW.
  217. if name == api.NoBaseImageSpecifier {
  218. p := platforms.DefaultSpec()
  219. if platform != nil {
  220. p = *platform
  221. }
  222. imageImage := &image.Image{}
  223. imageImage.OS = p.OS
  224. // old windows scratch handling
  225. // TODO: scratch should not have an os. It should be nil image.
  226. // Windows supports scratch. What is not supported is running containers
  227. // from it.
  228. if runtime.GOOS == "windows" {
  229. if platform == nil || platform.OS == "linux" {
  230. if !system.LCOWSupported() {
  231. return nil, errors.New("Linux containers are not supported on this system")
  232. }
  233. imageImage.OS = "linux"
  234. } else if platform.OS == "windows" {
  235. return nil, errors.New("Windows does not support FROM scratch")
  236. } else {
  237. return nil, errors.Errorf("platform %s is not supported", platforms.Format(p))
  238. }
  239. }
  240. return builder.Image(imageImage), nil
  241. }
  242. imageMount, err := d.builder.imageSources.Get(name, localOnly, platform)
  243. if err != nil {
  244. return nil, err
  245. }
  246. return imageMount.Image(), nil
  247. }
  248. func (d *dispatchRequest) getFromImage(shlex *shell.Lex, name string, platform *specs.Platform) (builder.Image, error) {
  249. name, err := d.getExpandedString(shlex, name)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return d.getImageOrStage(name, platform)
  254. }
  255. func dispatchOnbuild(d dispatchRequest, c *instructions.OnbuildCommand) error {
  256. d.state.runConfig.OnBuild = append(d.state.runConfig.OnBuild, c.Expression)
  257. return d.builder.commit(d.state, "ONBUILD "+c.Expression)
  258. }
  259. // WORKDIR /tmp
  260. //
  261. // Set the working directory for future RUN/CMD/etc statements.
  262. //
  263. func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error {
  264. runConfig := d.state.runConfig
  265. var err error
  266. runConfig.WorkingDir, err = normalizeWorkdir(d.state.operatingSystem, runConfig.WorkingDir, c.Path)
  267. if err != nil {
  268. return err
  269. }
  270. // For performance reasons, we explicitly do a create/mkdir now
  271. // This avoids having an unnecessary expensive mount/unmount calls
  272. // (on Windows in particular) during each container create.
  273. // Prior to 1.13, the mkdir was deferred and not executed at this step.
  274. if d.builder.disableCommit {
  275. // Don't call back into the daemon if we're going through docker commit --change "WORKDIR /foo".
  276. // We've already updated the runConfig and that's enough.
  277. return nil
  278. }
  279. comment := "WORKDIR " + runConfig.WorkingDir
  280. runConfigWithCommentCmd := copyRunConfig(runConfig, withCmdCommentString(comment, d.state.operatingSystem))
  281. containerID, err := d.builder.probeAndCreate(d.state, runConfigWithCommentCmd)
  282. if err != nil || containerID == "" {
  283. return err
  284. }
  285. if err := d.builder.docker.ContainerCreateWorkdir(containerID); err != nil {
  286. return err
  287. }
  288. return d.builder.commitContainer(d.state, containerID, runConfigWithCommentCmd)
  289. }
  290. func resolveCmdLine(cmd instructions.ShellDependantCmdLine, runConfig *container.Config, os string) []string {
  291. result := cmd.CmdLine
  292. if cmd.PrependShell && result != nil {
  293. result = append(getShell(runConfig, os), result...)
  294. }
  295. return result
  296. }
  297. // RUN some command yo
  298. //
  299. // run a command and commit the image. Args are automatically prepended with
  300. // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
  301. // Windows, in the event there is only one argument The difference in processing:
  302. //
  303. // RUN echo hi # sh -c echo hi (Linux and LCOW)
  304. // RUN echo hi # cmd /S /C echo hi (Windows)
  305. // RUN [ "echo", "hi" ] # echo hi
  306. //
  307. func dispatchRun(d dispatchRequest, c *instructions.RunCommand) error {
  308. if !system.IsOSSupported(d.state.operatingSystem) {
  309. return system.ErrNotSupportedOperatingSystem
  310. }
  311. stateRunConfig := d.state.runConfig
  312. cmdFromArgs := resolveCmdLine(c.ShellDependantCmdLine, stateRunConfig, d.state.operatingSystem)
  313. buildArgs := d.state.buildArgs.FilterAllowed(stateRunConfig.Env)
  314. saveCmd := cmdFromArgs
  315. if len(buildArgs) > 0 {
  316. saveCmd = prependEnvOnCmd(d.state.buildArgs, buildArgs, cmdFromArgs)
  317. }
  318. runConfigForCacheProbe := copyRunConfig(stateRunConfig,
  319. withCmd(saveCmd),
  320. withEntrypointOverride(saveCmd, nil))
  321. if hit, err := d.builder.probeCache(d.state, runConfigForCacheProbe); err != nil || hit {
  322. return err
  323. }
  324. runConfig := copyRunConfig(stateRunConfig,
  325. withCmd(cmdFromArgs),
  326. withEnv(append(stateRunConfig.Env, buildArgs...)),
  327. withEntrypointOverride(saveCmd, strslice.StrSlice{""}))
  328. // set config as already being escaped, this prevents double escaping on windows
  329. runConfig.ArgsEscaped = true
  330. cID, err := d.builder.create(runConfig)
  331. if err != nil {
  332. return err
  333. }
  334. if err := d.builder.containerManager.Run(d.builder.clientCtx, cID, d.builder.Stdout, d.builder.Stderr); err != nil {
  335. if err, ok := err.(*statusCodeError); ok {
  336. // TODO: change error type, because jsonmessage.JSONError assumes HTTP
  337. msg := fmt.Sprintf(
  338. "The command '%s' returned a non-zero code: %d",
  339. strings.Join(runConfig.Cmd, " "), err.StatusCode())
  340. if err.Error() != "" {
  341. msg = fmt.Sprintf("%s: %s", msg, err.Error())
  342. }
  343. return &jsonmessage.JSONError{
  344. Message: msg,
  345. Code: err.StatusCode(),
  346. }
  347. }
  348. return err
  349. }
  350. return d.builder.commitContainer(d.state, cID, runConfigForCacheProbe)
  351. }
  352. // Derive the command to use for probeCache() and to commit in this container.
  353. // Note that we only do this if there are any build-time env vars. Also, we
  354. // use the special argument "|#" at the start of the args array. This will
  355. // avoid conflicts with any RUN command since commands can not
  356. // start with | (vertical bar). The "#" (number of build envs) is there to
  357. // help ensure proper cache matches. We don't want a RUN command
  358. // that starts with "foo=abc" to be considered part of a build-time env var.
  359. //
  360. // remove any unreferenced built-in args from the environment variables.
  361. // These args are transparent so resulting image should be the same regardless
  362. // of the value.
  363. func prependEnvOnCmd(buildArgs *BuildArgs, buildArgVars []string, cmd strslice.StrSlice) strslice.StrSlice {
  364. var tmpBuildEnv []string
  365. for _, env := range buildArgVars {
  366. key := strings.SplitN(env, "=", 2)[0]
  367. if buildArgs.IsReferencedOrNotBuiltin(key) {
  368. tmpBuildEnv = append(tmpBuildEnv, env)
  369. }
  370. }
  371. sort.Strings(tmpBuildEnv)
  372. tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...)
  373. return strslice.StrSlice(append(tmpEnv, cmd...))
  374. }
  375. // CMD foo
  376. //
  377. // Set the default command to run in the container (which may be empty).
  378. // Argument handling is the same as RUN.
  379. //
  380. func dispatchCmd(d dispatchRequest, c *instructions.CmdCommand) error {
  381. runConfig := d.state.runConfig
  382. cmd := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem)
  383. runConfig.Cmd = cmd
  384. // set config as already being escaped, this prevents double escaping on windows
  385. runConfig.ArgsEscaped = true
  386. if err := d.builder.commit(d.state, fmt.Sprintf("CMD %q", cmd)); err != nil {
  387. return err
  388. }
  389. if len(c.ShellDependantCmdLine.CmdLine) != 0 {
  390. d.state.cmdSet = true
  391. }
  392. return nil
  393. }
  394. // HEALTHCHECK foo
  395. //
  396. // Set the default healthcheck command to run in the container (which may be empty).
  397. // Argument handling is the same as RUN.
  398. //
  399. func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand) error {
  400. runConfig := d.state.runConfig
  401. if runConfig.Healthcheck != nil {
  402. oldCmd := runConfig.Healthcheck.Test
  403. if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
  404. fmt.Fprintf(d.builder.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
  405. }
  406. }
  407. runConfig.Healthcheck = c.Health
  408. return d.builder.commit(d.state, fmt.Sprintf("HEALTHCHECK %q", runConfig.Healthcheck))
  409. }
  410. // ENTRYPOINT /usr/sbin/nginx
  411. //
  412. // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
  413. // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
  414. //
  415. // Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
  416. // is initialized at newBuilder time instead of through argument parsing.
  417. //
  418. func dispatchEntrypoint(d dispatchRequest, c *instructions.EntrypointCommand) error {
  419. runConfig := d.state.runConfig
  420. cmd := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem)
  421. runConfig.Entrypoint = cmd
  422. if !d.state.cmdSet {
  423. runConfig.Cmd = nil
  424. }
  425. return d.builder.commit(d.state, fmt.Sprintf("ENTRYPOINT %q", runConfig.Entrypoint))
  426. }
  427. // EXPOSE 6667/tcp 7000/tcp
  428. //
  429. // Expose ports for links and port mappings. This all ends up in
  430. // req.runConfig.ExposedPorts for runconfig.
  431. //
  432. func dispatchExpose(d dispatchRequest, c *instructions.ExposeCommand, envs []string) error {
  433. // custom multi word expansion
  434. // expose $FOO with FOO="80 443" is expanded as EXPOSE [80,443]. This is the only command supporting word to words expansion
  435. // so the word processing has been de-generalized
  436. ports := []string{}
  437. for _, p := range c.Ports {
  438. ps, err := d.shlex.ProcessWords(p, envs)
  439. if err != nil {
  440. return err
  441. }
  442. ports = append(ports, ps...)
  443. }
  444. c.Ports = ports
  445. ps, _, err := nat.ParsePortSpecs(ports)
  446. if err != nil {
  447. return err
  448. }
  449. if d.state.runConfig.ExposedPorts == nil {
  450. d.state.runConfig.ExposedPorts = make(nat.PortSet)
  451. }
  452. for p := range ps {
  453. d.state.runConfig.ExposedPorts[p] = struct{}{}
  454. }
  455. return d.builder.commit(d.state, "EXPOSE "+strings.Join(c.Ports, " "))
  456. }
  457. // USER foo
  458. //
  459. // Set the user to 'foo' for future commands and when running the
  460. // ENTRYPOINT/CMD at container run time.
  461. //
  462. func dispatchUser(d dispatchRequest, c *instructions.UserCommand) error {
  463. d.state.runConfig.User = c.User
  464. return d.builder.commit(d.state, fmt.Sprintf("USER %v", c.User))
  465. }
  466. // VOLUME /foo
  467. //
  468. // Expose the volume /foo for use. Will also accept the JSON array form.
  469. //
  470. func dispatchVolume(d dispatchRequest, c *instructions.VolumeCommand) error {
  471. if d.state.runConfig.Volumes == nil {
  472. d.state.runConfig.Volumes = map[string]struct{}{}
  473. }
  474. for _, v := range c.Volumes {
  475. if v == "" {
  476. return errors.New("VOLUME specified can not be an empty string")
  477. }
  478. d.state.runConfig.Volumes[v] = struct{}{}
  479. }
  480. return d.builder.commit(d.state, fmt.Sprintf("VOLUME %v", c.Volumes))
  481. }
  482. // STOPSIGNAL signal
  483. //
  484. // Set the signal that will be used to kill the container.
  485. func dispatchStopSignal(d dispatchRequest, c *instructions.StopSignalCommand) error {
  486. _, err := signal.ParseSignal(c.Signal)
  487. if err != nil {
  488. return errdefs.InvalidParameter(err)
  489. }
  490. d.state.runConfig.StopSignal = c.Signal
  491. return d.builder.commit(d.state, fmt.Sprintf("STOPSIGNAL %v", c.Signal))
  492. }
  493. // ARG name[=value]
  494. //
  495. // Adds the variable foo to the trusted list of variables that can be passed
  496. // to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
  497. // Dockerfile author may optionally set a default value of this variable.
  498. func dispatchArg(d dispatchRequest, c *instructions.ArgCommand) error {
  499. commitStr := "ARG " + c.Key
  500. if c.Value != nil {
  501. commitStr += "=" + *c.Value
  502. }
  503. d.state.buildArgs.AddArg(c.Key, c.Value)
  504. return d.builder.commit(d.state, commitStr)
  505. }
  506. // SHELL powershell -command
  507. //
  508. // Set the non-default shell to use.
  509. func dispatchShell(d dispatchRequest, c *instructions.ShellCommand) error {
  510. d.state.runConfig.Shell = c.Shell
  511. return d.builder.commit(d.state, fmt.Sprintf("SHELL %v", d.state.runConfig.Shell))
  512. }