dispatchers.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. cmd := b.runConfig.Cmd
  247. b.runConfig.Cmd = strslice.StrSlice(append(getShell(b.runConfig), fmt.Sprintf("#(nop) WORKDIR %s", b.runConfig.WorkingDir)))
  248. defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
  249. if hit, err := b.probeCache(); err != nil {
  250. return err
  251. } else if hit {
  252. return nil
  253. }
  254. container, err := b.docker.ContainerCreate(types.ContainerCreateConfig{Config: b.runConfig}, true)
  255. if err != nil {
  256. return err
  257. }
  258. b.tmpContainers[container.ID] = struct{}{}
  259. if err := b.docker.ContainerCreateWorkdir(container.ID); err != nil {
  260. return err
  261. }
  262. return b.commit(container.ID, b.runConfig.Cmd, "WORKDIR "+b.runConfig.WorkingDir)
  263. }
  264. // RUN some command yo
  265. //
  266. // run a command and commit the image. Args are automatically prepended with
  267. // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
  268. // Windows, in the event there is only one argument The difference in processing:
  269. //
  270. // RUN echo hi # sh -c echo hi (Linux)
  271. // RUN echo hi # cmd /S /C echo hi (Windows)
  272. // RUN [ "echo", "hi" ] # echo hi
  273. //
  274. func run(b *Builder, args []string, attributes map[string]bool, original string) error {
  275. if b.image == "" && !b.noBaseImage {
  276. return fmt.Errorf("Please provide a source image with `from` prior to run")
  277. }
  278. if err := b.flags.Parse(); err != nil {
  279. return err
  280. }
  281. args = handleJSONArgs(args, attributes)
  282. if !attributes["json"] {
  283. args = append(getShell(b.runConfig), args...)
  284. }
  285. config := &container.Config{
  286. Cmd: strslice.StrSlice(args),
  287. Image: b.image,
  288. }
  289. // stash the cmd
  290. cmd := b.runConfig.Cmd
  291. if len(b.runConfig.Entrypoint) == 0 && len(b.runConfig.Cmd) == 0 {
  292. b.runConfig.Cmd = config.Cmd
  293. }
  294. // stash the config environment
  295. env := b.runConfig.Env
  296. defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
  297. defer func(env []string) { b.runConfig.Env = env }(env)
  298. // derive the net build-time environment for this run. We let config
  299. // environment override the build time environment.
  300. // This means that we take the b.buildArgs list of env vars and remove
  301. // any of those variables that are defined as part of the container. In other
  302. // words, anything in b.Config.Env. What's left is the list of build-time env
  303. // vars that we need to add to each RUN command - note the list could be empty.
  304. //
  305. // We don't persist the build time environment with container's config
  306. // environment, but just sort and prepend it to the command string at time
  307. // of commit.
  308. // This helps with tracing back the image's actual environment at the time
  309. // of RUN, without leaking it to the final image. It also aids cache
  310. // lookup for same image built with same build time environment.
  311. cmdBuildEnv := []string{}
  312. configEnv := runconfigopts.ConvertKVStringsToMap(b.runConfig.Env)
  313. for key, val := range b.options.BuildArgs {
  314. if !b.isBuildArgAllowed(key) {
  315. // skip build-args that are not in allowed list, meaning they have
  316. // not been defined by an "ARG" Dockerfile command yet.
  317. // This is an error condition but only if there is no "ARG" in the entire
  318. // Dockerfile, so we'll generate any necessary errors after we parsed
  319. // the entire file (see 'leftoverArgs' processing in evaluator.go )
  320. continue
  321. }
  322. if _, ok := configEnv[key]; !ok {
  323. cmdBuildEnv = append(cmdBuildEnv, fmt.Sprintf("%s=%s", key, val))
  324. }
  325. }
  326. // derive the command to use for probeCache() and to commit in this container.
  327. // Note that we only do this if there are any build-time env vars. Also, we
  328. // use the special argument "|#" at the start of the args array. This will
  329. // avoid conflicts with any RUN command since commands can not
  330. // start with | (vertical bar). The "#" (number of build envs) is there to
  331. // help ensure proper cache matches. We don't want a RUN command
  332. // that starts with "foo=abc" to be considered part of a build-time env var.
  333. saveCmd := config.Cmd
  334. if len(cmdBuildEnv) > 0 {
  335. sort.Strings(cmdBuildEnv)
  336. tmpEnv := append([]string{fmt.Sprintf("|%d", len(cmdBuildEnv))}, cmdBuildEnv...)
  337. saveCmd = strslice.StrSlice(append(tmpEnv, saveCmd...))
  338. }
  339. b.runConfig.Cmd = saveCmd
  340. hit, err := b.probeCache()
  341. if err != nil {
  342. return err
  343. }
  344. if hit {
  345. return nil
  346. }
  347. // set Cmd manually, this is special case only for Dockerfiles
  348. b.runConfig.Cmd = config.Cmd
  349. // set build-time environment for 'run'.
  350. b.runConfig.Env = append(b.runConfig.Env, cmdBuildEnv...)
  351. // set config as already being escaped, this prevents double escaping on windows
  352. b.runConfig.ArgsEscaped = true
  353. logrus.Debugf("[BUILDER] Command to be executed: %v", b.runConfig.Cmd)
  354. cID, err := b.create()
  355. if err != nil {
  356. return err
  357. }
  358. if err := b.run(cID); err != nil {
  359. return err
  360. }
  361. // revert to original config environment and set the command string to
  362. // have the build-time env vars in it (if any) so that future cache look-ups
  363. // properly match it.
  364. b.runConfig.Env = env
  365. b.runConfig.Cmd = saveCmd
  366. return b.commit(cID, cmd, "run")
  367. }
  368. // CMD foo
  369. //
  370. // Set the default command to run in the container (which may be empty).
  371. // Argument handling is the same as RUN.
  372. //
  373. func cmd(b *Builder, args []string, attributes map[string]bool, original string) error {
  374. if err := b.flags.Parse(); err != nil {
  375. return err
  376. }
  377. cmdSlice := handleJSONArgs(args, attributes)
  378. if !attributes["json"] {
  379. cmdSlice = append(getShell(b.runConfig), cmdSlice...)
  380. }
  381. b.runConfig.Cmd = strslice.StrSlice(cmdSlice)
  382. // set config as already being escaped, this prevents double escaping on windows
  383. b.runConfig.ArgsEscaped = true
  384. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
  385. return err
  386. }
  387. if len(args) != 0 {
  388. b.cmdSet = true
  389. }
  390. return nil
  391. }
  392. // parseOptInterval(flag) is the duration of flag.Value, or 0 if
  393. // empty. An error is reported if the value is given and is not positive.
  394. func parseOptInterval(f *Flag) (time.Duration, error) {
  395. s := f.Value
  396. if s == "" {
  397. return 0, nil
  398. }
  399. d, err := time.ParseDuration(s)
  400. if err != nil {
  401. return 0, err
  402. }
  403. if d <= 0 {
  404. return 0, fmt.Errorf("Interval %#v must be positive", f.name)
  405. }
  406. return d, nil
  407. }
  408. // HEALTHCHECK foo
  409. //
  410. // Set the default healthcheck command to run in the container (which may be empty).
  411. // Argument handling is the same as RUN.
  412. //
  413. func healthcheck(b *Builder, args []string, attributes map[string]bool, original string) error {
  414. if len(args) == 0 {
  415. return errAtLeastOneArgument("HEALTHCHECK")
  416. }
  417. typ := strings.ToUpper(args[0])
  418. args = args[1:]
  419. if typ == "NONE" {
  420. if len(args) != 0 {
  421. return fmt.Errorf("HEALTHCHECK NONE takes no arguments")
  422. }
  423. test := strslice.StrSlice{typ}
  424. b.runConfig.Healthcheck = &container.HealthConfig{
  425. Test: test,
  426. }
  427. } else {
  428. if b.runConfig.Healthcheck != nil {
  429. oldCmd := b.runConfig.Healthcheck.Test
  430. if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
  431. fmt.Fprintf(b.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
  432. }
  433. }
  434. healthcheck := container.HealthConfig{}
  435. flInterval := b.flags.AddString("interval", "")
  436. flTimeout := b.flags.AddString("timeout", "")
  437. flRetries := b.flags.AddString("retries", "")
  438. if err := b.flags.Parse(); err != nil {
  439. return err
  440. }
  441. switch typ {
  442. case "CMD":
  443. cmdSlice := handleJSONArgs(args, attributes)
  444. if len(cmdSlice) == 0 {
  445. return fmt.Errorf("Missing command after HEALTHCHECK CMD")
  446. }
  447. if !attributes["json"] {
  448. typ = "CMD-SHELL"
  449. }
  450. healthcheck.Test = strslice.StrSlice(append([]string{typ}, cmdSlice...))
  451. default:
  452. return fmt.Errorf("Unknown type %#v in HEALTHCHECK (try CMD)", typ)
  453. }
  454. interval, err := parseOptInterval(flInterval)
  455. if err != nil {
  456. return err
  457. }
  458. healthcheck.Interval = interval
  459. timeout, err := parseOptInterval(flTimeout)
  460. if err != nil {
  461. return err
  462. }
  463. healthcheck.Timeout = timeout
  464. if flRetries.Value != "" {
  465. retries, err := strconv.ParseInt(flRetries.Value, 10, 32)
  466. if err != nil {
  467. return err
  468. }
  469. if retries < 1 {
  470. return fmt.Errorf("--retries must be at least 1 (not %d)", retries)
  471. }
  472. healthcheck.Retries = int(retries)
  473. } else {
  474. healthcheck.Retries = 0
  475. }
  476. b.runConfig.Healthcheck = &healthcheck
  477. }
  478. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("HEALTHCHECK %q", b.runConfig.Healthcheck))
  479. }
  480. // ENTRYPOINT /usr/sbin/nginx
  481. //
  482. // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
  483. // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
  484. //
  485. // Handles command processing similar to CMD and RUN, only b.runConfig.Entrypoint
  486. // is initialized at NewBuilder time instead of through argument parsing.
  487. //
  488. func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error {
  489. if err := b.flags.Parse(); err != nil {
  490. return err
  491. }
  492. parsed := handleJSONArgs(args, attributes)
  493. switch {
  494. case attributes["json"]:
  495. // ENTRYPOINT ["echo", "hi"]
  496. b.runConfig.Entrypoint = strslice.StrSlice(parsed)
  497. case len(parsed) == 0:
  498. // ENTRYPOINT []
  499. b.runConfig.Entrypoint = nil
  500. default:
  501. // ENTRYPOINT echo hi
  502. b.runConfig.Entrypoint = strslice.StrSlice(append(getShell(b.runConfig), parsed[0]))
  503. }
  504. // when setting the entrypoint if a CMD was not explicitly set then
  505. // set the command to nil
  506. if !b.cmdSet {
  507. b.runConfig.Cmd = nil
  508. }
  509. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.runConfig.Entrypoint)); err != nil {
  510. return err
  511. }
  512. return nil
  513. }
  514. // EXPOSE 6667/tcp 7000/tcp
  515. //
  516. // Expose ports for links and port mappings. This all ends up in
  517. // b.runConfig.ExposedPorts for runconfig.
  518. //
  519. func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
  520. portsTab := args
  521. if len(args) == 0 {
  522. return errAtLeastOneArgument("EXPOSE")
  523. }
  524. if err := b.flags.Parse(); err != nil {
  525. return err
  526. }
  527. if b.runConfig.ExposedPorts == nil {
  528. b.runConfig.ExposedPorts = make(nat.PortSet)
  529. }
  530. ports, _, err := nat.ParsePortSpecs(portsTab)
  531. if err != nil {
  532. return err
  533. }
  534. // instead of using ports directly, we build a list of ports and sort it so
  535. // the order is consistent. This prevents cache burst where map ordering
  536. // changes between builds
  537. portList := make([]string, len(ports))
  538. var i int
  539. for port := range ports {
  540. if _, exists := b.runConfig.ExposedPorts[port]; !exists {
  541. b.runConfig.ExposedPorts[port] = struct{}{}
  542. }
  543. portList[i] = string(port)
  544. i++
  545. }
  546. sort.Strings(portList)
  547. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
  548. }
  549. // USER foo
  550. //
  551. // Set the user to 'foo' for future commands and when running the
  552. // ENTRYPOINT/CMD at container run time.
  553. //
  554. func user(b *Builder, args []string, attributes map[string]bool, original string) error {
  555. if len(args) != 1 {
  556. return errExactlyOneArgument("USER")
  557. }
  558. if err := b.flags.Parse(); err != nil {
  559. return err
  560. }
  561. b.runConfig.User = args[0]
  562. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("USER %v", args))
  563. }
  564. // VOLUME /foo
  565. //
  566. // Expose the volume /foo for use. Will also accept the JSON array form.
  567. //
  568. func volume(b *Builder, args []string, attributes map[string]bool, original string) error {
  569. if len(args) == 0 {
  570. return errAtLeastOneArgument("VOLUME")
  571. }
  572. if err := b.flags.Parse(); err != nil {
  573. return err
  574. }
  575. if b.runConfig.Volumes == nil {
  576. b.runConfig.Volumes = map[string]struct{}{}
  577. }
  578. for _, v := range args {
  579. v = strings.TrimSpace(v)
  580. if v == "" {
  581. return fmt.Errorf("VOLUME specified can not be an empty string")
  582. }
  583. b.runConfig.Volumes[v] = struct{}{}
  584. }
  585. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil {
  586. return err
  587. }
  588. return nil
  589. }
  590. // STOPSIGNAL signal
  591. //
  592. // Set the signal that will be used to kill the container.
  593. func stopSignal(b *Builder, args []string, attributes map[string]bool, original string) error {
  594. if len(args) != 1 {
  595. return errExactlyOneArgument("STOPSIGNAL")
  596. }
  597. sig := args[0]
  598. _, err := signal.ParseSignal(sig)
  599. if err != nil {
  600. return err
  601. }
  602. b.runConfig.StopSignal = sig
  603. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("STOPSIGNAL %v", args))
  604. }
  605. // ARG name[=value]
  606. //
  607. // Adds the variable foo to the trusted list of variables that can be passed
  608. // to builder using the --build-arg flag for expansion/subsitution or passing to 'run'.
  609. // Dockerfile author may optionally set a default value of this variable.
  610. func arg(b *Builder, args []string, attributes map[string]bool, original string) error {
  611. if len(args) != 1 {
  612. return errExactlyOneArgument("ARG")
  613. }
  614. var (
  615. name string
  616. value string
  617. hasDefault bool
  618. )
  619. arg := args[0]
  620. // 'arg' can just be a name or name-value pair. Note that this is different
  621. // from 'env' that handles the split of name and value at the parser level.
  622. // The reason for doing it differently for 'arg' is that we support just
  623. // defining an arg and not assign it a value (while 'env' always expects a
  624. // name-value pair). If possible, it will be good to harmonize the two.
  625. if strings.Contains(arg, "=") {
  626. parts := strings.SplitN(arg, "=", 2)
  627. if len(parts[0]) == 0 {
  628. return errBlankCommandNames("ARG")
  629. }
  630. name = parts[0]
  631. value = parts[1]
  632. hasDefault = true
  633. } else {
  634. name = arg
  635. hasDefault = false
  636. }
  637. // add the arg to allowed list of build-time args from this step on.
  638. b.allowedBuildArgs[name] = true
  639. // If there is a default value associated with this arg then add it to the
  640. // b.buildArgs if one is not already passed to the builder. The args passed
  641. // to builder override the default value of 'arg'.
  642. if _, ok := b.options.BuildArgs[name]; !ok && hasDefault {
  643. b.options.BuildArgs[name] = value
  644. }
  645. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ARG %s", arg))
  646. }
  647. // SHELL powershell -command
  648. //
  649. // Set the non-default shell to use.
  650. func shell(b *Builder, args []string, attributes map[string]bool, original string) error {
  651. if err := b.flags.Parse(); err != nil {
  652. return err
  653. }
  654. shellSlice := handleJSONArgs(args, attributes)
  655. switch {
  656. case len(shellSlice) == 0:
  657. // SHELL []
  658. return errAtLeastOneArgument("SHELL")
  659. case attributes["json"]:
  660. // SHELL ["powershell", "-command"]
  661. b.runConfig.Shell = strslice.StrSlice(shellSlice)
  662. default:
  663. // SHELL powershell -command - not JSON
  664. return errNotJSON("SHELL", original)
  665. }
  666. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("SHELL %v", shellSlice))
  667. }
  668. func errAtLeastOneArgument(command string) error {
  669. return fmt.Errorf("%s requires at least one argument", command)
  670. }
  671. func errExactlyOneArgument(command string) error {
  672. return fmt.Errorf("%s requires exactly one argument", command)
  673. }
  674. func errAtLeastTwoArguments(command string) error {
  675. return fmt.Errorf("%s requires at least two arguments", command)
  676. }
  677. func errBlankCommandNames(command string) error {
  678. return fmt.Errorf("%s names can not be blank", command)
  679. }
  680. func errTooManyArguments(command string) error {
  681. return fmt.Errorf("Bad input to %s, too many arguments", command)
  682. }
  683. // getShell is a helper function which gets the right shell for prefixing the
  684. // shell-form of RUN, ENTRYPOINT and CMD instructions
  685. func getShell(c *container.Config) []string {
  686. if 0 == len(c.Shell) {
  687. return defaultShell[:]
  688. }
  689. return c.Shell[:]
  690. }