build.go 9.7 KB

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