builder.go 8.7 KB

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