build_routes.go 12 KB

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