dispatchers.go 21 KB

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