evaluator.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 // import "github.com/docker/docker/builder/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/errdefs"
  28. "github.com/docker/docker/pkg/system"
  29. "github.com/docker/docker/runconfig/opts"
  30. "github.com/moby/buildkit/frontend/dockerfile/instructions"
  31. "github.com/moby/buildkit/frontend/dockerfile/shell"
  32. "github.com/pkg/errors"
  33. )
  34. func dispatch(d dispatchRequest, cmd instructions.Command) (err error) {
  35. if c, ok := cmd.(instructions.PlatformSpecific); ok {
  36. err := c.CheckPlatform(d.state.operatingSystem)
  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. operatingSystem string
  109. }
  110. func newDispatchState(baseArgs *BuildArgs) *dispatchState {
  111. args := baseArgs.Clone()
  112. args.ResetAllowed()
  113. return &dispatchState{runConfig: &container.Config{}, buildArgs: args}
  114. }
  115. type stagesBuildResults struct {
  116. flat []*container.Config
  117. indexed map[string]*container.Config
  118. }
  119. func newStagesBuildResults() *stagesBuildResults {
  120. return &stagesBuildResults{
  121. indexed: make(map[string]*container.Config),
  122. }
  123. }
  124. func (r *stagesBuildResults) getByName(name string) (*container.Config, bool) {
  125. c, ok := r.indexed[strings.ToLower(name)]
  126. return c, ok
  127. }
  128. func (r *stagesBuildResults) validateIndex(i int) error {
  129. if i == len(r.flat) {
  130. return errors.New("refers to current build stage")
  131. }
  132. if i < 0 || i > len(r.flat) {
  133. return errors.New("index out of bounds")
  134. }
  135. return nil
  136. }
  137. func (r *stagesBuildResults) get(nameOrIndex string) (*container.Config, error) {
  138. if c, ok := r.getByName(nameOrIndex); ok {
  139. return c, nil
  140. }
  141. ix, err := strconv.ParseInt(nameOrIndex, 10, 0)
  142. if err != nil {
  143. return nil, nil
  144. }
  145. if err := r.validateIndex(int(ix)); err != nil {
  146. return nil, err
  147. }
  148. return r.flat[ix], nil
  149. }
  150. func (r *stagesBuildResults) checkStageNameAvailable(name string) error {
  151. if name != "" {
  152. if _, ok := r.getByName(name); ok {
  153. return errors.Errorf("%s stage name already used", name)
  154. }
  155. }
  156. return nil
  157. }
  158. func (r *stagesBuildResults) commitStage(name string, config *container.Config) error {
  159. if name != "" {
  160. if _, ok := r.getByName(name); ok {
  161. return errors.Errorf("%s stage name already used", name)
  162. }
  163. r.indexed[strings.ToLower(name)] = config
  164. }
  165. r.flat = append(r.flat, config)
  166. return nil
  167. }
  168. func commitStage(state *dispatchState, stages *stagesBuildResults) error {
  169. return stages.commitStage(state.stageName, state.runConfig)
  170. }
  171. type dispatchRequest struct {
  172. state *dispatchState
  173. shlex *shell.Lex
  174. builder *Builder
  175. source builder.Source
  176. stages *stagesBuildResults
  177. }
  178. func newDispatchRequest(builder *Builder, escapeToken rune, source builder.Source, buildArgs *BuildArgs, stages *stagesBuildResults) dispatchRequest {
  179. return dispatchRequest{
  180. state: newDispatchState(buildArgs),
  181. shlex: shell.NewLex(escapeToken),
  182. builder: builder,
  183. source: source,
  184. stages: stages,
  185. }
  186. }
  187. func (s *dispatchState) updateRunConfig() {
  188. s.runConfig.Image = s.imageID
  189. }
  190. // hasFromImage returns true if the builder has processed a `FROM <image>` line
  191. func (s *dispatchState) hasFromImage() bool {
  192. return s.imageID != "" || (s.baseImage != nil && s.baseImage.ImageID() == "")
  193. }
  194. func (s *dispatchState) beginStage(stageName string, image builder.Image) error {
  195. s.stageName = stageName
  196. s.imageID = image.ImageID()
  197. s.operatingSystem = image.OperatingSystem()
  198. if !system.IsOSSupported(s.operatingSystem) {
  199. return system.ErrNotSupportedOperatingSystem
  200. }
  201. if image.RunConfig() != nil {
  202. // copy avoids referencing the same instance when 2 stages have the same base
  203. s.runConfig = copyRunConfig(image.RunConfig())
  204. } else {
  205. s.runConfig = &container.Config{}
  206. }
  207. s.baseImage = image
  208. s.setDefaultPath()
  209. s.runConfig.OpenStdin = false
  210. s.runConfig.StdinOnce = false
  211. return nil
  212. }
  213. // Add the default PATH to runConfig.ENV if one exists for the operating system and there
  214. // is no PATH set. Note that Windows containers on Windows won't have one as it's set by HCS
  215. func (s *dispatchState) setDefaultPath() {
  216. defaultPath := system.DefaultPathEnv(s.operatingSystem)
  217. if defaultPath == "" {
  218. return
  219. }
  220. envMap := opts.ConvertKVStringsToMap(s.runConfig.Env)
  221. if _, ok := envMap["PATH"]; !ok {
  222. s.runConfig.Env = append(s.runConfig.Env, "PATH="+defaultPath)
  223. }
  224. }