builder.go 12 KB

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