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. "io/ioutil"
  8. "sort"
  9. "strings"
  10. "github.com/containerd/containerd/platforms"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/backend"
  13. "github.com/docker/docker/api/types/container"
  14. "github.com/docker/docker/builder"
  15. "github.com/docker/docker/builder/remotecontext"
  16. "github.com/docker/docker/errdefs"
  17. "github.com/docker/docker/pkg/idtools"
  18. "github.com/docker/docker/pkg/streamformatter"
  19. "github.com/docker/docker/pkg/stringid"
  20. "github.com/docker/docker/pkg/system"
  21. "github.com/moby/buildkit/frontend/dockerfile/instructions"
  22. "github.com/moby/buildkit/frontend/dockerfile/parser"
  23. "github.com/moby/buildkit/frontend/dockerfile/shell"
  24. specs "github.com/opencontainers/image-spec/specs-go/v1"
  25. "github.com/pkg/errors"
  26. "github.com/sirupsen/logrus"
  27. "golang.org/x/sync/syncmap"
  28. )
  29. var validCommitCommands = map[string]bool{
  30. "cmd": true,
  31. "entrypoint": true,
  32. "healthcheck": true,
  33. "env": true,
  34. "expose": true,
  35. "label": true,
  36. "onbuild": true,
  37. "user": true,
  38. "volume": true,
  39. "workdir": true,
  40. }
  41. const (
  42. stepFormat = "Step %d/%d : %v"
  43. )
  44. // BuildManager is shared across all Builder objects
  45. type BuildManager struct {
  46. idMapping *idtools.IdentityMapping
  47. backend builder.Backend
  48. pathCache pathCache // TODO: make this persistent
  49. }
  50. // NewBuildManager creates a BuildManager
  51. func NewBuildManager(b builder.Backend, identityMapping *idtools.IdentityMapping) (*BuildManager, error) {
  52. bm := &BuildManager{
  53. backend: b,
  54. pathCache: &syncmap.Map{},
  55. idMapping: identityMapping,
  56. }
  57. return bm, nil
  58. }
  59. // Build starts a new build from a BuildConfig
  60. func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) {
  61. buildsTriggered.Inc()
  62. if config.Options.Dockerfile == "" {
  63. config.Options.Dockerfile = builder.DefaultDockerfileName
  64. }
  65. source, dockerfile, err := remotecontext.Detect(config)
  66. if err != nil {
  67. return nil, err
  68. }
  69. defer func() {
  70. if source != nil {
  71. if err := source.Close(); err != nil {
  72. logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
  73. }
  74. }
  75. }()
  76. ctx, cancel := context.WithCancel(ctx)
  77. defer cancel()
  78. builderOptions := builderOptions{
  79. Options: config.Options,
  80. ProgressWriter: config.ProgressWriter,
  81. Backend: bm.backend,
  82. PathCache: bm.pathCache,
  83. IDMapping: bm.idMapping,
  84. }
  85. b, err := newBuilder(ctx, builderOptions)
  86. if err != nil {
  87. return nil, err
  88. }
  89. return b.build(source, dockerfile)
  90. }
  91. // builderOptions are the dependencies required by the builder
  92. type builderOptions struct {
  93. Options *types.ImageBuildOptions
  94. Backend builder.Backend
  95. ProgressWriter backend.ProgressWriter
  96. PathCache pathCache
  97. IDMapping *idtools.IdentityMapping
  98. }
  99. // Builder is a Dockerfile builder
  100. // It implements the builder.Backend interface.
  101. type Builder struct {
  102. options *types.ImageBuildOptions
  103. Stdout io.Writer
  104. Stderr io.Writer
  105. Aux *streamformatter.AuxFormatter
  106. Output io.Writer
  107. docker builder.Backend
  108. clientCtx context.Context
  109. idMapping *idtools.IdentityMapping
  110. disableCommit bool
  111. imageSources *imageSources
  112. pathCache pathCache
  113. containerManager *containerManager
  114. imageProber ImageProber
  115. platform *specs.Platform
  116. }
  117. // newBuilder creates a new Dockerfile builder from an optional dockerfile and a Options.
  118. func newBuilder(clientCtx context.Context, options builderOptions) (*Builder, error) {
  119. config := options.Options
  120. if config == nil {
  121. config = new(types.ImageBuildOptions)
  122. }
  123. b := &Builder{
  124. clientCtx: clientCtx,
  125. options: config,
  126. Stdout: options.ProgressWriter.StdoutFormatter,
  127. Stderr: options.ProgressWriter.StderrFormatter,
  128. Aux: options.ProgressWriter.AuxFormatter,
  129. Output: options.ProgressWriter.Output,
  130. docker: options.Backend,
  131. idMapping: options.IDMapping,
  132. imageSources: newImageSources(clientCtx, options),
  133. pathCache: options.PathCache,
  134. imageProber: newImageProber(options.Backend, config.CacheFrom, config.NoCache),
  135. containerManager: newContainerManager(options.Backend),
  136. }
  137. // same as in Builder.Build in builder/builder-next/builder.go
  138. // TODO: remove once config.Platform is of type specs.Platform
  139. if config.Platform != "" {
  140. sp, err := platforms.Parse(config.Platform)
  141. if err != nil {
  142. return nil, err
  143. }
  144. if err := system.ValidatePlatform(sp); err != nil {
  145. return nil, err
  146. }
  147. b.platform = &sp
  148. }
  149. return b, nil
  150. }
  151. // Build 'LABEL' command(s) from '--label' options and add to the last stage
  152. func buildLabelOptions(labels map[string]string, stages []instructions.Stage) {
  153. keys := []string{}
  154. for key := range labels {
  155. keys = append(keys, key)
  156. }
  157. // Sort the label to have a repeatable order
  158. sort.Strings(keys)
  159. for _, key := range keys {
  160. value := labels[key]
  161. stages[len(stages)-1].AddCommand(instructions.NewLabelCommand(key, value, true))
  162. }
  163. }
  164. // Build runs the Dockerfile builder by parsing the Dockerfile and executing
  165. // the instructions from the file.
  166. func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
  167. defer b.imageSources.Unmount()
  168. stages, metaArgs, err := instructions.Parse(dockerfile.AST)
  169. if err != nil {
  170. var uiErr *instructions.UnknownInstruction
  171. if errors.As(err, &uiErr) {
  172. buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
  173. }
  174. return nil, errdefs.InvalidParameter(err)
  175. }
  176. if b.options.Target != "" {
  177. targetIx, found := instructions.HasStage(stages, b.options.Target)
  178. if !found {
  179. buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
  180. return nil, errdefs.InvalidParameter(errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target))
  181. }
  182. stages = stages[:targetIx+1]
  183. }
  184. // Add 'LABEL' command specified by '--label' option to the last stage
  185. buildLabelOptions(b.options.Labels, stages)
  186. dockerfile.PrintWarnings(b.Stderr)
  187. dispatchState, err := b.dispatchDockerfileWithCancellation(stages, metaArgs, dockerfile.EscapeToken, source)
  188. if err != nil {
  189. return nil, err
  190. }
  191. if dispatchState.imageID == "" {
  192. buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
  193. return nil, errors.New("No image was generated. Is your Dockerfile empty?")
  194. }
  195. return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
  196. }
  197. func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error {
  198. if aux == nil || state.imageID == "" {
  199. return nil
  200. }
  201. return aux.Emit("", types.BuildResult{ID: state.imageID})
  202. }
  203. func processMetaArg(meta instructions.ArgCommand, shlex *shell.Lex, args *BuildArgs) error {
  204. // shell.Lex currently only support the concatenated string format
  205. envs := convertMapToEnvList(args.GetAllAllowed())
  206. if err := meta.Expand(func(word string) (string, error) {
  207. return shlex.ProcessWord(word, envs)
  208. }); err != nil {
  209. return err
  210. }
  211. for _, arg := range meta.Args {
  212. args.AddArg(arg.Key, arg.Value)
  213. args.AddMetaArg(arg.Key, arg.Value)
  214. }
  215. return nil
  216. }
  217. func printCommand(out io.Writer, currentCommandIndex int, totalCommands int, cmd interface{}) int {
  218. fmt.Fprintf(out, stepFormat, currentCommandIndex, totalCommands, cmd)
  219. fmt.Fprintln(out)
  220. return currentCommandIndex + 1
  221. }
  222. func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.Stage, metaArgs []instructions.ArgCommand, escapeToken rune, source builder.Source) (*dispatchState, error) {
  223. dispatchRequest := dispatchRequest{}
  224. buildArgs := NewBuildArgs(b.options.BuildArgs)
  225. totalCommands := len(metaArgs) + len(parseResult)
  226. currentCommandIndex := 1
  227. for _, stage := range parseResult {
  228. totalCommands += len(stage.Commands)
  229. }
  230. shlex := shell.NewLex(escapeToken)
  231. for _, meta := range metaArgs {
  232. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, &meta)
  233. err := processMetaArg(meta, shlex, buildArgs)
  234. if err != nil {
  235. return nil, err
  236. }
  237. }
  238. stagesResults := newStagesBuildResults()
  239. for _, stage := range parseResult {
  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 = ioutil.Discard
  311. b.Stderr = ioutil.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. }