builder.go 12 KB

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