dispatchers.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. runConfigForCacheProbe := copyRunConfig(stateRunConfig,
  314. withCmd(saveCmd),
  315. withArgsEscaped(argsEscaped),
  316. withEntrypointOverride(saveCmd, nil))
  317. if hit, err := d.builder.probeCache(d.state, runConfigForCacheProbe); err != nil || hit {
  318. return err
  319. }
  320. runConfig := copyRunConfig(stateRunConfig,
  321. withCmd(cmdFromArgs),
  322. withArgsEscaped(argsEscaped),
  323. withEnv(append(stateRunConfig.Env, buildArgs...)),
  324. withEntrypointOverride(saveCmd, strslice.StrSlice{""}),
  325. withoutHealthcheck())
  326. cID, err := d.builder.create(ctx, runConfig)
  327. if err != nil {
  328. return err
  329. }
  330. if err := d.builder.containerManager.Run(ctx, cID, d.builder.Stdout, d.builder.Stderr); err != nil {
  331. if err, ok := err.(*statusCodeError); ok {
  332. // TODO: change error type, because jsonmessage.JSONError assumes HTTP
  333. msg := fmt.Sprintf(
  334. "The command '%s' returned a non-zero code: %d",
  335. strings.Join(runConfig.Cmd, " "), err.StatusCode())
  336. if err.Error() != "" {
  337. msg = fmt.Sprintf("%s: %s", msg, err.Error())
  338. }
  339. return &jsonmessage.JSONError{
  340. Message: msg,
  341. Code: err.StatusCode(),
  342. }
  343. }
  344. return err
  345. }
  346. // Don't persist the argsEscaped value in the committed image. Use the original
  347. // from previous build steps (only CMD and ENTRYPOINT persist this).
  348. if d.state.operatingSystem == "windows" {
  349. runConfigForCacheProbe.ArgsEscaped = stateRunConfig.ArgsEscaped
  350. }
  351. return d.builder.commitContainer(ctx, d.state, cID, runConfigForCacheProbe)
  352. }
  353. // Derive the command to use for probeCache() and to commit in this container.
  354. // Note that we only do this if there are any build-time env vars. Also, we
  355. // use the special argument "|#" at the start of the args array. This will
  356. // avoid conflicts with any RUN command since commands can not
  357. // start with | (vertical bar). The "#" (number of build envs) is there to
  358. // help ensure proper cache matches. We don't want a RUN command
  359. // that starts with "foo=abc" to be considered part of a build-time env var.
  360. //
  361. // remove any unreferenced built-in args from the environment variables.
  362. // These args are transparent so resulting image should be the same regardless
  363. // of the value.
  364. func prependEnvOnCmd(buildArgs *BuildArgs, buildArgVars []string, cmd strslice.StrSlice) strslice.StrSlice {
  365. tmpBuildEnv := make([]string, 0, len(buildArgVars))
  366. for _, env := range buildArgVars {
  367. key, _, _ := strings.Cut(env, "=")
  368. if buildArgs.IsReferencedOrNotBuiltin(key) {
  369. tmpBuildEnv = append(tmpBuildEnv, env)
  370. }
  371. }
  372. sort.Strings(tmpBuildEnv)
  373. tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...)
  374. return append(tmpEnv, cmd...)
  375. }
  376. // CMD foo
  377. //
  378. // Set the default command to run in the container (which may be empty).
  379. // Argument handling is the same as RUN.
  380. func dispatchCmd(ctx context.Context, d dispatchRequest, c *instructions.CmdCommand) error {
  381. runConfig := d.state.runConfig
  382. cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String())
  383. // We warn here as Windows shell processing operates differently to Linux.
  384. // Linux: /bin/sh -c "echo hello" world --> hello
  385. // Windows: cmd /s /c "echo hello" world --> hello world
  386. if d.state.operatingSystem == "windows" &&
  387. len(runConfig.Entrypoint) > 0 &&
  388. d.state.runConfig.ArgsEscaped != argsEscaped {
  389. fmt.Fprintf(d.builder.Stderr, " ---> [Warning] Shell-form ENTRYPOINT and exec-form CMD may have unexpected results\n")
  390. }
  391. runConfig.Cmd = cmd
  392. runConfig.ArgsEscaped = argsEscaped
  393. if err := d.builder.commit(ctx, d.state, fmt.Sprintf("CMD %q", cmd)); err != nil {
  394. return err
  395. }
  396. if len(c.ShellDependantCmdLine.CmdLine) != 0 {
  397. d.state.cmdSet = true
  398. }
  399. return nil
  400. }
  401. // HEALTHCHECK foo
  402. //
  403. // Set the default healthcheck command to run in the container (which may be empty).
  404. // Argument handling is the same as RUN.
  405. func dispatchHealthcheck(ctx context.Context, d dispatchRequest, c *instructions.HealthCheckCommand) error {
  406. runConfig := d.state.runConfig
  407. if runConfig.Healthcheck != nil {
  408. oldCmd := runConfig.Healthcheck.Test
  409. if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
  410. fmt.Fprintf(d.builder.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
  411. }
  412. }
  413. runConfig.Healthcheck = c.Health
  414. return d.builder.commit(ctx, d.state, fmt.Sprintf("HEALTHCHECK %q", runConfig.Healthcheck))
  415. }
  416. // ENTRYPOINT /usr/sbin/nginx
  417. //
  418. // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
  419. // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
  420. //
  421. // Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
  422. // is initialized at newBuilder time instead of through argument parsing.
  423. func dispatchEntrypoint(ctx context.Context, d dispatchRequest, c *instructions.EntrypointCommand) error {
  424. runConfig := d.state.runConfig
  425. cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String())
  426. // This warning is a little more complex than in dispatchCmd(), as the Windows base images (similar
  427. // universally to almost every Linux image out there) have a single .Cmd field populated so that
  428. // `docker run --rm image` starts the default shell which would typically be sh on Linux,
  429. // or cmd on Windows. The catch to this is that if a dockerfile had `CMD ["c:\\windows\\system32\\cmd.exe"]`,
  430. // we wouldn't be able to tell the difference. However, that would be highly unlikely, and besides, this
  431. // is only trying to give a helpful warning of possibly unexpected results.
  432. if d.state.operatingSystem == "windows" &&
  433. d.state.runConfig.ArgsEscaped != argsEscaped &&
  434. ((len(runConfig.Cmd) == 1 && strings.ToLower(runConfig.Cmd[0]) != `c:\windows\system32\cmd.exe` && len(runConfig.Shell) == 0) || (len(runConfig.Cmd) > 1)) {
  435. fmt.Fprintf(d.builder.Stderr, " ---> [Warning] Shell-form CMD and exec-form ENTRYPOINT may have unexpected results\n")
  436. }
  437. runConfig.Entrypoint = cmd
  438. runConfig.ArgsEscaped = argsEscaped
  439. if !d.state.cmdSet {
  440. runConfig.Cmd = nil
  441. }
  442. return d.builder.commit(ctx, d.state, fmt.Sprintf("ENTRYPOINT %q", runConfig.Entrypoint))
  443. }
  444. // EXPOSE 6667/tcp 7000/tcp
  445. //
  446. // Expose ports for links and port mappings. This all ends up in
  447. // req.runConfig.ExposedPorts for runconfig.
  448. func dispatchExpose(ctx context.Context, d dispatchRequest, c *instructions.ExposeCommand, envs []string) error {
  449. // custom multi word expansion
  450. // expose $FOO with FOO="80 443" is expanded as EXPOSE [80,443]. This is the only command supporting word to words expansion
  451. // so the word processing has been de-generalized
  452. ports := []string{}
  453. for _, p := range c.Ports {
  454. ps, err := d.shlex.ProcessWords(p, envs)
  455. if err != nil {
  456. return err
  457. }
  458. ports = append(ports, ps...)
  459. }
  460. c.Ports = ports
  461. ps, _, err := nat.ParsePortSpecs(ports)
  462. if err != nil {
  463. return err
  464. }
  465. if d.state.runConfig.ExposedPorts == nil {
  466. d.state.runConfig.ExposedPorts = make(nat.PortSet)
  467. }
  468. for p := range ps {
  469. d.state.runConfig.ExposedPorts[p] = struct{}{}
  470. }
  471. return d.builder.commit(ctx, d.state, "EXPOSE "+strings.Join(c.Ports, " "))
  472. }
  473. // USER foo
  474. //
  475. // Set the user to 'foo' for future commands and when running the
  476. // ENTRYPOINT/CMD at container run time.
  477. func dispatchUser(ctx context.Context, d dispatchRequest, c *instructions.UserCommand) error {
  478. d.state.runConfig.User = c.User
  479. return d.builder.commit(ctx, d.state, fmt.Sprintf("USER %v", c.User))
  480. }
  481. // VOLUME /foo
  482. //
  483. // Expose the volume /foo for use. Will also accept the JSON array form.
  484. func dispatchVolume(ctx context.Context, d dispatchRequest, c *instructions.VolumeCommand) error {
  485. if d.state.runConfig.Volumes == nil {
  486. d.state.runConfig.Volumes = map[string]struct{}{}
  487. }
  488. for _, v := range c.Volumes {
  489. if v == "" {
  490. return errors.New("VOLUME specified can not be an empty string")
  491. }
  492. d.state.runConfig.Volumes[v] = struct{}{}
  493. }
  494. return d.builder.commit(ctx, d.state, fmt.Sprintf("VOLUME %v", c.Volumes))
  495. }
  496. // STOPSIGNAL signal
  497. //
  498. // Set the signal that will be used to kill the container.
  499. func dispatchStopSignal(ctx context.Context, d dispatchRequest, c *instructions.StopSignalCommand) error {
  500. _, err := signal.ParseSignal(c.Signal)
  501. if err != nil {
  502. return errdefs.InvalidParameter(err)
  503. }
  504. d.state.runConfig.StopSignal = c.Signal
  505. return d.builder.commit(ctx, d.state, fmt.Sprintf("STOPSIGNAL %v", c.Signal))
  506. }
  507. // ARG name[=value]
  508. //
  509. // Adds the variable foo to the trusted list of variables that can be passed
  510. // to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
  511. // Dockerfile author may optionally set a default value of this variable.
  512. func dispatchArg(ctx context.Context, d dispatchRequest, c *instructions.ArgCommand) error {
  513. var commitStr strings.Builder
  514. commitStr.WriteString("ARG ")
  515. for i, arg := range c.Args {
  516. if i > 0 {
  517. commitStr.WriteString(" ")
  518. }
  519. commitStr.WriteString(arg.Key)
  520. if arg.Value != nil {
  521. commitStr.WriteString("=")
  522. commitStr.WriteString(*arg.Value)
  523. }
  524. d.state.buildArgs.AddArg(arg.Key, arg.Value)
  525. }
  526. return d.builder.commit(ctx, d.state, commitStr.String())
  527. }
  528. // SHELL powershell -command
  529. //
  530. // Set the non-default shell to use.
  531. func dispatchShell(ctx context.Context, d dispatchRequest, c *instructions.ShellCommand) error {
  532. d.state.runConfig.Shell = c.Shell
  533. return d.builder.commit(ctx, d.state, fmt.Sprintf("SHELL %v", d.state.runConfig.Shell))
  534. }