github.com/hustcat/docker@v1.3.3-0.20160314103604-901c67a8eeab/api/client/build.go (about)

     1  package client
     2  
     3  import (
     4  	"archive/tar"
     5  	"bufio"
     6  	"bytes"
     7  	"fmt"
     8  	"io"
     9  	"os"
    10  	"path/filepath"
    11  	"regexp"
    12  	"runtime"
    13  
    14  	"golang.org/x/net/context"
    15  
    16  	"github.com/docker/docker/api"
    17  	"github.com/docker/docker/builder"
    18  	"github.com/docker/docker/builder/dockerignore"
    19  	Cli "github.com/docker/docker/cli"
    20  	"github.com/docker/docker/opts"
    21  	"github.com/docker/docker/pkg/archive"
    22  	"github.com/docker/docker/pkg/fileutils"
    23  	"github.com/docker/docker/pkg/jsonmessage"
    24  	flag "github.com/docker/docker/pkg/mflag"
    25  	"github.com/docker/docker/pkg/progress"
    26  	"github.com/docker/docker/pkg/streamformatter"
    27  	"github.com/docker/docker/pkg/urlutil"
    28  	"github.com/docker/docker/reference"
    29  	runconfigopts "github.com/docker/docker/runconfig/opts"
    30  	"github.com/docker/engine-api/types"
    31  	"github.com/docker/engine-api/types/container"
    32  	"github.com/docker/go-units"
    33  )
    34  
    35  type translatorFunc func(reference.NamedTagged) (reference.Canonical, error)
    36  
    37  // CmdBuild builds a new image from the source code at a given path.
    38  //
    39  // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
    40  //
    41  // Usage: docker build [OPTIONS] PATH | URL | -
    42  func (cli *DockerCli) CmdBuild(args ...string) error {
    43  	cmd := Cli.Subcmd("build", []string{"PATH | URL | -"}, Cli.DockerCommands["build"].Description, true)
    44  	flTags := opts.NewListOpts(validateTag)
    45  	cmd.Var(&flTags, []string{"t", "-tag"}, "Name and optionally a tag in the 'name:tag' format")
    46  	suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the build output and print image ID on success")
    47  	noCache := cmd.Bool([]string{"-no-cache"}, false, "Do not use cache when building the image")
    48  	rm := cmd.Bool([]string{"-rm"}, true, "Remove intermediate containers after a successful build")
    49  	forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers")
    50  	pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image")
    51  	dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
    52  	flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit")
    53  	flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
    54  	flShmSize := cmd.String([]string{"-shm-size"}, "", "Size of /dev/shm, default value is 64MB")
    55  	flCPUShares := cmd.Int64([]string{"#c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
    56  	flCPUPeriod := cmd.Int64([]string{"-cpu-period"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) period")
    57  	flCPUQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
    58  	flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
    59  	flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
    60  	flCgroupParent := cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
    61  	flBuildArg := opts.NewListOpts(runconfigopts.ValidateEnv)
    62  	cmd.Var(&flBuildArg, []string{"-build-arg"}, "Set build-time variables")
    63  	isolation := cmd.String([]string{"-isolation"}, "", "Container isolation technology")
    64  
    65  	ulimits := make(map[string]*units.Ulimit)
    66  	flUlimits := runconfigopts.NewUlimitOpt(&ulimits)
    67  	cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
    68  
    69  	cmd.Require(flag.Exact, 1)
    70  
    71  	// For trusted pull on "FROM <image>" instruction.
    72  	addTrustedFlags(cmd, true)
    73  
    74  	cmd.ParseFlags(args, true)
    75  
    76  	var (
    77  		ctx io.ReadCloser
    78  		err error
    79  	)
    80  
    81  	specifiedContext := cmd.Arg(0)
    82  
    83  	var (
    84  		contextDir    string
    85  		tempDir       string
    86  		relDockerfile string
    87  		progBuff      io.Writer
    88  		buildBuff     io.Writer
    89  	)
    90  
    91  	progBuff = cli.out
    92  	buildBuff = cli.out
    93  	if *suppressOutput {
    94  		progBuff = bytes.NewBuffer(nil)
    95  		buildBuff = bytes.NewBuffer(nil)
    96  	}
    97  
    98  	switch {
    99  	case specifiedContext == "-":
   100  		ctx, relDockerfile, err = builder.GetContextFromReader(cli.in, *dockerfileName)
   101  	case urlutil.IsGitURL(specifiedContext):
   102  		tempDir, relDockerfile, err = builder.GetContextFromGitURL(specifiedContext, *dockerfileName)
   103  	case urlutil.IsURL(specifiedContext):
   104  		ctx, relDockerfile, err = builder.GetContextFromURL(progBuff, specifiedContext, *dockerfileName)
   105  	default:
   106  		contextDir, relDockerfile, err = builder.GetContextFromLocalDir(specifiedContext, *dockerfileName)
   107  	}
   108  
   109  	if err != nil {
   110  		if *suppressOutput && urlutil.IsURL(specifiedContext) {
   111  			fmt.Fprintln(cli.err, progBuff)
   112  		}
   113  		return fmt.Errorf("unable to prepare context: %s", err)
   114  	}
   115  
   116  	if tempDir != "" {
   117  		defer os.RemoveAll(tempDir)
   118  		contextDir = tempDir
   119  	}
   120  
   121  	if ctx == nil {
   122  		// And canonicalize dockerfile name to a platform-independent one
   123  		relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
   124  		if err != nil {
   125  			return fmt.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err)
   126  		}
   127  
   128  		f, err := os.Open(filepath.Join(contextDir, ".dockerignore"))
   129  		if err != nil && !os.IsNotExist(err) {
   130  			return err
   131  		}
   132  
   133  		var excludes []string
   134  		if err == nil {
   135  			excludes, err = dockerignore.ReadAll(f)
   136  			if err != nil {
   137  				return err
   138  			}
   139  		}
   140  
   141  		if err := builder.ValidateContextDirectory(contextDir, excludes); err != nil {
   142  			return fmt.Errorf("Error checking context: '%s'.", err)
   143  		}
   144  
   145  		// If .dockerignore mentions .dockerignore or the Dockerfile
   146  		// then make sure we send both files over to the daemon
   147  		// because Dockerfile is, obviously, needed no matter what, and
   148  		// .dockerignore is needed to know if either one needs to be
   149  		// removed. The daemon will remove them for us, if needed, after it
   150  		// parses the Dockerfile. Ignore errors here, as they will have been
   151  		// caught by validateContextDirectory above.
   152  		var includes = []string{"."}
   153  		keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
   154  		keepThem2, _ := fileutils.Matches(relDockerfile, excludes)
   155  		if keepThem1 || keepThem2 {
   156  			includes = append(includes, ".dockerignore", relDockerfile)
   157  		}
   158  
   159  		ctx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
   160  			Compression:     archive.Uncompressed,
   161  			ExcludePatterns: excludes,
   162  			IncludeFiles:    includes,
   163  		})
   164  		if err != nil {
   165  			return err
   166  		}
   167  	}
   168  
   169  	var resolvedTags []*resolvedTag
   170  	if isTrusted() {
   171  		// Wrap the tar archive to replace the Dockerfile entry with the rewritten
   172  		// Dockerfile which uses trusted pulls.
   173  		ctx = replaceDockerfileTarWrapper(ctx, relDockerfile, cli.trustedReference, &resolvedTags)
   174  	}
   175  
   176  	// Setup an upload progress bar
   177  	progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(progBuff, true)
   178  
   179  	var body io.Reader = progress.NewProgressReader(ctx, progressOutput, 0, "", "Sending build context to Docker daemon")
   180  
   181  	var memory int64
   182  	if *flMemoryString != "" {
   183  		parsedMemory, err := units.RAMInBytes(*flMemoryString)
   184  		if err != nil {
   185  			return err
   186  		}
   187  		memory = parsedMemory
   188  	}
   189  
   190  	var memorySwap int64
   191  	if *flMemorySwap != "" {
   192  		if *flMemorySwap == "-1" {
   193  			memorySwap = -1
   194  		} else {
   195  			parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
   196  			if err != nil {
   197  				return err
   198  			}
   199  			memorySwap = parsedMemorySwap
   200  		}
   201  	}
   202  
   203  	var shmSize int64
   204  	if *flShmSize != "" {
   205  		shmSize, err = units.RAMInBytes(*flShmSize)
   206  		if err != nil {
   207  			return err
   208  		}
   209  	}
   210  
   211  	options := types.ImageBuildOptions{
   212  		Context:        body,
   213  		Memory:         memory,
   214  		MemorySwap:     memorySwap,
   215  		Tags:           flTags.GetAll(),
   216  		SuppressOutput: *suppressOutput,
   217  		NoCache:        *noCache,
   218  		Remove:         *rm,
   219  		ForceRemove:    *forceRm,
   220  		PullParent:     *pull,
   221  		Isolation:      container.Isolation(*isolation),
   222  		CPUSetCPUs:     *flCPUSetCpus,
   223  		CPUSetMems:     *flCPUSetMems,
   224  		CPUShares:      *flCPUShares,
   225  		CPUQuota:       *flCPUQuota,
   226  		CPUPeriod:      *flCPUPeriod,
   227  		CgroupParent:   *flCgroupParent,
   228  		Dockerfile:     relDockerfile,
   229  		ShmSize:        shmSize,
   230  		Ulimits:        flUlimits.GetList(),
   231  		BuildArgs:      runconfigopts.ConvertKVStringsToMap(flBuildArg.GetAll()),
   232  		AuthConfigs:    cli.retrieveAuthConfigs(),
   233  	}
   234  
   235  	response, err := cli.client.ImageBuild(context.Background(), options)
   236  	if err != nil {
   237  		return err
   238  	}
   239  
   240  	err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, cli.outFd, cli.isTerminalOut, nil)
   241  	if err != nil {
   242  		if jerr, ok := err.(*jsonmessage.JSONError); ok {
   243  			// If no error code is set, default to 1
   244  			if jerr.Code == 0 {
   245  				jerr.Code = 1
   246  			}
   247  			if *suppressOutput {
   248  				fmt.Fprintf(cli.err, "%s%s", progBuff, buildBuff)
   249  			}
   250  			return Cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
   251  		}
   252  	}
   253  
   254  	// Windows: show error message about modified file permissions if the
   255  	// daemon isn't running Windows.
   256  	if response.OSType != "windows" && runtime.GOOS == "windows" {
   257  		fmt.Fprintln(cli.err, `SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.`)
   258  	}
   259  
   260  	// Everything worked so if -q was provided the output from the daemon
   261  	// should be just the image ID and we'll print that to stdout.
   262  	if *suppressOutput {
   263  		fmt.Fprintf(cli.out, "%s", buildBuff)
   264  	}
   265  
   266  	if isTrusted() {
   267  		// Since the build was successful, now we must tag any of the resolved
   268  		// images from the above Dockerfile rewrite.
   269  		for _, resolved := range resolvedTags {
   270  			if err := cli.tagTrusted(resolved.digestRef, resolved.tagRef); err != nil {
   271  				return err
   272  			}
   273  		}
   274  	}
   275  
   276  	return nil
   277  }
   278  
   279  // validateTag checks if the given image name can be resolved.
   280  func validateTag(rawRepo string) (string, error) {
   281  	_, err := reference.ParseNamed(rawRepo)
   282  	if err != nil {
   283  		return "", err
   284  	}
   285  
   286  	return rawRepo, nil
   287  }
   288  
   289  // writeToFile copies from the given reader and writes it to a file with the
   290  // given filename.
   291  func writeToFile(r io.Reader, filename string) error {
   292  	file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600))
   293  	if err != nil {
   294  		return fmt.Errorf("unable to create file: %v", err)
   295  	}
   296  	defer file.Close()
   297  
   298  	if _, err := io.Copy(file, r); err != nil {
   299  		return fmt.Errorf("unable to write file: %v", err)
   300  	}
   301  
   302  	return nil
   303  }
   304  
   305  var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
   306  
   307  // resolvedTag records the repository, tag, and resolved digest reference
   308  // from a Dockerfile rewrite.
   309  type resolvedTag struct {
   310  	digestRef reference.Canonical
   311  	tagRef    reference.NamedTagged
   312  }
   313  
   314  // rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
   315  // "FROM <image>" instructions to a digest reference. `translator` is a
   316  // function that takes a repository name and tag reference and returns a
   317  // trusted digest reference.
   318  func rewriteDockerfileFrom(dockerfile io.Reader, translator translatorFunc) (newDockerfile []byte, resolvedTags []*resolvedTag, err error) {
   319  	scanner := bufio.NewScanner(dockerfile)
   320  	buf := bytes.NewBuffer(nil)
   321  
   322  	// Scan the lines of the Dockerfile, looking for a "FROM" line.
   323  	for scanner.Scan() {
   324  		line := scanner.Text()
   325  
   326  		matches := dockerfileFromLinePattern.FindStringSubmatch(line)
   327  		if matches != nil && matches[1] != api.NoBaseImageSpecifier {
   328  			// Replace the line with a resolved "FROM repo@digest"
   329  			ref, err := reference.ParseNamed(matches[1])
   330  			if err != nil {
   331  				return nil, nil, err
   332  			}
   333  			ref = reference.WithDefaultTag(ref)
   334  			if ref, ok := ref.(reference.NamedTagged); ok && isTrusted() {
   335  				trustedRef, err := translator(ref)
   336  				if err != nil {
   337  					return nil, nil, err
   338  				}
   339  
   340  				line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.String()))
   341  				resolvedTags = append(resolvedTags, &resolvedTag{
   342  					digestRef: trustedRef,
   343  					tagRef:    ref,
   344  				})
   345  			}
   346  		}
   347  
   348  		_, err := fmt.Fprintln(buf, line)
   349  		if err != nil {
   350  			return nil, nil, err
   351  		}
   352  	}
   353  
   354  	return buf.Bytes(), resolvedTags, scanner.Err()
   355  }
   356  
   357  // replaceDockerfileTarWrapper wraps the given input tar archive stream and
   358  // replaces the entry with the given Dockerfile name with the contents of the
   359  // new Dockerfile. Returns a new tar archive stream with the replaced
   360  // Dockerfile.
   361  func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, dockerfileName string, translator translatorFunc, resolvedTags *[]*resolvedTag) io.ReadCloser {
   362  	pipeReader, pipeWriter := io.Pipe()
   363  	go func() {
   364  		tarReader := tar.NewReader(inputTarStream)
   365  		tarWriter := tar.NewWriter(pipeWriter)
   366  
   367  		defer inputTarStream.Close()
   368  
   369  		for {
   370  			hdr, err := tarReader.Next()
   371  			if err == io.EOF {
   372  				// Signals end of archive.
   373  				tarWriter.Close()
   374  				pipeWriter.Close()
   375  				return
   376  			}
   377  			if err != nil {
   378  				pipeWriter.CloseWithError(err)
   379  				return
   380  			}
   381  
   382  			var content io.Reader = tarReader
   383  			if hdr.Name == dockerfileName {
   384  				// This entry is the Dockerfile. Since the tar archive was
   385  				// generated from a directory on the local filesystem, the
   386  				// Dockerfile will only appear once in the archive.
   387  				var newDockerfile []byte
   388  				newDockerfile, *resolvedTags, err = rewriteDockerfileFrom(content, translator)
   389  				if err != nil {
   390  					pipeWriter.CloseWithError(err)
   391  					return
   392  				}
   393  				hdr.Size = int64(len(newDockerfile))
   394  				content = bytes.NewBuffer(newDockerfile)
   395  			}
   396  
   397  			if err := tarWriter.WriteHeader(hdr); err != nil {
   398  				pipeWriter.CloseWithError(err)
   399  				return
   400  			}
   401  
   402  			if _, err := io.Copy(tarWriter, content); err != nil {
   403  				pipeWriter.CloseWithError(err)
   404  				return
   405  			}
   406  		}
   407  	}()
   408  
   409  	return pipeReader
   410  }