dispatchers.go 21 KB

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