dispatchers.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. package 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. "fmt"
  10. "regexp"
  11. "runtime"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/api"
  18. "github.com/docker/docker/api/types"
  19. "github.com/docker/docker/api/types/container"
  20. "github.com/docker/docker/api/types/strslice"
  21. "github.com/docker/docker/builder"
  22. "github.com/docker/docker/pkg/signal"
  23. runconfigopts "github.com/docker/docker/runconfig/opts"
  24. "github.com/docker/go-connections/nat"
  25. )
  26. // ENV foo bar
  27. //
  28. // Sets the environment variable foo to bar, also makes interpolation
  29. // in the dockerfile available from the next statement on via ${foo}.
  30. //
  31. func env(b *Builder, args []string, attributes map[string]bool, original string) error {
  32. if len(args) == 0 {
  33. return errAtLeastOneArgument("ENV")
  34. }
  35. if len(args)%2 != 0 {
  36. // should never get here, but just in case
  37. return errTooManyArguments("ENV")
  38. }
  39. if err := b.flags.Parse(); err != nil {
  40. return err
  41. }
  42. // TODO/FIXME/NOT USED
  43. // Just here to show how to use the builder flags stuff within the
  44. // context of a builder command. Will remove once we actually add
  45. // a builder command to something!
  46. /*
  47. flBool1 := b.flags.AddBool("bool1", false)
  48. flStr1 := b.flags.AddString("str1", "HI")
  49. if err := b.flags.Parse(); err != nil {
  50. return err
  51. }
  52. fmt.Printf("Bool1:%v\n", flBool1)
  53. fmt.Printf("Str1:%v\n", flStr1)
  54. */
  55. commitStr := "ENV"
  56. for j := 0; j < len(args); j++ {
  57. // name ==> args[j]
  58. // value ==> args[j+1]
  59. if len(args[j]) == 0 {
  60. return errBlankCommandNames("ENV")
  61. }
  62. newVar := args[j] + "=" + args[j+1] + ""
  63. commitStr += " " + newVar
  64. gotOne := false
  65. for i, envVar := range b.runConfig.Env {
  66. envParts := strings.SplitN(envVar, "=", 2)
  67. if envParts[0] == args[j] {
  68. b.runConfig.Env[i] = newVar
  69. gotOne = true
  70. break
  71. }
  72. }
  73. if !gotOne {
  74. b.runConfig.Env = append(b.runConfig.Env, newVar)
  75. }
  76. j++
  77. }
  78. return b.commit("", b.runConfig.Cmd, commitStr)
  79. }
  80. // MAINTAINER some text <maybe@an.email.address>
  81. //
  82. // Sets the maintainer metadata.
  83. func maintainer(b *Builder, args []string, attributes map[string]bool, original string) error {
  84. if len(args) != 1 {
  85. return errExactlyOneArgument("MAINTAINER")
  86. }
  87. if err := b.flags.Parse(); err != nil {
  88. return err
  89. }
  90. b.maintainer = args[0]
  91. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer))
  92. }
  93. // LABEL some json data describing the image
  94. //
  95. // Sets the Label variable foo to bar,
  96. //
  97. func label(b *Builder, args []string, attributes map[string]bool, original string) error {
  98. if len(args) == 0 {
  99. return errAtLeastOneArgument("LABEL")
  100. }
  101. if len(args)%2 != 0 {
  102. // should never get here, but just in case
  103. return errTooManyArguments("LABEL")
  104. }
  105. if err := b.flags.Parse(); err != nil {
  106. return err
  107. }
  108. commitStr := "LABEL"
  109. if b.runConfig.Labels == nil {
  110. b.runConfig.Labels = map[string]string{}
  111. }
  112. for j := 0; j < len(args); j++ {
  113. // name ==> args[j]
  114. // value ==> args[j+1]
  115. if len(args[j]) == 0 {
  116. return errBlankCommandNames("LABEL")
  117. }
  118. newVar := args[j] + "=" + args[j+1] + ""
  119. commitStr += " " + newVar
  120. b.runConfig.Labels[args[j]] = args[j+1]
  121. j++
  122. }
  123. return b.commit("", b.runConfig.Cmd, commitStr)
  124. }
  125. // ADD foo /path
  126. //
  127. // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
  128. // exist here. If you do not wish to have this automatic handling, use COPY.
  129. //
  130. func add(b *Builder, args []string, attributes map[string]bool, original string) error {
  131. if len(args) < 2 {
  132. return errAtLeastTwoArguments("ADD")
  133. }
  134. if err := b.flags.Parse(); err != nil {
  135. return err
  136. }
  137. return b.runContextCommand(args, true, true, "ADD")
  138. }
  139. // COPY foo /path
  140. //
  141. // Same as 'ADD' but without the tar and remote url handling.
  142. //
  143. func dispatchCopy(b *Builder, args []string, attributes map[string]bool, original string) error {
  144. if len(args) < 2 {
  145. return errAtLeastTwoArguments("COPY")
  146. }
  147. if err := b.flags.Parse(); err != nil {
  148. return err
  149. }
  150. return b.runContextCommand(args, false, false, "COPY")
  151. }
  152. // FROM imagename
  153. //
  154. // This sets the image the dockerfile will build on top of.
  155. //
  156. func from(b *Builder, args []string, attributes map[string]bool, original string) error {
  157. if len(args) != 1 {
  158. return errExactlyOneArgument("FROM")
  159. }
  160. if err := b.flags.Parse(); err != nil {
  161. return err
  162. }
  163. name := args[0]
  164. var (
  165. image builder.Image
  166. err error
  167. )
  168. // Windows cannot support a container with no base image.
  169. if name == api.NoBaseImageSpecifier {
  170. if runtime.GOOS == "windows" {
  171. return fmt.Errorf("Windows does not support FROM scratch")
  172. }
  173. b.image = ""
  174. b.noBaseImage = true
  175. } else {
  176. // TODO: don't use `name`, instead resolve it to a digest
  177. if !b.options.PullParent {
  178. image, err = b.docker.GetImageOnBuild(name)
  179. // TODO: shouldn't we error out if error is different from "not found" ?
  180. }
  181. if image == nil {
  182. image, err = b.docker.PullOnBuild(b.clientCtx, name, b.options.AuthConfigs, b.Output)
  183. if err != nil {
  184. return err
  185. }
  186. }
  187. }
  188. b.from = image
  189. return b.processImageFrom(image)
  190. }
  191. // ONBUILD RUN echo yo
  192. //
  193. // ONBUILD triggers run when the image is used in a FROM statement.
  194. //
  195. // ONBUILD handling has a lot of special-case functionality, the heading in
  196. // evaluator.go and comments around dispatch() in the same file explain the
  197. // special cases. search for 'OnBuild' in internals.go for additional special
  198. // cases.
  199. //
  200. func onbuild(b *Builder, args []string, attributes map[string]bool, original string) error {
  201. if len(args) == 0 {
  202. return errAtLeastOneArgument("ONBUILD")
  203. }
  204. if err := b.flags.Parse(); err != nil {
  205. return err
  206. }
  207. triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0]))
  208. switch triggerInstruction {
  209. case "ONBUILD":
  210. return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  211. case "MAINTAINER", "FROM":
  212. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
  213. }
  214. original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "")
  215. b.runConfig.OnBuild = append(b.runConfig.OnBuild, original)
  216. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ONBUILD %s", original))
  217. }
  218. // WORKDIR /tmp
  219. //
  220. // Set the working directory for future RUN/CMD/etc statements.
  221. //
  222. func workdir(b *Builder, args []string, attributes map[string]bool, original string) error {
  223. if len(args) != 1 {
  224. return errExactlyOneArgument("WORKDIR")
  225. }
  226. err := b.flags.Parse()
  227. if err != nil {
  228. return err
  229. }
  230. // This is from the Dockerfile and will not necessarily be in platform
  231. // specific semantics, hence ensure it is converted.
  232. b.runConfig.WorkingDir, err = normaliseWorkdir(b.runConfig.WorkingDir, args[0])
  233. if err != nil {
  234. return err
  235. }
  236. // For performance reasons, we explicitly do a create/mkdir now
  237. // This avoids having an unnecessary expensive mount/unmount calls
  238. // (on Windows in particular) during each container create.
  239. // Prior to 1.13, the mkdir was deferred and not executed at this step.
  240. if b.disableCommit {
  241. // Don't call back into the daemon if we're going through docker commit --change "WORKDIR /foo".
  242. // We've already updated the runConfig and that's enough.
  243. return nil
  244. }
  245. b.runConfig.Image = b.image
  246. container, err := b.docker.ContainerCreate(types.ContainerCreateConfig{Config: b.runConfig}, true)
  247. if err != nil {
  248. return err
  249. }
  250. b.tmpContainers[container.ID] = struct{}{}
  251. if err := b.docker.ContainerCreateWorkdir(container.ID); err != nil {
  252. return err
  253. }
  254. return b.commit(container.ID, b.runConfig.Cmd, "WORKDIR "+b.runConfig.WorkingDir)
  255. }
  256. // RUN some command yo
  257. //
  258. // run a command and commit the image. Args are automatically prepended with
  259. // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
  260. // Windows, in the event there is only one argument The difference in processing:
  261. //
  262. // RUN echo hi # sh -c echo hi (Linux)
  263. // RUN echo hi # cmd /S /C echo hi (Windows)
  264. // RUN [ "echo", "hi" ] # echo hi
  265. //
  266. func run(b *Builder, args []string, attributes map[string]bool, original string) error {
  267. if b.image == "" && !b.noBaseImage {
  268. return fmt.Errorf("Please provide a source image with `from` prior to run")
  269. }
  270. if err := b.flags.Parse(); err != nil {
  271. return err
  272. }
  273. args = handleJSONArgs(args, attributes)
  274. if !attributes["json"] {
  275. args = append(getShell(b.runConfig), args...)
  276. }
  277. config := &container.Config{
  278. Cmd: strslice.StrSlice(args),
  279. Image: b.image,
  280. }
  281. // stash the cmd
  282. cmd := b.runConfig.Cmd
  283. if len(b.runConfig.Entrypoint) == 0 && len(b.runConfig.Cmd) == 0 {
  284. b.runConfig.Cmd = config.Cmd
  285. }
  286. // stash the config environment
  287. env := b.runConfig.Env
  288. defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
  289. defer func(env []string) { b.runConfig.Env = env }(env)
  290. // derive the net build-time environment for this run. We let config
  291. // environment override the build time environment.
  292. // This means that we take the b.buildArgs list of env vars and remove
  293. // any of those variables that are defined as part of the container. In other
  294. // words, anything in b.Config.Env. What's left is the list of build-time env
  295. // vars that we need to add to each RUN command - note the list could be empty.
  296. //
  297. // We don't persist the build time environment with container's config
  298. // environment, but just sort and prepend it to the command string at time
  299. // of commit.
  300. // This helps with tracing back the image's actual environment at the time
  301. // of RUN, without leaking it to the final image. It also aids cache
  302. // lookup for same image built with same build time environment.
  303. cmdBuildEnv := []string{}
  304. configEnv := runconfigopts.ConvertKVStringsToMap(b.runConfig.Env)
  305. for key, val := range b.options.BuildArgs {
  306. if !b.isBuildArgAllowed(key) {
  307. // skip build-args that are not in allowed list, meaning they have
  308. // not been defined by an "ARG" Dockerfile command yet.
  309. // This is an error condition but only if there is no "ARG" in the entire
  310. // Dockerfile, so we'll generate any necessary errors after we parsed
  311. // the entire file (see 'leftoverArgs' processing in evaluator.go )
  312. continue
  313. }
  314. if _, ok := configEnv[key]; !ok {
  315. cmdBuildEnv = append(cmdBuildEnv, fmt.Sprintf("%s=%s", key, val))
  316. }
  317. }
  318. // derive the command to use for probeCache() and to commit in this container.
  319. // Note that we only do this if there are any build-time env vars. Also, we
  320. // use the special argument "|#" at the start of the args array. This will
  321. // avoid conflicts with any RUN command since commands can not
  322. // start with | (vertical bar). The "#" (number of build envs) is there to
  323. // help ensure proper cache matches. We don't want a RUN command
  324. // that starts with "foo=abc" to be considered part of a build-time env var.
  325. saveCmd := config.Cmd
  326. if len(cmdBuildEnv) > 0 {
  327. sort.Strings(cmdBuildEnv)
  328. tmpEnv := append([]string{fmt.Sprintf("|%d", len(cmdBuildEnv))}, cmdBuildEnv...)
  329. saveCmd = strslice.StrSlice(append(tmpEnv, saveCmd...))
  330. }
  331. b.runConfig.Cmd = saveCmd
  332. hit, err := b.probeCache()
  333. if err != nil {
  334. return err
  335. }
  336. if hit {
  337. return nil
  338. }
  339. // set Cmd manually, this is special case only for Dockerfiles
  340. b.runConfig.Cmd = config.Cmd
  341. // set build-time environment for 'run'.
  342. b.runConfig.Env = append(b.runConfig.Env, cmdBuildEnv...)
  343. // set config as already being escaped, this prevents double escaping on windows
  344. b.runConfig.ArgsEscaped = true
  345. logrus.Debugf("[BUILDER] Command to be executed: %v", b.runConfig.Cmd)
  346. cID, err := b.create()
  347. if err != nil {
  348. return err
  349. }
  350. if err := b.run(cID); err != nil {
  351. return err
  352. }
  353. // revert to original config environment and set the command string to
  354. // have the build-time env vars in it (if any) so that future cache look-ups
  355. // properly match it.
  356. b.runConfig.Env = env
  357. b.runConfig.Cmd = saveCmd
  358. return b.commit(cID, cmd, "run")
  359. }
  360. // CMD foo
  361. //
  362. // Set the default command to run in the container (which may be empty).
  363. // Argument handling is the same as RUN.
  364. //
  365. func cmd(b *Builder, args []string, attributes map[string]bool, original string) error {
  366. if err := b.flags.Parse(); err != nil {
  367. return err
  368. }
  369. cmdSlice := handleJSONArgs(args, attributes)
  370. if !attributes["json"] {
  371. cmdSlice = append(getShell(b.runConfig), cmdSlice...)
  372. }
  373. b.runConfig.Cmd = strslice.StrSlice(cmdSlice)
  374. // set config as already being escaped, this prevents double escaping on windows
  375. b.runConfig.ArgsEscaped = true
  376. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
  377. return err
  378. }
  379. if len(args) != 0 {
  380. b.cmdSet = true
  381. }
  382. return nil
  383. }
  384. // parseOptInterval(flag) is the duration of flag.Value, or 0 if
  385. // empty. An error is reported if the value is given and is not positive.
  386. func parseOptInterval(f *Flag) (time.Duration, error) {
  387. s := f.Value
  388. if s == "" {
  389. return 0, nil
  390. }
  391. d, err := time.ParseDuration(s)
  392. if err != nil {
  393. return 0, err
  394. }
  395. if d <= 0 {
  396. return 0, fmt.Errorf("Interval %#v must be positive", f.name)
  397. }
  398. return d, nil
  399. }
  400. // HEALTHCHECK foo
  401. //
  402. // Set the default healthcheck command to run in the container (which may be empty).
  403. // Argument handling is the same as RUN.
  404. //
  405. func healthcheck(b *Builder, args []string, attributes map[string]bool, original string) error {
  406. if len(args) == 0 {
  407. return errAtLeastOneArgument("HEALTHCHECK")
  408. }
  409. typ := strings.ToUpper(args[0])
  410. args = args[1:]
  411. if typ == "NONE" {
  412. if len(args) != 0 {
  413. return fmt.Errorf("HEALTHCHECK NONE takes no arguments")
  414. }
  415. test := strslice.StrSlice{typ}
  416. b.runConfig.Healthcheck = &container.HealthConfig{
  417. Test: test,
  418. }
  419. } else {
  420. if b.runConfig.Healthcheck != nil {
  421. oldCmd := b.runConfig.Healthcheck.Test
  422. if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
  423. fmt.Fprintf(b.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
  424. }
  425. }
  426. healthcheck := container.HealthConfig{}
  427. flInterval := b.flags.AddString("interval", "")
  428. flTimeout := b.flags.AddString("timeout", "")
  429. flRetries := b.flags.AddString("retries", "")
  430. if err := b.flags.Parse(); err != nil {
  431. return err
  432. }
  433. switch typ {
  434. case "CMD":
  435. cmdSlice := handleJSONArgs(args, attributes)
  436. if len(cmdSlice) == 0 {
  437. return fmt.Errorf("Missing command after HEALTHCHECK CMD")
  438. }
  439. if !attributes["json"] {
  440. typ = "CMD-SHELL"
  441. }
  442. healthcheck.Test = strslice.StrSlice(append([]string{typ}, cmdSlice...))
  443. default:
  444. return fmt.Errorf("Unknown type %#v in HEALTHCHECK (try CMD)", typ)
  445. }
  446. interval, err := parseOptInterval(flInterval)
  447. if err != nil {
  448. return err
  449. }
  450. healthcheck.Interval = interval
  451. timeout, err := parseOptInterval(flTimeout)
  452. if err != nil {
  453. return err
  454. }
  455. healthcheck.Timeout = timeout
  456. if flRetries.Value != "" {
  457. retries, err := strconv.ParseInt(flRetries.Value, 10, 32)
  458. if err != nil {
  459. return err
  460. }
  461. if retries < 1 {
  462. return fmt.Errorf("--retries must be at least 1 (not %d)", retries)
  463. }
  464. healthcheck.Retries = int(retries)
  465. } else {
  466. healthcheck.Retries = 0
  467. }
  468. b.runConfig.Healthcheck = &healthcheck
  469. }
  470. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("HEALTHCHECK %q", b.runConfig.Healthcheck))
  471. }
  472. // ENTRYPOINT /usr/sbin/nginx
  473. //
  474. // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
  475. // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
  476. //
  477. // Handles command processing similar to CMD and RUN, only b.runConfig.Entrypoint
  478. // is initialized at NewBuilder time instead of through argument parsing.
  479. //
  480. func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error {
  481. if err := b.flags.Parse(); err != nil {
  482. return err
  483. }
  484. parsed := handleJSONArgs(args, attributes)
  485. switch {
  486. case attributes["json"]:
  487. // ENTRYPOINT ["echo", "hi"]
  488. b.runConfig.Entrypoint = strslice.StrSlice(parsed)
  489. case len(parsed) == 0:
  490. // ENTRYPOINT []
  491. b.runConfig.Entrypoint = nil
  492. default:
  493. // ENTRYPOINT echo hi
  494. b.runConfig.Entrypoint = strslice.StrSlice(append(getShell(b.runConfig), parsed[0]))
  495. }
  496. // when setting the entrypoint if a CMD was not explicitly set then
  497. // set the command to nil
  498. if !b.cmdSet {
  499. b.runConfig.Cmd = nil
  500. }
  501. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.runConfig.Entrypoint)); err != nil {
  502. return err
  503. }
  504. return nil
  505. }
  506. // EXPOSE 6667/tcp 7000/tcp
  507. //
  508. // Expose ports for links and port mappings. This all ends up in
  509. // b.runConfig.ExposedPorts for runconfig.
  510. //
  511. func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
  512. portsTab := args
  513. if len(args) == 0 {
  514. return errAtLeastOneArgument("EXPOSE")
  515. }
  516. if err := b.flags.Parse(); err != nil {
  517. return err
  518. }
  519. if b.runConfig.ExposedPorts == nil {
  520. b.runConfig.ExposedPorts = make(nat.PortSet)
  521. }
  522. ports, _, err := nat.ParsePortSpecs(portsTab)
  523. if err != nil {
  524. return err
  525. }
  526. // instead of using ports directly, we build a list of ports and sort it so
  527. // the order is consistent. This prevents cache burst where map ordering
  528. // changes between builds
  529. portList := make([]string, len(ports))
  530. var i int
  531. for port := range ports {
  532. if _, exists := b.runConfig.ExposedPorts[port]; !exists {
  533. b.runConfig.ExposedPorts[port] = struct{}{}
  534. }
  535. portList[i] = string(port)
  536. i++
  537. }
  538. sort.Strings(portList)
  539. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
  540. }
  541. // USER foo
  542. //
  543. // Set the user to 'foo' for future commands and when running the
  544. // ENTRYPOINT/CMD at container run time.
  545. //
  546. func user(b *Builder, args []string, attributes map[string]bool, original string) error {
  547. if len(args) != 1 {
  548. return errExactlyOneArgument("USER")
  549. }
  550. if err := b.flags.Parse(); err != nil {
  551. return err
  552. }
  553. b.runConfig.User = args[0]
  554. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("USER %v", args))
  555. }
  556. // VOLUME /foo
  557. //
  558. // Expose the volume /foo for use. Will also accept the JSON array form.
  559. //
  560. func volume(b *Builder, args []string, attributes map[string]bool, original string) error {
  561. if len(args) == 0 {
  562. return errAtLeastOneArgument("VOLUME")
  563. }
  564. if err := b.flags.Parse(); err != nil {
  565. return err
  566. }
  567. if b.runConfig.Volumes == nil {
  568. b.runConfig.Volumes = map[string]struct{}{}
  569. }
  570. for _, v := range args {
  571. v = strings.TrimSpace(v)
  572. if v == "" {
  573. return fmt.Errorf("VOLUME specified can not be an empty string")
  574. }
  575. b.runConfig.Volumes[v] = struct{}{}
  576. }
  577. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil {
  578. return err
  579. }
  580. return nil
  581. }
  582. // STOPSIGNAL signal
  583. //
  584. // Set the signal that will be used to kill the container.
  585. func stopSignal(b *Builder, args []string, attributes map[string]bool, original string) error {
  586. if len(args) != 1 {
  587. return errExactlyOneArgument("STOPSIGNAL")
  588. }
  589. sig := args[0]
  590. _, err := signal.ParseSignal(sig)
  591. if err != nil {
  592. return err
  593. }
  594. b.runConfig.StopSignal = sig
  595. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("STOPSIGNAL %v", args))
  596. }
  597. // ARG name[=value]
  598. //
  599. // Adds the variable foo to the trusted list of variables that can be passed
  600. // to builder using the --build-arg flag for expansion/subsitution or passing to 'run'.
  601. // Dockerfile author may optionally set a default value of this variable.
  602. func arg(b *Builder, args []string, attributes map[string]bool, original string) error {
  603. if len(args) != 1 {
  604. return errExactlyOneArgument("ARG")
  605. }
  606. var (
  607. name string
  608. value string
  609. hasDefault bool
  610. )
  611. arg := args[0]
  612. // 'arg' can just be a name or name-value pair. Note that this is different
  613. // from 'env' that handles the split of name and value at the parser level.
  614. // The reason for doing it differently for 'arg' is that we support just
  615. // defining an arg and not assign it a value (while 'env' always expects a
  616. // name-value pair). If possible, it will be good to harmonize the two.
  617. if strings.Contains(arg, "=") {
  618. parts := strings.SplitN(arg, "=", 2)
  619. if len(parts[0]) == 0 {
  620. return errBlankCommandNames("ARG")
  621. }
  622. name = parts[0]
  623. value = parts[1]
  624. hasDefault = true
  625. } else {
  626. name = arg
  627. hasDefault = false
  628. }
  629. // add the arg to allowed list of build-time args from this step on.
  630. b.allowedBuildArgs[name] = true
  631. // If there is a default value associated with this arg then add it to the
  632. // b.buildArgs if one is not already passed to the builder. The args passed
  633. // to builder override the default value of 'arg'.
  634. if _, ok := b.options.BuildArgs[name]; !ok && hasDefault {
  635. b.options.BuildArgs[name] = value
  636. }
  637. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ARG %s", arg))
  638. }
  639. // SHELL powershell -command
  640. //
  641. // Set the non-default shell to use.
  642. func shell(b *Builder, args []string, attributes map[string]bool, original string) error {
  643. if err := b.flags.Parse(); err != nil {
  644. return err
  645. }
  646. shellSlice := handleJSONArgs(args, attributes)
  647. switch {
  648. case len(shellSlice) == 0:
  649. // SHELL []
  650. return errAtLeastOneArgument("SHELL")
  651. case attributes["json"]:
  652. // SHELL ["powershell", "-command"]
  653. b.runConfig.Shell = strslice.StrSlice(shellSlice)
  654. default:
  655. // SHELL powershell -command - not JSON
  656. return errNotJSON("SHELL", original)
  657. }
  658. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("SHELL %v", shellSlice))
  659. }
  660. func errAtLeastOneArgument(command string) error {
  661. return fmt.Errorf("%s requires at least one argument", command)
  662. }
  663. func errExactlyOneArgument(command string) error {
  664. return fmt.Errorf("%s requires exactly one argument", command)
  665. }
  666. func errAtLeastTwoArguments(command string) error {
  667. return fmt.Errorf("%s requires at least two arguments", command)
  668. }
  669. func errBlankCommandNames(command string) error {
  670. return fmt.Errorf("%s names can not be blank", command)
  671. }
  672. func errTooManyArguments(command string) error {
  673. return fmt.Errorf("Bad input to %s, too many arguments", command)
  674. }
  675. // getShell is a helper function which gets the right shell for prefixing the
  676. // shell-form of RUN, ENTRYPOINT and CMD instructions
  677. func getShell(c *container.Config) []string {
  678. if 0 == len(c.Shell) {
  679. return defaultShell[:]
  680. }
  681. return c.Shell[:]
  682. }