evaluator.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. "strconv"
  24. "strings"
  25. "github.com/docker/docker/api/types/container"
  26. "github.com/docker/docker/builder"
  27. "github.com/docker/docker/builder/dockerfile/instructions"
  28. "github.com/docker/docker/errdefs"
  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) (err error) {
  34. if c, ok := cmd.(instructions.PlatformSpecific); ok {
  35. optionsOS := system.ParsePlatform(d.builder.options.Platform).OS
  36. err := c.CheckPlatform(optionsOS)
  37. if err != nil {
  38. return errdefs.InvalidParameter(err)
  39. }
  40. }
  41. runConfigEnv := d.state.runConfig.Env
  42. envs := append(runConfigEnv, d.state.buildArgs.FilterAllowed(runConfigEnv)...)
  43. if ex, ok := cmd.(instructions.SupportsSingleWordExpansion); ok {
  44. err := ex.Expand(func(word string) (string, error) {
  45. return d.shlex.ProcessWord(word, envs)
  46. })
  47. if err != nil {
  48. return errdefs.InvalidParameter(err)
  49. }
  50. }
  51. defer func() {
  52. if d.builder.options.ForceRemove {
  53. d.builder.containerManager.RemoveAll(d.builder.Stdout)
  54. return
  55. }
  56. if d.builder.options.Remove && err == nil {
  57. d.builder.containerManager.RemoveAll(d.builder.Stdout)
  58. return
  59. }
  60. }()
  61. switch c := cmd.(type) {
  62. case *instructions.EnvCommand:
  63. return dispatchEnv(d, c)
  64. case *instructions.MaintainerCommand:
  65. return dispatchMaintainer(d, c)
  66. case *instructions.LabelCommand:
  67. return dispatchLabel(d, c)
  68. case *instructions.AddCommand:
  69. return dispatchAdd(d, c)
  70. case *instructions.CopyCommand:
  71. return dispatchCopy(d, c)
  72. case *instructions.OnbuildCommand:
  73. return dispatchOnbuild(d, c)
  74. case *instructions.WorkdirCommand:
  75. return dispatchWorkdir(d, c)
  76. case *instructions.RunCommand:
  77. return dispatchRun(d, c)
  78. case *instructions.CmdCommand:
  79. return dispatchCmd(d, c)
  80. case *instructions.HealthCheckCommand:
  81. return dispatchHealthcheck(d, c)
  82. case *instructions.EntrypointCommand:
  83. return dispatchEntrypoint(d, c)
  84. case *instructions.ExposeCommand:
  85. return dispatchExpose(d, c, envs)
  86. case *instructions.UserCommand:
  87. return dispatchUser(d, c)
  88. case *instructions.VolumeCommand:
  89. return dispatchVolume(d, c)
  90. case *instructions.StopSignalCommand:
  91. return dispatchStopSignal(d, c)
  92. case *instructions.ArgCommand:
  93. return dispatchArg(d, c)
  94. case *instructions.ShellCommand:
  95. return dispatchShell(d, c)
  96. }
  97. return errors.Errorf("unsupported command type: %v", reflect.TypeOf(cmd))
  98. }
  99. // dispatchState is a data object which is modified by dispatchers
  100. type dispatchState struct {
  101. runConfig *container.Config
  102. maintainer string
  103. cmdSet bool
  104. imageID string
  105. baseImage builder.Image
  106. stageName string
  107. buildArgs *buildArgs
  108. }
  109. func newDispatchState(baseArgs *buildArgs) *dispatchState {
  110. args := baseArgs.Clone()
  111. args.ResetAllowed()
  112. return &dispatchState{runConfig: &container.Config{}, buildArgs: args}
  113. }
  114. type stagesBuildResults struct {
  115. flat []*container.Config
  116. indexed map[string]*container.Config
  117. }
  118. func newStagesBuildResults() *stagesBuildResults {
  119. return &stagesBuildResults{
  120. indexed: make(map[string]*container.Config),
  121. }
  122. }
  123. func (r *stagesBuildResults) getByName(name string) (*container.Config, bool) {
  124. c, ok := r.indexed[strings.ToLower(name)]
  125. return c, ok
  126. }
  127. func (r *stagesBuildResults) validateIndex(i int) error {
  128. if i == len(r.flat) {
  129. return errors.New("refers to current build stage")
  130. }
  131. if i < 0 || i > len(r.flat) {
  132. return errors.New("index out of bounds")
  133. }
  134. return nil
  135. }
  136. func (r *stagesBuildResults) get(nameOrIndex string) (*container.Config, error) {
  137. if c, ok := r.getByName(nameOrIndex); ok {
  138. return c, nil
  139. }
  140. ix, err := strconv.ParseInt(nameOrIndex, 10, 0)
  141. if err != nil {
  142. return nil, nil
  143. }
  144. if err := r.validateIndex(int(ix)); err != nil {
  145. return nil, err
  146. }
  147. return r.flat[ix], nil
  148. }
  149. func (r *stagesBuildResults) checkStageNameAvailable(name string) error {
  150. if name != "" {
  151. if _, ok := r.getByName(name); ok {
  152. return errors.Errorf("%s stage name already used", name)
  153. }
  154. }
  155. return nil
  156. }
  157. func (r *stagesBuildResults) commitStage(name string, config *container.Config) error {
  158. if name != "" {
  159. if _, ok := r.getByName(name); ok {
  160. return errors.Errorf("%s stage name already used", name)
  161. }
  162. r.indexed[strings.ToLower(name)] = config
  163. }
  164. r.flat = append(r.flat, config)
  165. return nil
  166. }
  167. func commitStage(state *dispatchState, stages *stagesBuildResults) error {
  168. return stages.commitStage(state.stageName, state.runConfig)
  169. }
  170. type dispatchRequest struct {
  171. state *dispatchState
  172. shlex *ShellLex
  173. builder *Builder
  174. source builder.Source
  175. stages *stagesBuildResults
  176. }
  177. func newDispatchRequest(builder *Builder, escapeToken rune, source builder.Source, buildArgs *buildArgs, stages *stagesBuildResults) dispatchRequest {
  178. return dispatchRequest{
  179. state: newDispatchState(buildArgs),
  180. shlex: NewShellLex(escapeToken),
  181. builder: builder,
  182. source: source,
  183. stages: stages,
  184. }
  185. }
  186. func (s *dispatchState) updateRunConfig() {
  187. s.runConfig.Image = s.imageID
  188. }
  189. // hasFromImage returns true if the builder has processed a `FROM <image>` line
  190. func (s *dispatchState) hasFromImage() bool {
  191. return s.imageID != "" || (s.baseImage != nil && s.baseImage.ImageID() == "")
  192. }
  193. func (s *dispatchState) beginStage(stageName string, image builder.Image) {
  194. s.stageName = stageName
  195. s.imageID = image.ImageID()
  196. if image.RunConfig() != nil {
  197. // copy avoids referencing the same instance when 2 stages have the same base
  198. s.runConfig = copyRunConfig(image.RunConfig())
  199. } else {
  200. s.runConfig = &container.Config{}
  201. }
  202. s.baseImage = image
  203. s.setDefaultPath()
  204. s.runConfig.OpenStdin = false
  205. s.runConfig.StdinOnce = false
  206. }
  207. // Add the default PATH to runConfig.ENV if one exists for the operating system and there
  208. // is no PATH set. Note that Windows containers on Windows won't have one as it's set by HCS
  209. func (s *dispatchState) setDefaultPath() {
  210. defaultPath := system.DefaultPathEnv(s.baseImage.OperatingSystem())
  211. if defaultPath == "" {
  212. return
  213. }
  214. envMap := opts.ConvertKVStringsToMap(s.runConfig.Env)
  215. if _, ok := envMap["PATH"]; !ok {
  216. s.runConfig.Env = append(s.runConfig.Env, "PATH="+defaultPath)
  217. }
  218. }