builder.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. args.AddArg(meta.Key, meta.Value)
  212. args.AddMetaArg(meta.Key, meta.Value)
  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(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 _, meta := range metaArgs {
  230. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, &meta)
  231. err := processMetaArg(meta, shlex, buildArgs)
  232. if err != nil {
  233. return nil, err
  234. }
  235. }
  236. stagesResults := newStagesBuildResults()
  237. for _, stage := range parseResult {
  238. if err := stagesResults.checkStageNameAvailable(stage.Name); err != nil {
  239. return nil, err
  240. }
  241. dispatchRequest = newDispatchRequest(b, escapeToken, source, buildArgs, stagesResults)
  242. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, stage.SourceCode)
  243. if err := initializeStage(dispatchRequest, &stage); err != nil {
  244. return nil, err
  245. }
  246. dispatchRequest.state.updateRunConfig()
  247. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  248. for _, cmd := range stage.Commands {
  249. select {
  250. case <-b.clientCtx.Done():
  251. logrus.Debug("Builder: build cancelled!")
  252. fmt.Fprint(b.Stdout, "Build cancelled\n")
  253. buildsFailed.WithValues(metricsBuildCanceled).Inc()
  254. return nil, errors.New("Build cancelled")
  255. default:
  256. // Not cancelled yet, keep going...
  257. }
  258. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, cmd)
  259. if err := dispatch(dispatchRequest, cmd); err != nil {
  260. return nil, err
  261. }
  262. dispatchRequest.state.updateRunConfig()
  263. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  264. }
  265. if err := emitImageID(b.Aux, dispatchRequest.state); err != nil {
  266. return nil, err
  267. }
  268. buildArgs.MergeReferencedArgs(dispatchRequest.state.buildArgs)
  269. if err := commitStage(dispatchRequest.state, stagesResults); err != nil {
  270. return nil, err
  271. }
  272. }
  273. buildArgs.WarnOnUnusedBuildArgs(b.Stdout)
  274. return dispatchRequest.state, nil
  275. }
  276. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  277. // It will:
  278. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  279. // - Do build by calling builder.dispatch() to call all entries' handling routines
  280. //
  281. // BuildFromConfig is used by the /commit endpoint, with the changes
  282. // coming from the query parameter of the same name.
  283. //
  284. // TODO: Remove?
  285. func BuildFromConfig(config *container.Config, changes []string, os string) (*container.Config, error) {
  286. if !system.IsOSSupported(os) {
  287. return nil, errdefs.InvalidParameter(system.ErrNotSupportedOperatingSystem)
  288. }
  289. if len(changes) == 0 {
  290. return config, nil
  291. }
  292. dockerfile, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  293. if err != nil {
  294. return nil, errdefs.InvalidParameter(err)
  295. }
  296. b, err := newBuilder(context.Background(), builderOptions{
  297. Options: &types.ImageBuildOptions{NoCache: true},
  298. })
  299. if err != nil {
  300. return nil, err
  301. }
  302. // ensure that the commands are valid
  303. for _, n := range dockerfile.AST.Children {
  304. if !validCommitCommands[n.Value] {
  305. return nil, errdefs.InvalidParameter(errors.Errorf("%s is not a valid change command", n.Value))
  306. }
  307. }
  308. b.Stdout = ioutil.Discard
  309. b.Stderr = ioutil.Discard
  310. b.disableCommit = true
  311. var commands []instructions.Command
  312. for _, n := range dockerfile.AST.Children {
  313. cmd, err := instructions.ParseCommand(n)
  314. if err != nil {
  315. return nil, errdefs.InvalidParameter(err)
  316. }
  317. commands = append(commands, cmd)
  318. }
  319. dispatchRequest := newDispatchRequest(b, dockerfile.EscapeToken, nil, NewBuildArgs(b.options.BuildArgs), newStagesBuildResults())
  320. // We make mutations to the configuration, ensure we have a copy
  321. dispatchRequest.state.runConfig = copyRunConfig(config)
  322. dispatchRequest.state.imageID = config.Image
  323. dispatchRequest.state.operatingSystem = os
  324. for _, cmd := range commands {
  325. err := dispatch(dispatchRequest, cmd)
  326. if err != nil {
  327. return nil, errdefs.InvalidParameter(err)
  328. }
  329. dispatchRequest.state.updateRunConfig()
  330. }
  331. return dispatchRequest.state.runConfig, nil
  332. }
  333. func convertMapToEnvList(m map[string]string) []string {
  334. result := []string{}
  335. for k, v := range m {
  336. result = append(result, k+"="+v)
  337. }
  338. return result
  339. }