builder.go 13 KB

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