github.com/guilhermebr/docker@v1.4.2-0.20150428121140-67da055cebca/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/Sirupsen/logrus" 21 "github.com/docker/docker/api" 22 "github.com/docker/docker/graph" 23 "github.com/docker/docker/pkg/archive" 24 "github.com/docker/docker/pkg/fileutils" 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", "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 flCpuQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota") 59 flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)") 60 flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)") 61 62 cmd.Require(flag.Exact, 1) 63 cmd.ParseFlags(args, true) 64 65 var ( 66 context archive.Archive 67 isRemote bool 68 err error 69 ) 70 71 _, err = exec.LookPath("git") 72 hasGit := err == nil 73 if cmd.Arg(0) == "-" { 74 // As a special case, 'docker build -' will build from either an empty context with the 75 // contents of stdin as a Dockerfile, or a tar-ed context from stdin. 76 buf := bufio.NewReader(cli.in) 77 magic, err := buf.Peek(tarHeaderSize) 78 if err != nil && err != io.EOF { 79 return fmt.Errorf("failed to peek context header from STDIN: %v", err) 80 } 81 if !archive.IsArchive(magic) { 82 dockerfile, err := ioutil.ReadAll(buf) 83 if err != nil { 84 return fmt.Errorf("failed to read Dockerfile from STDIN: %v", err) 85 } 86 87 // -f option has no meaning when we're reading it from stdin, 88 // so just use our default Dockerfile name 89 *dockerfileName = api.DefaultDockerfileName 90 context, err = archive.Generate(*dockerfileName, string(dockerfile)) 91 } else { 92 context = ioutil.NopCloser(buf) 93 } 94 } else if urlutil.IsURL(cmd.Arg(0)) && (!urlutil.IsGitURL(cmd.Arg(0)) || !hasGit) { 95 isRemote = true 96 } else { 97 root := cmd.Arg(0) 98 if urlutil.IsGitURL(root) { 99 root, err = utils.GitClone(root) 100 if err != nil { 101 return err 102 } 103 defer os.RemoveAll(root) 104 } 105 if _, err := os.Stat(root); err != nil { 106 return err 107 } 108 109 absRoot, err := filepath.Abs(root) 110 if err != nil { 111 return err 112 } 113 114 filename := *dockerfileName // path to Dockerfile 115 116 if *dockerfileName == "" { 117 // No -f/--file was specified so use the default 118 *dockerfileName = api.DefaultDockerfileName 119 filename = filepath.Join(absRoot, *dockerfileName) 120 121 // Just to be nice ;-) look for 'dockerfile' too but only 122 // use it if we found it, otherwise ignore this check 123 if _, err = os.Lstat(filename); os.IsNotExist(err) { 124 tmpFN := path.Join(absRoot, strings.ToLower(*dockerfileName)) 125 if _, err = os.Lstat(tmpFN); err == nil { 126 *dockerfileName = strings.ToLower(*dockerfileName) 127 filename = tmpFN 128 } 129 } 130 } 131 132 origDockerfile := *dockerfileName // used for error msg 133 if filename, err = filepath.Abs(filename); err != nil { 134 return err 135 } 136 137 // Verify that 'filename' is within the build context 138 filename, err = symlink.FollowSymlinkInScope(filename, absRoot) 139 if err != nil { 140 return fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", origDockerfile, root) 141 } 142 143 // Now reset the dockerfileName to be relative to the build context 144 *dockerfileName, err = filepath.Rel(absRoot, filename) 145 if err != nil { 146 return err 147 } 148 // And canonicalize dockerfile name to a platform-independent one 149 *dockerfileName, err = archive.CanonicalTarNameForPath(*dockerfileName) 150 if err != nil { 151 return fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", *dockerfileName, err) 152 } 153 154 if _, err = os.Lstat(filename); os.IsNotExist(err) { 155 return fmt.Errorf("Cannot locate Dockerfile: %s", origDockerfile) 156 } 157 var includes = []string{"."} 158 159 excludes, err := utils.ReadDockerIgnore(path.Join(root, ".dockerignore")) 160 if err != nil { 161 return err 162 } 163 164 // If .dockerignore mentions .dockerignore or the Dockerfile 165 // then make sure we send both files over to the daemon 166 // because Dockerfile is, obviously, needed no matter what, and 167 // .dockerignore is needed to know if either one needs to be 168 // removed. The deamon will remove them for us, if needed, after it 169 // parses the Dockerfile. 170 keepThem1, _ := fileutils.Matches(".dockerignore", excludes) 171 keepThem2, _ := fileutils.Matches(*dockerfileName, excludes) 172 if keepThem1 || keepThem2 { 173 includes = append(includes, ".dockerignore", *dockerfileName) 174 } 175 176 if err := utils.ValidateContextDirectory(root, excludes); err != nil { 177 return fmt.Errorf("Error checking context is accessible: '%s'. Please check permissions and try again.", err) 178 } 179 options := &archive.TarOptions{ 180 Compression: archive.Uncompressed, 181 ExcludePatterns: excludes, 182 IncludeFiles: includes, 183 } 184 context, err = archive.TarWithOptions(root, options) 185 if err != nil { 186 return err 187 } 188 } 189 190 // windows: show error message about modified file permissions 191 // FIXME: this is not a valid warning when the daemon is running windows. should be removed once docker engine for windows can build. 192 if runtime.GOOS == "windows" { 193 logrus.Warn(`SECURITY WARNING: You are building a Docker image from Windows against a Linux 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.`) 194 } 195 196 var body io.Reader 197 // Setup an upload progress bar 198 // FIXME: ProgressReader shouldn't be this annoying to use 199 if context != nil { 200 sf := streamformatter.NewStreamFormatter(false) 201 body = progressreader.New(progressreader.Config{ 202 In: context, 203 Out: cli.out, 204 Formatter: sf, 205 NewLines: true, 206 ID: "", 207 Action: "Sending build context to Docker daemon", 208 }) 209 } 210 211 var memory int64 212 if *flMemoryString != "" { 213 parsedMemory, err := units.RAMInBytes(*flMemoryString) 214 if err != nil { 215 return err 216 } 217 memory = parsedMemory 218 } 219 220 var memorySwap int64 221 if *flMemorySwap != "" { 222 if *flMemorySwap == "-1" { 223 memorySwap = -1 224 } else { 225 parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap) 226 if err != nil { 227 return err 228 } 229 memorySwap = parsedMemorySwap 230 } 231 } 232 // Send the build context 233 v := &url.Values{} 234 235 //Check if the given image name can be resolved 236 if *tag != "" { 237 repository, tag := parsers.ParseRepositoryTag(*tag) 238 if err := registry.ValidateRepositoryName(repository); err != nil { 239 return err 240 } 241 if len(tag) > 0 { 242 if err := graph.ValidateTagName(tag); err != nil { 243 return err 244 } 245 } 246 } 247 248 v.Set("t", *tag) 249 250 if *suppressOutput { 251 v.Set("q", "1") 252 } 253 if isRemote { 254 v.Set("remote", cmd.Arg(0)) 255 } 256 if *noCache { 257 v.Set("nocache", "1") 258 } 259 if *rm { 260 v.Set("rm", "1") 261 } else { 262 v.Set("rm", "0") 263 } 264 265 if *forceRm { 266 v.Set("forcerm", "1") 267 } 268 269 if *pull { 270 v.Set("pull", "1") 271 } 272 273 v.Set("cpusetcpus", *flCPUSetCpus) 274 v.Set("cpusetmems", *flCPUSetMems) 275 v.Set("cpushares", strconv.FormatInt(*flCPUShares, 10)) 276 v.Set("cpuquota", strconv.FormatInt(*flCpuQuota, 10)) 277 v.Set("memory", strconv.FormatInt(memory, 10)) 278 v.Set("memswap", strconv.FormatInt(memorySwap, 10)) 279 280 v.Set("dockerfile", *dockerfileName) 281 282 headers := http.Header(make(map[string][]string)) 283 buf, err := json.Marshal(cli.configFile.AuthConfigs) 284 if err != nil { 285 return err 286 } 287 headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) 288 289 if context != nil { 290 headers.Set("Content-Type", "application/tar") 291 } 292 err = cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), body, cli.out, headers) 293 if jerr, ok := err.(*jsonmessage.JSONError); ok { 294 // If no error code is set, default to 1 295 if jerr.Code == 0 { 296 jerr.Code = 1 297 } 298 return StatusError{Status: jerr.Message, StatusCode: jerr.Code} 299 } 300 return err 301 }