build.go 9.1 KB

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