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