evaluator.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // Package dockerfile is the evaluation step in the Dockerfile parse/evaluate pipeline.
  2. //
  3. // It incorporates a dispatch table based on the parser.Node values (see the
  4. // parser package for more information) that are yielded from the parser itself.
  5. // Calling newBuilder with the BuildOpts struct can be used to customize the
  6. // experience for execution purposes only. Parsing is controlled in the parser
  7. // package, and this division of responsibility should be respected.
  8. //
  9. // Please see the jump table targets for the actual invocations, most of which
  10. // will call out to the functions in internals.go to deal with their tasks.
  11. //
  12. // ONBUILD is a special case, which is covered in the onbuild() func in
  13. // dispatchers.go.
  14. //
  15. // The evaluator uses the concept of "steps", which are usually each processable
  16. // line in the Dockerfile. Each step is numbered and certain actions are taken
  17. // before and after each step, such as creating an image ID and removing temporary
  18. // containers and images. Note that ONBUILD creates a kinda-sorta "sub run" which
  19. // includes its own set of steps (usually only one of them).
  20. package dockerfile
  21. import (
  22. "reflect"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "github.com/docker/docker/api/types/container"
  27. "github.com/docker/docker/builder"
  28. "github.com/docker/docker/builder/dockerfile/instructions"
  29. "github.com/docker/docker/pkg/system"
  30. "github.com/docker/docker/runconfig/opts"
  31. "github.com/pkg/errors"
  32. )
  33. func dispatch(d dispatchRequest, cmd instructions.Command) error {
  34. if c, ok := cmd.(instructions.PlatformSpecific); ok {
  35. err := c.CheckPlatform(d.builder.platform)
  36. if err != nil {
  37. return validationError{err}
  38. }
  39. }
  40. runConfigEnv := d.state.runConfig.Env
  41. envs := append(runConfigEnv, d.state.buildArgs.FilterAllowed(runConfigEnv)...)
  42. if ex, ok := cmd.(instructions.SupportsSingleWordExpansion); ok {
  43. err := ex.Expand(func(word string) (string, error) {
  44. return d.shlex.ProcessWord(word, envs)
  45. })
  46. if err != nil {
  47. return validationError{err}
  48. }
  49. }
  50. if d.builder.options.ForceRemove {
  51. defer d.builder.containerManager.RemoveAll(d.builder.Stdout)
  52. }
  53. switch c := cmd.(type) {
  54. case *instructions.EnvCommand:
  55. return dispatchEnv(d, c)
  56. case *instructions.MaintainerCommand:
  57. return dispatchMaintainer(d, c)
  58. case *instructions.LabelCommand:
  59. return dispatchLabel(d, c)
  60. case *instructions.AddCommand:
  61. return dispatchAdd(d, c)
  62. case *instructions.CopyCommand:
  63. return dispatchCopy(d, c)
  64. case *instructions.OnbuildCommand:
  65. return dispatchOnbuild(d, c)
  66. case *instructions.WorkdirCommand:
  67. return dispatchWorkdir(d, c)
  68. case *instructions.RunCommand:
  69. return dispatchRun(d, c)
  70. case *instructions.CmdCommand:
  71. return dispatchCmd(d, c)
  72. case *instructions.HealthCheckCommand:
  73. return dispatchHealthcheck(d, c)
  74. case *instructions.EntrypointCommand:
  75. return dispatchEntrypoint(d, c)
  76. case *instructions.ExposeCommand:
  77. return dispatchExpose(d, c, envs)
  78. case *instructions.UserCommand:
  79. return dispatchUser(d, c)
  80. case *instructions.VolumeCommand:
  81. return dispatchVolume(d, c)
  82. case *instructions.StopSignalCommand:
  83. return dispatchStopSignal(d, c)
  84. case *instructions.ArgCommand:
  85. return dispatchArg(d, c)
  86. case *instructions.ShellCommand:
  87. return dispatchShell(d, c)
  88. }
  89. return errors.Errorf("unsupported command type: %v", reflect.TypeOf(cmd))
  90. }
  91. // dispatchState is a data object which is modified by dispatchers
  92. type dispatchState struct {
  93. runConfig *container.Config
  94. maintainer string
  95. cmdSet bool
  96. imageID string
  97. baseImage builder.Image
  98. stageName string
  99. buildArgs *buildArgs
  100. }
  101. func newDispatchState(baseArgs *buildArgs) *dispatchState {
  102. args := baseArgs.Clone()
  103. args.ResetAllowed()
  104. return &dispatchState{runConfig: &container.Config{}, buildArgs: args}
  105. }
  106. type stagesBuildResults struct {
  107. flat []*container.Config
  108. indexed map[string]*container.Config
  109. }
  110. func newStagesBuildResults() *stagesBuildResults {
  111. return &stagesBuildResults{
  112. indexed: make(map[string]*container.Config),
  113. }
  114. }
  115. func (r *stagesBuildResults) getByName(name string) (*container.Config, bool) {
  116. c, ok := r.indexed[strings.ToLower(name)]
  117. return c, ok
  118. }
  119. func (r *stagesBuildResults) validateIndex(i int) error {
  120. if i == len(r.flat) {
  121. return errors.New("refers to current build stage")
  122. }
  123. if i < 0 || i > len(r.flat) {
  124. return errors.New("index out of bounds")
  125. }
  126. return nil
  127. }
  128. func (r *stagesBuildResults) get(nameOrIndex string) (*container.Config, error) {
  129. if c, ok := r.getByName(nameOrIndex); ok {
  130. return c, nil
  131. }
  132. ix, err := strconv.ParseInt(nameOrIndex, 10, 0)
  133. if err != nil {
  134. return nil, nil
  135. }
  136. if err := r.validateIndex(int(ix)); err != nil {
  137. return nil, err
  138. }
  139. return r.flat[ix], nil
  140. }
  141. func (r *stagesBuildResults) checkStageNameAvailable(name string) error {
  142. if name != "" {
  143. if _, ok := r.getByName(name); ok {
  144. return errors.Errorf("%s stage name already used", name)
  145. }
  146. }
  147. return nil
  148. }
  149. func (r *stagesBuildResults) commitStage(name string, config *container.Config) error {
  150. if name != "" {
  151. if _, ok := r.getByName(name); ok {
  152. return errors.Errorf("%s stage name already used", name)
  153. }
  154. r.indexed[strings.ToLower(name)] = config
  155. }
  156. r.flat = append(r.flat, config)
  157. return nil
  158. }
  159. func commitStage(state *dispatchState, stages *stagesBuildResults) error {
  160. return stages.commitStage(state.stageName, state.runConfig)
  161. }
  162. type dispatchRequest struct {
  163. state *dispatchState
  164. shlex *ShellLex
  165. builder *Builder
  166. source builder.Source
  167. stages *stagesBuildResults
  168. }
  169. func newDispatchRequest(builder *Builder, escapeToken rune, source builder.Source, buildArgs *buildArgs, stages *stagesBuildResults) dispatchRequest {
  170. return dispatchRequest{
  171. state: newDispatchState(buildArgs),
  172. shlex: NewShellLex(escapeToken),
  173. builder: builder,
  174. source: source,
  175. stages: stages,
  176. }
  177. }
  178. func (s *dispatchState) updateRunConfig() {
  179. s.runConfig.Image = s.imageID
  180. }
  181. // hasFromImage returns true if the builder has processed a `FROM <image>` line
  182. func (s *dispatchState) hasFromImage() bool {
  183. return s.imageID != "" || (s.baseImage != nil && s.baseImage.ImageID() == "")
  184. }
  185. func (s *dispatchState) isCurrentStage(target string) bool {
  186. if target == "" {
  187. return false
  188. }
  189. return strings.EqualFold(s.stageName, target)
  190. }
  191. func (s *dispatchState) beginStage(stageName string, image builder.Image) {
  192. s.stageName = stageName
  193. s.imageID = image.ImageID()
  194. if image.RunConfig() != nil {
  195. s.runConfig = copyRunConfig(image.RunConfig()) // copy avoids referencing the same instance when 2 stages have the same base
  196. } else {
  197. s.runConfig = &container.Config{}
  198. }
  199. s.baseImage = image
  200. s.setDefaultPath()
  201. s.runConfig.OpenStdin = false
  202. s.runConfig.StdinOnce = false
  203. }
  204. // Add the default PATH to runConfig.ENV if one exists for the platform and there
  205. // is no PATH set. Note that Windows containers on Windows won't have one as it's set by HCS
  206. func (s *dispatchState) setDefaultPath() {
  207. // TODO @jhowardmsft LCOW Support - This will need revisiting later
  208. platform := runtime.GOOS
  209. if system.LCOWSupported() {
  210. platform = "linux"
  211. }
  212. if system.DefaultPathEnv(platform) == "" {
  213. return
  214. }
  215. envMap := opts.ConvertKVStringsToMap(s.runConfig.Env)
  216. if _, ok := envMap["PATH"]; !ok {
  217. s.runConfig.Env = append(s.runConfig.Env, "PATH="+system.DefaultPathEnv(platform))
  218. }
  219. }