builder.go 8.1 KB

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