dispatchers.go 22 KB

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