build_routes.go 8.6 KB

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