builder.go 13 KB

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