dispatchers.go 18 KB

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