build_routes.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. builderVersion := BuilderVersion(*br.features)
  222. // check if the builder feature has been enabled from daemon as well.
  223. if buildOptions.Version == types.BuilderBuildKit && builderVersion != "" && builderVersion != types.BuilderBuildKit {
  224. return errdefs.InvalidParameter(errors.New("buildkit is not enabled on daemon"))
  225. }
  226. out := io.Writer(output)
  227. if buildOptions.SuppressOutput {
  228. out = notVerboseBuffer
  229. }
  230. // Currently, only used if context is from a remote url.
  231. // Look at code in DetectContextFromRemoteURL for more information.
  232. createProgressReader := func(in io.ReadCloser) io.ReadCloser {
  233. progressOutput := streamformatter.NewJSONProgressOutput(out, true)
  234. return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", buildOptions.RemoteContext)
  235. }
  236. wantAux := versions.GreaterThanOrEqualTo(version, "1.30")
  237. imgID, err := br.backend.Build(ctx, backend.BuildConfig{
  238. Source: body,
  239. Options: buildOptions,
  240. ProgressWriter: buildProgressWriter(out, wantAux, createProgressReader),
  241. })
  242. if err != nil {
  243. return errf(err)
  244. }
  245. // Everything worked so if -q was provided the output from the daemon
  246. // should be just the image ID and we'll print that to stdout.
  247. if buildOptions.SuppressOutput {
  248. fmt.Fprintln(streamformatter.NewStdoutWriter(output), imgID)
  249. }
  250. return nil
  251. }
  252. func getAuthConfigs(header http.Header) map[string]types.AuthConfig {
  253. authConfigs := map[string]types.AuthConfig{}
  254. authConfigsEncoded := header.Get("X-Registry-Config")
  255. if authConfigsEncoded == "" {
  256. return authConfigs
  257. }
  258. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  259. // Pulling an image does not error when no auth is provided so to remain
  260. // consistent with the existing api decode errors are ignored
  261. json.NewDecoder(authConfigsJSON).Decode(&authConfigs)
  262. return authConfigs
  263. }
  264. type syncWriter struct {
  265. w io.Writer
  266. mu sync.Mutex
  267. }
  268. func (s *syncWriter) Write(b []byte) (count int, err error) {
  269. s.mu.Lock()
  270. count, err = s.w.Write(b)
  271. s.mu.Unlock()
  272. return
  273. }
  274. func buildProgressWriter(out io.Writer, wantAux bool, createProgressReader func(io.ReadCloser) io.ReadCloser) backend.ProgressWriter {
  275. out = &syncWriter{w: out}
  276. var aux *streamformatter.AuxFormatter
  277. if wantAux {
  278. aux = &streamformatter.AuxFormatter{Writer: out}
  279. }
  280. return backend.ProgressWriter{
  281. Output: out,
  282. StdoutFormatter: streamformatter.NewStdoutWriter(out),
  283. StderrFormatter: streamformatter.NewStderrWriter(out),
  284. AuxFormatter: aux,
  285. ProgressReaderFunc: createProgressReader,
  286. }
  287. }
  288. type flusher interface {
  289. Flush()
  290. }
  291. func wrapOutputBufferedUntilRequestRead(rc io.ReadCloser, out io.Writer) (io.ReadCloser, io.Writer) {
  292. var fl flusher = &ioutils.NopFlusher{}
  293. if f, ok := out.(flusher); ok {
  294. fl = f
  295. }
  296. w := &wcf{
  297. buf: bytes.NewBuffer(nil),
  298. Writer: out,
  299. flusher: fl,
  300. }
  301. r := bufio.NewReader(rc)
  302. _, err := r.Peek(1)
  303. if err != nil {
  304. return rc, out
  305. }
  306. rc = &rcNotifier{
  307. Reader: r,
  308. Closer: rc,
  309. notify: w.notify,
  310. }
  311. return rc, w
  312. }
  313. type rcNotifier struct {
  314. io.Reader
  315. io.Closer
  316. notify func()
  317. }
  318. func (r *rcNotifier) Read(b []byte) (int, error) {
  319. n, err := r.Reader.Read(b)
  320. if err != nil {
  321. r.notify()
  322. }
  323. return n, err
  324. }
  325. func (r *rcNotifier) Close() error {
  326. r.notify()
  327. return r.Closer.Close()
  328. }
  329. type wcf struct {
  330. io.Writer
  331. flusher
  332. mu sync.Mutex
  333. ready bool
  334. buf *bytes.Buffer
  335. flushed bool
  336. }
  337. func (w *wcf) Flush() {
  338. w.mu.Lock()
  339. w.flushed = true
  340. if !w.ready {
  341. w.mu.Unlock()
  342. return
  343. }
  344. w.mu.Unlock()
  345. w.flusher.Flush()
  346. }
  347. func (w *wcf) Flushed() bool {
  348. w.mu.Lock()
  349. b := w.flushed
  350. w.mu.Unlock()
  351. return b
  352. }
  353. func (w *wcf) Write(b []byte) (int, error) {
  354. w.mu.Lock()
  355. if !w.ready {
  356. n, err := w.buf.Write(b)
  357. w.mu.Unlock()
  358. return n, err
  359. }
  360. w.mu.Unlock()
  361. return w.Writer.Write(b)
  362. }
  363. func (w *wcf) notify() {
  364. w.mu.Lock()
  365. if !w.ready {
  366. if w.buf.Len() > 0 {
  367. io.Copy(w.Writer, w.buf)
  368. }
  369. if w.flushed {
  370. w.flusher.Flush()
  371. }
  372. w.ready = true
  373. }
  374. w.mu.Unlock()
  375. }