builder.go 12 KB

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