dispatchers.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. package builder
  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. "io/ioutil"
  11. "path/filepath"
  12. "regexp"
  13. "sort"
  14. "strings"
  15. log "github.com/Sirupsen/logrus"
  16. "github.com/docker/docker/nat"
  17. flag "github.com/docker/docker/pkg/mflag"
  18. "github.com/docker/docker/runconfig"
  19. )
  20. const (
  21. // NoBaseImageSpecifier is the symbol used by the FROM
  22. // command to specify that no base image is to be used.
  23. NoBaseImageSpecifier string = "scratch"
  24. )
  25. // dispatch with no layer / parsing. This is effectively not a command.
  26. func nullDispatch(b *Builder, args []string, attributes map[string]bool, original string) error {
  27. return nil
  28. }
  29. // ENV foo bar
  30. //
  31. // Sets the environment variable foo to bar, also makes interpolation
  32. // in the dockerfile available from the next statement on via ${foo}.
  33. //
  34. func env(b *Builder, args []string, attributes map[string]bool, original string) error {
  35. if len(args) == 0 {
  36. return fmt.Errorf("ENV is missing arguments")
  37. }
  38. if len(args)%2 != 0 {
  39. // should never get here, but just in case
  40. return fmt.Errorf("Bad input to ENV, too many args")
  41. }
  42. commitStr := "ENV"
  43. for j := 0; j < len(args); j++ {
  44. // name ==> args[j]
  45. // value ==> args[j+1]
  46. newVar := args[j] + "=" + args[j+1] + ""
  47. commitStr += " " + newVar
  48. gotOne := false
  49. for i, envVar := range b.Config.Env {
  50. envParts := strings.SplitN(envVar, "=", 2)
  51. if envParts[0] == args[j] {
  52. b.Config.Env[i] = newVar
  53. gotOne = true
  54. break
  55. }
  56. }
  57. if !gotOne {
  58. b.Config.Env = append(b.Config.Env, newVar)
  59. }
  60. j++
  61. }
  62. return b.commit("", b.Config.Cmd, commitStr)
  63. }
  64. // MAINTAINER some text <maybe@an.email.address>
  65. //
  66. // Sets the maintainer metadata.
  67. func maintainer(b *Builder, args []string, attributes map[string]bool, original string) error {
  68. if len(args) != 1 {
  69. return fmt.Errorf("MAINTAINER requires only one argument")
  70. }
  71. b.maintainer = args[0]
  72. return b.commit("", b.Config.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer))
  73. }
  74. // ADD foo /path
  75. //
  76. // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
  77. // exist here. If you do not wish to have this automatic handling, use COPY.
  78. //
  79. func add(b *Builder, args []string, attributes map[string]bool, original string) error {
  80. if len(args) < 2 {
  81. return fmt.Errorf("ADD requires at least two arguments")
  82. }
  83. return b.runContextCommand(args, true, true, "ADD")
  84. }
  85. // COPY foo /path
  86. //
  87. // Same as 'ADD' but without the tar and remote url handling.
  88. //
  89. func dispatchCopy(b *Builder, args []string, attributes map[string]bool, original string) error {
  90. if len(args) < 2 {
  91. return fmt.Errorf("COPY requires at least two arguments")
  92. }
  93. return b.runContextCommand(args, false, false, "COPY")
  94. }
  95. // FROM imagename
  96. //
  97. // This sets the image the dockerfile will build on top of.
  98. //
  99. func from(b *Builder, args []string, attributes map[string]bool, original string) error {
  100. if len(args) != 1 {
  101. return fmt.Errorf("FROM requires one argument")
  102. }
  103. name := args[0]
  104. if name == NoBaseImageSpecifier {
  105. b.image = ""
  106. b.noBaseImage = true
  107. return nil
  108. }
  109. image, err := b.Daemon.Repositories().LookupImage(name)
  110. if b.Pull {
  111. image, err = b.pullImage(name)
  112. if err != nil {
  113. return err
  114. }
  115. }
  116. if err != nil {
  117. if b.Daemon.Graph().IsNotExist(err) {
  118. image, err = b.pullImage(name)
  119. }
  120. // note that the top level err will still be !nil here if IsNotExist is
  121. // not the error. This approach just simplifies hte logic a bit.
  122. if err != nil {
  123. return err
  124. }
  125. }
  126. return b.processImageFrom(image)
  127. }
  128. // ONBUILD RUN echo yo
  129. //
  130. // ONBUILD triggers run when the image is used in a FROM statement.
  131. //
  132. // ONBUILD handling has a lot of special-case functionality, the heading in
  133. // evaluator.go and comments around dispatch() in the same file explain the
  134. // special cases. search for 'OnBuild' in internals.go for additional special
  135. // cases.
  136. //
  137. func onbuild(b *Builder, args []string, attributes map[string]bool, original string) error {
  138. triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0]))
  139. switch triggerInstruction {
  140. case "ONBUILD":
  141. return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  142. case "MAINTAINER", "FROM":
  143. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
  144. }
  145. original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "")
  146. b.Config.OnBuild = append(b.Config.OnBuild, original)
  147. return b.commit("", b.Config.Cmd, fmt.Sprintf("ONBUILD %s", original))
  148. }
  149. // WORKDIR /tmp
  150. //
  151. // Set the working directory for future RUN/CMD/etc statements.
  152. //
  153. func workdir(b *Builder, args []string, attributes map[string]bool, original string) error {
  154. if len(args) != 1 {
  155. return fmt.Errorf("WORKDIR requires exactly one argument")
  156. }
  157. workdir := args[0]
  158. if !filepath.IsAbs(workdir) {
  159. workdir = filepath.Join("/", b.Config.WorkingDir, workdir)
  160. }
  161. b.Config.WorkingDir = workdir
  162. return b.commit("", b.Config.Cmd, fmt.Sprintf("WORKDIR %v", workdir))
  163. }
  164. // RUN some command yo
  165. //
  166. // run a command and commit the image. Args are automatically prepended with
  167. // 'sh -c' in the event there is only one argument. The difference in
  168. // processing:
  169. //
  170. // RUN echo hi # sh -c echo hi
  171. // RUN [ "echo", "hi" ] # echo hi
  172. //
  173. func run(b *Builder, args []string, attributes map[string]bool, original string) error {
  174. if b.image == "" && !b.noBaseImage {
  175. return fmt.Errorf("Please provide a source image with `from` prior to run")
  176. }
  177. args = handleJsonArgs(args, attributes)
  178. if len(args) == 1 {
  179. args = append([]string{"/bin/sh", "-c"}, args[0])
  180. }
  181. runCmd := flag.NewFlagSet("run", flag.ContinueOnError)
  182. runCmd.SetOutput(ioutil.Discard)
  183. runCmd.Usage = nil
  184. config, _, _, err := runconfig.Parse(runCmd, append([]string{b.image}, args...))
  185. if err != nil {
  186. return err
  187. }
  188. cmd := b.Config.Cmd
  189. // set Cmd manually, this is special case only for Dockerfiles
  190. b.Config.Cmd = config.Cmd
  191. runconfig.Merge(b.Config, config)
  192. defer func(cmd []string) { b.Config.Cmd = cmd }(cmd)
  193. log.Debugf("[BUILDER] Command to be executed: %v", b.Config.Cmd)
  194. hit, err := b.probeCache()
  195. if err != nil {
  196. return err
  197. }
  198. if hit {
  199. return nil
  200. }
  201. c, err := b.create()
  202. if err != nil {
  203. return err
  204. }
  205. // Ensure that we keep the container mounted until the commit
  206. // to avoid unmounting and then mounting directly again
  207. c.Mount()
  208. defer c.Unmount()
  209. err = b.run(c)
  210. if err != nil {
  211. return err
  212. }
  213. if err := b.commit(c.ID, cmd, "run"); err != nil {
  214. return err
  215. }
  216. return nil
  217. }
  218. // CMD foo
  219. //
  220. // Set the default command to run in the container (which may be empty).
  221. // Argument handling is the same as RUN.
  222. //
  223. func cmd(b *Builder, args []string, attributes map[string]bool, original string) error {
  224. b.Config.Cmd = handleJsonArgs(args, attributes)
  225. if !attributes["json"] {
  226. b.Config.Cmd = append([]string{"/bin/sh", "-c"}, b.Config.Cmd...)
  227. }
  228. if err := b.commit("", b.Config.Cmd, fmt.Sprintf("CMD %v", b.Config.Cmd)); err != nil {
  229. return err
  230. }
  231. if len(args) != 0 {
  232. b.cmdSet = true
  233. }
  234. return nil
  235. }
  236. // ENTRYPOINT /usr/sbin/nginx
  237. //
  238. // Set the entrypoint (which defaults to sh -c) to /usr/sbin/nginx. Will
  239. // accept the CMD as the arguments to /usr/sbin/nginx.
  240. //
  241. // Handles command processing similar to CMD and RUN, only b.Config.Entrypoint
  242. // is initialized at NewBuilder time instead of through argument parsing.
  243. //
  244. func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error {
  245. parsed := handleJsonArgs(args, attributes)
  246. switch {
  247. case attributes["json"]:
  248. // ENTRYPOINT ["echo", "hi"]
  249. b.Config.Entrypoint = parsed
  250. case len(parsed) == 0:
  251. // ENTRYPOINT []
  252. b.Config.Entrypoint = nil
  253. default:
  254. // ENTRYPOINT echo hi
  255. b.Config.Entrypoint = []string{"/bin/sh", "-c", parsed[0]}
  256. }
  257. // when setting the entrypoint if a CMD was not explicitly set then
  258. // set the command to nil
  259. if !b.cmdSet {
  260. b.Config.Cmd = nil
  261. }
  262. if err := b.commit("", b.Config.Cmd, fmt.Sprintf("ENTRYPOINT %v", b.Config.Entrypoint)); err != nil {
  263. return err
  264. }
  265. return nil
  266. }
  267. // EXPOSE 6667/tcp 7000/tcp
  268. //
  269. // Expose ports for links and port mappings. This all ends up in
  270. // b.Config.ExposedPorts for runconfig.
  271. //
  272. func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
  273. portsTab := args
  274. if b.Config.ExposedPorts == nil {
  275. b.Config.ExposedPorts = make(nat.PortSet)
  276. }
  277. ports, _, err := nat.ParsePortSpecs(append(portsTab, b.Config.PortSpecs...))
  278. if err != nil {
  279. return err
  280. }
  281. // instead of using ports directly, we build a list of ports and sort it so
  282. // the order is consistent. This prevents cache burst where map ordering
  283. // changes between builds
  284. portList := make([]string, len(ports))
  285. var i int
  286. for port := range ports {
  287. if _, exists := b.Config.ExposedPorts[port]; !exists {
  288. b.Config.ExposedPorts[port] = struct{}{}
  289. }
  290. portList[i] = string(port)
  291. i++
  292. }
  293. sort.Strings(portList)
  294. b.Config.PortSpecs = nil
  295. return b.commit("", b.Config.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
  296. }
  297. // USER foo
  298. //
  299. // Set the user to 'foo' for future commands and when running the
  300. // ENTRYPOINT/CMD at container run time.
  301. //
  302. func user(b *Builder, args []string, attributes map[string]bool, original string) error {
  303. if len(args) != 1 {
  304. return fmt.Errorf("USER requires exactly one argument")
  305. }
  306. b.Config.User = args[0]
  307. return b.commit("", b.Config.Cmd, fmt.Sprintf("USER %v", args))
  308. }
  309. // VOLUME /foo
  310. //
  311. // Expose the volume /foo for use. Will also accept the JSON array form.
  312. //
  313. func volume(b *Builder, args []string, attributes map[string]bool, original string) error {
  314. if len(args) == 0 {
  315. return fmt.Errorf("Volume cannot be empty")
  316. }
  317. if b.Config.Volumes == nil {
  318. b.Config.Volumes = map[string]struct{}{}
  319. }
  320. for _, v := range args {
  321. b.Config.Volumes[v] = struct{}{}
  322. }
  323. if err := b.commit("", b.Config.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil {
  324. return err
  325. }
  326. return nil
  327. }
  328. // INSERT is no longer accepted, but we still parse it.
  329. func insert(b *Builder, args []string, attributes map[string]bool, original string) error {
  330. return fmt.Errorf("INSERT has been deprecated. Please use ADD instead")
  331. }