builder.go 9.3 KB

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