dispatchers.go 20 KB

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