dispatchers.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. "os"
  11. "path/filepath"
  12. "regexp"
  13. "runtime"
  14. "sort"
  15. "strings"
  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. "github.com/docker/docker/pkg/system"
  21. runconfigopts "github.com/docker/docker/runconfig/opts"
  22. "github.com/docker/engine-api/types/container"
  23. "github.com/docker/engine-api/types/strslice"
  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. newVar := args[j] + "=" + args[j+1] + ""
  60. commitStr += " " + newVar
  61. gotOne := false
  62. for i, envVar := range b.runConfig.Env {
  63. envParts := strings.SplitN(envVar, "=", 2)
  64. if envParts[0] == args[j] {
  65. b.runConfig.Env[i] = newVar
  66. gotOne = true
  67. break
  68. }
  69. }
  70. if !gotOne {
  71. b.runConfig.Env = append(b.runConfig.Env, newVar)
  72. }
  73. j++
  74. }
  75. return b.commit("", b.runConfig.Cmd, commitStr)
  76. }
  77. // MAINTAINER some text <maybe@an.email.address>
  78. //
  79. // Sets the maintainer metadata.
  80. func maintainer(b *Builder, args []string, attributes map[string]bool, original string) error {
  81. if len(args) != 1 {
  82. return errExactlyOneArgument("MAINTAINER")
  83. }
  84. if err := b.flags.Parse(); err != nil {
  85. return err
  86. }
  87. b.maintainer = args[0]
  88. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer))
  89. }
  90. // LABEL some json data describing the image
  91. //
  92. // Sets the Label variable foo to bar,
  93. //
  94. func label(b *Builder, args []string, attributes map[string]bool, original string) error {
  95. if len(args) == 0 {
  96. return errAtLeastOneArgument("LABEL")
  97. }
  98. if len(args)%2 != 0 {
  99. // should never get here, but just in case
  100. return errTooManyArguments("LABEL")
  101. }
  102. if err := b.flags.Parse(); err != nil {
  103. return err
  104. }
  105. commitStr := "LABEL"
  106. if b.runConfig.Labels == nil {
  107. b.runConfig.Labels = map[string]string{}
  108. }
  109. for j := 0; j < len(args); j++ {
  110. // name ==> args[j]
  111. // value ==> args[j+1]
  112. newVar := args[j] + "=" + args[j+1] + ""
  113. commitStr += " " + newVar
  114. b.runConfig.Labels[args[j]] = args[j+1]
  115. j++
  116. }
  117. return b.commit("", b.runConfig.Cmd, commitStr)
  118. }
  119. // ADD foo /path
  120. //
  121. // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
  122. // exist here. If you do not wish to have this automatic handling, use COPY.
  123. //
  124. func add(b *Builder, args []string, attributes map[string]bool, original string) error {
  125. if len(args) < 2 {
  126. return errAtLeastOneArgument("ADD")
  127. }
  128. if err := b.flags.Parse(); err != nil {
  129. return err
  130. }
  131. return b.runContextCommand(args, true, true, "ADD")
  132. }
  133. // COPY foo /path
  134. //
  135. // Same as 'ADD' but without the tar and remote url handling.
  136. //
  137. func dispatchCopy(b *Builder, args []string, attributes map[string]bool, original string) error {
  138. if len(args) < 2 {
  139. return errAtLeastOneArgument("COPY")
  140. }
  141. if err := b.flags.Parse(); err != nil {
  142. return err
  143. }
  144. return b.runContextCommand(args, false, false, "COPY")
  145. }
  146. // FROM imagename
  147. //
  148. // This sets the image the dockerfile will build on top of.
  149. //
  150. func from(b *Builder, args []string, attributes map[string]bool, original string) error {
  151. if len(args) != 1 {
  152. return errExactlyOneArgument("FROM")
  153. }
  154. if err := b.flags.Parse(); err != nil {
  155. return err
  156. }
  157. name := args[0]
  158. var (
  159. image builder.Image
  160. err error
  161. )
  162. // Windows cannot support a container with no base image.
  163. if name == api.NoBaseImageSpecifier {
  164. if runtime.GOOS == "windows" {
  165. return fmt.Errorf("Windows does not support FROM scratch")
  166. }
  167. b.image = ""
  168. b.noBaseImage = true
  169. } else {
  170. // TODO: don't use `name`, instead resolve it to a digest
  171. if !b.options.PullParent {
  172. image, err = b.docker.GetImageOnBuild(name)
  173. // TODO: shouldn't we error out if error is different from "not found" ?
  174. }
  175. if image == nil {
  176. image, err = b.docker.PullOnBuild(b.clientCtx, name, b.options.AuthConfigs, b.Output)
  177. if err != nil {
  178. return err
  179. }
  180. }
  181. }
  182. return b.processImageFrom(image)
  183. }
  184. // ONBUILD RUN echo yo
  185. //
  186. // ONBUILD triggers run when the image is used in a FROM statement.
  187. //
  188. // ONBUILD handling has a lot of special-case functionality, the heading in
  189. // evaluator.go and comments around dispatch() in the same file explain the
  190. // special cases. search for 'OnBuild' in internals.go for additional special
  191. // cases.
  192. //
  193. func onbuild(b *Builder, args []string, attributes map[string]bool, original string) error {
  194. if len(args) == 0 {
  195. return errAtLeastOneArgument("ONBUILD")
  196. }
  197. if err := b.flags.Parse(); err != nil {
  198. return err
  199. }
  200. triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0]))
  201. switch triggerInstruction {
  202. case "ONBUILD":
  203. return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  204. case "MAINTAINER", "FROM":
  205. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
  206. }
  207. original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "")
  208. b.runConfig.OnBuild = append(b.runConfig.OnBuild, original)
  209. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ONBUILD %s", original))
  210. }
  211. // WORKDIR /tmp
  212. //
  213. // Set the working directory for future RUN/CMD/etc statements.
  214. //
  215. func workdir(b *Builder, args []string, attributes map[string]bool, original string) error {
  216. if len(args) != 1 {
  217. return errExactlyOneArgument("WORKDIR")
  218. }
  219. if err := b.flags.Parse(); err != nil {
  220. return err
  221. }
  222. // This is from the Dockerfile and will not necessarily be in platform
  223. // specific semantics, hence ensure it is converted.
  224. workdir := filepath.FromSlash(args[0])
  225. if !system.IsAbs(workdir) {
  226. current := filepath.FromSlash(b.runConfig.WorkingDir)
  227. workdir = filepath.Join(string(os.PathSeparator), current, workdir)
  228. }
  229. b.runConfig.WorkingDir = workdir
  230. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("WORKDIR %v", workdir))
  231. }
  232. // RUN some command yo
  233. //
  234. // run a command and commit the image. Args are automatically prepended with
  235. // 'sh -c' under linux or 'cmd /S /C' under Windows, in the event there is
  236. // only one argument. The difference in processing:
  237. //
  238. // RUN echo hi # sh -c echo hi (Linux)
  239. // RUN echo hi # cmd /S /C echo hi (Windows)
  240. // RUN [ "echo", "hi" ] # echo hi
  241. //
  242. func run(b *Builder, args []string, attributes map[string]bool, original string) error {
  243. if b.image == "" && !b.noBaseImage {
  244. return fmt.Errorf("Please provide a source image with `from` prior to run")
  245. }
  246. if err := b.flags.Parse(); err != nil {
  247. return err
  248. }
  249. args = handleJSONArgs(args, attributes)
  250. if !attributes["json"] {
  251. if runtime.GOOS != "windows" {
  252. args = append([]string{"/bin/sh", "-c"}, args...)
  253. } else {
  254. args = append([]string{"cmd", "/S", "/C"}, args...)
  255. }
  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. if runtime.GOOS != "windows" {
  352. cmdSlice = append([]string{"/bin/sh", "-c"}, cmdSlice...)
  353. } else {
  354. cmdSlice = append([]string{"cmd", "/S", "/C"}, cmdSlice...)
  355. }
  356. }
  357. b.runConfig.Cmd = strslice.StrSlice(cmdSlice)
  358. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
  359. return err
  360. }
  361. if len(args) != 0 {
  362. b.cmdSet = true
  363. }
  364. return nil
  365. }
  366. // ENTRYPOINT /usr/sbin/nginx
  367. //
  368. // Set the entrypoint (which defaults to sh -c on linux, or cmd /S /C on Windows) to
  369. // /usr/sbin/nginx. Will accept the CMD as the arguments to /usr/sbin/nginx.
  370. //
  371. // Handles command processing similar to CMD and RUN, only b.runConfig.Entrypoint
  372. // is initialized at NewBuilder time instead of through argument parsing.
  373. //
  374. func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error {
  375. if err := b.flags.Parse(); err != nil {
  376. return err
  377. }
  378. parsed := handleJSONArgs(args, attributes)
  379. switch {
  380. case attributes["json"]:
  381. // ENTRYPOINT ["echo", "hi"]
  382. b.runConfig.Entrypoint = strslice.StrSlice(parsed)
  383. case len(parsed) == 0:
  384. // ENTRYPOINT []
  385. b.runConfig.Entrypoint = nil
  386. default:
  387. // ENTRYPOINT echo hi
  388. if runtime.GOOS != "windows" {
  389. b.runConfig.Entrypoint = strslice.StrSlice{"/bin/sh", "-c", parsed[0]}
  390. } else {
  391. b.runConfig.Entrypoint = strslice.StrSlice{"cmd", "/S", "/C", parsed[0]}
  392. }
  393. }
  394. // when setting the entrypoint if a CMD was not explicitly set then
  395. // set the command to nil
  396. if !b.cmdSet {
  397. b.runConfig.Cmd = nil
  398. }
  399. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.runConfig.Entrypoint)); err != nil {
  400. return err
  401. }
  402. return nil
  403. }
  404. // EXPOSE 6667/tcp 7000/tcp
  405. //
  406. // Expose ports for links and port mappings. This all ends up in
  407. // b.runConfig.ExposedPorts for runconfig.
  408. //
  409. func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
  410. portsTab := args
  411. if len(args) == 0 {
  412. return errAtLeastOneArgument("EXPOSE")
  413. }
  414. if err := b.flags.Parse(); err != nil {
  415. return err
  416. }
  417. if b.runConfig.ExposedPorts == nil {
  418. b.runConfig.ExposedPorts = make(nat.PortSet)
  419. }
  420. ports, _, err := nat.ParsePortSpecs(portsTab)
  421. if err != nil {
  422. return err
  423. }
  424. // instead of using ports directly, we build a list of ports and sort it so
  425. // the order is consistent. This prevents cache burst where map ordering
  426. // changes between builds
  427. portList := make([]string, len(ports))
  428. var i int
  429. for port := range ports {
  430. if _, exists := b.runConfig.ExposedPorts[port]; !exists {
  431. b.runConfig.ExposedPorts[port] = struct{}{}
  432. }
  433. portList[i] = string(port)
  434. i++
  435. }
  436. sort.Strings(portList)
  437. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
  438. }
  439. // USER foo
  440. //
  441. // Set the user to 'foo' for future commands and when running the
  442. // ENTRYPOINT/CMD at container run time.
  443. //
  444. func user(b *Builder, args []string, attributes map[string]bool, original string) error {
  445. if len(args) != 1 {
  446. return errExactlyOneArgument("USER")
  447. }
  448. if err := b.flags.Parse(); err != nil {
  449. return err
  450. }
  451. b.runConfig.User = args[0]
  452. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("USER %v", args))
  453. }
  454. // VOLUME /foo
  455. //
  456. // Expose the volume /foo for use. Will also accept the JSON array form.
  457. //
  458. func volume(b *Builder, args []string, attributes map[string]bool, original string) error {
  459. if len(args) == 0 {
  460. return errAtLeastOneArgument("VOLUME")
  461. }
  462. if err := b.flags.Parse(); err != nil {
  463. return err
  464. }
  465. if b.runConfig.Volumes == nil {
  466. b.runConfig.Volumes = map[string]struct{}{}
  467. }
  468. for _, v := range args {
  469. v = strings.TrimSpace(v)
  470. if v == "" {
  471. return fmt.Errorf("Volume specified can not be an empty string")
  472. }
  473. b.runConfig.Volumes[v] = struct{}{}
  474. }
  475. if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil {
  476. return err
  477. }
  478. return nil
  479. }
  480. // STOPSIGNAL signal
  481. //
  482. // Set the signal that will be used to kill the container.
  483. func stopSignal(b *Builder, args []string, attributes map[string]bool, original string) error {
  484. if len(args) != 1 {
  485. return fmt.Errorf("STOPSIGNAL requires exactly one argument")
  486. }
  487. sig := args[0]
  488. _, err := signal.ParseSignal(sig)
  489. if err != nil {
  490. return err
  491. }
  492. b.runConfig.StopSignal = sig
  493. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("STOPSIGNAL %v", args))
  494. }
  495. // ARG name[=value]
  496. //
  497. // Adds the variable foo to the trusted list of variables that can be passed
  498. // to builder using the --build-arg flag for expansion/subsitution or passing to 'run'.
  499. // Dockerfile author may optionally set a default value of this variable.
  500. func arg(b *Builder, args []string, attributes map[string]bool, original string) error {
  501. if len(args) != 1 {
  502. return fmt.Errorf("ARG requires exactly one argument definition")
  503. }
  504. var (
  505. name string
  506. value string
  507. hasDefault bool
  508. )
  509. arg := args[0]
  510. // 'arg' can just be a name or name-value pair. Note that this is different
  511. // from 'env' that handles the split of name and value at the parser level.
  512. // The reason for doing it differently for 'arg' is that we support just
  513. // defining an arg and not assign it a value (while 'env' always expects a
  514. // name-value pair). If possible, it will be good to harmonize the two.
  515. if strings.Contains(arg, "=") {
  516. parts := strings.SplitN(arg, "=", 2)
  517. name = parts[0]
  518. value = parts[1]
  519. hasDefault = true
  520. } else {
  521. name = arg
  522. hasDefault = false
  523. }
  524. // add the arg to allowed list of build-time args from this step on.
  525. b.allowedBuildArgs[name] = true
  526. // If there is a default value associated with this arg then add it to the
  527. // b.buildArgs if one is not already passed to the builder. The args passed
  528. // to builder override the default value of 'arg'.
  529. if _, ok := b.options.BuildArgs[name]; !ok && hasDefault {
  530. b.options.BuildArgs[name] = value
  531. }
  532. return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ARG %s", arg))
  533. }
  534. func errAtLeastOneArgument(command string) error {
  535. return fmt.Errorf("%s requires at least one argument", command)
  536. }
  537. func errExactlyOneArgument(command string) error {
  538. return fmt.Errorf("%s requires exactly one argument", command)
  539. }
  540. func errTooManyArguments(command string) error {
  541. return fmt.Errorf("Bad input to %s, too many arguments", command)
  542. }