dispatchers.go 21 KB

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