builder.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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/dockerfile/instructions"
  16. "github.com/docker/docker/builder/dockerfile/parser"
  17. "github.com/docker/docker/builder/dockerfile/shell"
  18. "github.com/docker/docker/builder/fscache"
  19. "github.com/docker/docker/builder/remotecontext"
  20. "github.com/docker/docker/errdefs"
  21. "github.com/docker/docker/pkg/idtools"
  22. "github.com/docker/docker/pkg/streamformatter"
  23. "github.com/docker/docker/pkg/stringid"
  24. "github.com/docker/docker/pkg/system"
  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. os := ""
  96. apiPlatform := system.ParsePlatform(config.Options.Platform)
  97. if apiPlatform.OS != "" {
  98. os = apiPlatform.OS
  99. }
  100. config.Options.Platform = os
  101. builderOptions := builderOptions{
  102. Options: config.Options,
  103. ProgressWriter: config.ProgressWriter,
  104. Backend: bm.backend,
  105. PathCache: bm.pathCache,
  106. IDMappings: bm.idMappings,
  107. }
  108. return newBuilder(ctx, builderOptions).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. IDMappings *idtools.IDMappings
  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. idMappings *idtools.IDMappings
  159. disableCommit bool
  160. imageSources *imageSources
  161. pathCache pathCache
  162. containerManager *containerManager
  163. imageProber ImageProber
  164. }
  165. // newBuilder creates a new Dockerfile builder from an optional dockerfile and a Options.
  166. func newBuilder(clientCtx context.Context, options builderOptions) *Builder {
  167. config := options.Options
  168. if config == nil {
  169. config = new(types.ImageBuildOptions)
  170. }
  171. b := &Builder{
  172. clientCtx: clientCtx,
  173. options: config,
  174. Stdout: options.ProgressWriter.StdoutFormatter,
  175. Stderr: options.ProgressWriter.StderrFormatter,
  176. Aux: options.ProgressWriter.AuxFormatter,
  177. Output: options.ProgressWriter.Output,
  178. docker: options.Backend,
  179. idMappings: options.IDMappings,
  180. imageSources: newImageSources(clientCtx, options),
  181. pathCache: options.PathCache,
  182. imageProber: newImageProber(options.Backend, config.CacheFrom, config.NoCache),
  183. containerManager: newContainerManager(options.Backend),
  184. }
  185. return b
  186. }
  187. // Build 'LABEL' command(s) from '--label' options and add to the last stage
  188. func buildLabelOptions(labels map[string]string, stages []instructions.Stage) {
  189. keys := []string{}
  190. for key := range labels {
  191. keys = append(keys, key)
  192. }
  193. // Sort the label to have a repeatable order
  194. sort.Strings(keys)
  195. for _, key := range keys {
  196. value := labels[key]
  197. stages[len(stages)-1].AddCommand(instructions.NewLabelCommand(key, value, true))
  198. }
  199. }
  200. // Build runs the Dockerfile builder by parsing the Dockerfile and executing
  201. // the instructions from the file.
  202. func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
  203. defer b.imageSources.Unmount()
  204. stages, metaArgs, err := instructions.Parse(dockerfile.AST)
  205. if err != nil {
  206. if instructions.IsUnknownInstruction(err) {
  207. buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
  208. }
  209. return nil, errdefs.InvalidParameter(err)
  210. }
  211. if b.options.Target != "" {
  212. targetIx, found := instructions.HasStage(stages, b.options.Target)
  213. if !found {
  214. buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
  215. return nil, errdefs.InvalidParameter(errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target))
  216. }
  217. stages = stages[:targetIx+1]
  218. }
  219. // Add 'LABEL' command specified by '--label' option to the last stage
  220. buildLabelOptions(b.options.Labels, stages)
  221. dockerfile.PrintWarnings(b.Stderr)
  222. dispatchState, err := b.dispatchDockerfileWithCancellation(stages, metaArgs, dockerfile.EscapeToken, source)
  223. if err != nil {
  224. return nil, err
  225. }
  226. if dispatchState.imageID == "" {
  227. buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
  228. return nil, errors.New("No image was generated. Is your Dockerfile empty?")
  229. }
  230. return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
  231. }
  232. func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error {
  233. if aux == nil || state.imageID == "" {
  234. return nil
  235. }
  236. return aux.Emit(types.BuildResult{ID: state.imageID})
  237. }
  238. func processMetaArg(meta instructions.ArgCommand, shlex *shell.Lex, args *BuildArgs) error {
  239. // shell.Lex currently only support the concatenated string format
  240. envs := convertMapToEnvList(args.GetAllAllowed())
  241. if err := meta.Expand(func(word string) (string, error) {
  242. return shlex.ProcessWord(word, envs)
  243. }); err != nil {
  244. return err
  245. }
  246. args.AddArg(meta.Key, meta.Value)
  247. args.AddMetaArg(meta.Key, meta.Value)
  248. return nil
  249. }
  250. func printCommand(out io.Writer, currentCommandIndex int, totalCommands int, cmd interface{}) int {
  251. fmt.Fprintf(out, stepFormat, currentCommandIndex, totalCommands, cmd)
  252. fmt.Fprintln(out)
  253. return currentCommandIndex + 1
  254. }
  255. func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.Stage, metaArgs []instructions.ArgCommand, escapeToken rune, source builder.Source) (*dispatchState, error) {
  256. dispatchRequest := dispatchRequest{}
  257. buildArgs := NewBuildArgs(b.options.BuildArgs)
  258. totalCommands := len(metaArgs) + len(parseResult)
  259. currentCommandIndex := 1
  260. for _, stage := range parseResult {
  261. totalCommands += len(stage.Commands)
  262. }
  263. shlex := shell.NewLex(escapeToken)
  264. for _, meta := range metaArgs {
  265. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, &meta)
  266. err := processMetaArg(meta, shlex, buildArgs)
  267. if err != nil {
  268. return nil, err
  269. }
  270. }
  271. stagesResults := newStagesBuildResults()
  272. for _, stage := range parseResult {
  273. if err := stagesResults.checkStageNameAvailable(stage.Name); err != nil {
  274. return nil, err
  275. }
  276. dispatchRequest = newDispatchRequest(b, escapeToken, source, buildArgs, stagesResults)
  277. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, stage.SourceCode)
  278. if err := initializeStage(dispatchRequest, &stage); err != nil {
  279. return nil, err
  280. }
  281. dispatchRequest.state.updateRunConfig()
  282. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  283. for _, cmd := range stage.Commands {
  284. select {
  285. case <-b.clientCtx.Done():
  286. logrus.Debug("Builder: build cancelled!")
  287. fmt.Fprint(b.Stdout, "Build cancelled\n")
  288. buildsFailed.WithValues(metricsBuildCanceled).Inc()
  289. return nil, errors.New("Build cancelled")
  290. default:
  291. // Not cancelled yet, keep going...
  292. }
  293. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, cmd)
  294. if err := dispatch(dispatchRequest, cmd); err != nil {
  295. return nil, err
  296. }
  297. dispatchRequest.state.updateRunConfig()
  298. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  299. }
  300. if err := emitImageID(b.Aux, dispatchRequest.state); err != nil {
  301. return nil, err
  302. }
  303. buildArgs.MergeReferencedArgs(dispatchRequest.state.buildArgs)
  304. if err := commitStage(dispatchRequest.state, stagesResults); err != nil {
  305. return nil, err
  306. }
  307. }
  308. buildArgs.WarnOnUnusedBuildArgs(b.Stdout)
  309. return dispatchRequest.state, nil
  310. }
  311. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  312. // It will:
  313. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  314. // - Do build by calling builder.dispatch() to call all entries' handling routines
  315. //
  316. // BuildFromConfig is used by the /commit endpoint, with the changes
  317. // coming from the query parameter of the same name.
  318. //
  319. // TODO: Remove?
  320. func BuildFromConfig(config *container.Config, changes []string, os string) (*container.Config, error) {
  321. if !system.IsOSSupported(os) {
  322. return nil, errdefs.InvalidParameter(system.ErrNotSupportedOperatingSystem)
  323. }
  324. if len(changes) == 0 {
  325. return config, nil
  326. }
  327. dockerfile, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  328. if err != nil {
  329. return nil, errdefs.InvalidParameter(err)
  330. }
  331. b := newBuilder(context.Background(), builderOptions{
  332. Options: &types.ImageBuildOptions{NoCache: true},
  333. })
  334. // ensure that the commands are valid
  335. for _, n := range dockerfile.AST.Children {
  336. if !validCommitCommands[n.Value] {
  337. return nil, errdefs.InvalidParameter(errors.Errorf("%s is not a valid change command", n.Value))
  338. }
  339. }
  340. b.Stdout = ioutil.Discard
  341. b.Stderr = ioutil.Discard
  342. b.disableCommit = true
  343. var commands []instructions.Command
  344. for _, n := range dockerfile.AST.Children {
  345. cmd, err := instructions.ParseCommand(n)
  346. if err != nil {
  347. return nil, errdefs.InvalidParameter(err)
  348. }
  349. commands = append(commands, cmd)
  350. }
  351. dispatchRequest := newDispatchRequest(b, dockerfile.EscapeToken, nil, NewBuildArgs(b.options.BuildArgs), newStagesBuildResults())
  352. // We make mutations to the configuration, ensure we have a copy
  353. dispatchRequest.state.runConfig = copyRunConfig(config)
  354. dispatchRequest.state.imageID = config.Image
  355. dispatchRequest.state.operatingSystem = os
  356. for _, cmd := range commands {
  357. err := dispatch(dispatchRequest, cmd)
  358. if err != nil {
  359. return nil, errdefs.InvalidParameter(err)
  360. }
  361. dispatchRequest.state.updateRunConfig()
  362. }
  363. return dispatchRequest.state.runConfig, nil
  364. }
  365. func convertMapToEnvList(m map[string]string) []string {
  366. result := []string{}
  367. for k, v := range m {
  368. result = append(result, k+"="+v)
  369. }
  370. return result
  371. }