dispatchers.go 9.3 KB

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