build_routes.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package build
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/api/server/httputils"
  14. "github.com/docker/docker/builder"
  15. "github.com/docker/docker/builder/dockerfile"
  16. "github.com/docker/docker/daemon/daemonbuilder"
  17. "github.com/docker/docker/pkg/ioutils"
  18. "github.com/docker/docker/pkg/progress"
  19. "github.com/docker/docker/pkg/streamformatter"
  20. "github.com/docker/docker/reference"
  21. "github.com/docker/docker/utils"
  22. "github.com/docker/engine-api/types"
  23. "github.com/docker/engine-api/types/container"
  24. "github.com/docker/go-units"
  25. "golang.org/x/net/context"
  26. )
  27. // sanitizeRepoAndTags parses the raw "t" parameter received from the client
  28. // to a slice of repoAndTag.
  29. // It also validates each repoName and tag.
  30. func sanitizeRepoAndTags(names []string) ([]reference.Named, error) {
  31. var (
  32. repoAndTags []reference.Named
  33. // This map is used for deduplicating the "-t" parameter.
  34. uniqNames = make(map[string]struct{})
  35. )
  36. for _, repo := range names {
  37. if repo == "" {
  38. continue
  39. }
  40. ref, err := reference.ParseNamed(repo)
  41. if err != nil {
  42. return nil, err
  43. }
  44. ref = reference.WithDefaultTag(ref)
  45. if _, isCanonical := ref.(reference.Canonical); isCanonical {
  46. return nil, errors.New("build tag cannot contain a digest")
  47. }
  48. if _, isTagged := ref.(reference.NamedTagged); !isTagged {
  49. ref, err = reference.WithTag(ref, reference.DefaultTag)
  50. }
  51. nameWithTag := ref.String()
  52. if _, exists := uniqNames[nameWithTag]; !exists {
  53. uniqNames[nameWithTag] = struct{}{}
  54. repoAndTags = append(repoAndTags, ref)
  55. }
  56. }
  57. return repoAndTags, nil
  58. }
  59. func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBuildOptions, error) {
  60. version := httputils.VersionFromContext(ctx)
  61. options := &types.ImageBuildOptions{}
  62. if httputils.BoolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
  63. options.Remove = true
  64. } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
  65. options.Remove = true
  66. } else {
  67. options.Remove = httputils.BoolValue(r, "rm")
  68. }
  69. if httputils.BoolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
  70. options.PullParent = true
  71. }
  72. options.Dockerfile = r.FormValue("dockerfile")
  73. options.SuppressOutput = httputils.BoolValue(r, "q")
  74. options.NoCache = httputils.BoolValue(r, "nocache")
  75. options.ForceRemove = httputils.BoolValue(r, "forcerm")
  76. options.MemorySwap = httputils.Int64ValueOrZero(r, "memswap")
  77. options.Memory = httputils.Int64ValueOrZero(r, "memory")
  78. options.CPUShares = httputils.Int64ValueOrZero(r, "cpushares")
  79. options.CPUPeriod = httputils.Int64ValueOrZero(r, "cpuperiod")
  80. options.CPUQuota = httputils.Int64ValueOrZero(r, "cpuquota")
  81. options.CPUSetCPUs = r.FormValue("cpusetcpus")
  82. options.CPUSetMems = r.FormValue("cpusetmems")
  83. options.CgroupParent = r.FormValue("cgroupparent")
  84. if r.Form.Get("shmsize") != "" {
  85. shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
  86. if err != nil {
  87. return nil, err
  88. }
  89. options.ShmSize = shmSize
  90. }
  91. if i := container.IsolationLevel(r.FormValue("isolation")); i != "" {
  92. if !container.IsolationLevel.IsValid(i) {
  93. return nil, fmt.Errorf("Unsupported isolation: %q", i)
  94. }
  95. options.IsolationLevel = i
  96. }
  97. var buildUlimits = []*units.Ulimit{}
  98. ulimitsJSON := r.FormValue("ulimits")
  99. if ulimitsJSON != "" {
  100. if err := json.NewDecoder(strings.NewReader(ulimitsJSON)).Decode(&buildUlimits); err != nil {
  101. return nil, err
  102. }
  103. options.Ulimits = buildUlimits
  104. }
  105. var buildArgs = map[string]string{}
  106. buildArgsJSON := r.FormValue("buildargs")
  107. if buildArgsJSON != "" {
  108. if err := json.NewDecoder(strings.NewReader(buildArgsJSON)).Decode(&buildArgs); err != nil {
  109. return nil, err
  110. }
  111. options.BuildArgs = buildArgs
  112. }
  113. return options, nil
  114. }
  115. func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  116. var (
  117. authConfigs = map[string]types.AuthConfig{}
  118. authConfigsEncoded = r.Header.Get("X-Registry-Config")
  119. notVerboseBuffer = bytes.NewBuffer(nil)
  120. )
  121. if authConfigsEncoded != "" {
  122. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  123. if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
  124. // for a pull it is not an error if no auth was given
  125. // to increase compatibility with the existing api it is defaulting
  126. // to be empty.
  127. }
  128. }
  129. w.Header().Set("Content-Type", "application/json")
  130. output := ioutils.NewWriteFlusher(w)
  131. defer output.Close()
  132. sf := streamformatter.NewJSONStreamFormatter()
  133. errf := func(err error) error {
  134. if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
  135. output.Write(notVerboseBuffer.Bytes())
  136. }
  137. // Do not write the error in the http output if it's still empty.
  138. // This prevents from writing a 200(OK) when there is an internal error.
  139. if !output.Flushed() {
  140. return err
  141. }
  142. _, err = w.Write(sf.FormatError(errors.New(utils.GetErrorMessage(err))))
  143. if err != nil {
  144. logrus.Warnf("could not write error response: %v", err)
  145. }
  146. return nil
  147. }
  148. buildOptions, err := newImageBuildOptions(ctx, r)
  149. if err != nil {
  150. return errf(err)
  151. }
  152. repoAndTags, err := sanitizeRepoAndTags(r.Form["t"])
  153. if err != nil {
  154. return errf(err)
  155. }
  156. remoteURL := r.FormValue("remote")
  157. // Currently, only used if context is from a remote url.
  158. // Look at code in DetectContextFromRemoteURL for more information.
  159. createProgressReader := func(in io.ReadCloser) io.ReadCloser {
  160. progressOutput := sf.NewProgressOutput(output, true)
  161. if buildOptions.SuppressOutput {
  162. progressOutput = sf.NewProgressOutput(notVerboseBuffer, true)
  163. }
  164. return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL)
  165. }
  166. var (
  167. context builder.ModifiableContext
  168. dockerfileName string
  169. )
  170. context, dockerfileName, err = daemonbuilder.DetectContextFromRemoteURL(r.Body, remoteURL, createProgressReader)
  171. if err != nil {
  172. return errf(err)
  173. }
  174. defer func() {
  175. if err := context.Close(); err != nil {
  176. logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
  177. }
  178. }()
  179. if len(dockerfileName) > 0 {
  180. buildOptions.Dockerfile = dockerfileName
  181. }
  182. b, err := dockerfile.NewBuilder(
  183. buildOptions, // result of newBuildConfig
  184. &daemonbuilder.Docker{br.backend},
  185. builder.DockerIgnoreContext{ModifiableContext: context},
  186. nil)
  187. if err != nil {
  188. return errf(err)
  189. }
  190. if buildOptions.SuppressOutput {
  191. b.Output = notVerboseBuffer
  192. } else {
  193. b.Output = output
  194. }
  195. b.Stdout = &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf}
  196. b.Stderr = &streamformatter.StderrFormatter{Writer: output, StreamFormatter: sf}
  197. if buildOptions.SuppressOutput {
  198. b.Stdout = &streamformatter.StdoutFormatter{Writer: notVerboseBuffer, StreamFormatter: sf}
  199. b.Stderr = &streamformatter.StderrFormatter{Writer: notVerboseBuffer, StreamFormatter: sf}
  200. }
  201. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  202. finished := make(chan struct{})
  203. defer close(finished)
  204. clientGone := closeNotifier.CloseNotify()
  205. go func() {
  206. select {
  207. case <-finished:
  208. case <-clientGone:
  209. logrus.Infof("Client disconnected, cancelling job: build")
  210. b.Cancel()
  211. }
  212. }()
  213. }
  214. imgID, err := b.Build()
  215. if err != nil {
  216. return errf(err)
  217. }
  218. for _, rt := range repoAndTags {
  219. if err := br.backend.TagImage(rt, imgID); err != nil {
  220. return errf(err)
  221. }
  222. }
  223. // Everything worked so if -q was provided the output from the daemon
  224. // should be just the image ID and we'll print that to stdout.
  225. if buildOptions.SuppressOutput {
  226. stdout := &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf}
  227. fmt.Fprintf(stdout, "%s\n", string(imgID))
  228. }
  229. return nil
  230. }