build_routes.go 11 KB

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