dispatchers.go 18 KB

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