build_routes.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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.SecurityOpt = r.Form["securityopt"]
  53. options.Squash = httputils.BoolValue(r, "squash")
  54. if r.Form.Get("shmsize") != "" {
  55. shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
  56. if err != nil {
  57. return nil, err
  58. }
  59. options.ShmSize = shmSize
  60. }
  61. if i := container.Isolation(r.FormValue("isolation")); i != "" {
  62. if !container.Isolation.IsValid(i) {
  63. return nil, fmt.Errorf("Unsupported isolation: %q", i)
  64. }
  65. options.Isolation = i
  66. }
  67. if runtime.GOOS != "windows" && options.SecurityOpt != nil {
  68. return nil, fmt.Errorf("the daemon on this platform does not support --security-opt to build")
  69. }
  70. var buildUlimits = []*units.Ulimit{}
  71. ulimitsJSON := r.FormValue("ulimits")
  72. if ulimitsJSON != "" {
  73. if err := json.Unmarshal([]byte(ulimitsJSON), &buildUlimits); err != nil {
  74. return nil, err
  75. }
  76. options.Ulimits = buildUlimits
  77. }
  78. var buildArgs = map[string]*string{}
  79. buildArgsJSON := r.FormValue("buildargs")
  80. // Note that there are two ways a --build-arg might appear in the
  81. // json of the query param:
  82. // "foo":"bar"
  83. // and "foo":nil
  84. // The first is the normal case, ie. --build-arg foo=bar
  85. // or --build-arg foo
  86. // where foo's value was picked up from an env var.
  87. // The second ("foo":nil) is where they put --build-arg foo
  88. // but "foo" isn't set as an env var. In that case we can't just drop
  89. // the fact they mentioned it, we need to pass that along to the builder
  90. // so that it can print a warning about "foo" being unused if there is
  91. // no "ARG foo" in the Dockerfile.
  92. if buildArgsJSON != "" {
  93. if err := json.Unmarshal([]byte(buildArgsJSON), &buildArgs); err != nil {
  94. return nil, err
  95. }
  96. options.BuildArgs = buildArgs
  97. }
  98. var labels = map[string]string{}
  99. labelsJSON := r.FormValue("labels")
  100. if labelsJSON != "" {
  101. if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {
  102. return nil, err
  103. }
  104. options.Labels = labels
  105. }
  106. var cacheFrom = []string{}
  107. cacheFromJSON := r.FormValue("cachefrom")
  108. if cacheFromJSON != "" {
  109. if err := json.Unmarshal([]byte(cacheFromJSON), &cacheFrom); err != nil {
  110. return nil, err
  111. }
  112. options.CacheFrom = cacheFrom
  113. }
  114. return options, nil
  115. }
  116. type syncWriter struct {
  117. w io.Writer
  118. mu sync.Mutex
  119. }
  120. func (s *syncWriter) Write(b []byte) (count int, err error) {
  121. s.mu.Lock()
  122. count, err = s.w.Write(b)
  123. s.mu.Unlock()
  124. return
  125. }
  126. func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  127. var (
  128. authConfigs = map[string]types.AuthConfig{}
  129. authConfigsEncoded = r.Header.Get("X-Registry-Config")
  130. notVerboseBuffer = bytes.NewBuffer(nil)
  131. )
  132. if authConfigsEncoded != "" {
  133. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  134. if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
  135. // for a pull it is not an error if no auth was given
  136. // to increase compatibility with the existing api it is defaulting
  137. // to be empty.
  138. }
  139. }
  140. w.Header().Set("Content-Type", "application/json")
  141. output := ioutils.NewWriteFlusher(w)
  142. defer output.Close()
  143. sf := streamformatter.NewJSONStreamFormatter()
  144. errf := func(err error) error {
  145. if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
  146. output.Write(notVerboseBuffer.Bytes())
  147. }
  148. // Do not write the error in the http output if it's still empty.
  149. // This prevents from writing a 200(OK) when there is an internal error.
  150. if !output.Flushed() {
  151. return err
  152. }
  153. _, err = w.Write(sf.FormatError(err))
  154. if err != nil {
  155. logrus.Warnf("could not write error response: %v", err)
  156. }
  157. return nil
  158. }
  159. buildOptions, err := newImageBuildOptions(ctx, r)
  160. if err != nil {
  161. return errf(err)
  162. }
  163. buildOptions.AuthConfigs = authConfigs
  164. remoteURL := r.FormValue("remote")
  165. // Currently, only used if context is from a remote url.
  166. // Look at code in DetectContextFromRemoteURL for more information.
  167. createProgressReader := func(in io.ReadCloser) io.ReadCloser {
  168. progressOutput := sf.NewProgressOutput(output, true)
  169. if buildOptions.SuppressOutput {
  170. progressOutput = sf.NewProgressOutput(notVerboseBuffer, true)
  171. }
  172. return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL)
  173. }
  174. out := io.Writer(output)
  175. if buildOptions.SuppressOutput {
  176. out = notVerboseBuffer
  177. }
  178. out = &syncWriter{w: out}
  179. stdout := &streamformatter.StdoutFormatter{Writer: out, StreamFormatter: sf}
  180. stderr := &streamformatter.StderrFormatter{Writer: out, StreamFormatter: sf}
  181. pg := backend.ProgressWriter{
  182. Output: out,
  183. StdoutFormatter: stdout,
  184. StderrFormatter: stderr,
  185. ProgressReaderFunc: createProgressReader,
  186. }
  187. imgID, err := br.backend.BuildFromContext(ctx, r.Body, remoteURL, buildOptions, pg)
  188. if err != nil {
  189. return errf(err)
  190. }
  191. // Everything worked so if -q was provided the output from the daemon
  192. // should be just the image ID and we'll print that to stdout.
  193. if buildOptions.SuppressOutput {
  194. stdout := &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf}
  195. fmt.Fprintf(stdout, "%s\n", string(imgID))
  196. }
  197. return nil
  198. }