build_routes.go 9.1 KB

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