2015-12-17 19:17:50 -05:00
|
|
|
package build
|
|
|
|
|
|
|
|
import (
|
2015-10-27 20:29:21 -04:00
|
|
|
"bytes"
|
2015-12-17 19:17:50 -05:00
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2016-06-07 15:15:50 -04:00
|
|
|
"runtime"
|
2015-12-17 19:17:50 -05:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2016-03-22 16:57:24 -04:00
|
|
|
"sync"
|
2015-12-17 19:17:50 -05:00
|
|
|
|
|
|
|
"github.com/Sirupsen/logrus"
|
|
|
|
"github.com/docker/docker/api/server/httputils"
|
2016-09-06 14:46:37 -04:00
|
|
|
"github.com/docker/docker/api/types"
|
2016-03-29 18:51:14 -04:00
|
|
|
"github.com/docker/docker/api/types/backend"
|
2016-09-06 14:46:37 -04:00
|
|
|
"github.com/docker/docker/api/types/container"
|
|
|
|
"github.com/docker/docker/api/types/versions"
|
2015-12-17 19:17:50 -05:00
|
|
|
"github.com/docker/docker/pkg/ioutils"
|
|
|
|
"github.com/docker/docker/pkg/progress"
|
|
|
|
"github.com/docker/docker/pkg/streamformatter"
|
2015-12-21 15:10:53 -05:00
|
|
|
"github.com/docker/go-units"
|
2015-12-17 19:17:50 -05:00
|
|
|
"golang.org/x/net/context"
|
|
|
|
)
|
|
|
|
|
2015-12-29 15:49:17 -05:00
|
|
|
func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBuildOptions, error) {
|
|
|
|
version := httputils.VersionFromContext(ctx)
|
|
|
|
options := &types.ImageBuildOptions{}
|
2016-04-19 10:56:54 -04:00
|
|
|
if httputils.BoolValue(r, "forcerm") && versions.GreaterThanOrEqualTo(version, "1.12") {
|
2015-12-29 15:49:17 -05:00
|
|
|
options.Remove = true
|
2016-04-19 10:56:54 -04:00
|
|
|
} else if r.FormValue("rm") == "" && versions.GreaterThanOrEqualTo(version, "1.12") {
|
2015-12-29 15:49:17 -05:00
|
|
|
options.Remove = true
|
|
|
|
} else {
|
|
|
|
options.Remove = httputils.BoolValue(r, "rm")
|
|
|
|
}
|
2016-04-19 10:56:54 -04:00
|
|
|
if httputils.BoolValue(r, "pull") && versions.GreaterThanOrEqualTo(version, "1.16") {
|
2015-12-29 15:49:17 -05:00
|
|
|
options.PullParent = true
|
|
|
|
}
|
|
|
|
|
|
|
|
options.Dockerfile = r.FormValue("dockerfile")
|
|
|
|
options.SuppressOutput = httputils.BoolValue(r, "q")
|
|
|
|
options.NoCache = httputils.BoolValue(r, "nocache")
|
|
|
|
options.ForceRemove = httputils.BoolValue(r, "forcerm")
|
|
|
|
options.MemorySwap = httputils.Int64ValueOrZero(r, "memswap")
|
|
|
|
options.Memory = httputils.Int64ValueOrZero(r, "memory")
|
|
|
|
options.CPUShares = httputils.Int64ValueOrZero(r, "cpushares")
|
|
|
|
options.CPUPeriod = httputils.Int64ValueOrZero(r, "cpuperiod")
|
|
|
|
options.CPUQuota = httputils.Int64ValueOrZero(r, "cpuquota")
|
|
|
|
options.CPUSetCPUs = r.FormValue("cpusetcpus")
|
|
|
|
options.CPUSetMems = r.FormValue("cpusetmems")
|
|
|
|
options.CgroupParent = r.FormValue("cgroupparent")
|
2016-03-06 07:29:23 -05:00
|
|
|
options.NetworkMode = r.FormValue("networkmode")
|
2016-01-20 18:32:02 -05:00
|
|
|
options.Tags = r.Form["t"]
|
2016-06-07 15:15:50 -04:00
|
|
|
options.SecurityOpt = r.Form["securityopt"]
|
2016-04-21 12:08:37 -04:00
|
|
|
options.Squash = httputils.BoolValue(r, "squash")
|
2015-12-29 15:49:17 -05:00
|
|
|
|
|
|
|
if r.Form.Get("shmsize") != "" {
|
|
|
|
shmSize, err := strconv.ParseInt(r.Form.Get("shmsize"), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
options.ShmSize = shmSize
|
|
|
|
}
|
|
|
|
|
2016-02-03 15:07:00 -05:00
|
|
|
if i := container.Isolation(r.FormValue("isolation")); i != "" {
|
|
|
|
if !container.Isolation.IsValid(i) {
|
2015-12-29 15:49:17 -05:00
|
|
|
return nil, fmt.Errorf("Unsupported isolation: %q", i)
|
|
|
|
}
|
2016-02-03 15:07:00 -05:00
|
|
|
options.Isolation = i
|
2015-12-29 15:49:17 -05:00
|
|
|
}
|
|
|
|
|
2016-06-07 15:15:50 -04:00
|
|
|
if runtime.GOOS != "windows" && options.SecurityOpt != nil {
|
|
|
|
return nil, fmt.Errorf("the daemon on this platform does not support --security-opt to build")
|
|
|
|
}
|
|
|
|
|
2015-12-29 15:49:17 -05:00
|
|
|
var buildUlimits = []*units.Ulimit{}
|
|
|
|
ulimitsJSON := r.FormValue("ulimits")
|
|
|
|
if ulimitsJSON != "" {
|
2016-09-22 17:38:00 -04:00
|
|
|
if err := json.Unmarshal([]byte(ulimitsJSON), &buildUlimits); err != nil {
|
2015-12-29 15:49:17 -05:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
options.Ulimits = buildUlimits
|
|
|
|
}
|
|
|
|
|
2016-12-03 08:46:04 -05:00
|
|
|
var buildArgs = map[string]*string{}
|
2015-12-29 15:49:17 -05:00
|
|
|
buildArgsJSON := r.FormValue("buildargs")
|
2016-12-03 08:46:04 -05:00
|
|
|
|
|
|
|
// Note that there are two ways a --build-arg might appear in the
|
|
|
|
// json of the query param:
|
|
|
|
// "foo":"bar"
|
|
|
|
// and "foo":nil
|
|
|
|
// The first is the normal case, ie. --build-arg foo=bar
|
|
|
|
// or --build-arg foo
|
|
|
|
// where foo's value was picked up from an env var.
|
|
|
|
// The second ("foo":nil) is where they put --build-arg foo
|
|
|
|
// but "foo" isn't set as an env var. In that case we can't just drop
|
|
|
|
// the fact they mentioned it, we need to pass that along to the builder
|
|
|
|
// so that it can print a warning about "foo" being unused if there is
|
|
|
|
// no "ARG foo" in the Dockerfile.
|
2015-12-29 15:49:17 -05:00
|
|
|
if buildArgsJSON != "" {
|
2016-09-22 17:38:00 -04:00
|
|
|
if err := json.Unmarshal([]byte(buildArgsJSON), &buildArgs); err != nil {
|
2015-12-29 15:49:17 -05:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
options.BuildArgs = buildArgs
|
|
|
|
}
|
2016-12-03 08:46:04 -05:00
|
|
|
|
2016-03-16 17:52:34 -04:00
|
|
|
var labels = map[string]string{}
|
|
|
|
labelsJSON := r.FormValue("labels")
|
|
|
|
if labelsJSON != "" {
|
2016-09-22 17:38:00 -04:00
|
|
|
if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {
|
2016-03-16 17:52:34 -04:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
options.Labels = labels
|
|
|
|
}
|
|
|
|
|
2016-09-22 17:38:00 -04:00
|
|
|
var cacheFrom = []string{}
|
|
|
|
cacheFromJSON := r.FormValue("cachefrom")
|
|
|
|
if cacheFromJSON != "" {
|
|
|
|
if err := json.Unmarshal([]byte(cacheFromJSON), &cacheFrom); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
options.CacheFrom = cacheFrom
|
|
|
|
}
|
|
|
|
|
2015-12-29 15:49:17 -05:00
|
|
|
return options, nil
|
|
|
|
}
|
|
|
|
|
2016-03-22 16:57:24 -04:00
|
|
|
type syncWriter struct {
|
|
|
|
w io.Writer
|
|
|
|
mu sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *syncWriter) Write(b []byte) (count int, err error) {
|
|
|
|
s.mu.Lock()
|
|
|
|
count, err = s.w.Write(b)
|
|
|
|
s.mu.Unlock()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-12-17 19:17:50 -05:00
|
|
|
func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
|
|
|
|
var (
|
|
|
|
authConfigs = map[string]types.AuthConfig{}
|
|
|
|
authConfigsEncoded = r.Header.Get("X-Registry-Config")
|
2015-10-27 20:29:21 -04:00
|
|
|
notVerboseBuffer = bytes.NewBuffer(nil)
|
2015-12-17 19:17:50 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
if authConfigsEncoded != "" {
|
|
|
|
authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
|
|
|
|
if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
|
|
|
|
// for a pull it is not an error if no auth was given
|
|
|
|
// to increase compatibility with the existing api it is defaulting
|
|
|
|
// to be empty.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
|
|
|
output := ioutils.NewWriteFlusher(w)
|
|
|
|
defer output.Close()
|
|
|
|
sf := streamformatter.NewJSONStreamFormatter()
|
|
|
|
errf := func(err error) error {
|
2015-12-29 15:49:17 -05:00
|
|
|
if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 {
|
2015-10-27 20:29:21 -04:00
|
|
|
output.Write(notVerboseBuffer.Bytes())
|
|
|
|
}
|
2015-12-17 19:17:50 -05:00
|
|
|
// Do not write the error in the http output if it's still empty.
|
|
|
|
// This prevents from writing a 200(OK) when there is an internal error.
|
|
|
|
if !output.Flushed() {
|
|
|
|
return err
|
|
|
|
}
|
Remove static errors from errors package.
Moving all strings to the errors package wasn't a good idea after all.
Our custom implementation of Go errors predates everything that's nice
and good about working with errors in Go. Take as an example what we
have to do to get an error message:
```go
func GetErrorMessage(err error) string {
switch err.(type) {
case errcode.Error:
e, _ := err.(errcode.Error)
return e.Message
case errcode.ErrorCode:
ec, _ := err.(errcode.ErrorCode)
return ec.Message()
default:
return err.Error()
}
}
```
This goes against every good practice for Go development. The language already provides a simple, intuitive and standard way to get error messages, that is calling the `Error()` method from an error. Reinventing the error interface is a mistake.
Our custom implementation also makes very hard to reason about errors, another nice thing about Go. I found several (>10) error declarations that we don't use anywhere. This is a clear sign about how little we know about the errors we return. I also found several error usages where the number of arguments was different than the parameters declared in the error, another clear example of how difficult is to reason about errors.
Moreover, our custom implementation didn't really make easier for people to return custom HTTP status code depending on the errors. Again, it's hard to reason about when to set custom codes and how. Take an example what we have to do to extract the message and status code from an error before returning a response from the API:
```go
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
```
You can notice two things in that code:
1. We have to explain how errors work, because our implementation goes against how easy to use Go errors are.
2. At no moment we arrived to remove that `switch` statement that was the original reason to use our custom implementation.
This change removes all our status errors from the errors package and puts them back in their specific contexts.
IT puts the messages back with their contexts. That way, we know right away when errors used and how to generate their messages.
It uses custom interfaces to reason about errors. Errors that need to response with a custom status code MUST implementent this simple interface:
```go
type errorWithStatus interface {
HTTPErrorStatusCode() int
}
```
This interface is very straightforward to implement. It also preserves Go errors real behavior, getting the message is as simple as using the `Error()` method.
I included helper functions to generate errors that use custom status code in `errors/errors.go`.
By doing this, we remove the hard dependency we have eeverywhere to our custom errors package. Yes, you can use it as a helper to generate error, but it's still very easy to generate errors without it.
Please, read this fantastic blog post about errors in Go: http://dave.cheney.net/2014/12/24/inspecting-errors
Signed-off-by: David Calavera <david.calavera@gmail.com>
2016-02-25 10:53:35 -05:00
|
|
|
_, err = w.Write(sf.FormatError(err))
|
2015-12-17 19:17:50 -05:00
|
|
|
if err != nil {
|
|
|
|
logrus.Warnf("could not write error response: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-12-29 15:49:17 -05:00
|
|
|
buildOptions, err := newImageBuildOptions(ctx, r)
|
|
|
|
if err != nil {
|
|
|
|
return errf(err)
|
2015-12-17 19:17:50 -05:00
|
|
|
}
|
2016-03-29 18:51:14 -04:00
|
|
|
buildOptions.AuthConfigs = authConfigs
|
2015-12-17 19:17:50 -05:00
|
|
|
|
|
|
|
remoteURL := r.FormValue("remote")
|
|
|
|
|
|
|
|
// Currently, only used if context is from a remote url.
|
|
|
|
// Look at code in DetectContextFromRemoteURL for more information.
|
|
|
|
createProgressReader := func(in io.ReadCloser) io.ReadCloser {
|
|
|
|
progressOutput := sf.NewProgressOutput(output, true)
|
2015-12-29 15:49:17 -05:00
|
|
|
if buildOptions.SuppressOutput {
|
2015-10-27 20:29:21 -04:00
|
|
|
progressOutput = sf.NewProgressOutput(notVerboseBuffer, true)
|
|
|
|
}
|
2015-12-17 19:17:50 -05:00
|
|
|
return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", remoteURL)
|
|
|
|
}
|
|
|
|
|
2016-08-29 16:36:16 -04:00
|
|
|
out := io.Writer(output)
|
2015-12-29 15:49:17 -05:00
|
|
|
if buildOptions.SuppressOutput {
|
2016-01-20 18:32:02 -05:00
|
|
|
out = notVerboseBuffer
|
2015-10-27 20:29:21 -04:00
|
|
|
}
|
2016-03-22 16:57:24 -04:00
|
|
|
out = &syncWriter{w: out}
|
2016-01-20 18:32:02 -05:00
|
|
|
stdout := &streamformatter.StdoutFormatter{Writer: out, StreamFormatter: sf}
|
|
|
|
stderr := &streamformatter.StderrFormatter{Writer: out, StreamFormatter: sf}
|
2015-12-17 19:17:50 -05:00
|
|
|
|
2016-03-29 18:51:14 -04:00
|
|
|
pg := backend.ProgressWriter{
|
|
|
|
Output: out,
|
|
|
|
StdoutFormatter: stdout,
|
|
|
|
StderrFormatter: stderr,
|
|
|
|
ProgressReaderFunc: createProgressReader,
|
|
|
|
}
|
|
|
|
|
|
|
|
imgID, err := br.backend.BuildFromContext(ctx, r.Body, remoteURL, buildOptions, pg)
|
2015-12-17 19:17:50 -05:00
|
|
|
if err != nil {
|
|
|
|
return errf(err)
|
|
|
|
}
|
|
|
|
|
2015-10-27 20:29:21 -04:00
|
|
|
// Everything worked so if -q was provided the output from the daemon
|
|
|
|
// should be just the image ID and we'll print that to stdout.
|
2015-12-29 15:49:17 -05:00
|
|
|
if buildOptions.SuppressOutput {
|
2015-10-27 20:29:21 -04:00
|
|
|
stdout := &streamformatter.StdoutFormatter{Writer: output, StreamFormatter: sf}
|
|
|
|
fmt.Fprintf(stdout, "%s\n", string(imgID))
|
|
|
|
}
|
|
|
|
|
2015-12-17 19:17:50 -05:00
|
|
|
return nil
|
|
|
|
}
|