build_routes.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. return options, nil
  137. }
  138. func parseVersion(s string) (types.BuilderVersion, error) {
  139. if s == "" || s == string(types.BuilderV1) {
  140. return types.BuilderV1, nil
  141. }
  142. if s == string(types.BuilderBuildKit) {
  143. return types.BuilderBuildKit, nil
  144. }
  145. return "", errors.Errorf("invalid version %s", s)
  146. }
  147. func (br *buildRouter) postPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  148. if err := httputils.ParseForm(r); err != nil {
  149. return err
  150. }
  151. filters, err := filters.FromJSON(r.Form.Get("filters"))
  152. if err != nil {
  153. return errors.Wrap(err, "could not parse filters")
  154. }
  155. ksfv := r.FormValue("keep-storage")
  156. ks, err := strconv.Atoi(ksfv)
  157. if err != nil {
  158. return errors.Wrapf(err, "keep-storage is in bytes and expects an integer, got %v", ksfv)
  159. }
  160. opts := types.BuildCachePruneOptions{
  161. All: httputils.BoolValue(r, "all"),
  162. Filters: filters,
  163. KeepStorage: int64(ks),
  164. }
  165. report, err := br.backend.PruneCache(ctx, opts)
  166. if err != nil {
  167. return err
  168. }
  169. return httputils.WriteJSON(w, http.StatusOK, report)
  170. }
  171. func (br *buildRouter) postCancel(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  172. w.Header().Set("Content-Type", "application/json")
  173. id := r.FormValue("id")
  174. if id == "" {
  175. return errors.Errorf("build ID not provided")
  176. }
  177. return br.backend.Cancel(ctx, id)
  178. }
  179. func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  180. var (
  181. notVerboseBuffer = bytes.NewBuffer(nil)
  182. version = httputils.VersionFromContext(ctx)
  183. )
  184. w.Header().Set("Content-Type", "application/json")
  185. body := r.Body
  186. var ww io.Writer = w
  187. if body != nil {
  188. // there is a possibility that output is written before request body
  189. // has been fully read so we need to protect against it.
  190. // this can be removed when
  191. // https://github.com/golang/go/issues/15527
  192. // https://github.com/golang/go/issues/22209
  193. // has been fixed
  194. body, ww = wrapOutputBufferedUntilRequestRead(body, ww)
  195. }
  196. output := ioutils.NewWriteFlusher(ww)
  197. defer output.Close()
  198. errf := func(err error) error {
  199. if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
  200. output.Write(notVerboseBuffer.Bytes())
  201. }
  202. // Do not write the error in the http output if it's still empty.
  203. // This prevents from writing a 200(OK) when there is an internal error.
  204. if !output.Flushed() {
  205. return err
  206. }
  207. _, err = output.Write(streamformatter.FormatError(err))
  208. if err != nil {
  209. logrus.Warnf("could not write error response: %v", err)
  210. }
  211. return nil
  212. }
  213. buildOptions, err := newImageBuildOptions(ctx, r)
  214. if err != nil {
  215. return errf(err)
  216. }
  217. buildOptions.AuthConfigs = getAuthConfigs(r.Header)
  218. if buildOptions.Squash && !br.daemon.HasExperimental() {
  219. return errdefs.InvalidParameter(errors.New("squash is only supported with experimental mode"))
  220. }
  221. out := io.Writer(output)
  222. if buildOptions.SuppressOutput {
  223. out = notVerboseBuffer
  224. }
  225. // Currently, only used if context is from a remote url.
  226. // Look at code in DetectContextFromRemoteURL for more information.
  227. createProgressReader := func(in io.ReadCloser) io.ReadCloser {
  228. progressOutput := streamformatter.NewJSONProgressOutput(out, true)
  229. return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", buildOptions.RemoteContext)
  230. }
  231. wantAux := versions.GreaterThanOrEqualTo(version, "1.30")
  232. imgID, err := br.backend.Build(ctx, backend.BuildConfig{
  233. Source: body,
  234. Options: buildOptions,
  235. ProgressWriter: buildProgressWriter(out, wantAux, createProgressReader),
  236. })
  237. if err != nil {
  238. return errf(err)
  239. }
  240. // Everything worked so if -q was provided the output from the daemon
  241. // should be just the image ID and we'll print that to stdout.
  242. if buildOptions.SuppressOutput {
  243. fmt.Fprintln(streamformatter.NewStdoutWriter(output), imgID)
  244. }
  245. return nil
  246. }
  247. func getAuthConfigs(header http.Header) map[string]types.AuthConfig {
  248. authConfigs := map[string]types.AuthConfig{}
  249. authConfigsEncoded := header.Get("X-Registry-Config")
  250. if authConfigsEncoded == "" {
  251. return authConfigs
  252. }
  253. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  254. // Pulling an image does not error when no auth is provided so to remain
  255. // consistent with the existing api decode errors are ignored
  256. json.NewDecoder(authConfigsJSON).Decode(&authConfigs)
  257. return authConfigs
  258. }
  259. type syncWriter struct {
  260. w io.Writer
  261. mu sync.Mutex
  262. }
  263. func (s *syncWriter) Write(b []byte) (count int, err error) {
  264. s.mu.Lock()
  265. count, err = s.w.Write(b)
  266. s.mu.Unlock()
  267. return
  268. }
  269. func buildProgressWriter(out io.Writer, wantAux bool, createProgressReader func(io.ReadCloser) io.ReadCloser) backend.ProgressWriter {
  270. out = &syncWriter{w: out}
  271. var aux *streamformatter.AuxFormatter
  272. if wantAux {
  273. aux = &streamformatter.AuxFormatter{Writer: out}
  274. }
  275. return backend.ProgressWriter{
  276. Output: out,
  277. StdoutFormatter: streamformatter.NewStdoutWriter(out),
  278. StderrFormatter: streamformatter.NewStderrWriter(out),
  279. AuxFormatter: aux,
  280. ProgressReaderFunc: createProgressReader,
  281. }
  282. }
  283. type flusher interface {
  284. Flush()
  285. }
  286. func wrapOutputBufferedUntilRequestRead(rc io.ReadCloser, out io.Writer) (io.ReadCloser, io.Writer) {
  287. var fl flusher = &ioutils.NopFlusher{}
  288. if f, ok := out.(flusher); ok {
  289. fl = f
  290. }
  291. w := &wcf{
  292. buf: bytes.NewBuffer(nil),
  293. Writer: out,
  294. flusher: fl,
  295. }
  296. r := bufio.NewReader(rc)
  297. _, err := r.Peek(1)
  298. if err != nil {
  299. return rc, out
  300. }
  301. rc = &rcNotifier{
  302. Reader: r,
  303. Closer: rc,
  304. notify: w.notify,
  305. }
  306. return rc, w
  307. }
  308. type rcNotifier struct {
  309. io.Reader
  310. io.Closer
  311. notify func()
  312. }
  313. func (r *rcNotifier) Read(b []byte) (int, error) {
  314. n, err := r.Reader.Read(b)
  315. if err != nil {
  316. r.notify()
  317. }
  318. return n, err
  319. }
  320. func (r *rcNotifier) Close() error {
  321. r.notify()
  322. return r.Closer.Close()
  323. }
  324. type wcf struct {
  325. io.Writer
  326. flusher
  327. mu sync.Mutex
  328. ready bool
  329. buf *bytes.Buffer
  330. flushed bool
  331. }
  332. func (w *wcf) Flush() {
  333. w.mu.Lock()
  334. w.flushed = true
  335. if !w.ready {
  336. w.mu.Unlock()
  337. return
  338. }
  339. w.mu.Unlock()
  340. w.flusher.Flush()
  341. }
  342. func (w *wcf) Flushed() bool {
  343. w.mu.Lock()
  344. b := w.flushed
  345. w.mu.Unlock()
  346. return b
  347. }
  348. func (w *wcf) Write(b []byte) (int, error) {
  349. w.mu.Lock()
  350. if !w.ready {
  351. n, err := w.buf.Write(b)
  352. w.mu.Unlock()
  353. return n, err
  354. }
  355. w.mu.Unlock()
  356. return w.Writer.Write(b)
  357. }
  358. func (w *wcf) notify() {
  359. w.mu.Lock()
  360. if !w.ready {
  361. if w.buf.Len() > 0 {
  362. io.Copy(w.Writer, w.buf)
  363. }
  364. if w.flushed {
  365. w.flusher.Flush()
  366. }
  367. w.ready = true
  368. }
  369. w.mu.Unlock()
  370. }