dispatchers.go 20 KB

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