build_routes.go 11 KB

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