builder.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package dockerfile
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "sort"
  10. "strings"
  11. "github.com/Sirupsen/logrus"
  12. apierrors "github.com/docker/docker/api/errors"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/api/types/backend"
  15. "github.com/docker/docker/api/types/container"
  16. "github.com/docker/docker/builder"
  17. "github.com/docker/docker/builder/dockerfile/parser"
  18. "github.com/docker/docker/image"
  19. "github.com/docker/docker/pkg/stringid"
  20. "github.com/docker/docker/reference"
  21. perrors "github.com/pkg/errors"
  22. "golang.org/x/net/context"
  23. )
  24. var validCommitCommands = map[string]bool{
  25. "cmd": true,
  26. "entrypoint": true,
  27. "healthcheck": true,
  28. "env": true,
  29. "expose": true,
  30. "label": true,
  31. "onbuild": true,
  32. "user": true,
  33. "volume": true,
  34. "workdir": true,
  35. }
  36. // BuiltinAllowedBuildArgs is list of built-in allowed build args
  37. var BuiltinAllowedBuildArgs = map[string]bool{
  38. "HTTP_PROXY": true,
  39. "http_proxy": true,
  40. "HTTPS_PROXY": true,
  41. "https_proxy": true,
  42. "FTP_PROXY": true,
  43. "ftp_proxy": true,
  44. "NO_PROXY": true,
  45. "no_proxy": true,
  46. }
  47. // Builder is a Dockerfile builder
  48. // It implements the builder.Backend interface.
  49. type Builder struct {
  50. options *types.ImageBuildOptions
  51. Stdout io.Writer
  52. Stderr io.Writer
  53. Output io.Writer
  54. docker builder.Backend
  55. context builder.Context
  56. clientCtx context.Context
  57. cancel context.CancelFunc
  58. dockerfile *parser.Node
  59. runConfig *container.Config // runconfig for cmd, run, entrypoint etc.
  60. flags *BFlags
  61. tmpContainers map[string]struct{}
  62. image string // imageID
  63. noBaseImage bool
  64. maintainer string
  65. cmdSet bool
  66. disableCommit bool
  67. cacheBusted bool
  68. allowedBuildArgs map[string]bool // list of build-time args that are allowed for expansion/substitution and passing to commands in 'run'.
  69. directive parser.Directive
  70. // TODO: remove once docker.Commit can receive a tag
  71. id string
  72. imageCache builder.ImageCache
  73. from builder.Image
  74. }
  75. // BuildManager implements builder.Backend and is shared across all Builder objects.
  76. type BuildManager struct {
  77. backend builder.Backend
  78. }
  79. // NewBuildManager creates a BuildManager.
  80. func NewBuildManager(b builder.Backend) (bm *BuildManager) {
  81. return &BuildManager{backend: b}
  82. }
  83. // BuildFromContext builds a new image from a given context.
  84. func (bm *BuildManager) BuildFromContext(ctx context.Context, src io.ReadCloser, remote string, buildOptions *types.ImageBuildOptions, pg backend.ProgressWriter) (string, error) {
  85. if buildOptions.Squash && !bm.backend.HasExperimental() {
  86. return "", apierrors.NewBadRequestError(errors.New("squash is only supported with experimental mode"))
  87. }
  88. buildContext, dockerfileName, err := builder.DetectContextFromRemoteURL(src, remote, pg.ProgressReaderFunc)
  89. if err != nil {
  90. return "", err
  91. }
  92. defer func() {
  93. if err := buildContext.Close(); err != nil {
  94. logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
  95. }
  96. }()
  97. if len(dockerfileName) > 0 {
  98. buildOptions.Dockerfile = dockerfileName
  99. }
  100. b, err := NewBuilder(ctx, buildOptions, bm.backend, builder.DockerIgnoreContext{ModifiableContext: buildContext}, nil)
  101. if err != nil {
  102. return "", err
  103. }
  104. return b.build(pg.StdoutFormatter, pg.StderrFormatter, pg.Output)
  105. }
  106. // NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config.
  107. // If dockerfile is nil, the Dockerfile specified by Config.DockerfileName,
  108. // will be read from the Context passed to Build().
  109. func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, backend builder.Backend, buildContext builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) {
  110. if config == nil {
  111. config = new(types.ImageBuildOptions)
  112. }
  113. if config.BuildArgs == nil {
  114. config.BuildArgs = make(map[string]*string)
  115. }
  116. ctx, cancel := context.WithCancel(clientCtx)
  117. b = &Builder{
  118. clientCtx: ctx,
  119. cancel: cancel,
  120. options: config,
  121. Stdout: os.Stdout,
  122. Stderr: os.Stderr,
  123. docker: backend,
  124. context: buildContext,
  125. runConfig: new(container.Config),
  126. tmpContainers: map[string]struct{}{},
  127. id: stringid.GenerateNonCryptoID(),
  128. allowedBuildArgs: make(map[string]bool),
  129. directive: parser.Directive{
  130. EscapeSeen: false,
  131. LookingForDirectives: true,
  132. },
  133. }
  134. if icb, ok := backend.(builder.ImageCacheBuilder); ok {
  135. b.imageCache = icb.MakeImageCache(config.CacheFrom)
  136. }
  137. parser.SetEscapeToken(parser.DefaultEscapeToken, &b.directive) // Assume the default token for escape
  138. if dockerfile != nil {
  139. b.dockerfile, err = parser.Parse(dockerfile, &b.directive)
  140. if err != nil {
  141. return nil, err
  142. }
  143. }
  144. return b, nil
  145. }
  146. // sanitizeRepoAndTags parses the raw "t" parameter received from the client
  147. // to a slice of repoAndTag.
  148. // It also validates each repoName and tag.
  149. func sanitizeRepoAndTags(names []string) ([]reference.Named, error) {
  150. var (
  151. repoAndTags []reference.Named
  152. // This map is used for deduplicating the "-t" parameter.
  153. uniqNames = make(map[string]struct{})
  154. )
  155. for _, repo := range names {
  156. if repo == "" {
  157. continue
  158. }
  159. ref, err := reference.ParseNamed(repo)
  160. if err != nil {
  161. return nil, err
  162. }
  163. ref = reference.WithDefaultTag(ref)
  164. if _, isCanonical := ref.(reference.Canonical); isCanonical {
  165. return nil, errors.New("build tag cannot contain a digest")
  166. }
  167. if _, isTagged := ref.(reference.NamedTagged); !isTagged {
  168. ref, err = reference.WithTag(ref, reference.DefaultTag)
  169. if err != nil {
  170. return nil, err
  171. }
  172. }
  173. nameWithTag := ref.String()
  174. if _, exists := uniqNames[nameWithTag]; !exists {
  175. uniqNames[nameWithTag] = struct{}{}
  176. repoAndTags = append(repoAndTags, ref)
  177. }
  178. }
  179. return repoAndTags, nil
  180. }
  181. func (b *Builder) processLabels() error {
  182. if len(b.options.Labels) == 0 {
  183. return nil
  184. }
  185. var labels []string
  186. for k, v := range b.options.Labels {
  187. labels = append(labels, fmt.Sprintf("%q='%s'", k, v))
  188. }
  189. // Sort the label to have a repeatable order
  190. sort.Strings(labels)
  191. line := "LABEL " + strings.Join(labels, " ")
  192. _, node, err := parser.ParseLine(line, &b.directive, false)
  193. if err != nil {
  194. return err
  195. }
  196. b.dockerfile.Children = append(b.dockerfile.Children, node)
  197. return nil
  198. }
  199. // build runs the Dockerfile builder from a context and a docker object that allows to make calls
  200. // to Docker.
  201. //
  202. // This will (barring errors):
  203. //
  204. // * read the dockerfile from context
  205. // * parse the dockerfile if not already parsed
  206. // * walk the AST and execute it by dispatching to handlers. If Remove
  207. // or ForceRemove is set, additional cleanup around containers happens after
  208. // processing.
  209. // * Tag image, if applicable.
  210. // * Print a happy message and return the image ID.
  211. //
  212. func (b *Builder) build(stdout io.Writer, stderr io.Writer, out io.Writer) (string, error) {
  213. b.Stdout = stdout
  214. b.Stderr = stderr
  215. b.Output = out
  216. // If Dockerfile was not parsed yet, extract it from the Context
  217. if b.dockerfile == nil {
  218. if err := b.readDockerfile(); err != nil {
  219. return "", err
  220. }
  221. }
  222. repoAndTags, err := sanitizeRepoAndTags(b.options.Tags)
  223. if err != nil {
  224. return "", err
  225. }
  226. if err := b.processLabels(); err != nil {
  227. return "", err
  228. }
  229. var shortImgID string
  230. total := len(b.dockerfile.Children)
  231. for _, n := range b.dockerfile.Children {
  232. if err := b.checkDispatch(n, false); err != nil {
  233. return "", perrors.Wrapf(err, "Dockerfile parse error line %d", n.StartLine)
  234. }
  235. }
  236. for i, n := range b.dockerfile.Children {
  237. select {
  238. case <-b.clientCtx.Done():
  239. logrus.Debug("Builder: build cancelled!")
  240. fmt.Fprint(b.Stdout, "Build cancelled")
  241. return "", errors.New("Build cancelled")
  242. default:
  243. // Not cancelled yet, keep going...
  244. }
  245. if err := b.dispatch(i, total, n); err != nil {
  246. if b.options.ForceRemove {
  247. b.clearTmp()
  248. }
  249. return "", err
  250. }
  251. shortImgID = stringid.TruncateID(b.image)
  252. fmt.Fprintf(b.Stdout, " ---> %s\n", shortImgID)
  253. if b.options.Remove {
  254. b.clearTmp()
  255. }
  256. }
  257. // check if there are any leftover build-args that were passed but not
  258. // consumed during build. Return a warning, if there are any.
  259. leftoverArgs := []string{}
  260. for arg := range b.options.BuildArgs {
  261. if !b.isBuildArgAllowed(arg) {
  262. leftoverArgs = append(leftoverArgs, arg)
  263. }
  264. }
  265. if len(leftoverArgs) > 0 {
  266. fmt.Fprintf(b.Stderr, "[Warning] One or more build-args %v were not consumed\n", leftoverArgs)
  267. }
  268. if b.image == "" {
  269. return "", errors.New("No image was generated. Is your Dockerfile empty?")
  270. }
  271. if b.options.Squash {
  272. var fromID string
  273. if b.from != nil {
  274. fromID = b.from.ImageID()
  275. }
  276. b.image, err = b.docker.SquashImage(b.image, fromID)
  277. if err != nil {
  278. return "", perrors.Wrap(err, "error squashing image")
  279. }
  280. }
  281. imageID := image.ID(b.image)
  282. for _, rt := range repoAndTags {
  283. if err := b.docker.TagImageWithReference(imageID, rt); err != nil {
  284. return "", err
  285. }
  286. }
  287. fmt.Fprintf(b.Stdout, "Successfully built %s\n", shortImgID)
  288. return b.image, nil
  289. }
  290. // Cancel cancels an ongoing Dockerfile build.
  291. func (b *Builder) Cancel() {
  292. b.cancel()
  293. }
  294. // BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
  295. // It will:
  296. // - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
  297. // - Do build by calling builder.dispatch() to call all entries' handling routines
  298. //
  299. // BuildFromConfig is used by the /commit endpoint, with the changes
  300. // coming from the query parameter of the same name.
  301. //
  302. // TODO: Remove?
  303. func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
  304. b, err := NewBuilder(context.Background(), nil, nil, nil, nil)
  305. if err != nil {
  306. return nil, err
  307. }
  308. ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")), &b.directive)
  309. if err != nil {
  310. return nil, err
  311. }
  312. // ensure that the commands are valid
  313. for _, n := range ast.Children {
  314. if !validCommitCommands[n.Value] {
  315. return nil, fmt.Errorf("%s is not a valid change command", n.Value)
  316. }
  317. }
  318. b.runConfig = config
  319. b.Stdout = ioutil.Discard
  320. b.Stderr = ioutil.Discard
  321. b.disableCommit = true
  322. total := len(ast.Children)
  323. for _, n := range ast.Children {
  324. if err := b.checkDispatch(n, false); err != nil {
  325. return nil, err
  326. }
  327. }
  328. for i, n := range ast.Children {
  329. if err := b.dispatch(i, total, n); err != nil {
  330. return nil, err
  331. }
  332. }
  333. return b.runConfig, nil
  334. }