build_routes.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package build
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "github.com/Sirupsen/logrus"
  14. "github.com/docker/docker/api/server/httputils"
  15. "github.com/docker/docker/api/types"
  16. "github.com/docker/docker/api/types/backend"
  17. "github.com/docker/docker/api/types/container"
  18. "github.com/docker/docker/api/types/versions"
  19. "github.com/docker/docker/pkg/ioutils"
  20. "github.com/docker/docker/pkg/progress"
  21. "github.com/docker/docker/pkg/streamformatter"
  22. "github.com/docker/go-units"
  23. "golang.org/x/net/context"
  24. )
  25. func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBuildOptions, error) {
  26. version := httputils.VersionFromContext(ctx)
  27. options := &types.ImageBuildOptions{}
  28. if httputils.BoolValue(r, "forcerm") && versions.GreaterThanOrEqualTo(version, "1.12") {
  29. options.Remove = true
  30. } else if r.FormValue("rm") == "" && versions.GreaterThanOrEqualTo(version, "1.12") {
  31. options.Remove = true
  32. } else {
  33. options.Remove = httputils.BoolValue(r, "rm")
  34. }
  35. if httputils.BoolValue(r, "pull") && versions.GreaterThanOrEqualTo(version, "1.16") {
  36. options.PullParent = true
  37. }
  38. options.Dockerfile = r.FormValue("dockerfile")
  39. options.SuppressOutput = httputils.BoolValue(r, "q")
  40. options.NoCache = httputils.BoolValue(r, "nocache")
  41. options.ForceRemove = httputils.BoolValue(r, "forcerm")
  42. options.MemorySwap = httputils.Int64ValueOrZero(r, "memswap")
  43. options.Memory = httputils.Int64ValueOrZero(r, "memory")
  44. options.CPUShares = httputils.Int64ValueOrZero(r, "cpushares")
  45. options.CPUPeriod = httputils.Int64ValueOrZero(r, "cpuperiod")
  46. options.CPUQuota = httputils.Int64ValueOrZero(r, "cpuquota")
  47. options.CPUSetCPUs = r.FormValue("cpusetcpus")
  48. options.CPUSetMems = r.FormValue("cpusetmems")
  49. options.CgroupParent = r.FormValue("cgroupparent")
  50. options.NetworkMode = r.FormValue("networkmode")
  51. options.Tags = r.Form["t"]
  52. options.ExtraHosts = r.Form["extrahosts"]
  53. options.SecurityOpt = r.Form["securityopt"]
  54. options.Squash = httputils.BoolValue(r, "squash")
  55. options.Target = r.FormValue("target")
  56. if r.Form.Get("shmsize") != "" {
  57. shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
  58. if err != nil {
  59. return nil, err
  60. }
  61. options.ShmSize = shmSize
  62. }
  63. if i := container.Isolation(r.FormValue("isolation")); i != "" {
  64. if !container.Isolation.IsValid(i) {
  65. return nil, fmt.Errorf("Unsupported isolation: %q", i)
  66. }
  67. options.Isolation = i
  68. }
  69. if runtime.GOOS != "windows" && options.SecurityOpt != nil {
  70. return nil, fmt.Errorf("the daemon on this platform does not support --security-opt to build")
  71. }
  72. var buildUlimits = []*units.Ulimit{}
  73. ulimitsJSON := r.FormValue("ulimits")
  74. if ulimitsJSON != "" {
  75. if err := json.Unmarshal([]byte(ulimitsJSON), &buildUlimits); err != nil {
  76. return nil, err
  77. }
  78. options.Ulimits = buildUlimits
  79. }
  80. var buildArgs = map[string]*string{}
  81. buildArgsJSON := r.FormValue("buildargs")
  82. // Note that there are two ways a --build-arg might appear in the
  83. // json of the query param:
  84. // "foo":"bar"
  85. // and "foo":nil
  86. // The first is the normal case, ie. --build-arg foo=bar
  87. // or --build-arg foo
  88. // where foo's value was picked up from an env var.
  89. // The second ("foo":nil) is where they put --build-arg foo
  90. // but "foo" isn't set as an env var. In that case we can't just drop
  91. // the fact they mentioned it, we need to pass that along to the builder
  92. // so that it can print a warning about "foo" being unused if there is
  93. // no "ARG foo" in the Dockerfile.
  94. if buildArgsJSON != "" {
  95. if err := json.Unmarshal([]byte(buildArgsJSON), &buildArgs); err != nil {
  96. return nil, err
  97. }
  98. options.BuildArgs = buildArgs
  99. }
  100. var labels = map[string]string{}
  101. labelsJSON := r.FormValue("labels")
  102. if labelsJSON != "" {
  103. if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {
  104. return nil, err
  105. }
  106. options.Labels = labels
  107. }
  108. var cacheFrom = []string{}
  109. cacheFromJSON := r.FormValue("cachefrom")
  110. if cacheFromJSON != "" {
  111. if err := json.Unmarshal([]byte(cacheFromJSON), &cacheFrom); err != nil {
  112. return nil, err
  113. }
  114. options.CacheFrom = cacheFrom
  115. }
  116. return options, nil
  117. }
  118. type syncWriter struct {
  119. w io.Writer
  120. mu sync.Mutex
  121. }
  122. func (s *syncWriter) Write(b []byte) (count int, err error) {
  123. s.mu.Lock()
  124. count, err = s.w.Write(b)
  125. s.mu.Unlock()
  126. return
  127. }
  128. func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  129. var (
  130. authConfigs = map[string]types.AuthConfig{}
  131. authConfigsEncoded = r.Header.Get("X-Registry-Config")
  132. notVerboseBuffer = bytes.NewBuffer(nil)
  133. )
  134. if authConfigsEncoded != "" {
  135. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  136. if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
  137. // for a pull it is not an error if no auth was given
  138. // to increase compatibility with the existing api it is defaulting
  139. // to be empty.
  140. }
  141. }
  142. w.Header().Set("Content-Type", "application/json")
  143. output := ioutils.NewWriteFlusher(w)
  144. defer output.Close()
  145. sf := streamformatter.NewJSONStreamFormatter()
  146. errf := func(err error) error {
  147. if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
  148. output.Write(notVerboseBuffer.Bytes())
  149. }
  150. // Do not write the error in the http output if it's still empty.
  151. // This prevents from writing a 200(OK) when there is an internal error.
  152. if !output.Flushed() {
  153. return err
  154. }
  155. _, err = w.Write(sf.FormatError(err))
  156. if err != nil {
  157. logrus.Warnf("could not write error response: %v", err)
  158. }
  159. return nil
  160. }
  161. buildOptions, err := newImageBuildOptions(ctx, r)
  162. if err != nil {
  163. return errf(err)
  164. }
  165. buildOptions.AuthConfigs = authConfigs
  166. remoteURL := r.FormValue("remote")
  167. // Currently, only used if context is from a remote url.
  168. // Look at code in DetectContextFromRemoteURL for more information.
  169. createProgressReader := func(in io.ReadCloser) io.ReadCloser {
  170. progressOutput := sf.NewProgressOutput(output, true)
  171. if buildOptions.SuppressOutput {
  172. progressOutput = sf.NewProgressOutput(notVerboseBuffer, true)
  173. }
  174. return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL)
  175. }
  176. out := io.Writer(output)
  177. if buildOptions.SuppressOutput {
  178. out = notVerboseBuffer
  179. }
  180. out = &syncWriter{w: out}
  181. stdout := &streamformatter.StdoutFormatter{Writer: out, StreamFormatter: sf}
  182. stderr := &streamformatter.StderrFormatter{Writer: out, StreamFormatter: sf}
  183. pg := backend.ProgressWriter{
  184. Output: out,
  185. StdoutFormatter: stdout,
  186. StderrFormatter: stderr,
  187. ProgressReaderFunc: createProgressReader,
  188. }
  189. imgID, err := br.backend.BuildFromContext(ctx, r.Body, remoteURL, buildOptions, pg)
  190. if err != nil {
  191. return errf(err)
  192. }
  193. // Everything worked so if -q was provided the output from the daemon
  194. // should be just the image ID and we'll print that to stdout.
  195. if buildOptions.SuppressOutput {
  196. stdout := &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf}
  197. fmt.Fprintf(stdout, "%s\n", string(imgID))
  198. }
  199. return nil
  200. }