builder.go 12 KB

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