build_routes.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package build // import "github.com/docker/docker/api/server/router/build"
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/base64"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "runtime"
  12. "strconv"
  13. "strings"
  14. "sync"
  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/errdefs"
  21. "github.com/docker/docker/pkg/ioutils"
  22. "github.com/docker/docker/pkg/progress"
  23. "github.com/docker/docker/pkg/streamformatter"
  24. "github.com/docker/docker/pkg/system"
  25. "github.com/docker/go-units"
  26. "github.com/pkg/errors"
  27. "github.com/sirupsen/logrus"
  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. apiPlatform := r.FormValue("platform")
  68. p := system.ParsePlatform(apiPlatform)
  69. if err := system.ValidatePlatform(p); err != nil {
  70. return nil, errdefs.InvalidParameter(errors.Errorf("invalid platform: %s", err))
  71. }
  72. options.Platform = p.OS
  73. }
  74. if r.Form.Get("shmsize") != "" {
  75. shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
  76. if err != nil {
  77. return nil, err
  78. }
  79. options.ShmSize = shmSize
  80. }
  81. if i := container.Isolation(r.FormValue("isolation")); i != "" {
  82. if !container.Isolation.IsValid(i) {
  83. return nil, invalidIsolationError(i)
  84. }
  85. options.Isolation = i
  86. }
  87. if runtime.GOOS != "windows" && options.SecurityOpt != nil {
  88. return nil, errdefs.InvalidParameter(errors.New("The daemon on this platform does not support setting security options on build"))
  89. }
  90. var buildUlimits = []*units.Ulimit{}
  91. ulimitsJSON := r.FormValue("ulimits")
  92. if ulimitsJSON != "" {
  93. if err := json.Unmarshal([]byte(ulimitsJSON), &buildUlimits); err != nil {
  94. return nil, errors.Wrap(errdefs.InvalidParameter(err), "error reading ulimit settings")
  95. }
  96. options.Ulimits = buildUlimits
  97. }
  98. // Note that there are two ways a --build-arg might appear in the
  99. // json of the query param:
  100. // "foo":"bar"
  101. // and "foo":nil
  102. // The first is the normal case, ie. --build-arg foo=bar
  103. // or --build-arg foo
  104. // where foo's value was picked up from an env var.
  105. // The second ("foo":nil) is where they put --build-arg foo
  106. // but "foo" isn't set as an env var. In that case we can't just drop
  107. // the fact they mentioned it, we need to pass that along to the builder
  108. // so that it can print a warning about "foo" being unused if there is
  109. // no "ARG foo" in the Dockerfile.
  110. buildArgsJSON := r.FormValue("buildargs")
  111. if buildArgsJSON != "" {
  112. var buildArgs = map[string]*string{}
  113. if err := json.Unmarshal([]byte(buildArgsJSON), &buildArgs); err != nil {
  114. return nil, errors.Wrap(errdefs.InvalidParameter(err), "error reading build args")
  115. }
  116. options.BuildArgs = buildArgs
  117. }
  118. labelsJSON := r.FormValue("labels")
  119. if labelsJSON != "" {
  120. var labels = map[string]string{}
  121. if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {
  122. return nil, errors.Wrap(errdefs.InvalidParameter(err), "error reading labels")
  123. }
  124. options.Labels = labels
  125. }
  126. cacheFromJSON := r.FormValue("cachefrom")
  127. if cacheFromJSON != "" {
  128. var cacheFrom = []string{}
  129. if err := json.Unmarshal([]byte(cacheFromJSON), &cacheFrom); err != nil {
  130. return nil, err
  131. }
  132. options.CacheFrom = cacheFrom
  133. }
  134. options.SessionID = r.FormValue("session")
  135. options.BuildID = r.FormValue("buildid")
  136. builderVersion, err := parseVersion(r.FormValue("version"))
  137. if err != nil {
  138. return nil, err
  139. }
  140. options.Version = builderVersion
  141. return options, nil
  142. }
  143. func parseVersion(s string) (types.BuilderVersion, error) {
  144. if s == "" || s == string(types.BuilderV1) {
  145. return types.BuilderV1, nil
  146. }
  147. if s == string(types.BuilderBuildKit) {
  148. return types.BuilderBuildKit, nil
  149. }
  150. return "", errors.Errorf("invalid version %s", s)
  151. }
  152. func (br *buildRouter) postPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  153. report, err := br.backend.PruneCache(ctx)
  154. if err != nil {
  155. return err
  156. }
  157. return httputils.WriteJSON(w, http.StatusOK, report)
  158. }
  159. func (br *buildRouter) postCancel(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  160. w.Header().Set("Content-Type", "application/json")
  161. id := r.FormValue("id")
  162. if id == "" {
  163. return errors.Errorf("build ID not provided")
  164. }
  165. return br.backend.Cancel(ctx, id)
  166. }
  167. func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  168. var (
  169. notVerboseBuffer = bytes.NewBuffer(nil)
  170. version = httputils.VersionFromContext(ctx)
  171. )
  172. w.Header().Set("Content-Type", "application/json")
  173. var output writeCloseFlusher = ioutils.NewWriteFlusher(w)
  174. defer output.Close()
  175. body := r.Body
  176. if body != nil {
  177. // there is a possibility that output is written before request body
  178. // has been fully read so we need to protect against it.
  179. // this can be removed when
  180. // https://github.com/golang/go/issues/15527
  181. // https://github.com/golang/go/issues/22209
  182. // has been fixed
  183. body, output = wrapOutputBufferedUntilRequestRead(body, output)
  184. }
  185. errf := func(err error) error {
  186. if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
  187. output.Write(notVerboseBuffer.Bytes())
  188. }
  189. // Do not write the error in the http output if it's still empty.
  190. // This prevents from writing a 200(OK) when there is an internal error.
  191. if !output.Flushed() {
  192. return err
  193. }
  194. _, err = w.Write(streamformatter.FormatError(err))
  195. if err != nil {
  196. logrus.Warnf("could not write error response: %v", err)
  197. }
  198. return nil
  199. }
  200. buildOptions, err := newImageBuildOptions(ctx, r)
  201. if err != nil {
  202. return errf(err)
  203. }
  204. buildOptions.AuthConfigs = getAuthConfigs(r.Header)
  205. if buildOptions.Squash && !br.daemon.HasExperimental() {
  206. return errdefs.InvalidParameter(errors.New("squash is only supported with experimental mode"))
  207. }
  208. out := io.Writer(output)
  209. if buildOptions.SuppressOutput {
  210. out = notVerboseBuffer
  211. }
  212. // Currently, only used if context is from a remote url.
  213. // Look at code in DetectContextFromRemoteURL for more information.
  214. createProgressReader := func(in io.ReadCloser) io.ReadCloser {
  215. progressOutput := streamformatter.NewJSONProgressOutput(out, true)
  216. return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", buildOptions.RemoteContext)
  217. }
  218. wantAux := versions.GreaterThanOrEqualTo(version, "1.30")
  219. imgID, err := br.backend.Build(ctx, backend.BuildConfig{
  220. Source: body,
  221. Options: buildOptions,
  222. ProgressWriter: buildProgressWriter(out, wantAux, createProgressReader),
  223. })
  224. if err != nil {
  225. return errf(err)
  226. }
  227. // Everything worked so if -q was provided the output from the daemon
  228. // should be just the image ID and we'll print that to stdout.
  229. if buildOptions.SuppressOutput {
  230. fmt.Fprintln(streamformatter.NewStdoutWriter(output), imgID)
  231. }
  232. return nil
  233. }
  234. func getAuthConfigs(header http.Header) map[string]types.AuthConfig {
  235. authConfigs := map[string]types.AuthConfig{}
  236. authConfigsEncoded := header.Get("X-Registry-Config")
  237. if authConfigsEncoded == "" {
  238. return authConfigs
  239. }
  240. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  241. // Pulling an image does not error when no auth is provided so to remain
  242. // consistent with the existing api decode errors are ignored
  243. json.NewDecoder(authConfigsJSON).Decode(&authConfigs)
  244. return authConfigs
  245. }
  246. type syncWriter struct {
  247. w io.Writer
  248. mu sync.Mutex
  249. }
  250. func (s *syncWriter) Write(b []byte) (count int, err error) {
  251. s.mu.Lock()
  252. count, err = s.w.Write(b)
  253. s.mu.Unlock()
  254. return
  255. }
  256. func buildProgressWriter(out io.Writer, wantAux bool, createProgressReader func(io.ReadCloser) io.ReadCloser) backend.ProgressWriter {
  257. out = &syncWriter{w: out}
  258. var aux *streamformatter.AuxFormatter
  259. if wantAux {
  260. aux = &streamformatter.AuxFormatter{Writer: out}
  261. }
  262. return backend.ProgressWriter{
  263. Output: out,
  264. StdoutFormatter: streamformatter.NewStdoutWriter(out),
  265. StderrFormatter: streamformatter.NewStderrWriter(out),
  266. AuxFormatter: aux,
  267. ProgressReaderFunc: createProgressReader,
  268. }
  269. }
  270. type writeCloseFlusher interface {
  271. Flush()
  272. Flushed() bool
  273. io.WriteCloser
  274. }
  275. func wrapOutputBufferedUntilRequestRead(rc io.ReadCloser, out writeCloseFlusher) (io.ReadCloser, writeCloseFlusher) {
  276. w := &wcf{
  277. buf: bytes.NewBuffer(nil),
  278. writeCloseFlusher: out,
  279. }
  280. r := bufio.NewReader(rc)
  281. _, err := r.Peek(1)
  282. if err != nil {
  283. return rc, out
  284. }
  285. rc = &rcNotifier{
  286. Reader: r,
  287. Closer: rc,
  288. notify: w.notify,
  289. }
  290. return rc, w
  291. }
  292. type rcNotifier struct {
  293. io.Reader
  294. io.Closer
  295. notify func()
  296. }
  297. func (r *rcNotifier) Read(b []byte) (int, error) {
  298. n, err := r.Reader.Read(b)
  299. if err != nil {
  300. r.notify()
  301. }
  302. return n, err
  303. }
  304. type wcf struct {
  305. writeCloseFlusher
  306. mu sync.Mutex
  307. ready bool
  308. buf *bytes.Buffer
  309. flushed bool
  310. }
  311. func (w *wcf) Flush() {
  312. w.mu.Lock()
  313. w.flushed = true
  314. if !w.ready {
  315. w.mu.Unlock()
  316. return
  317. }
  318. w.mu.Unlock()
  319. w.writeCloseFlusher.Flush()
  320. }
  321. func (w *wcf) Flushed() bool {
  322. w.mu.Lock()
  323. b := w.flushed
  324. w.mu.Unlock()
  325. return b
  326. }
  327. func (w *wcf) Write(b []byte) (int, error) {
  328. w.mu.Lock()
  329. if !w.ready {
  330. n, err := w.buf.Write(b)
  331. w.mu.Unlock()
  332. return n, err
  333. }
  334. w.mu.Unlock()
  335. return w.writeCloseFlusher.Write(b)
  336. }
  337. func (w *wcf) notify() {
  338. w.mu.Lock()
  339. if !w.ready {
  340. if w.buf.Len() > 0 {
  341. io.Copy(w.writeCloseFlusher, w.buf)
  342. }
  343. if w.flushed {
  344. w.writeCloseFlusher.Flush()
  345. }
  346. w.ready = true
  347. }
  348. w.mu.Unlock()
  349. }