builder.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package dockerfile // import "github.com/docker/docker/builder/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/dockerfile/shell"
  17. "github.com/docker/docker/builder/fscache"
  18. "github.com/docker/docker/builder/remotecontext"
  19. "github.com/docker/docker/errdefs"
  20. "github.com/docker/docker/pkg/idtools"
  21. "github.com/docker/docker/pkg/streamformatter"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/docker/pkg/system"
  24. "github.com/moby/buildkit/session"
  25. "github.com/pkg/errors"
  26. "github.com/sirupsen/logrus"
  27. "golang.org/x/net/context"
  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 := runtime.GOOS
  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 runs the Dockerfile builder by parsing the Dockerfile and executing
  188. // the instructions from the file.
  189. func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
  190. defer b.imageSources.Unmount()
  191. addNodesForLabelOption(dockerfile.AST, b.options.Labels)
  192. stages, metaArgs, err := instructions.Parse(dockerfile.AST)
  193. if err != nil {
  194. if instructions.IsUnknownInstruction(err) {
  195. buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
  196. }
  197. return nil, errdefs.InvalidParameter(err)
  198. }
  199. if b.options.Target != "" {
  200. targetIx, found := instructions.HasStage(stages, b.options.Target)
  201. if !found {
  202. buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
  203. return nil, errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target)
  204. }
  205. stages = stages[:targetIx+1]
  206. }
  207. dockerfile.PrintWarnings(b.Stderr)
  208. dispatchState, err := b.dispatchDockerfileWithCancellation(stages, metaArgs, dockerfile.EscapeToken, source)
  209. if err != nil {
  210. return nil, err
  211. }
  212. if dispatchState.imageID == "" {
  213. buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
  214. return nil, errors.New("No image was generated. Is your Dockerfile empty?")
  215. }
  216. return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
  217. }
  218. func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error {
  219. if aux == nil || state.imageID == "" {
  220. return nil
  221. }
  222. return aux.Emit(types.BuildResult{ID: state.imageID})
  223. }
  224. func processMetaArg(meta instructions.ArgCommand, shlex *shell.Lex, args *buildArgs) error {
  225. // shell.Lex currently only support the concatenated string format
  226. envs := convertMapToEnvList(args.GetAllAllowed())
  227. if err := meta.Expand(func(word string) (string, error) {
  228. return shlex.ProcessWord(word, envs)
  229. }); err != nil {
  230. return err
  231. }
  232. args.AddArg(meta.Key, meta.Value)
  233. args.AddMetaArg(meta.Key, meta.Value)
  234. return nil
  235. }
  236. func printCommand(out io.Writer, currentCommandIndex int, totalCommands int, cmd interface{}) int {
  237. fmt.Fprintf(out, stepFormat, currentCommandIndex, totalCommands, cmd)
  238. fmt.Fprintln(out)
  239. return currentCommandIndex + 1
  240. }
  241. func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.Stage, metaArgs []instructions.ArgCommand, escapeToken rune, source builder.Source) (*dispatchState, error) {
  242. dispatchRequest := dispatchRequest{}
  243. buildArgs := newBuildArgs(b.options.BuildArgs)
  244. totalCommands := len(metaArgs) + len(parseResult)
  245. currentCommandIndex := 1
  246. for _, stage := range parseResult {
  247. totalCommands += len(stage.Commands)
  248. }
  249. shlex := shell.NewLex(escapeToken)
  250. for _, meta := range metaArgs {
  251. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, &meta)
  252. err := processMetaArg(meta, shlex, buildArgs)
  253. if err != nil {
  254. return nil, err
  255. }
  256. }
  257. stagesResults := newStagesBuildResults()
  258. for _, stage := range parseResult {
  259. if err := stagesResults.checkStageNameAvailable(stage.Name); err != nil {
  260. return nil, err
  261. }
  262. dispatchRequest = newDispatchRequest(b, escapeToken, source, buildArgs, stagesResults)
  263. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, stage.SourceCode)
  264. if err := initializeStage(dispatchRequest, &stage); err != nil {
  265. return nil, err
  266. }
  267. dispatchRequest.state.updateRunConfig()
  268. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  269. for _, cmd := range stage.Commands {
  270. select {
  271. case <-b.clientCtx.Done():
  272. logrus.Debug("Builder: build cancelled!")
  273. fmt.Fprint(b.Stdout, "Build cancelled\n")
  274. buildsFailed.WithValues(metricsBuildCanceled).Inc()
  275. return nil, errors.New("Build cancelled")
  276. default:
  277. // Not cancelled yet, keep going...
  278. }
  279. currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, cmd)
  280. if err := dispatch(dispatchRequest, cmd); err != nil {
  281. return nil, err
  282. }
  283. dispatchRequest.state.updateRunConfig()
  284. fmt.Fprintf(b.Stdout, " ---> %s\n", stringid.TruncateID(dispatchRequest.state.imageID))
  285. }
  286. if err := emitImageID(b.Aux, dispatchRequest.state); err != nil {
  287. return nil, err
  288. }
  289. buildArgs.MergeReferencedArgs(dispatchRequest.state.buildArgs)
  290. if err := commitStage(dispatchRequest.state, stagesResults); err != nil {
  291. return nil, err
  292. }
  293. }
  294. buildArgs.WarnOnUnusedBuildArgs(b.Stdout)
  295. return dispatchRequest.state, nil
  296. }
  297. func addNodesForLabelOption(dockerfile *parser.Node, labels map[string]string) {
  298. if len(labels) == 0 {
  299. return
  300. }
  301. node := parser.NodeFromLabels(labels)
  302. dockerfile.Children = append(dockerfile.Children, node)
  303. }
  304. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  305. // It will:
  306. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  307. // - Do build by calling builder.dispatch() to call all entries' handling routines
  308. //
  309. // BuildFromConfig is used by the /commit endpoint, with the changes
  310. // coming from the query parameter of the same name.
  311. //
  312. // TODO: Remove?
  313. func BuildFromConfig(config *container.Config, changes []string, os string) (*container.Config, error) {
  314. if !system.IsOSSupported(os) {
  315. return nil, errdefs.InvalidParameter(system.ErrNotSupportedOperatingSystem)
  316. }
  317. if len(changes) == 0 {
  318. return config, nil
  319. }
  320. dockerfile, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
  321. if err != nil {
  322. return nil, errdefs.InvalidParameter(err)
  323. }
  324. b := newBuilder(context.Background(), builderOptions{
  325. Options: &types.ImageBuildOptions{NoCache: true},
  326. })
  327. // ensure that the commands are valid
  328. for _, n := range dockerfile.AST.Children {
  329. if !validCommitCommands[n.Value] {
  330. return nil, errdefs.InvalidParameter(errors.Errorf("%s is not a valid change command", n.Value))
  331. }
  332. }
  333. b.Stdout = ioutil.Discard
  334. b.Stderr = ioutil.Discard
  335. b.disableCommit = true
  336. commands := []instructions.Command{}
  337. for _, n := range dockerfile.AST.Children {
  338. cmd, err := instructions.ParseCommand(n)
  339. if err != nil {
  340. return nil, errdefs.InvalidParameter(err)
  341. }
  342. commands = append(commands, cmd)
  343. }
  344. dispatchRequest := newDispatchRequest(b, dockerfile.EscapeToken, nil, newBuildArgs(b.options.BuildArgs), newStagesBuildResults())
  345. // We make mutations to the configuration, ensure we have a copy
  346. dispatchRequest.state.runConfig = copyRunConfig(config)
  347. dispatchRequest.state.imageID = config.Image
  348. dispatchRequest.state.operatingSystem = os
  349. for _, cmd := range commands {
  350. err := dispatch(dispatchRequest, cmd)
  351. if err != nil {
  352. return nil, errdefs.InvalidParameter(err)
  353. }
  354. dispatchRequest.state.updateRunConfig()
  355. }
  356. return dispatchRequest.state.runConfig, nil
  357. }
  358. func convertMapToEnvList(m map[string]string) []string {
  359. result := []string{}
  360. for k, v := range m {
  361. result = append(result, k+"="+v)
  362. }
  363. return result
  364. }