builder.go 9.4 KB

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