builder.go 11 KB

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