build_routes.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package build
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "github.com/docker/docker/api/server/httputils"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/api/types/backend"
  16. "github.com/docker/docker/api/types/container"
  17. "github.com/docker/docker/api/types/versions"
  18. "github.com/docker/docker/pkg/ioutils"
  19. "github.com/docker/docker/pkg/progress"
  20. "github.com/docker/docker/pkg/streamformatter"
  21. units "github.com/docker/go-units"
  22. "github.com/pkg/errors"
  23. "github.com/sirupsen/logrus"
  24. "golang.org/x/net/context"
  25. )
  26. type invalidIsolationError string
  27. func (e invalidIsolationError) Error() string {
  28. return fmt.Sprintf("Unsupported isolation: %q", string(e))
  29. }
  30. func (e invalidIsolationError) InvalidParameter() {}
  31. func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBuildOptions, error) {
  32. version := httputils.VersionFromContext(ctx)
  33. options := &types.ImageBuildOptions{}
  34. if httputils.BoolValue(r, "forcerm") && versions.GreaterThanOrEqualTo(version, "1.12") {
  35. options.Remove = true
  36. } else if r.FormValue("rm") == "" && versions.GreaterThanOrEqualTo(version, "1.12") {
  37. options.Remove = true
  38. } else {
  39. options.Remove = httputils.BoolValue(r, "rm")
  40. }
  41. if httputils.BoolValue(r, "pull") && versions.GreaterThanOrEqualTo(version, "1.16") {
  42. options.PullParent = true
  43. }
  44. options.Dockerfile = r.FormValue("dockerfile")
  45. options.SuppressOutput = httputils.BoolValue(r, "q")
  46. options.NoCache = httputils.BoolValue(r, "nocache")
  47. options.ForceRemove = httputils.BoolValue(r, "forcerm")
  48. options.MemorySwap = httputils.Int64ValueOrZero(r, "memswap")
  49. options.Memory = httputils.Int64ValueOrZero(r, "memory")
  50. options.CPUShares = httputils.Int64ValueOrZero(r, "cpushares")
  51. options.CPUPeriod = httputils.Int64ValueOrZero(r, "cpuperiod")
  52. options.CPUQuota = httputils.Int64ValueOrZero(r, "cpuquota")
  53. options.CPUSetCPUs = r.FormValue("cpusetcpus")
  54. options.CPUSetMems = r.FormValue("cpusetmems")
  55. options.CgroupParent = r.FormValue("cgroupparent")
  56. options.NetworkMode = r.FormValue("networkmode")
  57. options.Tags = r.Form["t"]
  58. options.ExtraHosts = r.Form["extrahosts"]
  59. options.SecurityOpt = r.Form["securityopt"]
  60. options.Squash = httputils.BoolValue(r, "squash")
  61. options.Target = r.FormValue("target")
  62. options.RemoteContext = r.FormValue("remote")
  63. if r.Form.Get("shmsize") != "" {
  64. shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
  65. if err != nil {
  66. return nil, err
  67. }
  68. options.ShmSize = shmSize
  69. }
  70. if i := container.Isolation(r.FormValue("isolation")); i != "" {
  71. if !container.Isolation.IsValid(i) {
  72. return nil, invalidIsolationError(i)
  73. }
  74. options.Isolation = i
  75. }
  76. if runtime.GOOS != "windows" && options.SecurityOpt != nil {
  77. return nil, validationError{fmt.Errorf("The daemon on this platform does not support setting security options on build")}
  78. }
  79. var buildUlimits = []*units.Ulimit{}
  80. ulimitsJSON := r.FormValue("ulimits")
  81. if ulimitsJSON != "" {
  82. if err := json.Unmarshal([]byte(ulimitsJSON), &buildUlimits); err != nil {
  83. return nil, errors.Wrap(validationError{err}, "error reading ulimit settings")
  84. }
  85. options.Ulimits = buildUlimits
  86. }
  87. // Note that there are two ways a --build-arg might appear in the
  88. // json of the query param:
  89. // "foo":"bar"
  90. // and "foo":nil
  91. // The first is the normal case, ie. --build-arg foo=bar
  92. // or --build-arg foo
  93. // where foo's value was picked up from an env var.
  94. // The second ("foo":nil) is where they put --build-arg foo
  95. // but "foo" isn't set as an env var. In that case we can't just drop
  96. // the fact they mentioned it, we need to pass that along to the builder
  97. // so that it can print a warning about "foo" being unused if there is
  98. // no "ARG foo" in the Dockerfile.
  99. buildArgsJSON := r.FormValue("buildargs")
  100. if buildArgsJSON != "" {
  101. var buildArgs = map[string]*string{}
  102. if err := json.Unmarshal([]byte(buildArgsJSON), &buildArgs); err != nil {
  103. return nil, errors.Wrap(validationError{err}, "error reading build args")
  104. }
  105. options.BuildArgs = buildArgs
  106. }
  107. labelsJSON := r.FormValue("labels")
  108. if labelsJSON != "" {
  109. var labels = map[string]string{}
  110. if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {
  111. return nil, errors.Wrap(validationError{err}, "error reading labels")
  112. }
  113. options.Labels = labels
  114. }
  115. cacheFromJSON := r.FormValue("cachefrom")
  116. if cacheFromJSON != "" {
  117. var cacheFrom = []string{}
  118. if err := json.Unmarshal([]byte(cacheFromJSON), &cacheFrom); err != nil {
  119. return nil, err
  120. }
  121. options.CacheFrom = cacheFrom
  122. }
  123. options.SessionID = r.FormValue("session")
  124. return options, nil
  125. }
  126. func (br *buildRouter) postPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  127. report, err := br.backend.PruneCache(ctx)
  128. if err != nil {
  129. return err
  130. }
  131. return httputils.WriteJSON(w, http.StatusOK, report)
  132. }
  133. type validationError struct {
  134. cause error
  135. }
  136. func (e validationError) Error() string {
  137. return e.cause.Error()
  138. }
  139. func (e validationError) InvalidParameter() {}
  140. func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  141. var (
  142. notVerboseBuffer = bytes.NewBuffer(nil)
  143. version = httputils.VersionFromContext(ctx)
  144. )
  145. w.Header().Set("Content-Type", "application/json")
  146. output := ioutils.NewWriteFlusher(w)
  147. defer output.Close()
  148. errf := func(err error) error {
  149. if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
  150. output.Write(notVerboseBuffer.Bytes())
  151. }
  152. // Do not write the error in the http output if it's still empty.
  153. // This prevents from writing a 200(OK) when there is an internal error.
  154. if !output.Flushed() {
  155. return err
  156. }
  157. _, err = w.Write(streamformatter.FormatError(err))
  158. if err != nil {
  159. logrus.Warnf("could not write error response: %v", err)
  160. }
  161. return nil
  162. }
  163. buildOptions, err := newImageBuildOptions(ctx, r)
  164. if err != nil {
  165. return errf(err)
  166. }
  167. buildOptions.AuthConfigs = getAuthConfigs(r.Header)
  168. if buildOptions.Squash && !br.daemon.HasExperimental() {
  169. return validationError{errors.New("squash is only supported with experimental mode")}
  170. }
  171. out := io.Writer(output)
  172. if buildOptions.SuppressOutput {
  173. out = notVerboseBuffer
  174. }
  175. // Currently, only used if context is from a remote url.
  176. // Look at code in DetectContextFromRemoteURL for more information.
  177. createProgressReader := func(in io.ReadCloser) io.ReadCloser {
  178. progressOutput := streamformatter.NewJSONProgressOutput(out, true)
  179. return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", buildOptions.RemoteContext)
  180. }
  181. wantAux := versions.GreaterThanOrEqualTo(version, "1.30")
  182. imgID, err := br.backend.Build(ctx, backend.BuildConfig{
  183. Source: r.Body,
  184. Options: buildOptions,
  185. ProgressWriter: buildProgressWriter(out, wantAux, createProgressReader),
  186. })
  187. if err != nil {
  188. return errf(err)
  189. }
  190. // Everything worked so if -q was provided the output from the daemon
  191. // should be just the image ID and we'll print that to stdout.
  192. if buildOptions.SuppressOutput {
  193. fmt.Fprintln(streamformatter.NewStdoutWriter(output), imgID)
  194. }
  195. return nil
  196. }
  197. func getAuthConfigs(header http.Header) map[string]types.AuthConfig {
  198. authConfigs := map[string]types.AuthConfig{}
  199. authConfigsEncoded := header.Get("X-Registry-Config")
  200. if authConfigsEncoded == "" {
  201. return authConfigs
  202. }
  203. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  204. // Pulling an image does not error when no auth is provided so to remain
  205. // consistent with the existing api decode errors are ignored
  206. json.NewDecoder(authConfigsJSON).Decode(&authConfigs)
  207. return authConfigs
  208. }
  209. type syncWriter struct {
  210. w io.Writer
  211. mu sync.Mutex
  212. }
  213. func (s *syncWriter) Write(b []byte) (count int, err error) {
  214. s.mu.Lock()
  215. count, err = s.w.Write(b)
  216. s.mu.Unlock()
  217. return
  218. }
  219. func buildProgressWriter(out io.Writer, wantAux bool, createProgressReader func(io.ReadCloser) io.ReadCloser) backend.ProgressWriter {
  220. out = &syncWriter{w: out}
  221. var aux *streamformatter.AuxFormatter
  222. if wantAux {
  223. aux = &streamformatter.AuxFormatter{Writer: out}
  224. }
  225. return backend.ProgressWriter{
  226. Output: out,
  227. StdoutFormatter: streamformatter.NewStdoutWriter(out),
  228. StderrFormatter: streamformatter.NewStderrWriter(out),
  229. AuxFormatter: aux,
  230. ProgressReaderFunc: createProgressReader,
  231. }
  232. }