dispatchers.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. package dockerfile
  2. // This file contains the dispatchers for each command. Note that
  3. // `nullDispatch` is not actually a command, but support for commands we parse
  4. // but do nothing with.
  5. //
  6. // See evaluator.go for a higher level discussion of the whole evaluator
  7. // package.
  8. import (
  9. "fmt"
  10. "regexp"
  11. "runtime"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/api"
  18. "github.com/docker/docker/api/types"
  19. "github.com/docker/docker/api/types/container"
  20. "github.com/docker/docker/api/types/strslice"
  21. "github.com/docker/docker/builder"
  22. "github.com/docker/docker/pkg/signal"
  23. "github.com/docker/go-connections/nat"
  24. "github.com/pkg/errors"
  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", nil)
  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. flFrom := b.flags.AddString("from", "")
  155. if err := b.flags.Parse(); err != nil {
  156. return err
  157. }
  158. var contextID *int
  159. if flFrom.IsUsed() {
  160. var err error
  161. context, err := strconv.Atoi(flFrom.Value)
  162. if err != nil {
  163. return errors.Wrap(err, "from expects an integer value corresponding to the context number")
  164. }
  165. if err := b.imageContexts.validate(context); err != nil {
  166. return err
  167. }
  168. contextID = &context
  169. }
  170. return b.runContextCommand(args, false, false, "COPY", contextID)
  171. }
  172. // FROM imagename
  173. //
  174. // This sets the image the dockerfile will build on top of.
  175. //
  176. func from(b *Builder, args []string, attributes map[string]bool, original string) error {
  177. if len(args) != 1 {
  178. return errExactlyOneArgument("FROM")
  179. }
  180. if err := b.flags.Parse(); err != nil {
  181. return err
  182. }
  183. name := args[0]
  184. var image builder.Image
  185. b.resetImageCache()
  186. b.imageContexts.new()
  187. // Windows cannot support a container with no base image.
  188. if name == api.NoBaseImageSpecifier {
  189. if runtime.GOOS == "windows" {
  190. return errors.New("Windows does not support FROM scratch")
  191. }
  192. b.image = ""
  193. b.noBaseImage = true
  194. } else {
  195. // TODO: don't use `name`, instead resolve it to a digest
  196. if !b.options.PullParent {
  197. image, _ = b.docker.GetImageOnBuild(name)
  198. // TODO: shouldn't we error out if error is different from "not found" ?
  199. }
  200. if image == nil {
  201. var err error
  202. image, err = b.docker.PullOnBuild(b.clientCtx, name, b.options.AuthConfigs, b.Output)
  203. if err != nil {
  204. return err
  205. }
  206. }
  207. b.imageContexts.update(image.ImageID())
  208. }
  209. b.from = image
  210. b.allowedBuildArgs = make(map[string]*string)
  211. return b.processImageFrom(image)
  212. }
  213. // ONBUILD RUN echo yo
  214. //
  215. // ONBUILD triggers run when the image is used in a FROM statement.
  216. //
  217. // ONBUILD handling has a lot of special-case functionality, the heading in
  218. // evaluator.go and comments around dispatch() in the same file explain the
  219. // special cases. search for 'OnBuild' in internals.go for additional special
  220. // cases.
  221. //
  222. func onbuild(b *Builder, args []string, attributes map[string]bool, original string) error {
  223. if len(args) == 0 {
  224. return errAtLeastOneArgument("ONBUILD")
  225. }
  226. if err := b.flags.Parse(); err != nil {
  227. return err
  228. }
  229. triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0]))
  230. switch triggerInstruction {
  231. case "ONBUILD":
  232. return errors.New("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  233. case "MAINTAINER", "FROM":
  234. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
  235. }
  236. original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "")
  237. b.runConfig.OnBuild = append(b.runConfig.OnBuild, original)
  238. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ONBUILD %s", original))
  239. }
  240. // WORKDIR /tmp
  241. //
  242. // Set the working directory for future RUN/CMD/etc statements.
  243. //
  244. func workdir(b *Builder, args []string, attributes map[string]bool, original string) error {
  245. if len(args) != 1 {
  246. return errExactlyOneArgument("WORKDIR")
  247. }
  248. err := b.flags.Parse()
  249. if err != nil {
  250. return err
  251. }
  252. // This is from the Dockerfile and will not necessarily be in platform
  253. // specific semantics, hence ensure it is converted.
  254. b.runConfig.WorkingDir, err = normaliseWorkdir(b.runConfig.WorkingDir, args[0])
  255. if err != nil {
  256. return err
  257. }
  258. // For performance reasons, we explicitly do a create/mkdir now
  259. // This avoids having an unnecessary expensive mount/unmount calls
  260. // (on Windows in particular) during each container create.
  261. // Prior to 1.13, the mkdir was deferred and not executed at this step.
  262. if b.disableCommit {
  263. // Don't call back into the daemon if we're going through docker commit --change "WORKDIR /foo".
  264. // We've already updated the runConfig and that's enough.
  265. return nil
  266. }
  267. b.runConfig.Image = b.image
  268. cmd := b.runConfig.Cmd
  269. comment := "WORKDIR " + b.runConfig.WorkingDir
  270. // reset the command for cache detection
  271. b.runConfig.Cmd = strslice.StrSlice(append(getShell(b.runConfig), "#(nop) "+comment))
  272. defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
  273. if hit, err := b.probeCache(); err != nil {
  274. return err
  275. } else if hit {
  276. return nil
  277. }
  278. container, err := b.docker.ContainerCreate(types.ContainerCreateConfig{
  279. Config: b.runConfig,
  280. // Set a log config to override any default value set on the daemon
  281. HostConfig: &container.HostConfig{LogConfig: defaultLogConfig},
  282. })
  283. if err != nil {
  284. return err
  285. }
  286. b.tmpContainers[container.ID] = struct{}{}
  287. if err := b.docker.ContainerCreateWorkdir(container.ID); err != nil {
  288. return err
  289. }
  290. return b.commit(container.ID, cmd, comment)
  291. }
  292. // RUN some command yo
  293. //
  294. // run a command and commit the image. Args are automatically prepended with
  295. // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
  296. // Windows, in the event there is only one argument The difference in processing:
  297. //
  298. // RUN echo hi # sh -c echo hi (Linux)
  299. // RUN echo hi # cmd /S /C echo hi (Windows)
  300. // RUN [ "echo", "hi" ] # echo hi
  301. //
  302. func run(b *Builder, args []string, attributes map[string]bool, original string) error {
  303. if b.image == "" && !b.noBaseImage {
  304. return errors.New("Please provide a source image with `from` prior to run")
  305. }
  306. if err := b.flags.Parse(); err != nil {
  307. return err
  308. }
  309. args = handleJSONArgs(args, attributes)
  310. if !attributes["json"] {
  311. args = append(getShell(b.runConfig), args...)
  312. }
  313. config := &container.Config{
  314. Cmd: strslice.StrSlice(args),
  315. Image: b.image,
  316. }
  317. // stash the cmd
  318. cmd := b.runConfig.Cmd
  319. if len(b.runConfig.Entrypoint) == 0 && len(b.runConfig.Cmd) == 0 {
  320. b.runConfig.Cmd = config.Cmd
  321. }
  322. // stash the config environment
  323. env := b.runConfig.Env
  324. defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
  325. defer func(env []string) { b.runConfig.Env = env }(env)
  326. cmdBuildEnv := b.buildArgsWithoutConfigEnv()
  327. // derive the command to use for probeCache() and to commit in this container.
  328. // Note that we only do this if there are any build-time env vars. Also, we
  329. // use the special argument "|#" at the start of the args array. This will
  330. // avoid conflicts with any RUN command since commands can not
  331. // start with | (vertical bar). The "#" (number of build envs) is there to
  332. // help ensure proper cache matches. We don't want a RUN command
  333. // that starts with "foo=abc" to be considered part of a build-time env var.
  334. saveCmd := config.Cmd
  335. if len(cmdBuildEnv) > 0 {
  336. sort.Strings(cmdBuildEnv)
  337. tmpEnv := append([]string{fmt.Sprintf("|%d", len(cmdBuildEnv))}, cmdBuildEnv...)
  338. saveCmd = strslice.StrSlice(append(tmpEnv, saveCmd...))
  339. }
  340. b.runConfig.Cmd = saveCmd
  341. hit, err := b.probeCache()
  342. if err != nil {
  343. return err
  344. }
  345. if hit {
  346. return nil
  347. }
  348. // set Cmd manually, this is special case only for Dockerfiles
  349. b.runConfig.Cmd = config.Cmd
  350. // set build-time environment for 'run'.
  351. b.runConfig.Env = append(b.runConfig.Env, cmdBuildEnv...)
  352. // set config as already being escaped, this prevents double escaping on windows
  353. b.runConfig.ArgsEscaped = true
  354. logrus.Debugf("[BUILDER] Command to be executed: %v", b.runConfig.Cmd)
  355. cID, err := b.create()
  356. if err != nil {
  357. return err
  358. }
  359. if err := b.run(cID); err != nil {
  360. return err
  361. }
  362. // revert to original config environment and set the command string to
  363. // have the build-time env vars in it (if any) so that future cache look-ups
  364. // properly match it.
  365. b.runConfig.Env = env
  366. // remove BuiltinAllowedBuildArgs (see: builder.go) from the saveCmd
  367. // these args are transparent so resulting image should be the same regardless of the value
  368. if len(cmdBuildEnv) > 0 {
  369. saveCmd = config.Cmd
  370. tmpBuildEnv := make([]string, len(cmdBuildEnv))
  371. copy(tmpBuildEnv, cmdBuildEnv)
  372. for i, env := range tmpBuildEnv {
  373. key := strings.SplitN(env, "=", 2)[0]
  374. if _, ok := BuiltinAllowedBuildArgs[key]; ok {
  375. // If an built-in arg is explicitly added in the Dockerfile, don't prune it
  376. if _, ok := b.allowedBuildArgs[key]; !ok {
  377. tmpBuildEnv = append(tmpBuildEnv[:i], tmpBuildEnv[i+1:]...)
  378. }
  379. }
  380. }
  381. sort.Strings(tmpBuildEnv)
  382. tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...)
  383. saveCmd = strslice.StrSlice(append(tmpEnv, saveCmd...))
  384. }
  385. b.runConfig.Cmd = saveCmd
  386. return b.commit(cID, cmd, "run")
  387. }
  388. // CMD foo
  389. //
  390. // Set the default command to run in the container (which may be empty).
  391. // Argument handling is the same as RUN.
  392. //
  393. func cmd(b *Builder, args []string, attributes map[string]bool, original string) error {
  394. if err := b.flags.Parse(); err != nil {
  395. return err
  396. }
  397. cmdSlice := handleJSONArgs(args, attributes)
  398. if !attributes["json"] {
  399. cmdSlice = append(getShell(b.runConfig), cmdSlice...)
  400. }
  401. b.runConfig.Cmd = strslice.StrSlice(cmdSlice)
  402. // set config as already being escaped, this prevents double escaping on windows
  403. b.runConfig.ArgsEscaped = true
  404. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
  405. return err
  406. }
  407. if len(args) != 0 {
  408. b.cmdSet = true
  409. }
  410. return nil
  411. }
  412. // parseOptInterval(flag) is the duration of flag.Value, or 0 if
  413. // empty. An error is reported if the value is given and less than 1 second.
  414. func parseOptInterval(f *Flag) (time.Duration, error) {
  415. s := f.Value
  416. if s == "" {
  417. return 0, nil
  418. }
  419. d, err := time.ParseDuration(s)
  420. if err != nil {
  421. return 0, err
  422. }
  423. if d < time.Duration(time.Second) {
  424. return 0, fmt.Errorf("Interval %#v cannot be less than 1 second", f.name)
  425. }
  426. return d, nil
  427. }
  428. // HEALTHCHECK foo
  429. //
  430. // Set the default healthcheck command to run in the container (which may be empty).
  431. // Argument handling is the same as RUN.
  432. //
  433. func healthcheck(b *Builder, args []string, attributes map[string]bool, original string) error {
  434. if len(args) == 0 {
  435. return errAtLeastOneArgument("HEALTHCHECK")
  436. }
  437. typ := strings.ToUpper(args[0])
  438. args = args[1:]
  439. if typ == "NONE" {
  440. if len(args) != 0 {
  441. return errors.New("HEALTHCHECK NONE takes no arguments")
  442. }
  443. test := strslice.StrSlice{typ}
  444. b.runConfig.Healthcheck = &container.HealthConfig{
  445. Test: test,
  446. }
  447. } else {
  448. if b.runConfig.Healthcheck != nil {
  449. oldCmd := b.runConfig.Healthcheck.Test
  450. if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
  451. fmt.Fprintf(b.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
  452. }
  453. }
  454. healthcheck := container.HealthConfig{}
  455. flInterval := b.flags.AddString("interval", "")
  456. flTimeout := b.flags.AddString("timeout", "")
  457. flRetries := b.flags.AddString("retries", "")
  458. if err := b.flags.Parse(); err != nil {
  459. return err
  460. }
  461. switch typ {
  462. case "CMD":
  463. cmdSlice := handleJSONArgs(args, attributes)
  464. if len(cmdSlice) == 0 {
  465. return errors.New("Missing command after HEALTHCHECK CMD")
  466. }
  467. if !attributes["json"] {
  468. typ = "CMD-SHELL"
  469. }
  470. healthcheck.Test = strslice.StrSlice(append([]string{typ}, cmdSlice...))
  471. default:
  472. return fmt.Errorf("Unknown type %#v in HEALTHCHECK (try CMD)", typ)
  473. }
  474. interval, err := parseOptInterval(flInterval)
  475. if err != nil {
  476. return err
  477. }
  478. healthcheck.Interval = interval
  479. timeout, err := parseOptInterval(flTimeout)
  480. if err != nil {
  481. return err
  482. }
  483. healthcheck.Timeout = timeout
  484. if flRetries.Value != "" {
  485. retries, err := strconv.ParseInt(flRetries.Value, 10, 32)
  486. if err != nil {
  487. return err
  488. }
  489. if retries < 1 {
  490. return fmt.Errorf("--retries must be at least 1 (not %d)", retries)
  491. }
  492. healthcheck.Retries = int(retries)
  493. } else {
  494. healthcheck.Retries = 0
  495. }
  496. b.runConfig.Healthcheck = &healthcheck
  497. }
  498. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("HEALTHCHECK %q", b.runConfig.Healthcheck))
  499. }
  500. // ENTRYPOINT /usr/sbin/nginx
  501. //
  502. // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
  503. // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
  504. //
  505. // Handles command processing similar to CMD and RUN, only b.runConfig.Entrypoint
  506. // is initialized at NewBuilder time instead of through argument parsing.
  507. //
  508. func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error {
  509. if err := b.flags.Parse(); err != nil {
  510. return err
  511. }
  512. parsed := handleJSONArgs(args, attributes)
  513. switch {
  514. case attributes["json"]:
  515. // ENTRYPOINT ["echo", "hi"]
  516. b.runConfig.Entrypoint = strslice.StrSlice(parsed)
  517. case len(parsed) == 0:
  518. // ENTRYPOINT []
  519. b.runConfig.Entrypoint = nil
  520. default:
  521. // ENTRYPOINT echo hi
  522. b.runConfig.Entrypoint = strslice.StrSlice(append(getShell(b.runConfig), parsed[0]))
  523. }
  524. // when setting the entrypoint if a CMD was not explicitly set then
  525. // set the command to nil
  526. if !b.cmdSet {
  527. b.runConfig.Cmd = nil
  528. }
  529. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.runConfig.Entrypoint)); err != nil {
  530. return err
  531. }
  532. return nil
  533. }
  534. // EXPOSE 6667/tcp 7000/tcp
  535. //
  536. // Expose ports for links and port mappings. This all ends up in
  537. // b.runConfig.ExposedPorts for runconfig.
  538. //
  539. func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
  540. portsTab := args
  541. if len(args) == 0 {
  542. return errAtLeastOneArgument("EXPOSE")
  543. }
  544. if err := b.flags.Parse(); err != nil {
  545. return err
  546. }
  547. if b.runConfig.ExposedPorts == nil {
  548. b.runConfig.ExposedPorts = make(nat.PortSet)
  549. }
  550. ports, _, err := nat.ParsePortSpecs(portsTab)
  551. if err != nil {
  552. return err
  553. }
  554. // instead of using ports directly, we build a list of ports and sort it so
  555. // the order is consistent. This prevents cache burst where map ordering
  556. // changes between builds
  557. portList := make([]string, len(ports))
  558. var i int
  559. for port := range ports {
  560. if _, exists := b.runConfig.ExposedPorts[port]; !exists {
  561. b.runConfig.ExposedPorts[port] = struct{}{}
  562. }
  563. portList[i] = string(port)
  564. i++
  565. }
  566. sort.Strings(portList)
  567. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
  568. }
  569. // USER foo
  570. //
  571. // Set the user to 'foo' for future commands and when running the
  572. // ENTRYPOINT/CMD at container run time.
  573. //
  574. func user(b *Builder, args []string, attributes map[string]bool, original string) error {
  575. if len(args) != 1 {
  576. return errExactlyOneArgument("USER")
  577. }
  578. if err := b.flags.Parse(); err != nil {
  579. return err
  580. }
  581. b.runConfig.User = args[0]
  582. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("USER %v", args))
  583. }
  584. // VOLUME /foo
  585. //
  586. // Expose the volume /foo for use. Will also accept the JSON array form.
  587. //
  588. func volume(b *Builder, args []string, attributes map[string]bool, original string) error {
  589. if len(args) == 0 {
  590. return errAtLeastOneArgument("VOLUME")
  591. }
  592. if err := b.flags.Parse(); err != nil {
  593. return err
  594. }
  595. if b.runConfig.Volumes == nil {
  596. b.runConfig.Volumes = map[string]struct{}{}
  597. }
  598. for _, v := range args {
  599. v = strings.TrimSpace(v)
  600. if v == "" {
  601. return errors.New("VOLUME specified can not be an empty string")
  602. }
  603. b.runConfig.Volumes[v] = struct{}{}
  604. }
  605. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil {
  606. return err
  607. }
  608. return nil
  609. }
  610. // STOPSIGNAL signal
  611. //
  612. // Set the signal that will be used to kill the container.
  613. func stopSignal(b *Builder, args []string, attributes map[string]bool, original string) error {
  614. if len(args) != 1 {
  615. return errExactlyOneArgument("STOPSIGNAL")
  616. }
  617. sig := args[0]
  618. _, err := signal.ParseSignal(sig)
  619. if err != nil {
  620. return err
  621. }
  622. b.runConfig.StopSignal = sig
  623. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("STOPSIGNAL %v", args))
  624. }
  625. // ARG name[=value]
  626. //
  627. // Adds the variable foo to the trusted list of variables that can be passed
  628. // to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
  629. // Dockerfile author may optionally set a default value of this variable.
  630. func arg(b *Builder, args []string, attributes map[string]bool, original string) error {
  631. if len(args) != 1 {
  632. return errExactlyOneArgument("ARG")
  633. }
  634. var (
  635. name string
  636. newValue string
  637. hasDefault bool
  638. )
  639. arg := args[0]
  640. // 'arg' can just be a name or name-value pair. Note that this is different
  641. // from 'env' that handles the split of name and value at the parser level.
  642. // The reason for doing it differently for 'arg' is that we support just
  643. // defining an arg and not assign it a value (while 'env' always expects a
  644. // name-value pair). If possible, it will be good to harmonize the two.
  645. if strings.Contains(arg, "=") {
  646. parts := strings.SplitN(arg, "=", 2)
  647. if len(parts[0]) == 0 {
  648. return errBlankCommandNames("ARG")
  649. }
  650. name = parts[0]
  651. newValue = parts[1]
  652. hasDefault = true
  653. } else {
  654. name = arg
  655. hasDefault = false
  656. }
  657. // add the arg to allowed list of build-time args from this step on.
  658. b.allBuildArgs[name] = struct{}{}
  659. var value *string
  660. if hasDefault {
  661. value = &newValue
  662. }
  663. b.allowedBuildArgs[name] = value
  664. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ARG %s", arg))
  665. }
  666. // SHELL powershell -command
  667. //
  668. // Set the non-default shell to use.
  669. func shell(b *Builder, args []string, attributes map[string]bool, original string) error {
  670. if err := b.flags.Parse(); err != nil {
  671. return err
  672. }
  673. shellSlice := handleJSONArgs(args, attributes)
  674. switch {
  675. case len(shellSlice) == 0:
  676. // SHELL []
  677. return errAtLeastOneArgument("SHELL")
  678. case attributes["json"]:
  679. // SHELL ["powershell", "-command"]
  680. b.runConfig.Shell = strslice.StrSlice(shellSlice)
  681. default:
  682. // SHELL powershell -command - not JSON
  683. return errNotJSON("SHELL", original)
  684. }
  685. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("SHELL %v", shellSlice))
  686. }
  687. func errAtLeastOneArgument(command string) error {
  688. return fmt.Errorf("%s requires at least one argument", command)
  689. }
  690. func errExactlyOneArgument(command string) error {
  691. return fmt.Errorf("%s requires exactly one argument", command)
  692. }
  693. func errAtLeastTwoArguments(command string) error {
  694. return fmt.Errorf("%s requires at least two arguments", command)
  695. }
  696. func errBlankCommandNames(command string) error {
  697. return fmt.Errorf("%s names can not be blank", command)
  698. }
  699. func errTooManyArguments(command string) error {
  700. return fmt.Errorf("Bad input to %s, too many arguments", command)
  701. }
  702. // getShell is a helper function which gets the right shell for prefixing the
  703. // shell-form of RUN, ENTRYPOINT and CMD instructions
  704. func getShell(c *container.Config) []string {
  705. if 0 == len(c.Shell) {
  706. return append([]string{}, defaultShell[:]...)
  707. }
  708. return append([]string{}, c.Shell[:]...)
  709. }