build_routes.go 7.5 KB

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