build_routes.go 11 KB

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