build.go 9.7 KB

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