dispatchers.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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. "bytes"
  17. "github.com/Sirupsen/logrus"
  18. "github.com/docker/docker/api"
  19. "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/api/types/container"
  21. "github.com/docker/docker/api/types/strslice"
  22. "github.com/docker/docker/builder"
  23. "github.com/docker/docker/pkg/signal"
  24. "github.com/docker/go-connections/nat"
  25. "github.com/pkg/errors"
  26. )
  27. // ENV foo bar
  28. //
  29. // Sets the environment variable foo to bar, also makes interpolation
  30. // in the dockerfile available from the next statement on via ${foo}.
  31. //
  32. func env(req dispatchRequest) error {
  33. if len(req.args) == 0 {
  34. return errAtLeastOneArgument("ENV")
  35. }
  36. if len(req.args)%2 != 0 {
  37. // should never get here, but just in case
  38. return errTooManyArguments("ENV")
  39. }
  40. if err := req.flags.Parse(); err != nil {
  41. return err
  42. }
  43. commitMessage := bytes.NewBufferString("ENV")
  44. for j := 0; j < len(req.args); j += 2 {
  45. if len(req.args[j]) == 0 {
  46. return errBlankCommandNames("ENV")
  47. }
  48. name := req.args[j]
  49. value := req.args[j+1]
  50. newVar := name + "=" + value
  51. commitMessage.WriteString(" " + newVar)
  52. gotOne := false
  53. for i, envVar := range req.runConfig.Env {
  54. envParts := strings.SplitN(envVar, "=", 2)
  55. compareFrom := envParts[0]
  56. if equalEnvKeys(compareFrom, name) {
  57. req.runConfig.Env[i] = newVar
  58. gotOne = true
  59. break
  60. }
  61. }
  62. if !gotOne {
  63. req.runConfig.Env = append(req.runConfig.Env, newVar)
  64. }
  65. }
  66. return req.builder.commit(commitMessage.String())
  67. }
  68. // MAINTAINER some text <maybe@an.email.address>
  69. //
  70. // Sets the maintainer metadata.
  71. func maintainer(req dispatchRequest) error {
  72. if len(req.args) != 1 {
  73. return errExactlyOneArgument("MAINTAINER")
  74. }
  75. if err := req.flags.Parse(); err != nil {
  76. return err
  77. }
  78. maintainer := req.args[0]
  79. req.builder.maintainer = maintainer
  80. return req.builder.commit("MAINTAINER " + maintainer)
  81. }
  82. // LABEL some json data describing the image
  83. //
  84. // Sets the Label variable foo to bar,
  85. //
  86. func label(req dispatchRequest) error {
  87. if len(req.args) == 0 {
  88. return errAtLeastOneArgument("LABEL")
  89. }
  90. if len(req.args)%2 != 0 {
  91. // should never get here, but just in case
  92. return errTooManyArguments("LABEL")
  93. }
  94. if err := req.flags.Parse(); err != nil {
  95. return err
  96. }
  97. commitStr := "LABEL"
  98. if req.runConfig.Labels == nil {
  99. req.runConfig.Labels = map[string]string{}
  100. }
  101. for j := 0; j < len(req.args); j++ {
  102. // name ==> req.args[j]
  103. // value ==> req.args[j+1]
  104. if len(req.args[j]) == 0 {
  105. return errBlankCommandNames("LABEL")
  106. }
  107. newVar := req.args[j] + "=" + req.args[j+1] + ""
  108. commitStr += " " + newVar
  109. req.runConfig.Labels[req.args[j]] = req.args[j+1]
  110. j++
  111. }
  112. return req.builder.commit(commitStr)
  113. }
  114. // ADD foo /path
  115. //
  116. // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
  117. // exist here. If you do not wish to have this automatic handling, use COPY.
  118. //
  119. func add(req dispatchRequest) error {
  120. if len(req.args) < 2 {
  121. return errAtLeastTwoArguments("ADD")
  122. }
  123. if err := req.flags.Parse(); err != nil {
  124. return err
  125. }
  126. return req.builder.runContextCommand(req.args, true, true, "ADD", nil)
  127. }
  128. // COPY foo /path
  129. //
  130. // Same as 'ADD' but without the tar and remote url handling.
  131. //
  132. func dispatchCopy(req dispatchRequest) error {
  133. if len(req.args) < 2 {
  134. return errAtLeastTwoArguments("COPY")
  135. }
  136. flFrom := req.flags.AddString("from", "")
  137. if err := req.flags.Parse(); err != nil {
  138. return err
  139. }
  140. var im *imageMount
  141. if flFrom.IsUsed() {
  142. var err error
  143. im, err = req.builder.imageContexts.get(flFrom.Value)
  144. if err != nil {
  145. return err
  146. }
  147. }
  148. return req.builder.runContextCommand(req.args, false, false, "COPY", im)
  149. }
  150. // FROM imagename[:tag | @digest] [AS build-stage-name]
  151. //
  152. func from(req dispatchRequest) error {
  153. ctxName, err := parseBuildStageName(req.args)
  154. if err != nil {
  155. return err
  156. }
  157. if err := req.flags.Parse(); err != nil {
  158. return err
  159. }
  160. req.builder.resetImageCache()
  161. if _, err := req.builder.imageContexts.add(ctxName); err != nil {
  162. return err
  163. }
  164. image, err := req.builder.getFromImage(req.shlex, req.args[0])
  165. if err != nil {
  166. return err
  167. }
  168. if image != nil {
  169. req.builder.imageContexts.update(image.ImageID(), image.RunConfig())
  170. }
  171. req.builder.from = image
  172. req.builder.buildArgs.ResetAllowed()
  173. return req.builder.processImageFrom(image)
  174. }
  175. func parseBuildStageName(args []string) (string, error) {
  176. stageName := ""
  177. switch {
  178. case len(args) == 3 && strings.EqualFold(args[1], "as"):
  179. stageName = strings.ToLower(args[2])
  180. if ok, _ := regexp.MatchString("^[a-z][a-z0-9-_\\.]*$", stageName); !ok {
  181. return "", errors.Errorf("invalid name for build stage: %q, name can't start with a number or contain symbols", stageName)
  182. }
  183. case len(args) != 1:
  184. return "", errors.New("FROM requires either one or three arguments")
  185. }
  186. return stageName, nil
  187. }
  188. func (b *Builder) getFromImage(shlex *ShellLex, name string) (builder.Image, error) {
  189. substitutionArgs := []string{}
  190. for key, value := range b.buildArgs.GetAllMeta() {
  191. substitutionArgs = append(substitutionArgs, key+"="+value)
  192. }
  193. name, err := shlex.ProcessWord(name, substitutionArgs)
  194. if err != nil {
  195. return nil, err
  196. }
  197. if im, ok := b.imageContexts.byName[name]; ok {
  198. if len(im.ImageID()) > 0 {
  199. return im, nil
  200. }
  201. // FROM scratch does not have an ImageID
  202. return nil, nil
  203. }
  204. // Windows cannot support a container with no base image.
  205. if name == api.NoBaseImageSpecifier {
  206. if runtime.GOOS == "windows" {
  207. return nil, errors.New("Windows does not support FROM scratch")
  208. }
  209. b.image = ""
  210. b.noBaseImage = true
  211. return nil, nil
  212. }
  213. return pullOrGetImage(b, name)
  214. }
  215. // ONBUILD RUN echo yo
  216. //
  217. // ONBUILD triggers run when the image is used in a FROM statement.
  218. //
  219. // ONBUILD handling has a lot of special-case functionality, the heading in
  220. // evaluator.go and comments around dispatch() in the same file explain the
  221. // special cases. search for 'OnBuild' in internals.go for additional special
  222. // cases.
  223. //
  224. func onbuild(req dispatchRequest) error {
  225. if len(req.args) == 0 {
  226. return errAtLeastOneArgument("ONBUILD")
  227. }
  228. if err := req.flags.Parse(); err != nil {
  229. return err
  230. }
  231. triggerInstruction := strings.ToUpper(strings.TrimSpace(req.args[0]))
  232. switch triggerInstruction {
  233. case "ONBUILD":
  234. return errors.New("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  235. case "MAINTAINER", "FROM":
  236. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
  237. }
  238. original := regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(req.original, "")
  239. req.runConfig.OnBuild = append(req.runConfig.OnBuild, original)
  240. return req.builder.commit("ONBUILD " + original)
  241. }
  242. // WORKDIR /tmp
  243. //
  244. // Set the working directory for future RUN/CMD/etc statements.
  245. //
  246. func workdir(req dispatchRequest) error {
  247. if len(req.args) != 1 {
  248. return errExactlyOneArgument("WORKDIR")
  249. }
  250. err := req.flags.Parse()
  251. if err != nil {
  252. return err
  253. }
  254. // This is from the Dockerfile and will not necessarily be in platform
  255. // specific semantics, hence ensure it is converted.
  256. req.runConfig.WorkingDir, err = normaliseWorkdir(req.runConfig.WorkingDir, req.args[0])
  257. if err != nil {
  258. return err
  259. }
  260. // For performance reasons, we explicitly do a create/mkdir now
  261. // This avoids having an unnecessary expensive mount/unmount calls
  262. // (on Windows in particular) during each container create.
  263. // Prior to 1.13, the mkdir was deferred and not executed at this step.
  264. if req.builder.disableCommit {
  265. // Don't call back into the daemon if we're going through docker commit --change "WORKDIR /foo".
  266. // We've already updated the runConfig and that's enough.
  267. return nil
  268. }
  269. // TODO: why is this done here. This seems to be done at random places all over
  270. // the builder
  271. req.runConfig.Image = req.builder.image
  272. comment := "WORKDIR " + req.runConfig.WorkingDir
  273. runConfigWithCommentCmd := copyRunConfig(req.runConfig, withCmdCommentString(comment))
  274. if hit, err := req.builder.probeCache(req.builder.image, runConfigWithCommentCmd); err != nil || hit {
  275. return err
  276. }
  277. container, err := req.builder.docker.ContainerCreate(types.ContainerCreateConfig{
  278. Config: runConfigWithCommentCmd,
  279. // Set a log config to override any default value set on the daemon
  280. HostConfig: &container.HostConfig{LogConfig: defaultLogConfig},
  281. })
  282. if err != nil {
  283. return err
  284. }
  285. req.builder.tmpContainers[container.ID] = struct{}{}
  286. if err := req.builder.docker.ContainerCreateWorkdir(container.ID); err != nil {
  287. return err
  288. }
  289. return req.builder.commitContainer(container.ID, runConfigWithCommentCmd)
  290. }
  291. // RUN some command yo
  292. //
  293. // run a command and commit the image. Args are automatically prepended with
  294. // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
  295. // Windows, in the event there is only one argument The difference in processing:
  296. //
  297. // RUN echo hi # sh -c echo hi (Linux)
  298. // RUN echo hi # cmd /S /C echo hi (Windows)
  299. // RUN [ "echo", "hi" ] # echo hi
  300. //
  301. func run(req dispatchRequest) error {
  302. if !req.builder.hasFromImage() {
  303. return errors.New("Please provide a source image with `from` prior to run")
  304. }
  305. if err := req.flags.Parse(); err != nil {
  306. return err
  307. }
  308. args := handleJSONArgs(req.args, req.attributes)
  309. if !req.attributes["json"] {
  310. args = append(getShell(req.runConfig), args...)
  311. }
  312. cmdFromArgs := strslice.StrSlice(args)
  313. buildArgs := req.builder.buildArgsWithoutConfigEnv()
  314. saveCmd := cmdFromArgs
  315. if len(buildArgs) > 0 {
  316. saveCmd = prependEnvOnCmd(req.builder.buildArgs, buildArgs, cmdFromArgs)
  317. }
  318. // TODO: this was previously in b.create(), why is it necessary?
  319. req.runConfig.Image = req.builder.image
  320. runConfigForCacheProbe := copyRunConfig(req.runConfig, withCmd(saveCmd))
  321. hit, err := req.builder.probeCache(req.builder.image, runConfigForCacheProbe)
  322. if err != nil || hit {
  323. return err
  324. }
  325. runConfig := copyRunConfig(req.runConfig,
  326. withCmd(cmdFromArgs),
  327. withEnv(append(req.runConfig.Env, buildArgs...)))
  328. // set config as already being escaped, this prevents double escaping on windows
  329. runConfig.ArgsEscaped = true
  330. logrus.Debugf("[BUILDER] Command to be executed: %v", runConfig.Cmd)
  331. cID, err := req.builder.create(runConfig)
  332. if err != nil {
  333. return err
  334. }
  335. if err := req.builder.run(cID, runConfig.Cmd); err != nil {
  336. return err
  337. }
  338. return req.builder.commitContainer(cID, runConfigForCacheProbe)
  339. }
  340. // Derive the command to use for probeCache() and to commit in this container.
  341. // Note that we only do this if there are any build-time env vars. Also, we
  342. // use the special argument "|#" at the start of the args array. This will
  343. // avoid conflicts with any RUN command since commands can not
  344. // start with | (vertical bar). The "#" (number of build envs) is there to
  345. // help ensure proper cache matches. We don't want a RUN command
  346. // that starts with "foo=abc" to be considered part of a build-time env var.
  347. //
  348. // remove any unreferenced built-in args from the environment variables.
  349. // These args are transparent so resulting image should be the same regardless
  350. // of the value.
  351. func prependEnvOnCmd(buildArgs *buildArgs, buildArgVars []string, cmd strslice.StrSlice) strslice.StrSlice {
  352. var tmpBuildEnv []string
  353. for _, env := range buildArgVars {
  354. key := strings.SplitN(env, "=", 2)[0]
  355. if !buildArgs.IsUnreferencedBuiltin(key) {
  356. tmpBuildEnv = append(tmpBuildEnv, env)
  357. }
  358. }
  359. sort.Strings(tmpBuildEnv)
  360. tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...)
  361. return strslice.StrSlice(append(tmpEnv, cmd...))
  362. }
  363. // CMD foo
  364. //
  365. // Set the default command to run in the container (which may be empty).
  366. // Argument handling is the same as RUN.
  367. //
  368. func cmd(req dispatchRequest) error {
  369. if err := req.flags.Parse(); err != nil {
  370. return err
  371. }
  372. cmdSlice := handleJSONArgs(req.args, req.attributes)
  373. if !req.attributes["json"] {
  374. cmdSlice = append(getShell(req.runConfig), cmdSlice...)
  375. }
  376. req.runConfig.Cmd = strslice.StrSlice(cmdSlice)
  377. // set config as already being escaped, this prevents double escaping on windows
  378. req.runConfig.ArgsEscaped = true
  379. if err := req.builder.commit(fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
  380. return err
  381. }
  382. if len(req.args) != 0 {
  383. req.builder.cmdSet = true
  384. }
  385. return nil
  386. }
  387. // parseOptInterval(flag) is the duration of flag.Value, or 0 if
  388. // empty. An error is reported if the value is given and less than minimum duration.
  389. func parseOptInterval(f *Flag) (time.Duration, error) {
  390. s := f.Value
  391. if s == "" {
  392. return 0, nil
  393. }
  394. d, err := time.ParseDuration(s)
  395. if err != nil {
  396. return 0, err
  397. }
  398. if d < time.Duration(container.MinimumDuration) {
  399. return 0, fmt.Errorf("Interval %#v cannot be less than %s", f.name, container.MinimumDuration)
  400. }
  401. return d, nil
  402. }
  403. // HEALTHCHECK foo
  404. //
  405. // Set the default healthcheck command to run in the container (which may be empty).
  406. // Argument handling is the same as RUN.
  407. //
  408. func healthcheck(req dispatchRequest) error {
  409. if len(req.args) == 0 {
  410. return errAtLeastOneArgument("HEALTHCHECK")
  411. }
  412. typ := strings.ToUpper(req.args[0])
  413. args := req.args[1:]
  414. if typ == "NONE" {
  415. if len(args) != 0 {
  416. return errors.New("HEALTHCHECK NONE takes no arguments")
  417. }
  418. test := strslice.StrSlice{typ}
  419. req.runConfig.Healthcheck = &container.HealthConfig{
  420. Test: test,
  421. }
  422. } else {
  423. if req.runConfig.Healthcheck != nil {
  424. oldCmd := req.runConfig.Healthcheck.Test
  425. if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
  426. fmt.Fprintf(req.builder.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
  427. }
  428. }
  429. healthcheck := container.HealthConfig{}
  430. flInterval := req.flags.AddString("interval", "")
  431. flTimeout := req.flags.AddString("timeout", "")
  432. flStartPeriod := req.flags.AddString("start-period", "")
  433. flRetries := req.flags.AddString("retries", "")
  434. if err := req.flags.Parse(); err != nil {
  435. return err
  436. }
  437. switch typ {
  438. case "CMD":
  439. cmdSlice := handleJSONArgs(args, req.attributes)
  440. if len(cmdSlice) == 0 {
  441. return errors.New("Missing command after HEALTHCHECK CMD")
  442. }
  443. if !req.attributes["json"] {
  444. typ = "CMD-SHELL"
  445. }
  446. healthcheck.Test = strslice.StrSlice(append([]string{typ}, cmdSlice...))
  447. default:
  448. return fmt.Errorf("Unknown type %#v in HEALTHCHECK (try CMD)", typ)
  449. }
  450. interval, err := parseOptInterval(flInterval)
  451. if err != nil {
  452. return err
  453. }
  454. healthcheck.Interval = interval
  455. timeout, err := parseOptInterval(flTimeout)
  456. if err != nil {
  457. return err
  458. }
  459. healthcheck.Timeout = timeout
  460. startPeriod, err := parseOptInterval(flStartPeriod)
  461. if err != nil {
  462. return err
  463. }
  464. healthcheck.StartPeriod = startPeriod
  465. if flRetries.Value != "" {
  466. retries, err := strconv.ParseInt(flRetries.Value, 10, 32)
  467. if err != nil {
  468. return err
  469. }
  470. if retries < 1 {
  471. return fmt.Errorf("--retries must be at least 1 (not %d)", retries)
  472. }
  473. healthcheck.Retries = int(retries)
  474. } else {
  475. healthcheck.Retries = 0
  476. }
  477. req.runConfig.Healthcheck = &healthcheck
  478. }
  479. return req.builder.commit(fmt.Sprintf("HEALTHCHECK %q", req.runConfig.Healthcheck))
  480. }
  481. // ENTRYPOINT /usr/sbin/nginx
  482. //
  483. // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
  484. // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
  485. //
  486. // Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
  487. // is initialized at newBuilder time instead of through argument parsing.
  488. //
  489. func entrypoint(req dispatchRequest) error {
  490. if err := req.flags.Parse(); err != nil {
  491. return err
  492. }
  493. parsed := handleJSONArgs(req.args, req.attributes)
  494. switch {
  495. case req.attributes["json"]:
  496. // ENTRYPOINT ["echo", "hi"]
  497. req.runConfig.Entrypoint = strslice.StrSlice(parsed)
  498. case len(parsed) == 0:
  499. // ENTRYPOINT []
  500. req.runConfig.Entrypoint = nil
  501. default:
  502. // ENTRYPOINT echo hi
  503. req.runConfig.Entrypoint = strslice.StrSlice(append(getShell(req.runConfig), parsed[0]))
  504. }
  505. // when setting the entrypoint if a CMD was not explicitly set then
  506. // set the command to nil
  507. if !req.builder.cmdSet {
  508. req.runConfig.Cmd = nil
  509. }
  510. return req.builder.commit(fmt.Sprintf("ENTRYPOINT %q", req.runConfig.Entrypoint))
  511. }
  512. // EXPOSE 6667/tcp 7000/tcp
  513. //
  514. // Expose ports for links and port mappings. This all ends up in
  515. // req.runConfig.ExposedPorts for runconfig.
  516. //
  517. func expose(req dispatchRequest) error {
  518. portsTab := req.args
  519. if len(req.args) == 0 {
  520. return errAtLeastOneArgument("EXPOSE")
  521. }
  522. if err := req.flags.Parse(); err != nil {
  523. return err
  524. }
  525. if req.runConfig.ExposedPorts == nil {
  526. req.runConfig.ExposedPorts = make(nat.PortSet)
  527. }
  528. ports, _, err := nat.ParsePortSpecs(portsTab)
  529. if err != nil {
  530. return err
  531. }
  532. // instead of using ports directly, we build a list of ports and sort it so
  533. // the order is consistent. This prevents cache burst where map ordering
  534. // changes between builds
  535. portList := make([]string, len(ports))
  536. var i int
  537. for port := range ports {
  538. if _, exists := req.runConfig.ExposedPorts[port]; !exists {
  539. req.runConfig.ExposedPorts[port] = struct{}{}
  540. }
  541. portList[i] = string(port)
  542. i++
  543. }
  544. sort.Strings(portList)
  545. return req.builder.commit("EXPOSE " + strings.Join(portList, " "))
  546. }
  547. // USER foo
  548. //
  549. // Set the user to 'foo' for future commands and when running the
  550. // ENTRYPOINT/CMD at container run time.
  551. //
  552. func user(req dispatchRequest) error {
  553. if len(req.args) != 1 {
  554. return errExactlyOneArgument("USER")
  555. }
  556. if err := req.flags.Parse(); err != nil {
  557. return err
  558. }
  559. req.runConfig.User = req.args[0]
  560. return req.builder.commit(fmt.Sprintf("USER %v", req.args))
  561. }
  562. // VOLUME /foo
  563. //
  564. // Expose the volume /foo for use. Will also accept the JSON array form.
  565. //
  566. func volume(req dispatchRequest) error {
  567. if len(req.args) == 0 {
  568. return errAtLeastOneArgument("VOLUME")
  569. }
  570. if err := req.flags.Parse(); err != nil {
  571. return err
  572. }
  573. if req.runConfig.Volumes == nil {
  574. req.runConfig.Volumes = map[string]struct{}{}
  575. }
  576. for _, v := range req.args {
  577. v = strings.TrimSpace(v)
  578. if v == "" {
  579. return errors.New("VOLUME specified can not be an empty string")
  580. }
  581. req.runConfig.Volumes[v] = struct{}{}
  582. }
  583. return req.builder.commit(fmt.Sprintf("VOLUME %v", req.args))
  584. }
  585. // STOPSIGNAL signal
  586. //
  587. // Set the signal that will be used to kill the container.
  588. func stopSignal(req dispatchRequest) error {
  589. if len(req.args) != 1 {
  590. return errExactlyOneArgument("STOPSIGNAL")
  591. }
  592. sig := req.args[0]
  593. _, err := signal.ParseSignal(sig)
  594. if err != nil {
  595. return err
  596. }
  597. req.runConfig.StopSignal = sig
  598. return req.builder.commit(fmt.Sprintf("STOPSIGNAL %v", req.args))
  599. }
  600. // ARG name[=value]
  601. //
  602. // Adds the variable foo to the trusted list of variables that can be passed
  603. // to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
  604. // Dockerfile author may optionally set a default value of this variable.
  605. func arg(req dispatchRequest) error {
  606. if len(req.args) != 1 {
  607. return errExactlyOneArgument("ARG")
  608. }
  609. var (
  610. name string
  611. newValue string
  612. hasDefault bool
  613. )
  614. arg := req.args[0]
  615. // 'arg' can just be a name or name-value pair. Note that this is different
  616. // from 'env' that handles the split of name and value at the parser level.
  617. // The reason for doing it differently for 'arg' is that we support just
  618. // defining an arg and not assign it a value (while 'env' always expects a
  619. // name-value pair). If possible, it will be good to harmonize the two.
  620. if strings.Contains(arg, "=") {
  621. parts := strings.SplitN(arg, "=", 2)
  622. if len(parts[0]) == 0 {
  623. return errBlankCommandNames("ARG")
  624. }
  625. name = parts[0]
  626. newValue = parts[1]
  627. hasDefault = true
  628. } else {
  629. name = arg
  630. hasDefault = false
  631. }
  632. var value *string
  633. if hasDefault {
  634. value = &newValue
  635. }
  636. req.builder.buildArgs.AddArg(name, value)
  637. // Arg before FROM doesn't add a layer
  638. if !req.builder.hasFromImage() {
  639. req.builder.buildArgs.AddMetaArg(name, value)
  640. return nil
  641. }
  642. return req.builder.commit("ARG " + arg)
  643. }
  644. // SHELL powershell -command
  645. //
  646. // Set the non-default shell to use.
  647. func shell(req dispatchRequest) error {
  648. if err := req.flags.Parse(); err != nil {
  649. return err
  650. }
  651. shellSlice := handleJSONArgs(req.args, req.attributes)
  652. switch {
  653. case len(shellSlice) == 0:
  654. // SHELL []
  655. return errAtLeastOneArgument("SHELL")
  656. case req.attributes["json"]:
  657. // SHELL ["powershell", "-command"]
  658. req.runConfig.Shell = strslice.StrSlice(shellSlice)
  659. default:
  660. // SHELL powershell -command - not JSON
  661. return errNotJSON("SHELL", req.original)
  662. }
  663. return req.builder.commit(fmt.Sprintf("SHELL %v", shellSlice))
  664. }
  665. func errAtLeastOneArgument(command string) error {
  666. return fmt.Errorf("%s requires at least one argument", command)
  667. }
  668. func errExactlyOneArgument(command string) error {
  669. return fmt.Errorf("%s requires exactly one argument", command)
  670. }
  671. func errAtLeastTwoArguments(command string) error {
  672. return fmt.Errorf("%s requires at least two arguments", command)
  673. }
  674. func errBlankCommandNames(command string) error {
  675. return fmt.Errorf("%s names can not be blank", command)
  676. }
  677. func errTooManyArguments(command string) error {
  678. return fmt.Errorf("Bad input to %s, too many arguments", command)
  679. }
  680. // mountByRef creates an imageMount from a reference. pulling the image if needed.
  681. func mountByRef(b *Builder, name string) (*imageMount, error) {
  682. image, err := pullOrGetImage(b, name)
  683. if err != nil {
  684. return nil, err
  685. }
  686. im := b.imageContexts.newImageMount(image.ImageID())
  687. return im, nil
  688. }
  689. func pullOrGetImage(b *Builder, name string) (builder.Image, error) {
  690. var image builder.Image
  691. if !b.options.PullParent {
  692. image, _ = b.docker.GetImageOnBuild(name)
  693. // TODO: shouldn't we error out if error is different from "not found" ?
  694. }
  695. if image == nil {
  696. var err error
  697. image, err = b.docker.PullOnBuild(b.clientCtx, name, b.options.AuthConfigs, b.Output)
  698. if err != nil {
  699. return nil, err
  700. }
  701. }
  702. return image, nil
  703. }