github.com/kobeld/docker@v1.12.0-rc1/builder/dockerfile/builder.go (about)

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