dispatchers.go 20 KB

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