dispatchers.go 23 KB

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