build_routes.go 12 KB

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