builder.go 13 KB

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