dispatchers.go 23 KB

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