builder.go 10.0 KB

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