evaluator.go 7.5 KB

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