dispatchers.go 24 KB

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