builder.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package dockerfile // import "github.com/docker/docker/builder/dockerfile"
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "sort"
  8. "strings"
  9. "github.com/containerd/containerd/platforms"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/backend"
  12. "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/builder"
  14. "github.com/docker/docker/builder/remotecontext"
  15. "github.com/docker/docker/errdefs"
  16. "github.com/docker/docker/pkg/idtools"
  17. "github.com/docker/docker/pkg/streamformatter"
  18. "github.com/docker/docker/pkg/stringid"
  19. "github.com/moby/buildkit/frontend/dockerfile/instructions"
  20. "github.com/moby/buildkit/frontend/dockerfile/parser"
  21. "github.com/moby/buildkit/frontend/dockerfile/shell"
  22. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  23. "github.com/pkg/errors"
  24. "github.com/sirupsen/logrus"
  25. "golang.org/x/sync/syncmap"
  26. )
  27. var validCommitCommands = map[string]bool{
  28. "cmd": true,
  29. "entrypoint": true,
  30. "healthcheck": true,
  31. "env": true,
  32. "expose": true,
  33. "label": true,
  34. "onbuild": true,
  35. "stopsignal": true,
  36. "user": true,
  37. "volume": true,
  38. "workdir": true,
  39. }
  40. const (
  41. stepFormat = "Step %d/%d : %v"
  42. )
  43. // BuildManager is shared across all Builder objects
  44. type BuildManager struct {
  45. idMapping idtools.IdentityMapping
  46. backend builder.Backend
  47. pathCache pathCache // TODO: make this persistent
  48. }
  49. // NewBuildManager creates a BuildManager
  50. func NewBuildManager(b builder.Backend, identityMapping idtools.IdentityMapping) (*BuildManager, error) {
  51. bm := &BuildManager{
  52. backend: b,
  53. pathCache: &syncmap.Map{},
  54. idMapping: identityMapping,
  55. }
  56. return bm, nil
  57. }
  58. // Build starts a new build from a BuildConfig
  59. func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) {
  60. buildsTriggered.Inc()
  61. if config.Options.Dockerfile == "" {
  62. config.Options.Dockerfile = builder.DefaultDockerfileName
  63. }
  64. source, dockerfile, err := remotecontext.Detect(config)
  65. if err != nil {
  66. return nil, err
  67. }
  68. defer func() {
  69. if source != nil {
  70. if err := source.Close(); err != nil {
  71. logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
  72. }
  73. }
  74. }()
  75. ctx, cancel := context.WithCancel(ctx)
  76. defer cancel()
  77. builderOptions := builderOptions{
  78. Options: config.Options,
  79. ProgressWriter: config.ProgressWriter,
  80. Backend: bm.backend,
  81. PathCache: bm.pathCache,
  82. IDMapping: bm.idMapping,
  83. }
  84. b, err := newBuilder(ctx, builderOptions)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return b.build(ctx, source, dockerfile)
  89. }
  90. // builderOptions are the dependencies required by the builder
  91. type builderOptions struct {
  92. Options *types.ImageBuildOptions
  93. Backend builder.Backend
  94. ProgressWriter backend.ProgressWriter
  95. PathCache pathCache
  96. IDMapping idtools.IdentityMapping
  97. }
  98. // Builder is a Dockerfile builder
  99. // It implements the builder.Backend interface.
  100. type Builder struct {
  101. options *types.ImageBuildOptions
  102. Stdout io.Writer
  103. Stderr io.Writer
  104. Aux *streamformatter.AuxFormatter
  105. Output io.Writer
  106. docker builder.Backend
  107. idMapping idtools.IdentityMapping
  108. disableCommit bool
  109. imageSources *imageSources
  110. pathCache pathCache
  111. containerManager *containerManager
  112. imageProber ImageProber
  113. platform *ocispec.Platform
  114. }
  115. // newBuilder creates a new Dockerfile builder from an optional dockerfile and a Options.
  116. func newBuilder(ctx context.Context, options builderOptions) (*Builder, error) {
  117. config := options.Options
  118. if config == nil {
  119. config = new(types.ImageBuildOptions)
  120. }
  121. imageProber, err := newImageProber(ctx, options.Backend, config.CacheFrom, config.NoCache)
  122. if err != nil {
  123. return nil, err
  124. }
  125. b := &Builder{
  126. options: config,
  127. Stdout: options.ProgressWriter.StdoutFormatter,
  128. Stderr: options.ProgressWriter.StderrFormatter,
  129. Aux: options.ProgressWriter.AuxFormatter,
  130. Output: options.ProgressWriter.Output,
  131. docker: options.Backend,
  132. idMapping: options.IDMapping,
  133. imageSources: newImageSources(options),
  134. pathCache: options.PathCache,
  135. imageProber: imageProber,
  136. containerManager: newContainerManager(options.Backend),
  137. }
  138. // same as in Builder.Build in builder/builder-next/builder.go
  139. // TODO: remove once config.Platform is of type specs.Platform
  140. if config.Platform != "" {
  141. sp, err := platforms.Parse(config.Platform)
  142. if err != nil {
  143. return nil, err
  144. }
  145. b.platform = &sp
  146. }
  147. return b, nil
  148. }
  149. // Build 'LABEL' command(s) from '--label' options and add to the last stage
  150. func buildLabelOptions(labels map[string]string, stages []instructions.Stage) {
  151. keys := []string{}
  152. for key := range labels {
  153. keys = append(keys, key)
  154. }
  155. // Sort the label to have a repeatable order
  156. sort.Strings(keys)
  157. for _, key := range keys {
  158. value := labels[key]
  159. stages[len(stages)-1].AddCommand(instructions.NewLabelCommand(key, value, true))
  160. }
  161. }
  162. // Build runs the Dockerfile builder by parsing the Dockerfile and executing
  163. // the instructions from the file.
  164. func (b *Builder) build(ctx context.Context, source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
  165. defer b.imageSources.Unmount()
  166. stages, metaArgs, err := instructions.Parse(dockerfile.AST)
  167. if err != nil {
  168. var uiErr *instructions.UnknownInstructionError
  169. if errors.As(err, &uiErr) {
  170. buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
  171. }
  172. return nil, errdefs.InvalidParameter(err)
  173. }
  174. if b.options.Target != "" {
  175. targetIx, found := instructions.HasStage(stages, b.options.Target)
  176. if !found {
  177. buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
  178. return nil, errdefs.InvalidParameter(errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target))
  179. }
  180. stages = stages[:targetIx+1]
  181. }
  182. // Add 'LABEL' command specified by '--label' option to the last stage
  183. buildLabelOptions(b.options.Labels, stages)
  184. dockerfile.PrintWarnings(b.Stderr)
  185. dispatchState, err := b.dispatchDockerfileWithCancellation(ctx, stages, metaArgs, dockerfile.EscapeToken, source)
  186. if err != nil {
  187. return nil, err
  188. }
  189. if dispatchState.imageID == "" {
  190. buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
  191. return nil, errors.New("No image was generated. Is your Dockerfile empty?")
  192. }
  193. return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
  194. }
  195. func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error {
  196. if aux == nil || state.imageID == "" {
  197. return nil
  198. }
  199. return aux.Emit("", types.BuildResult{ID: state.imageID})
  200. }
  201. func processMetaArg(meta instructions.ArgCommand, shlex *shell.Lex, args *BuildArgs) error {
  202. // shell.Lex currently only support the concatenated string format
  203. envs := convertMapToEnvList(args.GetAllAllowed())
  204. if err := meta.Expand(func(word string) (string, error) {
  205. return shlex.ProcessWord(word, envs)
  206. }); err != nil {
  207. return err
  208. }
  209. for _, arg := range meta.Args {
  210. args.AddArg(arg.Key, arg.Value)
  211. args.AddMetaArg(arg.Key, arg.Value)
  212. }
  213. return nil
  214. }
  215. func printCommand(out io.Writer, currentCommandIndex int, totalCommands int, cmd interface{}) int {
  216. fmt.Fprintf(out, stepFormat, currentCommandIndex, totalCommands, cmd)
  217. fmt.Fprintln(out)
  218. return currentCommandIndex + 1
  219. }
  220. func (b *Builder) dispatchDockerfileWithCancellation(ctx context.Context, parseResult []instructions.Stage, metaArgs []instructions.ArgCommand, escapeToken rune, source builder.Source) (*dispatchState, error) {
  221. dispatchRequest := dispatchRequest{}
  222. buildArgs := NewBuildArgs(b.options.BuildArgs)
  223. totalCommands := len(metaArgs) + len(parseResult)
  224. currentCommandIndex := 1
  225. for _, stage := range parseResult {
  226. totalCommands += len(stage.Commands)
  227. }
  228. shlex := shell.NewLex(escapeToken)
  229. for i := range metaArgs {
  230. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, &metaArgs[i])
  231. err := processMetaArg(metaArgs[i], shlex, buildArgs)
  232. if err != nil {
  233. return nil, err
  234. }
  235. }
  236. stagesResults := newStagesBuildResults()
  237. for _, s := range parseResult {
  238. stage := s
  239. if err := stagesResults.checkStageNameAvailable(stage.Name); err != nil {
  240. return nil, err
  241. }
  242. dispatchRequest = newDispatchRequest(b, escapeToken, source, buildArgs, stagesResults)
  243. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, stage.SourceCode)
  244. if err := initializeStage(ctx, dispatchRequest, &stage); err != nil {
  245. return nil, err
  246. }
  247. dispatchRequest.state.updateRunConfig()
  248. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  249. for _, cmd := range stage.Commands {
  250. select {
  251. case <-ctx.Done():
  252. logrus.Debug("Builder: build cancelled!")
  253. fmt.Fprint(b.Stdout, "Build cancelled\n")
  254. buildsFailed.WithValues(metricsBuildCanceled).Inc()
  255. return nil, errors.New("Build cancelled")
  256. default:
  257. // Not cancelled yet, keep going...
  258. }
  259. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, cmd)
  260. if err := dispatch(ctx, dispatchRequest, cmd); err != nil {
  261. return nil, err
  262. }
  263. dispatchRequest.state.updateRunConfig()
  264. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  265. }
  266. if err := emitImageID(b.Aux, dispatchRequest.state); err != nil {
  267. return nil, err
  268. }
  269. buildArgs.MergeReferencedArgs(dispatchRequest.state.buildArgs)
  270. if err := commitStage(dispatchRequest.state, stagesResults); err != nil {
  271. return nil, err
  272. }
  273. }
  274. buildArgs.WarnOnUnusedBuildArgs(b.Stdout)
  275. return dispatchRequest.state, nil
  276. }
  277. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  278. // It will:
  279. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  280. // - Do build by calling builder.dispatch() to call all entries' handling routines
  281. //
  282. // BuildFromConfig is used by the /commit endpoint, with the changes
  283. // coming from the query parameter of the same name.
  284. //
  285. // TODO: Remove?
  286. func BuildFromConfig(ctx context.Context, config *container.Config, changes []string, os string) (*container.Config, error) {
  287. if len(changes) == 0 {
  288. return config, nil
  289. }
  290. dockerfile, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  291. if err != nil {
  292. return nil, errdefs.InvalidParameter(err)
  293. }
  294. b, err := newBuilder(ctx, builderOptions{
  295. Options: &types.ImageBuildOptions{NoCache: true},
  296. })
  297. if err != nil {
  298. return nil, err
  299. }
  300. // ensure that the commands are valid
  301. for _, n := range dockerfile.AST.Children {
  302. if !validCommitCommands[strings.ToLower(n.Value)] {
  303. return nil, errdefs.InvalidParameter(errors.Errorf("%s is not a valid change command", n.Value))
  304. }
  305. }
  306. b.Stdout = io.Discard
  307. b.Stderr = io.Discard
  308. b.disableCommit = true
  309. var commands []instructions.Command
  310. for _, n := range dockerfile.AST.Children {
  311. cmd, err := instructions.ParseCommand(n)
  312. if err != nil {
  313. return nil, errdefs.InvalidParameter(err)
  314. }
  315. commands = append(commands, cmd)
  316. }
  317. dispatchRequest := newDispatchRequest(b, dockerfile.EscapeToken, nil, NewBuildArgs(b.options.BuildArgs), newStagesBuildResults())
  318. // We make mutations to the configuration, ensure we have a copy
  319. dispatchRequest.state.runConfig = copyRunConfig(config)
  320. dispatchRequest.state.imageID = config.Image
  321. dispatchRequest.state.operatingSystem = os
  322. for _, cmd := range commands {
  323. err := dispatch(ctx, dispatchRequest, cmd)
  324. if err != nil {
  325. return nil, errdefs.InvalidParameter(err)
  326. }
  327. dispatchRequest.state.updateRunConfig()
  328. }
  329. return dispatchRequest.state.runConfig, nil
  330. }
  331. func convertMapToEnvList(m map[string]string) []string {
  332. result := []string{}
  333. for k, v := range m {
  334. result = append(result, k+"="+v)
  335. }
  336. return result
  337. }