build_routes.go 7.9 KB

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