builder.go 11 KB

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