github.com/chenchun/docker@v1.3.2-0.20150629222414-20467faf132b/api/client/build.go (about)

     1  package client
     2  
     3  import (
     4  	"bufio"
     5  	"encoding/base64"
     6  	"encoding/json"
     7  	"fmt"
     8  	"io"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"net/url"
    12  	"os"
    13  	"os/exec"
    14  	"path"
    15  	"path/filepath"
    16  	"runtime"
    17  	"strconv"
    18  	"strings"
    19  
    20  	"github.com/docker/docker/api"
    21  	"github.com/docker/docker/graph/tags"
    22  	"github.com/docker/docker/pkg/archive"
    23  	"github.com/docker/docker/pkg/fileutils"
    24  	"github.com/docker/docker/pkg/httputils"
    25  	"github.com/docker/docker/pkg/jsonmessage"
    26  	flag "github.com/docker/docker/pkg/mflag"
    27  	"github.com/docker/docker/pkg/parsers"
    28  	"github.com/docker/docker/pkg/progressreader"
    29  	"github.com/docker/docker/pkg/streamformatter"
    30  	"github.com/docker/docker/pkg/symlink"
    31  	"github.com/docker/docker/pkg/units"
    32  	"github.com/docker/docker/pkg/urlutil"
    33  	"github.com/docker/docker/registry"
    34  	"github.com/docker/docker/utils"
    35  )
    36  
    37  const (
    38  	tarHeaderSize = 512
    39  )
    40  
    41  // CmdBuild builds a new image from the source code at a given path.
    42  //
    43  // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
    44  //
    45  // Usage: docker build [OPTIONS] PATH | URL | -
    46  func (cli *DockerCli) CmdBuild(args ...string) error {
    47  	cmd := cli.Subcmd("build", []string{"PATH | URL | -"}, "Build a new image from the source code at PATH", true)
    48  	tag := cmd.String([]string{"t", "-tag"}, "", "Repository name (and optionally a tag) for the image")
    49  	suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers")
    50  	noCache := cmd.Bool([]string{"#no-cache", "-no-cache"}, false, "Do not use cache when building the image")
    51  	rm := cmd.Bool([]string{"#rm", "-rm"}, true, "Remove intermediate containers after a successful build")
    52  	forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers")
    53  	pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image")
    54  	dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
    55  	flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit")
    56  	flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap")
    57  	flCPUShares := cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
    58  	flCpuPeriod := cmd.Int64([]string{"-cpu-period"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) period")
    59  	flCpuQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
    60  	flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
    61  	flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
    62  	flCgroupParent := cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
    63  
    64  	cmd.Require(flag.Exact, 1)
    65  	cmd.ParseFlags(args, true)
    66  
    67  	var (
    68  		context  archive.Archive
    69  		isRemote bool
    70  		err      error
    71  	)
    72  
    73  	_, err = exec.LookPath("git")
    74  	hasGit := err == nil
    75  	if cmd.Arg(0) == "-" {
    76  		// As a special case, 'docker build -' will build from either an empty context with the
    77  		// contents of stdin as a Dockerfile, or a tar-ed context from stdin.
    78  		buf := bufio.NewReader(cli.in)
    79  		magic, err := buf.Peek(tarHeaderSize)
    80  		if err != nil && err != io.EOF {
    81  			return fmt.Errorf("failed to peek context header from STDIN: %v", err)
    82  		}
    83  		if !archive.IsArchive(magic) {
    84  			dockerfile, err := ioutil.ReadAll(buf)
    85  			if err != nil {
    86  				return fmt.Errorf("failed to read Dockerfile from STDIN: %v", err)
    87  			}
    88  
    89  			// -f option has no meaning when we're reading it from stdin,
    90  			// so just use our default Dockerfile name
    91  			*dockerfileName = api.DefaultDockerfileName
    92  			context, err = archive.Generate(*dockerfileName, string(dockerfile))
    93  		} else {
    94  			context = ioutil.NopCloser(buf)
    95  		}
    96  	} else if urlutil.IsURL(cmd.Arg(0)) && (!urlutil.IsGitURL(cmd.Arg(0)) || !hasGit) {
    97  		isRemote = true
    98  	} else {
    99  		root := cmd.Arg(0)
   100  		if urlutil.IsGitURL(root) {
   101  			root, err = utils.GitClone(root)
   102  			if err != nil {
   103  				return err
   104  			}
   105  			defer os.RemoveAll(root)
   106  		}
   107  		if _, err := os.Stat(root); err != nil {
   108  			return err
   109  		}
   110  
   111  		absRoot, err := filepath.Abs(root)
   112  		if err != nil {
   113  			return err
   114  		}
   115  
   116  		filename := *dockerfileName // path to Dockerfile
   117  
   118  		if *dockerfileName == "" {
   119  			// No -f/--file was specified so use the default
   120  			*dockerfileName = api.DefaultDockerfileName
   121  			filename = filepath.Join(absRoot, *dockerfileName)
   122  
   123  			// Just to be nice ;-) look for 'dockerfile' too but only
   124  			// use it if we found it, otherwise ignore this check
   125  			if _, err = os.Lstat(filename); os.IsNotExist(err) {
   126  				tmpFN := path.Join(absRoot, strings.ToLower(*dockerfileName))
   127  				if _, err = os.Lstat(tmpFN); err == nil {
   128  					*dockerfileName = strings.ToLower(*dockerfileName)
   129  					filename = tmpFN
   130  				}
   131  			}
   132  		}
   133  
   134  		origDockerfile := *dockerfileName // used for error msg
   135  		if filename, err = filepath.Abs(filename); err != nil {
   136  			return err
   137  		}
   138  
   139  		// Verify that 'filename' is within the build context
   140  		filename, err = symlink.FollowSymlinkInScope(filename, absRoot)
   141  		if err != nil {
   142  			return fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", origDockerfile, root)
   143  		}
   144  
   145  		// Now reset the dockerfileName to be relative to the build context
   146  		*dockerfileName, err = filepath.Rel(absRoot, filename)
   147  		if err != nil {
   148  			return err
   149  		}
   150  		// And canonicalize dockerfile name to a platform-independent one
   151  		*dockerfileName, err = archive.CanonicalTarNameForPath(*dockerfileName)
   152  		if err != nil {
   153  			return fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", *dockerfileName, err)
   154  		}
   155  
   156  		if _, err = os.Lstat(filename); os.IsNotExist(err) {
   157  			return fmt.Errorf("Cannot locate Dockerfile: %s", origDockerfile)
   158  		}
   159  		var includes = []string{"."}
   160  
   161  		excludes, err := utils.ReadDockerIgnore(path.Join(root, ".dockerignore"))
   162  		if err != nil {
   163  			return err
   164  		}
   165  
   166  		// If .dockerignore mentions .dockerignore or the Dockerfile
   167  		// then make sure we send both files over to the daemon
   168  		// because Dockerfile is, obviously, needed no matter what, and
   169  		// .dockerignore is needed to know if either one needs to be
   170  		// removed.  The deamon will remove them for us, if needed, after it
   171  		// parses the Dockerfile.
   172  		keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
   173  		keepThem2, _ := fileutils.Matches(*dockerfileName, excludes)
   174  		if keepThem1 || keepThem2 {
   175  			includes = append(includes, ".dockerignore", *dockerfileName)
   176  		}
   177  
   178  		if err := utils.ValidateContextDirectory(root, excludes); err != nil {
   179  			return fmt.Errorf("Error checking context: '%s'.", err)
   180  		}
   181  		options := &archive.TarOptions{
   182  			Compression:     archive.Uncompressed,
   183  			ExcludePatterns: excludes,
   184  			IncludeFiles:    includes,
   185  		}
   186  		context, err = archive.TarWithOptions(root, options)
   187  		if err != nil {
   188  			return err
   189  		}
   190  	}
   191  
   192  	var body io.Reader
   193  	// Setup an upload progress bar
   194  	// FIXME: ProgressReader shouldn't be this annoying to use
   195  	if context != nil {
   196  		sf := streamformatter.NewStreamFormatter()
   197  		body = progressreader.New(progressreader.Config{
   198  			In:        context,
   199  			Out:       cli.out,
   200  			Formatter: sf,
   201  			NewLines:  true,
   202  			ID:        "",
   203  			Action:    "Sending build context to Docker daemon",
   204  		})
   205  	}
   206  
   207  	var memory int64
   208  	if *flMemoryString != "" {
   209  		parsedMemory, err := units.RAMInBytes(*flMemoryString)
   210  		if err != nil {
   211  			return err
   212  		}
   213  		memory = parsedMemory
   214  	}
   215  
   216  	var memorySwap int64
   217  	if *flMemorySwap != "" {
   218  		if *flMemorySwap == "-1" {
   219  			memorySwap = -1
   220  		} else {
   221  			parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
   222  			if err != nil {
   223  				return err
   224  			}
   225  			memorySwap = parsedMemorySwap
   226  		}
   227  	}
   228  	// Send the build context
   229  	v := &url.Values{}
   230  
   231  	//Check if the given image name can be resolved
   232  	if *tag != "" {
   233  		repository, tag := parsers.ParseRepositoryTag(*tag)
   234  		if err := registry.ValidateRepositoryName(repository); err != nil {
   235  			return err
   236  		}
   237  		if len(tag) > 0 {
   238  			if err := tags.ValidateTagName(tag); err != nil {
   239  				return err
   240  			}
   241  		}
   242  	}
   243  
   244  	v.Set("t", *tag)
   245  
   246  	if *suppressOutput {
   247  		v.Set("q", "1")
   248  	}
   249  	if isRemote {
   250  		v.Set("remote", cmd.Arg(0))
   251  	}
   252  	if *noCache {
   253  		v.Set("nocache", "1")
   254  	}
   255  	if *rm {
   256  		v.Set("rm", "1")
   257  	} else {
   258  		v.Set("rm", "0")
   259  	}
   260  
   261  	if *forceRm {
   262  		v.Set("forcerm", "1")
   263  	}
   264  
   265  	if *pull {
   266  		v.Set("pull", "1")
   267  	}
   268  
   269  	v.Set("cpusetcpus", *flCPUSetCpus)
   270  	v.Set("cpusetmems", *flCPUSetMems)
   271  	v.Set("cpushares", strconv.FormatInt(*flCPUShares, 10))
   272  	v.Set("cpuquota", strconv.FormatInt(*flCpuQuota, 10))
   273  	v.Set("cpuperiod", strconv.FormatInt(*flCpuPeriod, 10))
   274  	v.Set("memory", strconv.FormatInt(memory, 10))
   275  	v.Set("memswap", strconv.FormatInt(memorySwap, 10))
   276  	v.Set("cgroupparent", *flCgroupParent)
   277  
   278  	v.Set("dockerfile", *dockerfileName)
   279  
   280  	headers := http.Header(make(map[string][]string))
   281  	buf, err := json.Marshal(cli.configFile.AuthConfigs)
   282  	if err != nil {
   283  		return err
   284  	}
   285  	headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf))
   286  
   287  	if context != nil {
   288  		headers.Set("Content-Type", "application/tar")
   289  	}
   290  	sopts := &streamOpts{
   291  		rawTerminal: true,
   292  		in:          body,
   293  		out:         cli.out,
   294  		headers:     headers,
   295  	}
   296  
   297  	serverResp, err := cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), sopts)
   298  
   299  	// Windows: show error message about modified file permissions.
   300  	if runtime.GOOS == "windows" {
   301  		h, err := httputils.ParseServerHeader(serverResp.header.Get("Server"))
   302  		if err == nil {
   303  			if h.OS != "windows" {
   304  				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.`)
   305  			}
   306  		}
   307  	}
   308  
   309  	if jerr, ok := err.(*jsonmessage.JSONError); ok {
   310  		// If no error code is set, default to 1
   311  		if jerr.Code == 0 {
   312  			jerr.Code = 1
   313  		}
   314  		return StatusError{Status: jerr.Message, StatusCode: jerr.Code}
   315  	}
   316  	return err
   317  }