build.go 9.4 KB

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