From 9c88801a12a97de49abf26e9604975eececa654c Mon Sep 17 00:00:00 2001 From: Stephen J Day Date: Fri, 11 Aug 2017 15:31:16 -0700 Subject: [PATCH] context: remove definition of Context Back in the before time, the best practices surrounding usage of Context weren't quite worked out. We defined our own type to make usage easier. As this packaged was used elsewhere, it make it more and more challenging to integrate with the forked `Context` type. Now that it is available in the standard library, we can just use that one directly. To make usage more consistent, we now use `dcontext` when referring to the distribution context package. Signed-off-by: Stephen J Day --- blobs.go | 2 +- context/context.go | 18 +-- context/http.go | 23 ++-- context/logger.go | 19 +-- context/trace.go | 5 +- context/trace_test.go | 8 +- context/util.go | 5 +- context/version.go | 16 ++- contrib/token-server/main.go | 61 +++++----- contrib/token-server/token.go | 5 +- manifest/schema1/config_builder.go | 2 +- manifest/schema1/config_builder_test.go | 7 +- manifest/schema1/reference_builder.go | 4 +- manifest/schema2/builder.go | 3 +- manifest/schema2/builder_test.go | 2 +- manifests.go | 2 +- notifications/listener.go | 29 ++--- registry.go | 3 +- registry/auth/auth.go | 3 +- registry/auth/htpasswd/access.go | 7 +- registry/auth/silly/access.go | 11 +- registry/auth/token/accesscontroller.go | 5 +- registry/client/blob_writer.go | 2 +- registry/client/repository.go | 2 +- registry/handlers/api_test.go | 2 +- registry/handlers/app.go | 113 +++++++++--------- registry/handlers/blobupload.go | 26 ++-- registry/handlers/context.go | 16 +-- registry/handlers/helpers.go | 11 +- registry/handlers/manifests.go | 18 +-- registry/middleware/registry/middleware.go | 2 +- registry/middleware/repository/middleware.go | 2 +- registry/proxy/proxyblobstore.go | 9 +- registry/proxy/proxyblobstore_test.go | 2 +- registry/proxy/proxymanifeststore.go | 5 +- registry/proxy/proxymanifeststore_test.go | 2 +- registry/proxy/proxyregistry.go | 5 +- registry/proxy/proxytagservice.go | 3 +- registry/proxy/proxytagservice_test.go | 2 +- registry/proxy/scheduler/scheduler.go | 15 +-- registry/registry.go | 19 +-- registry/root.go | 4 +- registry/storage/blob_test.go | 2 +- registry/storage/blobserver.go | 2 +- registry/storage/blobstore.go | 7 +- registry/storage/blobwriter.go | 15 +-- registry/storage/blobwriter_resumable.go | 2 +- registry/storage/cache/cachecheck/suite.go | 2 +- .../cache/cachedblobdescriptorstore.go | 11 +- registry/storage/cache/memory/memory.go | 2 +- registry/storage/cache/redis/redis.go | 2 +- registry/storage/catalog.go | 2 +- registry/storage/catalog_test.go | 2 +- registry/storage/driver/azure/azure.go | 2 +- registry/storage/driver/base/base.go | 21 ++-- registry/storage/driver/base/regulator.go | 2 +- registry/storage/driver/filesystem/driver.go | 2 +- registry/storage/driver/gcs/gcs.go | 33 +++-- registry/storage/driver/gcs/gcs_test.go | 18 +-- registry/storage/driver/inmemory/driver.go | 2 +- .../middleware/cloudfront/middleware.go | 5 +- .../driver/middleware/redirect/middleware.go | 2 +- registry/storage/driver/oss/oss.go | 3 +- registry/storage/driver/oss/oss_test.go | 8 +- registry/storage/driver/s3-aws/s3.go | 2 +- registry/storage/driver/s3-goamz/s3.go | 7 +- registry/storage/driver/storagedriver.go | 3 +- registry/storage/driver/swift/swift.go | 2 +- .../storage/driver/testdriver/testdriver.go | 3 +- .../storage/driver/testsuites/testsuites.go | 5 +- registry/storage/filereader.go | 2 +- registry/storage/garbagecollect.go | 2 +- registry/storage/io.go | 2 +- registry/storage/linkedblobstore.go | 11 +- registry/storage/linkedblobstore_test.go | 5 +- registry/storage/manifestlisthandler.go | 11 +- registry/storage/manifeststore.go | 13 +- registry/storage/manifeststore_test.go | 2 +- registry/storage/purgeuploads.go | 10 +- registry/storage/purgeuploads_test.go | 2 +- registry/storage/registry.go | 2 +- registry/storage/schema2manifesthandler.go | 9 +- registry/storage/signedmanifesthandler.go | 9 +- registry/storage/tagstore.go | 2 +- registry/storage/tagstore_test.go | 2 +- registry/storage/util.go | 3 +- registry/storage/vacuum.go | 7 +- registry/storage/walk.go | 2 +- registry/storage/walk_test.go | 2 +- tags.go | 2 +- 90 files changed, 396 insertions(+), 373 deletions(-) diff --git a/blobs.go b/blobs.go index 01d309029ff..145b078532b 100644 --- a/blobs.go +++ b/blobs.go @@ -1,13 +1,13 @@ package distribution import ( + "context" "errors" "fmt" "io" "net/http" "time" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/opencontainers/go-digest" ) diff --git a/context/context.go b/context/context.go index 23cbf5b5450..ab6865467b0 100644 --- a/context/context.go +++ b/context/context.go @@ -1,21 +1,16 @@ package context import ( + "context" "sync" "github.com/docker/distribution/uuid" - "golang.org/x/net/context" ) -// Context is a copy of Context from the golang.org/x/net/context package. -type Context interface { - context.Context -} - // instanceContext is a context that provides only an instance id. It is // provided as the main background context. type instanceContext struct { - Context + context.Context id string // id of context, logged as "instance.id" once sync.Once // once protect generation of the id } @@ -42,17 +37,10 @@ var background = &instanceContext{ // Background returns a non-nil, empty Context. The background context // provides a single key, "instance.id" that is globally unique to the // process. -func Background() Context { +func Background() context.Context { return background } -// WithValue returns a copy of parent in which the value associated with key is -// val. Use context Values only for request-scoped data that transits processes -// and APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key, val interface{}) Context { - return context.WithValue(parent, key, val) -} - // stringMapContext is a simple context implementation that checks a map for a // key, falling back to a parent if not present. type stringMapContext struct { diff --git a/context/http.go b/context/http.go index 7d65c8524e4..b7447800408 100644 --- a/context/http.go +++ b/context/http.go @@ -1,6 +1,7 @@ package context import ( + "context" "errors" "net" "net/http" @@ -68,7 +69,7 @@ func RemoteIP(r *http.Request) string { // is available at "http.request". Other common attributes are available under // the prefix "http.request.". If a request is already present on the context, // this method will panic. -func WithRequest(ctx Context, r *http.Request) Context { +func WithRequest(ctx context.Context, r *http.Request) context.Context { if ctx.Value("http.request") != nil { // NOTE(stevvooe): This needs to be considered a programming error. It // is unlikely that we'd want to have more than one request in @@ -87,7 +88,7 @@ func WithRequest(ctx Context, r *http.Request) Context { // GetRequest returns the http request in the given context. Returns // ErrNoRequestContext if the context does not have an http request associated // with it. -func GetRequest(ctx Context) (*http.Request, error) { +func GetRequest(ctx context.Context) (*http.Request, error) { if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok { return r, nil } @@ -96,13 +97,13 @@ func GetRequest(ctx Context) (*http.Request, error) { // GetRequestID attempts to resolve the current request id, if possible. An // error is return if it is not available on the context. -func GetRequestID(ctx Context) string { +func GetRequestID(ctx context.Context) string { return GetStringValue(ctx, "http.request.id") } // WithResponseWriter returns a new context and response writer that makes // interesting response statistics available within the context. -func WithResponseWriter(ctx Context, w http.ResponseWriter) (Context, http.ResponseWriter) { +func WithResponseWriter(ctx context.Context, w http.ResponseWriter) (context.Context, http.ResponseWriter) { if closeNotifier, ok := w.(http.CloseNotifier); ok { irwCN := &instrumentedResponseWriterCN{ instrumentedResponseWriter: instrumentedResponseWriter{ @@ -125,7 +126,7 @@ func WithResponseWriter(ctx Context, w http.ResponseWriter) (Context, http.Respo // GetResponseWriter returns the http.ResponseWriter from the provided // context. If not present, ErrNoResponseWriterContext is returned. The // returned instance provides instrumentation in the context. -func GetResponseWriter(ctx Context) (http.ResponseWriter, error) { +func GetResponseWriter(ctx context.Context) (http.ResponseWriter, error) { v := ctx.Value("http.response") rw, ok := v.(http.ResponseWriter) @@ -145,7 +146,7 @@ var getVarsFromRequest = mux.Vars // example, if looking for the variable "name", it can be accessed as // "vars.name". Implementations that are accessing values need not know that // the underlying context is implemented with gorilla/mux vars. -func WithVars(ctx Context, r *http.Request) Context { +func WithVars(ctx context.Context, r *http.Request) context.Context { return &muxVarsContext{ Context: ctx, vars: getVarsFromRequest(r), @@ -155,7 +156,7 @@ func WithVars(ctx Context, r *http.Request) Context { // GetRequestLogger returns a logger that contains fields from the request in // the current context. If the request is not available in the context, no // fields will display. Request loggers can safely be pushed onto the context. -func GetRequestLogger(ctx Context) Logger { +func GetRequestLogger(ctx context.Context) Logger { return GetLogger(ctx, "http.request.id", "http.request.method", @@ -171,7 +172,7 @@ func GetRequestLogger(ctx Context) Logger { // Because the values are read at call time, pushing a logger returned from // this function on the context will lead to missing or invalid data. Only // call this at the end of a request, after the response has been written. -func GetResponseLogger(ctx Context) Logger { +func GetResponseLogger(ctx context.Context) Logger { l := getLogrusLogger(ctx, "http.response.written", "http.response.status", @@ -188,7 +189,7 @@ func GetResponseLogger(ctx Context) Logger { // httpRequestContext makes information about a request available to context. type httpRequestContext struct { - Context + context.Context startedAt time.Time id string @@ -247,7 +248,7 @@ fallback: } type muxVarsContext struct { - Context + context.Context vars map[string]string } @@ -282,7 +283,7 @@ type instrumentedResponseWriterCN struct { // implemented by the parent ResponseWriter. type instrumentedResponseWriter struct { http.ResponseWriter - Context + context.Context mu sync.Mutex status int diff --git a/context/logger.go b/context/logger.go index 86c5964e49b..afc8860b16a 100644 --- a/context/logger.go +++ b/context/logger.go @@ -1,10 +1,11 @@ package context import ( + "context" "fmt" + "runtime" "github.com/sirupsen/logrus" - "runtime" ) // Logger provides a leveled-logging interface. @@ -40,22 +41,24 @@ type Logger interface { Warnln(args ...interface{}) } +type loggerKey struct{} + // WithLogger creates a new context with provided logger. -func WithLogger(ctx Context, logger Logger) Context { - return WithValue(ctx, "logger", logger) +func WithLogger(ctx context.Context, logger Logger) context.Context { + return context.WithValue(ctx, loggerKey{}, logger) } // GetLoggerWithField returns a logger instance with the specified field key // and value without affecting the context. Extra specified keys will be // resolved from the context. -func GetLoggerWithField(ctx Context, key, value interface{}, keys ...interface{}) Logger { +func GetLoggerWithField(ctx context.Context, key, value interface{}, keys ...interface{}) Logger { return getLogrusLogger(ctx, keys...).WithField(fmt.Sprint(key), value) } // GetLoggerWithFields returns a logger instance with the specified fields // without affecting the context. Extra specified keys will be resolved from // the context. -func GetLoggerWithFields(ctx Context, fields map[interface{}]interface{}, keys ...interface{}) Logger { +func GetLoggerWithFields(ctx context.Context, fields map[interface{}]interface{}, keys ...interface{}) Logger { // must convert from interface{} -> interface{} to string -> interface{} for logrus. lfields := make(logrus.Fields, len(fields)) for key, value := range fields { @@ -71,7 +74,7 @@ func GetLoggerWithFields(ctx Context, fields map[interface{}]interface{}, keys . // argument passed to GetLogger will be passed to fmt.Sprint when expanded as // a logging key field. If context keys are integer constants, for example, // its recommended that a String method is implemented. -func GetLogger(ctx Context, keys ...interface{}) Logger { +func GetLogger(ctx context.Context, keys ...interface{}) Logger { return getLogrusLogger(ctx, keys...) } @@ -79,11 +82,11 @@ func GetLogger(ctx Context, keys ...interface{}) Logger { // are provided, they will be resolved on the context and included in the // logger. Only use this function if specific logrus functionality is // required. -func getLogrusLogger(ctx Context, keys ...interface{}) *logrus.Entry { +func getLogrusLogger(ctx context.Context, keys ...interface{}) *logrus.Entry { var logger *logrus.Entry // Get a logger, if it is present. - loggerInterface := ctx.Value("logger") + loggerInterface := ctx.Value(loggerKey{}) if loggerInterface != nil { if lgr, ok := loggerInterface.(*logrus.Entry); ok { logger = lgr diff --git a/context/trace.go b/context/trace.go index 721964a8489..5b88ddaf44e 100644 --- a/context/trace.go +++ b/context/trace.go @@ -1,6 +1,7 @@ package context import ( + "context" "runtime" "time" @@ -36,7 +37,7 @@ import ( // // Notice that the function name is automatically resolved, along with the // package and a trace id is emitted that can be linked with parent ids. -func WithTrace(ctx Context) (Context, func(format string, a ...interface{})) { +func WithTrace(ctx context.Context) (context.Context, func(format string, a ...interface{})) { if ctx == nil { ctx = Background() } @@ -69,7 +70,7 @@ func WithTrace(ctx Context) (Context, func(format string, a ...interface{})) { // also provides fast lookup for the various attributes that are available on // the trace. type traced struct { - Context + context.Context id string parent string start time.Time diff --git a/context/trace_test.go b/context/trace_test.go index 4b969fbb0d0..f973f9a466b 100644 --- a/context/trace_test.go +++ b/context/trace_test.go @@ -1,6 +1,7 @@ package context import ( + "context" "runtime" "testing" "time" @@ -35,7 +36,7 @@ func TestWithTrace(t *testing.T) { ctx, done := WithTrace(Background()) defer done("this will be emitted at end of test") - checkContextForValues(t, ctx, append(base, valueTestCase{ + checkContextForValues(ctx, t, append(base, valueTestCase{ key: "trace.func", expected: f.Name(), })) @@ -48,7 +49,7 @@ func TestWithTrace(t *testing.T) { ctx, done := WithTrace(ctx) defer done("this should be subordinate to the other trace") time.Sleep(time.Second) - checkContextForValues(t, ctx, append(base, valueTestCase{ + checkContextForValues(ctx, t, append(base, valueTestCase{ key: "trace.func", expected: f.Name(), }, valueTestCase{ @@ -67,8 +68,7 @@ type valueTestCase struct { notnilorempty bool // just check not empty/not nil } -func checkContextForValues(t *testing.T, ctx Context, values []valueTestCase) { - +func checkContextForValues(ctx context.Context, t *testing.T, values []valueTestCase) { for _, testcase := range values { v := ctx.Value(testcase.key) if testcase.notnilorempty { diff --git a/context/util.go b/context/util.go index cb9ef52e38e..c462e756329 100644 --- a/context/util.go +++ b/context/util.go @@ -1,13 +1,14 @@ package context import ( + "context" "time" ) // Since looks up key, which should be a time.Time, and returns the duration // since that time. If the key is not found, the value returned will be zero. // This is helpful when inferring metrics related to context execution times. -func Since(ctx Context, key interface{}) time.Duration { +func Since(ctx context.Context, key interface{}) time.Duration { if startedAt, ok := ctx.Value(key).(time.Time); ok { return time.Since(startedAt) } @@ -16,7 +17,7 @@ func Since(ctx Context, key interface{}) time.Duration { // GetStringValue returns a string value from the context. The empty string // will be returned if not found. -func GetStringValue(ctx Context, key interface{}) (value string) { +func GetStringValue(ctx context.Context, key interface{}) (value string) { if valuev, ok := ctx.Value(key).(string); ok { value = valuev } diff --git a/context/version.go b/context/version.go index 746cda02ecd..97cf9d665f4 100644 --- a/context/version.go +++ b/context/version.go @@ -1,16 +1,22 @@ package context +import "context" + +type versionKey struct{} + +func (versionKey) String() string { return "version" } + // WithVersion stores the application version in the context. The new context // gets a logger to ensure log messages are marked with the application // version. -func WithVersion(ctx Context, version string) Context { - ctx = WithValue(ctx, "version", version) +func WithVersion(ctx context.Context, version string) context.Context { + ctx = context.WithValue(ctx, versionKey{}, version) // push a new logger onto the stack - return WithLogger(ctx, GetLogger(ctx, "version")) + return WithLogger(ctx, GetLogger(ctx, versionKey{})) } // GetVersion returns the application version from the context. An empty // string may returned if the version was not set on the context. -func GetVersion(ctx Context) string { - return GetStringValue(ctx, "version") +func GetVersion(ctx context.Context) string { + return GetStringValue(ctx, versionKey{}) } diff --git a/contrib/token-server/main.go b/contrib/token-server/main.go index bfbb470b3e7..138793c732a 100644 --- a/contrib/token-server/main.go +++ b/contrib/token-server/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "flag" "math/rand" @@ -9,7 +10,7 @@ import ( "strings" "time" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/auth" _ "github.com/docker/distribution/registry/auth/htpasswd" @@ -85,7 +86,7 @@ func main() { // TODO: Make configurable issuer.Expiration = 15 * time.Minute - ctx := context.Background() + ctx := dcontext.Background() ts := &tokenServer{ issuer: issuer, @@ -115,23 +116,23 @@ func main() { // request context from a base context. func handlerWithContext(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := context.WithRequest(ctx, r) - logger := context.GetRequestLogger(ctx) - ctx = context.WithLogger(ctx, logger) + ctx := dcontext.WithRequest(ctx, r) + logger := dcontext.GetRequestLogger(ctx) + ctx = dcontext.WithLogger(ctx, logger) handler(ctx, w, r) }) } func handleError(ctx context.Context, err error, w http.ResponseWriter) { - ctx, w = context.WithResponseWriter(ctx, w) + ctx, w = dcontext.WithResponseWriter(ctx, w) if serveErr := errcode.ServeJSON(w, err); serveErr != nil { - context.GetResponseLogger(ctx).Errorf("error sending error response: %v", serveErr) + dcontext.GetResponseLogger(ctx).Errorf("error sending error response: %v", serveErr) return } - context.GetResponseLogger(ctx).Info("application error") + dcontext.GetResponseLogger(ctx).Info("application error") } var refreshCharacters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") @@ -173,13 +174,13 @@ func filterAccessList(ctx context.Context, scope string, requestedAccessList []a for _, access := range requestedAccessList { if access.Type == "repository" { if !strings.HasPrefix(access.Name, scope) { - context.GetLogger(ctx).Debugf("Resource scope not allowed: %s", access.Name) + dcontext.GetLogger(ctx).Debugf("Resource scope not allowed: %s", access.Name) continue } if enforceRepoClass { if class, ok := repositoryClassCache[access.Name]; ok { if class != access.Class { - context.GetLogger(ctx).Debugf("Different repository class: %q, previously %q", access.Class, class) + dcontext.GetLogger(ctx).Debugf("Different repository class: %q, previously %q", access.Class, class) continue } } else if strings.EqualFold(access.Action, "push") { @@ -188,12 +189,12 @@ func filterAccessList(ctx context.Context, scope string, requestedAccessList []a } } else if access.Type == "registry" { if access.Name != "catalog" { - context.GetLogger(ctx).Debugf("Unknown registry resource: %s", access.Name) + dcontext.GetLogger(ctx).Debugf("Unknown registry resource: %s", access.Name) continue } // TODO: Limit some actions to "admin" users } else { - context.GetLogger(ctx).Debugf("Skipping unsupported resource type: %s", access.Type) + dcontext.GetLogger(ctx).Debugf("Skipping unsupported resource type: %s", access.Type) continue } grantedAccessList = append(grantedAccessList, access) @@ -216,7 +217,7 @@ func (grantedAccess) String() string { return "grantedAccess" } // getToken handles authenticating the request and authorizing access to the // requested scopes. func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *http.Request) { - context.GetLogger(ctx).Info("getToken") + dcontext.GetLogger(ctx).Info("getToken") params := r.URL.Query() service := params.Get("service") @@ -242,30 +243,30 @@ func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *h } // Get response context. - ctx, w = context.WithResponseWriter(ctx, w) + ctx, w = dcontext.WithResponseWriter(ctx, w) challenge.SetHeaders(w) handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail(challenge.Error()), w) - context.GetResponseLogger(ctx).Info("get token authentication challenge") + dcontext.GetResponseLogger(ctx).Info("get token authentication challenge") return } ctx = authorizedCtx - username := context.GetStringValue(ctx, "auth.user.name") + username := dcontext.GetStringValue(ctx, "auth.user.name") ctx = context.WithValue(ctx, acctSubject{}, username) - ctx = context.WithLogger(ctx, context.GetLogger(ctx, acctSubject{})) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, acctSubject{})) - context.GetLogger(ctx).Info("authenticated client") + dcontext.GetLogger(ctx).Info("authenticated client") ctx = context.WithValue(ctx, requestedAccess{}, requestedAccessList) - ctx = context.WithLogger(ctx, context.GetLogger(ctx, requestedAccess{})) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, requestedAccess{})) grantedAccessList := filterAccessList(ctx, username, requestedAccessList) ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList) - ctx = context.WithLogger(ctx, context.GetLogger(ctx, grantedAccess{})) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, grantedAccess{})) token, err := ts.issuer.CreateJWT(username, service, grantedAccessList) if err != nil { @@ -273,7 +274,7 @@ func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *h return } - context.GetLogger(ctx).Info("authorized client") + dcontext.GetLogger(ctx).Info("authorized client") response := tokenResponse{ Token: token, @@ -288,12 +289,12 @@ func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *h } } - ctx, w = context.WithResponseWriter(ctx, w) + ctx, w = dcontext.WithResponseWriter(ctx, w) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(response) - context.GetResponseLogger(ctx).Info("get token complete") + dcontext.GetResponseLogger(ctx).Info("get token complete") } type postTokenResponse struct { @@ -378,16 +379,16 @@ func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r * } ctx = context.WithValue(ctx, acctSubject{}, subject) - ctx = context.WithLogger(ctx, context.GetLogger(ctx, acctSubject{})) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, acctSubject{})) - context.GetLogger(ctx).Info("authenticated client") + dcontext.GetLogger(ctx).Info("authenticated client") ctx = context.WithValue(ctx, requestedAccess{}, requestedAccessList) - ctx = context.WithLogger(ctx, context.GetLogger(ctx, requestedAccess{})) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, requestedAccess{})) grantedAccessList := filterAccessList(ctx, subject, requestedAccessList) ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList) - ctx = context.WithLogger(ctx, context.GetLogger(ctx, grantedAccess{})) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, grantedAccess{})) token, err := ts.issuer.CreateJWT(subject, service, grantedAccessList) if err != nil { @@ -395,7 +396,7 @@ func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r * return } - context.GetLogger(ctx).Info("authorized client") + dcontext.GetLogger(ctx).Info("authorized client") response := postTokenResponse{ Token: token, @@ -416,10 +417,10 @@ func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r * response.RefreshToken = rToken } - ctx, w = context.WithResponseWriter(ctx, w) + ctx, w = dcontext.WithResponseWriter(ctx, w) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(response) - context.GetResponseLogger(ctx).Info("post token complete") + dcontext.GetResponseLogger(ctx).Info("post token complete") } diff --git a/contrib/token-server/token.go b/contrib/token-server/token.go index b0c2abff7dd..8df5b6a8563 100644 --- a/contrib/token-server/token.go +++ b/contrib/token-server/token.go @@ -1,6 +1,7 @@ package main import ( + "context" "crypto" "crypto/rand" "encoding/base64" @@ -11,7 +12,7 @@ import ( "strings" "time" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/auth" "github.com/docker/distribution/registry/auth/token" "github.com/docker/libtrust" @@ -27,7 +28,7 @@ func ResolveScopeSpecifiers(ctx context.Context, scopeSpecs []string) []auth.Acc parts := strings.SplitN(scopeSpecifier, ":", 3) if len(parts) != 3 { - context.GetLogger(ctx).Infof("ignoring unsupported scope format %s", scopeSpecifier) + dcontext.GetLogger(ctx).Infof("ignoring unsupported scope format %s", scopeSpecifier) continue } diff --git a/manifest/schema1/config_builder.go b/manifest/schema1/config_builder.go index 9d222566ca4..a96dc3d267d 100644 --- a/manifest/schema1/config_builder.go +++ b/manifest/schema1/config_builder.go @@ -1,6 +1,7 @@ package schema1 import ( + "context" "crypto/sha512" "encoding/json" "errors" @@ -8,7 +9,6 @@ import ( "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/manifest" "github.com/docker/distribution/reference" "github.com/docker/libtrust" diff --git a/manifest/schema1/config_builder_test.go b/manifest/schema1/config_builder_test.go index 399d8f315a5..360febd78fc 100644 --- a/manifest/schema1/config_builder_test.go +++ b/manifest/schema1/config_builder_test.go @@ -3,12 +3,13 @@ package schema1 import ( "bytes" "compress/gzip" + "context" "io" "reflect" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/libtrust" "github.com/opencontainers/go-digest" @@ -214,13 +215,13 @@ func TestConfigBuilder(t *testing.T) { } } - signed, err := builder.Build(context.Background()) + signed, err := builder.Build(dcontext.Background()) if err != nil { t.Fatalf("Build returned error: %v", err) } // Check that the gzipped empty layer tar was put in the blob store - _, err = bs.Stat(context.Background(), digestSHA256GzippedEmptyTar) + _, err = bs.Stat(dcontext.Background(), digestSHA256GzippedEmptyTar) if err != nil { t.Fatal("gzipped empty tar was not put in the blob store") } diff --git a/manifest/schema1/reference_builder.go b/manifest/schema1/reference_builder.go index ae401478192..a4f6032cd1e 100644 --- a/manifest/schema1/reference_builder.go +++ b/manifest/schema1/reference_builder.go @@ -1,11 +1,11 @@ package schema1 import ( + "context" + "errors" "fmt" - "errors" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/manifest" "github.com/docker/distribution/reference" "github.com/docker/libtrust" diff --git a/manifest/schema2/builder.go b/manifest/schema2/builder.go index 4b6ba5628ae..3facaae62e6 100644 --- a/manifest/schema2/builder.go +++ b/manifest/schema2/builder.go @@ -1,8 +1,9 @@ package schema2 import ( + "context" + "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/opencontainers/go-digest" ) diff --git a/manifest/schema2/builder_test.go b/manifest/schema2/builder_test.go index 697c1bc927e..cde73242e63 100644 --- a/manifest/schema2/builder_test.go +++ b/manifest/schema2/builder_test.go @@ -1,11 +1,11 @@ package schema2 import ( + "context" "reflect" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/opencontainers/go-digest" ) diff --git a/manifests.go b/manifests.go index 2c99f25d391..1816baea1d6 100644 --- a/manifests.go +++ b/manifests.go @@ -1,10 +1,10 @@ package distribution import ( + "context" "fmt" "mime" - "github.com/docker/distribution/context" "github.com/opencontainers/go-digest" ) diff --git a/notifications/listener.go b/notifications/listener.go index 25b5a800fe3..52ec0ee7993 100644 --- a/notifications/listener.go +++ b/notifications/listener.go @@ -1,10 +1,11 @@ package notifications import ( + "context" "net/http" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/opencontainers/go-digest" ) @@ -70,7 +71,7 @@ func (msl *manifestServiceListener) Delete(ctx context.Context, dgst digest.Dige err := msl.ManifestService.Delete(ctx, dgst) if err == nil { if err := msl.parent.listener.ManifestDeleted(msl.parent.Repository.Named(), dgst); err != nil { - context.GetLogger(ctx).Errorf("error dispatching manifest delete to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching manifest delete to listener: %v", err) } } @@ -81,7 +82,7 @@ func (msl *manifestServiceListener) Get(ctx context.Context, dgst digest.Digest, sm, err := msl.ManifestService.Get(ctx, dgst, options...) if err == nil { if err := msl.parent.listener.ManifestPulled(msl.parent.Repository.Named(), sm, options...); err != nil { - context.GetLogger(ctx).Errorf("error dispatching manifest pull to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching manifest pull to listener: %v", err) } } @@ -93,7 +94,7 @@ func (msl *manifestServiceListener) Put(ctx context.Context, sm distribution.Man if err == nil { if err := msl.parent.listener.ManifestPushed(msl.parent.Repository.Named(), sm, options...); err != nil { - context.GetLogger(ctx).Errorf("error dispatching manifest push to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching manifest push to listener: %v", err) } } @@ -111,10 +112,10 @@ func (bsl *blobServiceListener) Get(ctx context.Context, dgst digest.Digest) ([] p, err := bsl.BlobStore.Get(ctx, dgst) if err == nil { if desc, err := bsl.Stat(ctx, dgst); err != nil { - context.GetLogger(ctx).Errorf("error resolving descriptor in ServeBlob listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error resolving descriptor in ServeBlob listener: %v", err) } else { if err := bsl.parent.listener.BlobPulled(bsl.parent.Repository.Named(), desc); err != nil { - context.GetLogger(ctx).Errorf("error dispatching layer pull to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching layer pull to listener: %v", err) } } } @@ -126,10 +127,10 @@ func (bsl *blobServiceListener) Open(ctx context.Context, dgst digest.Digest) (d rc, err := bsl.BlobStore.Open(ctx, dgst) if err == nil { if desc, err := bsl.Stat(ctx, dgst); err != nil { - context.GetLogger(ctx).Errorf("error resolving descriptor in ServeBlob listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error resolving descriptor in ServeBlob listener: %v", err) } else { if err := bsl.parent.listener.BlobPulled(bsl.parent.Repository.Named(), desc); err != nil { - context.GetLogger(ctx).Errorf("error dispatching layer pull to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching layer pull to listener: %v", err) } } } @@ -141,10 +142,10 @@ func (bsl *blobServiceListener) ServeBlob(ctx context.Context, w http.ResponseWr err := bsl.BlobStore.ServeBlob(ctx, w, r, dgst) if err == nil { if desc, err := bsl.Stat(ctx, dgst); err != nil { - context.GetLogger(ctx).Errorf("error resolving descriptor in ServeBlob listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error resolving descriptor in ServeBlob listener: %v", err) } else { if err := bsl.parent.listener.BlobPulled(bsl.parent.Repository.Named(), desc); err != nil { - context.GetLogger(ctx).Errorf("error dispatching layer pull to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching layer pull to listener: %v", err) } } } @@ -156,7 +157,7 @@ func (bsl *blobServiceListener) Put(ctx context.Context, mediaType string, p []b desc, err := bsl.BlobStore.Put(ctx, mediaType, p) if err == nil { if err := bsl.parent.listener.BlobPushed(bsl.parent.Repository.Named(), desc); err != nil { - context.GetLogger(ctx).Errorf("error dispatching layer push to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching layer push to listener: %v", err) } } @@ -168,7 +169,7 @@ func (bsl *blobServiceListener) Create(ctx context.Context, options ...distribut switch err := err.(type) { case distribution.ErrBlobMounted: if err := bsl.parent.listener.BlobMounted(bsl.parent.Repository.Named(), err.Descriptor, err.From); err != nil { - context.GetLogger(ctx).Errorf("error dispatching blob mount to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching blob mount to listener: %v", err) } return nil, err } @@ -179,7 +180,7 @@ func (bsl *blobServiceListener) Delete(ctx context.Context, dgst digest.Digest) err := bsl.BlobStore.Delete(ctx, dgst) if err == nil { if err := bsl.parent.listener.BlobDeleted(bsl.parent.Repository.Named(), dgst); err != nil { - context.GetLogger(ctx).Errorf("error dispatching layer delete to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching layer delete to listener: %v", err) } } @@ -207,7 +208,7 @@ func (bwl *blobWriterListener) Commit(ctx context.Context, desc distribution.Des committed, err := bwl.BlobWriter.Commit(ctx, desc) if err == nil { if err := bwl.parent.parent.listener.BlobPushed(bwl.parent.parent.Repository.Named(), committed); err != nil { - context.GetLogger(ctx).Errorf("error dispatching blob push to listener: %v", err) + dcontext.GetLogger(ctx).Errorf("error dispatching blob push to listener: %v", err) } } diff --git a/registry.go b/registry.go index 1da1d533ff7..c34207d030b 100644 --- a/registry.go +++ b/registry.go @@ -1,7 +1,8 @@ package distribution import ( - "github.com/docker/distribution/context" + "context" + "github.com/docker/distribution/reference" ) diff --git a/registry/auth/auth.go b/registry/auth/auth.go index 1c9af8821df..91c7af3faec 100644 --- a/registry/auth/auth.go +++ b/registry/auth/auth.go @@ -33,11 +33,10 @@ package auth import ( + "context" "errors" "fmt" "net/http" - - "github.com/docker/distribution/context" ) const ( diff --git a/registry/auth/htpasswd/access.go b/registry/auth/htpasswd/access.go index 819b09ca841..8f40913b30a 100644 --- a/registry/auth/htpasswd/access.go +++ b/registry/auth/htpasswd/access.go @@ -6,13 +6,14 @@ package htpasswd import ( + "context" "fmt" "net/http" "os" "sync" "time" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/auth" ) @@ -41,7 +42,7 @@ func newAccessController(options map[string]interface{}) (auth.AccessController, } func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) { - req, err := context.GetRequest(ctx) + req, err := dcontext.GetRequest(ctx) if err != nil { return nil, err } @@ -83,7 +84,7 @@ func (ac *accessController) Authorized(ctx context.Context, accessRecords ...aut ac.mu.Unlock() if err := localHTPasswd.authenticateUser(username, password); err != nil { - context.GetLogger(ctx).Errorf("error authenticating user %q: %v", username, err) + dcontext.GetLogger(ctx).Errorf("error authenticating user %q: %v", username, err) return nil, &challenge{ realm: ac.realm, err: auth.ErrAuthenticationFailure, diff --git a/registry/auth/silly/access.go b/registry/auth/silly/access.go index 2b801d946e1..f7bbe6e0816 100644 --- a/registry/auth/silly/access.go +++ b/registry/auth/silly/access.go @@ -8,11 +8,12 @@ package silly import ( + "context" "fmt" "net/http" "strings" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/auth" ) @@ -43,7 +44,7 @@ func newAccessController(options map[string]interface{}) (auth.AccessController, // Authorized simply checks for the existence of the authorization header, // responding with a bearer challenge if it doesn't exist. func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) { - req, err := context.GetRequest(ctx) + req, err := dcontext.GetRequest(ctx) if err != nil { return nil, err } @@ -65,7 +66,11 @@ func (ac *accessController) Authorized(ctx context.Context, accessRecords ...aut return nil, &challenge } - return auth.WithUser(ctx, auth.UserInfo{Name: "silly"}), nil + ctx = auth.WithUser(ctx, auth.UserInfo{Name: "silly"}) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, auth.UserNameKey, auth.UserKey)) + + return ctx, nil + } type challenge struct { diff --git a/registry/auth/token/accesscontroller.go b/registry/auth/token/accesscontroller.go index 4e8b7f1cefe..3086c2cfb0f 100644 --- a/registry/auth/token/accesscontroller.go +++ b/registry/auth/token/accesscontroller.go @@ -1,6 +1,7 @@ package token import ( + "context" "crypto" "crypto/x509" "encoding/pem" @@ -11,7 +12,7 @@ import ( "os" "strings" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/auth" "github.com/docker/libtrust" ) @@ -221,7 +222,7 @@ func (ac *accessController) Authorized(ctx context.Context, accessItems ...auth. accessSet: newAccessSet(accessItems...), } - req, err := context.GetRequest(ctx) + req, err := dcontext.GetRequest(ctx) if err != nil { return nil, err } diff --git a/registry/client/blob_writer.go b/registry/client/blob_writer.go index e3ffcb00fd6..695bf852f16 100644 --- a/registry/client/blob_writer.go +++ b/registry/client/blob_writer.go @@ -2,6 +2,7 @@ package client import ( "bytes" + "context" "fmt" "io" "io/ioutil" @@ -9,7 +10,6 @@ import ( "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" ) type httpBlobUpload struct { diff --git a/registry/client/repository.go b/registry/client/repository.go index b82a968e28a..8bd2c3fb62e 100644 --- a/registry/client/repository.go +++ b/registry/client/repository.go @@ -2,6 +2,7 @@ package client import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -14,7 +15,6 @@ import ( "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/client/transport" diff --git a/registry/handlers/api_test.go b/registry/handlers/api_test.go index c8e756de60b..98dcaa71f3e 100644 --- a/registry/handlers/api_test.go +++ b/registry/handlers/api_test.go @@ -2,6 +2,7 @@ package handlers import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -21,7 +22,6 @@ import ( "github.com/docker/distribution" "github.com/docker/distribution/configuration" - "github.com/docker/distribution/context" "github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/schema1" diff --git a/registry/handlers/app.go b/registry/handlers/app.go index a5af88dc0bb..813bae16da3 100644 --- a/registry/handlers/app.go +++ b/registry/handlers/app.go @@ -1,6 +1,7 @@ package handlers import ( + "context" cryptorand "crypto/rand" "expvar" "fmt" @@ -16,7 +17,7 @@ import ( "github.com/docker/distribution" "github.com/docker/distribution/configuration" - ctxu "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/health" "github.com/docker/distribution/health/checks" "github.com/docker/distribution/notifications" @@ -37,8 +38,7 @@ import ( "github.com/docker/libtrust" "github.com/garyburd/redigo/redis" "github.com/gorilla/mux" - log "github.com/sirupsen/logrus" - "golang.org/x/net/context" + "github.com/sirupsen/logrus" ) // randomSecretSize is the number of random bytes to generate if no secret @@ -145,7 +145,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App { } } - startUploadPurger(app, app.driver, ctxu.GetLogger(app), purgeConfig) + startUploadPurger(app, app.driver, dcontext.GetLogger(app), purgeConfig) app.driver, err = applyStorageMiddleware(app.driver, config.Middleware["storage"]) if err != nil { @@ -208,7 +208,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App { } } if redirectDisabled { - ctxu.GetLogger(app).Infof("backend redirection disabled") + dcontext.GetLogger(app).Infof("backend redirection disabled") } else { options = append(options, storage.EnableRedirect) } @@ -269,7 +269,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App { if err != nil { panic("could not create registry: " + err.Error()) } - ctxu.GetLogger(app).Infof("using redis blob descriptor cache") + dcontext.GetLogger(app).Infof("using redis blob descriptor cache") case "inmemory": cacheProvider := memorycache.NewInMemoryBlobDescriptorCacheProvider() localOptions := append(options, storage.BlobDescriptorCacheProvider(cacheProvider)) @@ -277,10 +277,10 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App { if err != nil { panic("could not create registry: " + err.Error()) } - ctxu.GetLogger(app).Infof("using inmemory blob descriptor cache") + dcontext.GetLogger(app).Infof("using inmemory blob descriptor cache") default: if v != "" { - ctxu.GetLogger(app).Warnf("unknown cache type %q, caching disabled", config.Storage["cache"]) + dcontext.GetLogger(app).Warnf("unknown cache type %q, caching disabled", config.Storage["cache"]) } } } @@ -306,7 +306,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App { panic(fmt.Sprintf("unable to configure authorization (%s): %v", authType, err)) } app.accessController = accessController - ctxu.GetLogger(app).Debugf("configured %q access controller", authType) + dcontext.GetLogger(app).Debugf("configured %q access controller", authType) } // configure as a pull through cache @@ -316,7 +316,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App { panic(err.Error()) } app.isCache = true - ctxu.GetLogger(app).Info("Registry configured as a proxy cache to ", config.Proxy.RemoteURL) + dcontext.GetLogger(app).Info("Registry configured as a proxy cache to ", config.Proxy.RemoteURL) } return app @@ -361,7 +361,7 @@ func (app *App) RegisterHealthChecks(healthRegistries ...*health.Registry) { if interval == 0 { interval = defaultCheckInterval } - ctxu.GetLogger(app).Infof("configuring file health check path=%s, interval=%d", fileChecker.File, interval/time.Second) + dcontext.GetLogger(app).Infof("configuring file health check path=%s, interval=%d", fileChecker.File, interval/time.Second) healthRegistry.Register(fileChecker.File, health.PeriodicChecker(checks.FileChecker(fileChecker.File), interval)) } @@ -379,10 +379,10 @@ func (app *App) RegisterHealthChecks(healthRegistries ...*health.Registry) { checker := checks.HTTPChecker(httpChecker.URI, statusCode, httpChecker.Timeout, httpChecker.Headers) if httpChecker.Threshold != 0 { - ctxu.GetLogger(app).Infof("configuring HTTP health check uri=%s, interval=%d, threshold=%d", httpChecker.URI, interval/time.Second, httpChecker.Threshold) + dcontext.GetLogger(app).Infof("configuring HTTP health check uri=%s, interval=%d, threshold=%d", httpChecker.URI, interval/time.Second, httpChecker.Threshold) healthRegistry.Register(httpChecker.URI, health.PeriodicThresholdChecker(checker, interval, httpChecker.Threshold)) } else { - ctxu.GetLogger(app).Infof("configuring HTTP health check uri=%s, interval=%d", httpChecker.URI, interval/time.Second) + dcontext.GetLogger(app).Infof("configuring HTTP health check uri=%s, interval=%d", httpChecker.URI, interval/time.Second) healthRegistry.Register(httpChecker.URI, health.PeriodicChecker(checker, interval)) } } @@ -396,10 +396,10 @@ func (app *App) RegisterHealthChecks(healthRegistries ...*health.Registry) { checker := checks.TCPChecker(tcpChecker.Addr, tcpChecker.Timeout) if tcpChecker.Threshold != 0 { - ctxu.GetLogger(app).Infof("configuring TCP health check addr=%s, interval=%d, threshold=%d", tcpChecker.Addr, interval/time.Second, tcpChecker.Threshold) + dcontext.GetLogger(app).Infof("configuring TCP health check addr=%s, interval=%d, threshold=%d", tcpChecker.Addr, interval/time.Second, tcpChecker.Threshold) healthRegistry.Register(tcpChecker.Addr, health.PeriodicThresholdChecker(checker, interval, tcpChecker.Threshold)) } else { - ctxu.GetLogger(app).Infof("configuring TCP health check addr=%s, interval=%d", tcpChecker.Addr, interval/time.Second) + dcontext.GetLogger(app).Infof("configuring TCP health check addr=%s, interval=%d", tcpChecker.Addr, interval/time.Second) healthRegistry.Register(tcpChecker.Addr, health.PeriodicChecker(checker, interval)) } } @@ -425,11 +425,11 @@ func (app *App) configureEvents(configuration *configuration.Configuration) { var sinks []notifications.Sink for _, endpoint := range configuration.Notifications.Endpoints { if endpoint.Disabled { - ctxu.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name) + dcontext.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name) continue } - ctxu.GetLogger(app).Infof("configuring endpoint %v (%v), timeout=%s, headers=%v", endpoint.Name, endpoint.URL, endpoint.Timeout, endpoint.Headers) + dcontext.GetLogger(app).Infof("configuring endpoint %v (%v), timeout=%s, headers=%v", endpoint.Name, endpoint.URL, endpoint.Timeout, endpoint.Headers) endpoint := notifications.NewEndpoint(endpoint.Name, endpoint.URL, notifications.EndpointConfig{ Timeout: endpoint.Timeout, Threshold: endpoint.Threshold, @@ -461,7 +461,7 @@ func (app *App) configureEvents(configuration *configuration.Configuration) { app.events.source = notifications.SourceRecord{ Addr: hostname, - InstanceID: ctxu.GetStringValue(app, "instance.id"), + InstanceID: dcontext.GetStringValue(app, "instance.id"), } } @@ -469,7 +469,7 @@ type redisStartAtKey struct{} func (app *App) configureRedis(configuration *configuration.Configuration) { if configuration.Redis.Addr == "" { - ctxu.GetLogger(app).Infof("redis not configured") + dcontext.GetLogger(app).Infof("redis not configured") return } @@ -479,8 +479,8 @@ func (app *App) configureRedis(configuration *configuration.Configuration) { ctx := context.WithValue(app, redisStartAtKey{}, time.Now()) done := func(err error) { - logger := ctxu.GetLoggerWithField(ctx, "redis.connect.duration", - ctxu.Since(ctx, redisStartAtKey{})) + logger := dcontext.GetLoggerWithField(ctx, "redis.connect.duration", + dcontext.Since(ctx, redisStartAtKey{})) if err != nil { logger.Errorf("redis: error connecting: %v", err) } else { @@ -494,7 +494,7 @@ func (app *App) configureRedis(configuration *configuration.Configuration) { configuration.Redis.ReadTimeout, configuration.Redis.WriteTimeout) if err != nil { - ctxu.GetLogger(app).Errorf("error connecting to redis instance %s: %v", + dcontext.GetLogger(app).Errorf("error connecting to redis instance %s: %v", configuration.Redis.Addr, err) done(err) return nil, err @@ -551,7 +551,7 @@ func (app *App) configureRedis(configuration *configuration.Configuration) { // configureLogHook prepares logging hook parameters. func (app *App) configureLogHook(configuration *configuration.Configuration) { - entry, ok := ctxu.GetLogger(app).(*log.Entry) + entry, ok := dcontext.GetLogger(app).(*logrus.Entry) if !ok { // somehow, we are not using logrus return @@ -589,7 +589,7 @@ func (app *App) configureSecret(configuration *configuration.Configuration) { panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err)) } configuration.HTTP.Secret = string(secretBytes[:]) - ctxu.GetLogger(app).Warn("No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable.") + dcontext.GetLogger(app).Warn("No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable.") } } @@ -598,15 +598,15 @@ func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Prepare the context with our own little decorations. ctx := r.Context() - ctx = ctxu.WithRequest(ctx, r) - ctx, w = ctxu.WithResponseWriter(ctx, w) - ctx = ctxu.WithLogger(ctx, ctxu.GetRequestLogger(ctx)) + ctx = dcontext.WithRequest(ctx, r) + ctx, w = dcontext.WithResponseWriter(ctx, w) + ctx = dcontext.WithLogger(ctx, dcontext.GetRequestLogger(ctx)) r = r.WithContext(ctx) defer func() { status, ok := ctx.Value("http.response.status").(int) if ok && status >= 200 && status <= 399 { - ctxu.GetResponseLogger(r.Context()).Infof("response completed") + dcontext.GetResponseLogger(r.Context()).Infof("response completed") } }() @@ -637,12 +637,12 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler { context := app.context(w, r) if err := app.authorized(w, r, context); err != nil { - ctxu.GetLogger(context).Warnf("error authorizing context: %v", err) + dcontext.GetLogger(context).Warnf("error authorizing context: %v", err) return } // Add username to request logging - context.Context = ctxu.WithLogger(context.Context, ctxu.GetLogger(context.Context, auth.UserNameKey)) + context.Context = dcontext.WithLogger(context.Context, dcontext.GetLogger(context.Context, auth.UserNameKey)) // sync up context on the request. r = r.WithContext(context) @@ -650,20 +650,20 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler { if app.nameRequired(r) { nameRef, err := reference.WithName(getName(context)) if err != nil { - ctxu.GetLogger(context).Errorf("error parsing reference from context: %v", err) + dcontext.GetLogger(context).Errorf("error parsing reference from context: %v", err) context.Errors = append(context.Errors, distribution.ErrRepositoryNameInvalid{ Name: getName(context), Reason: err, }) if err := errcode.ServeJSON(w, context.Errors); err != nil { - ctxu.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) + dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) } return } repository, err := app.registry.Repository(context, nameRef) if err != nil { - ctxu.GetLogger(context).Errorf("error resolving repository: %v", err) + dcontext.GetLogger(context).Errorf("error resolving repository: %v", err) switch err := err.(type) { case distribution.ErrRepositoryUnknown: @@ -675,7 +675,7 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler { } if err := errcode.ServeJSON(w, context.Errors); err != nil { - ctxu.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) + dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) } return } @@ -687,11 +687,11 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler { context.Repository, err = applyRepoMiddleware(app, context.Repository, app.Config.Middleware["repository"]) if err != nil { - ctxu.GetLogger(context).Errorf("error initializing repository middleware: %v", err) + dcontext.GetLogger(context).Errorf("error initializing repository middleware: %v", err) context.Errors = append(context.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) if err := errcode.ServeJSON(w, context.Errors); err != nil { - ctxu.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) + dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) } return } @@ -703,7 +703,7 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler { // for layer upload). if context.Errors.Len() > 0 { if err := errcode.ServeJSON(w, context.Errors); err != nil { - ctxu.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) + dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) } app.logError(context, context.Errors) @@ -723,31 +723,31 @@ type errDetailKey struct{} func (errDetailKey) String() string { return "err.detail" } -func (app *App) logError(context context.Context, errors errcode.Errors) { +func (app *App) logError(ctx context.Context, errors errcode.Errors) { for _, e1 := range errors { - var c ctxu.Context + var c context.Context switch e1.(type) { case errcode.Error: e, _ := e1.(errcode.Error) - c = ctxu.WithValue(context, errCodeKey{}, e.Code) - c = ctxu.WithValue(c, errMessageKey{}, e.Code.Message()) - c = ctxu.WithValue(c, errDetailKey{}, e.Detail) + c = context.WithValue(ctx, errCodeKey{}, e.Code) + c = context.WithValue(c, errMessageKey{}, e.Code.Message()) + c = context.WithValue(c, errDetailKey{}, e.Detail) case errcode.ErrorCode: e, _ := e1.(errcode.ErrorCode) - c = ctxu.WithValue(context, errCodeKey{}, e) - c = ctxu.WithValue(c, errMessageKey{}, e.Message()) + c = context.WithValue(ctx, errCodeKey{}, e) + c = context.WithValue(c, errMessageKey{}, e.Message()) default: // just normal go 'error' - c = ctxu.WithValue(context, errCodeKey{}, errcode.ErrorCodeUnknown) - c = ctxu.WithValue(c, errMessageKey{}, e1.Error()) + c = context.WithValue(ctx, errCodeKey{}, errcode.ErrorCodeUnknown) + c = context.WithValue(c, errMessageKey{}, e1.Error()) } - c = ctxu.WithLogger(c, ctxu.GetLogger(c, + c = dcontext.WithLogger(c, dcontext.GetLogger(c, errCodeKey{}, errMessageKey{}, errDetailKey{})) - ctxu.GetResponseLogger(c).Errorf("response completed with error") + dcontext.GetResponseLogger(c).Errorf("response completed with error") } } @@ -755,8 +755,8 @@ func (app *App) logError(context context.Context, errors errcode.Errors) { // called once per request. func (app *App) context(w http.ResponseWriter, r *http.Request) *Context { ctx := r.Context() - ctx = ctxu.WithVars(ctx, r) - ctx = ctxu.WithLogger(ctx, ctxu.GetLogger(ctx, + ctx = dcontext.WithVars(ctx, r) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, "vars.name", "vars.reference", "vars.digest", @@ -783,7 +783,7 @@ func (app *App) context(w http.ResponseWriter, r *http.Request) *Context { // repository. If it succeeds, the context may access the requested // repository. An error will be returned if access is not available. func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Context) error { - ctxu.GetLogger(context).Debug("authorizing request") + dcontext.GetLogger(context).Debug("authorizing request") repo := getName(context) if app.accessController == nil { @@ -809,7 +809,7 @@ func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Cont // that mistake elsewhere in the code, allowing any operation to // proceed. if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized); err != nil { - ctxu.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) + dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) } return fmt.Errorf("forbidden: no repository name") } @@ -824,20 +824,21 @@ func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Cont err.SetHeaders(w) if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized.WithDetail(accessRecords)); err != nil { - ctxu.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) + dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors) } default: // This condition is a potential security problem either in // the configuration or whatever is backing the access // controller. Just return a bad request with no information // to avoid exposure. The request should not proceed. - ctxu.GetLogger(context).Errorf("error checking authorization: %v", err) + dcontext.GetLogger(context).Errorf("error checking authorization: %v", err) w.WriteHeader(http.StatusBadRequest) } return err } + dcontext.GetLogger(ctx).Info("authorized request") // TODO(stevvooe): This pattern needs to be cleaned up a bit. One context // should be replaced by another, rather than replacing the context on a // mutable object. @@ -851,7 +852,7 @@ func (app *App) eventBridge(ctx *Context, r *http.Request) notifications.Listene actor := notifications.ActorRecord{ Name: getUserName(ctx, r), } - request := notifications.NewRequestRecord(ctxu.GetRequestID(ctx), r) + request := notifications.NewRequestRecord(dcontext.GetRequestID(ctx), r) return notifications.NewBridge(ctx.urlBuilder, app.events.source, actor, request, app.events.sink) } @@ -986,7 +987,7 @@ func badPurgeUploadConfig(reason string) { // startUploadPurger schedules a goroutine which will periodically // check upload directories for old files and delete them -func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageDriver, log ctxu.Logger, config map[interface{}]interface{}) { +func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageDriver, log dcontext.Logger, config map[interface{}]interface{}) { if config["enabled"] == false { return } diff --git a/registry/handlers/blobupload.go b/registry/handlers/blobupload.go index 0b39fff5e08..49ab1aaa355 100644 --- a/registry/handlers/blobupload.go +++ b/registry/handlers/blobupload.go @@ -6,7 +6,7 @@ import ( "net/url" "github.com/docker/distribution" - ctxu "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/v2" @@ -39,7 +39,7 @@ func blobUploadDispatcher(ctx *Context, r *http.Request) http.Handler { state, err := hmacKey(ctx.Config.HTTP.Secret).unpackUploadState(r.FormValue("_state")) if err != nil { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctxu.GetLogger(ctx).Infof("error resolving upload: %v", err) + dcontext.GetLogger(ctx).Infof("error resolving upload: %v", err) buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) }) } @@ -47,14 +47,14 @@ func blobUploadDispatcher(ctx *Context, r *http.Request) http.Handler { if state.Name != ctx.Repository.Named().Name() { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctxu.GetLogger(ctx).Infof("mismatched repository name in upload state: %q != %q", state.Name, buh.Repository.Named().Name()) + dcontext.GetLogger(ctx).Infof("mismatched repository name in upload state: %q != %q", state.Name, buh.Repository.Named().Name()) buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) }) } if state.UUID != buh.UUID { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctxu.GetLogger(ctx).Infof("mismatched uuid in upload state: %q != %q", state.UUID, buh.UUID) + dcontext.GetLogger(ctx).Infof("mismatched uuid in upload state: %q != %q", state.UUID, buh.UUID) buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) }) } @@ -62,7 +62,7 @@ func blobUploadDispatcher(ctx *Context, r *http.Request) http.Handler { blobs := ctx.Repository.Blobs(buh) upload, err := blobs.Resume(buh, buh.UUID) if err != nil { - ctxu.GetLogger(ctx).Errorf("error resolving upload: %v", err) + dcontext.GetLogger(ctx).Errorf("error resolving upload: %v", err) if err == distribution.ErrBlobUploadUnknown { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown.WithDetail(err)) @@ -77,7 +77,7 @@ func blobUploadDispatcher(ctx *Context, r *http.Request) http.Handler { if size := upload.Size(); size != buh.State.Offset { defer upload.Close() - ctxu.GetLogger(ctx).Errorf("upload resumed at wrong offest: %d != %d", size, buh.State.Offset) + dcontext.GetLogger(ctx).Errorf("upload resumed at wrong offest: %d != %d", size, buh.State.Offset) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) upload.Cancel(buh) @@ -179,7 +179,7 @@ func (buh *blobUploadHandler) PatchBlobData(w http.ResponseWriter, r *http.Reque // TODO(dmcgowan): support Content-Range header to seek and write range - if err := copyFullPayload(w, r, buh.Upload, -1, buh, "blob PATCH"); err != nil { + if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PATCH"); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error())) return } @@ -218,7 +218,7 @@ func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *ht return } - if err := copyFullPayload(w, r, buh.Upload, -1, buh, "blob PUT"); err != nil { + if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PUT"); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error())) return } @@ -246,7 +246,7 @@ func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *ht case distribution.ErrBlobInvalidLength, distribution.ErrBlobDigestUnsupported: buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) default: - ctxu.GetLogger(buh).Errorf("unknown error completing upload: %v", err) + dcontext.GetLogger(buh).Errorf("unknown error completing upload: %v", err) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } @@ -255,7 +255,7 @@ func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *ht // Clean up the backend blob data if there was an error. if err := buh.Upload.Cancel(buh); err != nil { // If the cleanup fails, all we can do is observe and report. - ctxu.GetLogger(buh).Errorf("error canceling upload after error: %v", err) + dcontext.GetLogger(buh).Errorf("error canceling upload after error: %v", err) } return @@ -275,7 +275,7 @@ func (buh *blobUploadHandler) CancelBlobUpload(w http.ResponseWriter, r *http.Re w.Header().Set("Docker-Upload-UUID", buh.UUID) if err := buh.Upload.Cancel(buh); err != nil { - ctxu.GetLogger(buh).Errorf("error encountered canceling upload: %v", err) + dcontext.GetLogger(buh).Errorf("error encountered canceling upload: %v", err) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } @@ -297,7 +297,7 @@ func (buh *blobUploadHandler) blobUploadResponse(w http.ResponseWriter, r *http. token, err := hmacKey(buh.Config.HTTP.Secret).packUploadState(buh.State) if err != nil { - ctxu.GetLogger(buh).Infof("error building upload state token: %s", err) + dcontext.GetLogger(buh).Infof("error building upload state token: %s", err) return err } @@ -307,7 +307,7 @@ func (buh *blobUploadHandler) blobUploadResponse(w http.ResponseWriter, r *http. "_state": []string{token}, }) if err != nil { - ctxu.GetLogger(buh).Infof("error building upload url: %s", err) + dcontext.GetLogger(buh).Infof("error building upload url: %s", err) return err } diff --git a/registry/handlers/context.go b/registry/handlers/context.go index 6c1be5b3192..a775be7f5b7 100644 --- a/registry/handlers/context.go +++ b/registry/handlers/context.go @@ -5,7 +5,7 @@ import ( "net/http" "github.com/docker/distribution" - ctxu "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/auth" @@ -44,26 +44,26 @@ func (ctx *Context) Value(key interface{}) interface{} { } func getName(ctx context.Context) (name string) { - return ctxu.GetStringValue(ctx, "vars.name") + return dcontext.GetStringValue(ctx, "vars.name") } func getReference(ctx context.Context) (reference string) { - return ctxu.GetStringValue(ctx, "vars.reference") + return dcontext.GetStringValue(ctx, "vars.reference") } var errDigestNotAvailable = fmt.Errorf("digest not available in context") func getDigest(ctx context.Context) (dgst digest.Digest, err error) { - dgstStr := ctxu.GetStringValue(ctx, "vars.digest") + dgstStr := dcontext.GetStringValue(ctx, "vars.digest") if dgstStr == "" { - ctxu.GetLogger(ctx).Errorf("digest not available") + dcontext.GetLogger(ctx).Errorf("digest not available") return "", errDigestNotAvailable } d, err := digest.Parse(dgstStr) if err != nil { - ctxu.GetLogger(ctx).Errorf("error parsing digest=%q: %v", dgstStr, err) + dcontext.GetLogger(ctx).Errorf("error parsing digest=%q: %v", dgstStr, err) return "", err } @@ -71,13 +71,13 @@ func getDigest(ctx context.Context) (dgst digest.Digest, err error) { } func getUploadUUID(ctx context.Context) (uuid string) { - return ctxu.GetStringValue(ctx, "vars.uuid") + return dcontext.GetStringValue(ctx, "vars.uuid") } // getUserName attempts to resolve a username from the context and request. If // a username cannot be resolved, the empty string is returned. func getUserName(ctx context.Context, r *http.Request) string { - username := ctxu.GetStringValue(ctx, auth.UserNameKey) + username := dcontext.GetStringValue(ctx, auth.UserNameKey) // Fallback to request user with basic auth if username == "" { diff --git a/registry/handlers/helpers.go b/registry/handlers/helpers.go index dc3091a9c23..46ad797eba0 100644 --- a/registry/handlers/helpers.go +++ b/registry/handlers/helpers.go @@ -1,11 +1,12 @@ package handlers import ( + "context" "errors" "io" "net/http" - ctxu "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" ) // closeResources closes all the provided resources after running the target @@ -24,13 +25,13 @@ func closeResources(handler http.Handler, closers ...io.Closer) http.Handler { // upload, it avoids sending a 400 error to keep the logs cleaner. // // The copy will be limited to `limit` bytes, if limit is greater than zero. -func copyFullPayload(responseWriter http.ResponseWriter, r *http.Request, destWriter io.Writer, limit int64, context ctxu.Context, action string) error { +func copyFullPayload(ctx context.Context, responseWriter http.ResponseWriter, r *http.Request, destWriter io.Writer, limit int64, action string) error { // Get a channel that tells us if the client disconnects var clientClosed <-chan bool if notifier, ok := responseWriter.(http.CloseNotifier); ok { clientClosed = notifier.CloseNotify() } else { - ctxu.GetLogger(context).Warnf("the ResponseWriter does not implement CloseNotifier (type: %T)", responseWriter) + dcontext.GetLogger(ctx).Warnf("the ResponseWriter does not implement CloseNotifier (type: %T)", responseWriter) } var body = r.Body @@ -52,7 +53,7 @@ func copyFullPayload(responseWriter http.ResponseWriter, r *http.Request, destWr // instead of showing 0 for the HTTP status. responseWriter.WriteHeader(499) - ctxu.GetLoggerWithFields(context, map[interface{}]interface{}{ + dcontext.GetLoggerWithFields(ctx, map[interface{}]interface{}{ "error": err, "copied": copied, "contentLength": r.ContentLength, @@ -63,7 +64,7 @@ func copyFullPayload(responseWriter http.ResponseWriter, r *http.Request, destWr } if err != nil { - ctxu.GetLogger(context).Errorf("unknown error reading request payload: %v", err) + dcontext.GetLogger(ctx).Errorf("unknown error reading request payload: %v", err) return err } diff --git a/registry/handlers/manifests.go b/registry/handlers/manifests.go index bbbc10fa0a4..4e1d98681bf 100644 --- a/registry/handlers/manifests.go +++ b/registry/handlers/manifests.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/docker/distribution" - ctxu "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema2" @@ -66,7 +66,7 @@ type manifestHandler struct { // GetManifest fetches the image manifest from the storage backend, if it exists. func (imh *manifestHandler) GetManifest(w http.ResponseWriter, r *http.Request) { - ctxu.GetLogger(imh).Debug("GetImageManifest") + dcontext.GetLogger(imh).Debug("GetImageManifest") manifests, err := imh.Repository.Manifests(imh) if err != nil { imh.Errors = append(imh.Errors, err) @@ -143,7 +143,7 @@ func (imh *manifestHandler) GetManifest(w http.ResponseWriter, r *http.Request) // matching the digest. if imh.Tag != "" && isSchema2 && !supportsSchema2 { // Rewrite manifest in schema1 format - ctxu.GetLogger(imh).Infof("rewriting manifest %s in schema1 format to support old client", imh.Digest.String()) + dcontext.GetLogger(imh).Infof("rewriting manifest %s in schema1 format to support old client", imh.Digest.String()) manifest, err = imh.convertSchema2Manifest(schema2Manifest) if err != nil { @@ -151,7 +151,7 @@ func (imh *manifestHandler) GetManifest(w http.ResponseWriter, r *http.Request) } } else if imh.Tag != "" && isManifestList && !supportsManifestList { // Rewrite manifest in schema1 format - ctxu.GetLogger(imh).Infof("rewriting manifest list %s in schema1 format to support old client", imh.Digest.String()) + dcontext.GetLogger(imh).Infof("rewriting manifest list %s in schema1 format to support old client", imh.Digest.String()) // Find the image manifest corresponding to the default // platform @@ -252,7 +252,7 @@ func etagMatch(r *http.Request, etag string) bool { // PutManifest validates and stores a manifest in the registry. func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request) { - ctxu.GetLogger(imh).Debug("PutImageManifest") + dcontext.GetLogger(imh).Debug("PutImageManifest") manifests, err := imh.Repository.Manifests(imh) if err != nil { imh.Errors = append(imh.Errors, err) @@ -260,7 +260,7 @@ func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request) } var jsonBuf bytes.Buffer - if err := copyFullPayload(w, r, &jsonBuf, maxManifestBodySize, imh, "image manifest PUT"); err != nil { + if err := copyFullPayload(imh, w, r, &jsonBuf, maxManifestBodySize, "image manifest PUT"); err != nil { // copyFullPayload reports the error if necessary imh.Errors = append(imh.Errors, v2.ErrorCodeManifestInvalid.WithDetail(err.Error())) return @@ -275,7 +275,7 @@ func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request) if imh.Digest != "" { if desc.Digest != imh.Digest { - ctxu.GetLogger(imh).Errorf("payload digest does match: %q != %q", desc.Digest, imh.Digest) + dcontext.GetLogger(imh).Errorf("payload digest does match: %q != %q", desc.Digest, imh.Digest) imh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid) return } @@ -358,7 +358,7 @@ func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request) // NOTE(stevvooe): Given the behavior above, this absurdly unlikely to // happen. We'll log the error here but proceed as if it worked. Worst // case, we set an empty location header. - ctxu.GetLogger(imh).Errorf("error building manifest url from digest: %v", err) + dcontext.GetLogger(imh).Errorf("error building manifest url from digest: %v", err) } w.Header().Set("Location", location) @@ -435,7 +435,7 @@ func (imh *manifestHandler) applyResourcePolicy(manifest distribution.Manifest) // DeleteManifest removes the manifest with the given digest from the registry. func (imh *manifestHandler) DeleteManifest(w http.ResponseWriter, r *http.Request) { - ctxu.GetLogger(imh).Debug("DeleteImageManifest") + dcontext.GetLogger(imh).Debug("DeleteImageManifest") manifests, err := imh.Repository.Manifests(imh) if err != nil { diff --git a/registry/middleware/registry/middleware.go b/registry/middleware/registry/middleware.go index 3e6e5cc71a9..49defd8252a 100644 --- a/registry/middleware/registry/middleware.go +++ b/registry/middleware/registry/middleware.go @@ -1,10 +1,10 @@ package middleware import ( + "context" "fmt" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage" ) diff --git a/registry/middleware/repository/middleware.go b/registry/middleware/repository/middleware.go index 27b42aecfcb..f1554b70997 100644 --- a/registry/middleware/repository/middleware.go +++ b/registry/middleware/repository/middleware.go @@ -1,10 +1,10 @@ package middleware import ( + "context" "fmt" "github.com/docker/distribution" - "github.com/docker/distribution/context" ) // InitFunc is the type of a RepositoryMiddleware factory function and is diff --git a/registry/proxy/proxyblobstore.go b/registry/proxy/proxyblobstore.go index c3f1b92f1f2..0f2c7e39b4d 100644 --- a/registry/proxy/proxyblobstore.go +++ b/registry/proxy/proxyblobstore.go @@ -1,6 +1,7 @@ package proxy import ( + "context" "io" "net/http" "strconv" @@ -8,7 +9,7 @@ import ( "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/proxy/scheduler" "github.com/opencontainers/go-digest" @@ -116,7 +117,7 @@ func (pbs *proxyBlobStore) storeLocal(ctx context.Context, dgst digest.Digest) e func (pbs *proxyBlobStore) ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error { served, err := pbs.serveLocal(ctx, w, r, dgst) if err != nil { - context.GetLogger(ctx).Errorf("Error serving blob from local storage: %s", err.Error()) + dcontext.GetLogger(ctx).Errorf("Error serving blob from local storage: %s", err.Error()) return err } @@ -140,12 +141,12 @@ func (pbs *proxyBlobStore) ServeBlob(ctx context.Context, w http.ResponseWriter, go func(dgst digest.Digest) { if err := pbs.storeLocal(ctx, dgst); err != nil { - context.GetLogger(ctx).Errorf("Error committing to storage: %s", err.Error()) + dcontext.GetLogger(ctx).Errorf("Error committing to storage: %s", err.Error()) } blobRef, err := reference.WithDigest(pbs.repositoryName, dgst) if err != nil { - context.GetLogger(ctx).Errorf("Error creating reference: %s", err) + dcontext.GetLogger(ctx).Errorf("Error creating reference: %s", err) return } diff --git a/registry/proxy/proxyblobstore_test.go b/registry/proxy/proxyblobstore_test.go index 0bba01a6fef..9bee48d8f8e 100644 --- a/registry/proxy/proxyblobstore_test.go +++ b/registry/proxy/proxyblobstore_test.go @@ -1,6 +1,7 @@ package proxy import ( + "context" "io/ioutil" "math/rand" "net/http" @@ -10,7 +11,6 @@ import ( "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/proxy/scheduler" "github.com/docker/distribution/registry/storage" diff --git a/registry/proxy/proxymanifeststore.go b/registry/proxy/proxymanifeststore.go index e0a9f7d3f40..5c7264d9659 100644 --- a/registry/proxy/proxymanifeststore.go +++ b/registry/proxy/proxymanifeststore.go @@ -1,10 +1,11 @@ package proxy import ( + "context" "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/proxy/scheduler" "github.com/opencontainers/go-digest" @@ -72,7 +73,7 @@ func (pms proxyManifestStore) Get(ctx context.Context, dgst digest.Digest, optio // Schedule the manifest blob for removal repoBlob, err := reference.WithDigest(pms.repositoryName, dgst) if err != nil { - context.GetLogger(ctx).Errorf("Error creating reference: %s", err) + dcontext.GetLogger(ctx).Errorf("Error creating reference: %s", err) return nil, err } diff --git a/registry/proxy/proxymanifeststore_test.go b/registry/proxy/proxymanifeststore_test.go index ca0845b90da..5f3bd34e6c5 100644 --- a/registry/proxy/proxymanifeststore_test.go +++ b/registry/proxy/proxymanifeststore_test.go @@ -1,12 +1,12 @@ package proxy import ( + "context" "io" "sync" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/reference" diff --git a/registry/proxy/proxyregistry.go b/registry/proxy/proxyregistry.go index d64dcbb9548..aec220e8bbd 100644 --- a/registry/proxy/proxyregistry.go +++ b/registry/proxy/proxyregistry.go @@ -1,6 +1,7 @@ package proxy import ( + "context" "fmt" "net/http" "net/url" @@ -8,7 +9,7 @@ import ( "github.com/docker/distribution" "github.com/docker/distribution/configuration" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/client" "github.com/docker/distribution/registry/client/auth" @@ -218,7 +219,7 @@ func (r *remoteAuthChallenger) tryEstablishChallenges(ctx context.Context) error return err } - context.GetLogger(ctx).Infof("Challenge established with upstream : %s %s", remoteURL, r.cm) + dcontext.GetLogger(ctx).Infof("Challenge established with upstream : %s %s", remoteURL, r.cm) return nil } diff --git a/registry/proxy/proxytagservice.go b/registry/proxy/proxytagservice.go index a8273030df6..6a9256395ff 100644 --- a/registry/proxy/proxytagservice.go +++ b/registry/proxy/proxytagservice.go @@ -1,8 +1,9 @@ package proxy import ( + "context" + "github.com/docker/distribution" - "github.com/docker/distribution/context" ) // proxyTagService supports local and remote lookup of tags. diff --git a/registry/proxy/proxytagservice_test.go b/registry/proxy/proxytagservice_test.go index ce0fe78ba96..1314121e633 100644 --- a/registry/proxy/proxytagservice_test.go +++ b/registry/proxy/proxytagservice_test.go @@ -1,13 +1,13 @@ package proxy import ( + "context" "reflect" "sort" "sync" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" ) type mockTagStore struct { diff --git a/registry/proxy/scheduler/scheduler.go b/registry/proxy/scheduler/scheduler.go index bde9465761d..f8340184210 100644 --- a/registry/proxy/scheduler/scheduler.go +++ b/registry/proxy/scheduler/scheduler.go @@ -1,12 +1,13 @@ package scheduler import ( + "context" "encoding/json" "fmt" "sync" "time" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/driver" ) @@ -120,7 +121,7 @@ func (ttles *TTLExpirationScheduler) Start() error { return fmt.Errorf("Scheduler already started") } - context.GetLogger(ttles.ctx).Infof("Starting cached object TTL expiration scheduler...") + dcontext.GetLogger(ttles.ctx).Infof("Starting cached object TTL expiration scheduler...") ttles.stopped = false // Start timer for each deserialized entry @@ -142,7 +143,7 @@ func (ttles *TTLExpirationScheduler) Start() error { err := ttles.writeState() if err != nil { - context.GetLogger(ttles.ctx).Errorf("Error writing scheduler state: %s", err) + dcontext.GetLogger(ttles.ctx).Errorf("Error writing scheduler state: %s", err) } else { ttles.indexDirty = false } @@ -163,7 +164,7 @@ func (ttles *TTLExpirationScheduler) add(r reference.Reference, ttl time.Duratio Expiry: time.Now().Add(ttl), EntryType: eType, } - context.GetLogger(ttles.ctx).Infof("Adding new scheduler entry for %s with ttl=%s", entry.Key, entry.Expiry.Sub(time.Now())) + dcontext.GetLogger(ttles.ctx).Infof("Adding new scheduler entry for %s with ttl=%s", entry.Key, entry.Expiry.Sub(time.Now())) if oldEntry, present := ttles.entries[entry.Key]; present && oldEntry.timer != nil { oldEntry.timer.Stop() } @@ -193,10 +194,10 @@ func (ttles *TTLExpirationScheduler) startTimer(entry *schedulerEntry, ttl time. ref, err := reference.Parse(entry.Key) if err == nil { if err := f(ref); err != nil { - context.GetLogger(ttles.ctx).Errorf("Scheduler error returned from OnExpire(%s): %s", entry.Key, err) + dcontext.GetLogger(ttles.ctx).Errorf("Scheduler error returned from OnExpire(%s): %s", entry.Key, err) } } else { - context.GetLogger(ttles.ctx).Errorf("Error unpacking reference: %s", err) + dcontext.GetLogger(ttles.ctx).Errorf("Error unpacking reference: %s", err) } delete(ttles.entries, entry.Key) @@ -210,7 +211,7 @@ func (ttles *TTLExpirationScheduler) Stop() { defer ttles.Unlock() if err := ttles.writeState(); err != nil { - context.GetLogger(ttles.ctx).Errorf("Error writing scheduler state: %s", err) + dcontext.GetLogger(ttles.ctx).Errorf("Error writing scheduler state: %s", err) } for _, entry := range ttles.entries { diff --git a/registry/registry.go b/registry/registry.go index fbb4dd87920..2e8877842e1 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -1,6 +1,7 @@ package registry import ( + "context" "crypto/tls" "crypto/x509" "fmt" @@ -14,7 +15,7 @@ import ( logstash "github.com/bshuster-repo/logrus-logstash-hook" "github.com/bugsnag/bugsnag-go" "github.com/docker/distribution/configuration" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/health" "github.com/docker/distribution/registry/handlers" "github.com/docker/distribution/registry/listener" @@ -34,7 +35,7 @@ var ServeCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { // setup context - ctx := context.WithVersion(context.Background(), version.Version) + ctx := dcontext.WithVersion(dcontext.Background(), version.Version) config, err := resolveConfiguration(args) if err != nil { @@ -81,7 +82,7 @@ func NewRegistry(ctx context.Context, config *configuration.Configuration) (*Reg // inject a logger into the uuid library. warns us if there is a problem // with uuid generation under low entropy. - uuid.Loggerf = context.GetLogger(ctx).Warnf + uuid.Loggerf = dcontext.GetLogger(ctx).Warnf app := handlers.NewApp(ctx, config) // TODO(aaronl): The global scope of the health checks means NewRegistry @@ -170,7 +171,7 @@ func (registry *Registry) ListenAndServe() error { } for _, subj := range pool.Subjects() { - context.GetLogger(registry.app).Debugf("CA Subject: %s", string(subj)) + dcontext.GetLogger(registry.app).Debugf("CA Subject: %s", string(subj)) } tlsConf.ClientAuth = tls.RequireAndVerifyClientCert @@ -178,9 +179,9 @@ func (registry *Registry) ListenAndServe() error { } ln = tls.NewListener(ln, tlsConf) - context.GetLogger(registry.app).Infof("listening on %v, tls", ln.Addr()) + dcontext.GetLogger(registry.app).Infof("listening on %v, tls", ln.Addr()) } else { - context.GetLogger(registry.app).Infof("listening on %v", ln.Addr()) + dcontext.GetLogger(registry.app).Infof("listening on %v", ln.Addr()) } return registry.server.Serve(ln) @@ -228,7 +229,7 @@ func configureLogging(ctx context.Context, config *configuration.Configuration) if config.Log.Level == "" && config.Log.Formatter == "" { // If no config for logging is set, fallback to deprecated "Loglevel". log.SetLevel(logLevel(config.Loglevel)) - ctx = context.WithLogger(ctx, context.GetLogger(ctx)) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx)) return ctx, nil } @@ -270,8 +271,8 @@ func configureLogging(ctx context.Context, config *configuration.Configuration) fields = append(fields, k) } - ctx = context.WithValues(ctx, config.Log.Fields) - ctx = context.WithLogger(ctx, context.GetLogger(ctx, fields...)) + ctx = dcontext.WithValues(ctx, config.Log.Fields) + ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, fields...)) } return ctx, nil diff --git a/registry/root.go b/registry/root.go index 5d3005c26bd..538139f1850 100644 --- a/registry/root.go +++ b/registry/root.go @@ -4,7 +4,7 @@ import ( "fmt" "os" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage" "github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/version" @@ -56,7 +56,7 @@ var GCCmd = &cobra.Command{ os.Exit(1) } - ctx := context.Background() + ctx := dcontext.Background() ctx, err = configureLogging(ctx, config) if err != nil { fmt.Fprintf(os.Stderr, "unable to configure logging with config: %s", err) diff --git a/registry/storage/blob_test.go b/registry/storage/blob_test.go index a263dd6cd13..fc027f4e10b 100644 --- a/registry/storage/blob_test.go +++ b/registry/storage/blob_test.go @@ -2,6 +2,7 @@ package storage import ( "bytes" + "context" "crypto/sha256" "fmt" "io" @@ -12,7 +13,6 @@ import ( "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/cache/memory" "github.com/docker/distribution/registry/storage/driver/testdriver" diff --git a/registry/storage/blobserver.go b/registry/storage/blobserver.go index 739bf3cb396..57d4f907bbf 100644 --- a/registry/storage/blobserver.go +++ b/registry/storage/blobserver.go @@ -1,12 +1,12 @@ package storage import ( + "context" "fmt" "net/http" "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/driver" "github.com/opencontainers/go-digest" ) diff --git a/registry/storage/blobstore.go b/registry/storage/blobstore.go index 4a16488b81a..bfa41937d6c 100644 --- a/registry/storage/blobstore.go +++ b/registry/storage/blobstore.go @@ -1,10 +1,11 @@ package storage import ( + "context" "path" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/driver" "github.com/opencontainers/go-digest" ) @@ -64,7 +65,7 @@ func (bs *blobStore) Put(ctx context.Context, mediaType string, p []byte) (distr // content already present return desc, nil } else if err != distribution.ErrBlobUnknown { - context.GetLogger(ctx).Errorf("blobStore: error stating content (%v): %v", dgst, err) + dcontext.GetLogger(ctx).Errorf("blobStore: error stating content (%v): %v", dgst, err) // real error, return it return distribution.Descriptor{}, err } @@ -195,7 +196,7 @@ func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distributi // NOTE(stevvooe): This represents a corruption situation. Somehow, we // calculated a blob path and then detected a directory. We log the // error and then error on the side of not knowing about the blob. - context.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path) + dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path) return distribution.Descriptor{}, distribution.ErrBlobUnknown } diff --git a/registry/storage/blobwriter.go b/registry/storage/blobwriter.go index 392b166c620..d56f287492e 100644 --- a/registry/storage/blobwriter.go +++ b/registry/storage/blobwriter.go @@ -1,6 +1,7 @@ package storage import ( + "context" "errors" "fmt" "io" @@ -8,7 +9,7 @@ import ( "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" @@ -56,7 +57,7 @@ func (bw *blobWriter) StartedAt() time.Time { // Commit marks the upload as completed, returning a valid descriptor. The // final size and digest are checked against the first descriptor provided. func (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) { - context.GetLogger(ctx).Debug("(*blobWriter).Commit") + dcontext.GetLogger(ctx).Debug("(*blobWriter).Commit") if err := bw.fileWriter.Commit(); err != nil { return distribution.Descriptor{}, err @@ -94,13 +95,13 @@ func (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) // Cancel the blob upload process, releasing any resources associated with // the writer and canceling the operation. func (bw *blobWriter) Cancel(ctx context.Context) error { - context.GetLogger(ctx).Debug("(*blobWriter).Cancel") + dcontext.GetLogger(ctx).Debug("(*blobWriter).Cancel") if err := bw.fileWriter.Cancel(); err != nil { return err } if err := bw.Close(); err != nil { - context.GetLogger(ctx).Errorf("error closing blobwriter: %s", err) + dcontext.GetLogger(ctx).Errorf("error closing blobwriter: %s", err) } if err := bw.removeResources(ctx); err != nil { @@ -261,7 +262,7 @@ func (bw *blobWriter) validateBlob(ctx context.Context, desc distribution.Descri } if !verified { - context.GetLoggerWithFields(ctx, + dcontext.GetLoggerWithFields(ctx, map[interface{}]interface{}{ "canonical": canonical, "provided": desc.Digest, @@ -365,7 +366,7 @@ func (bw *blobWriter) removeResources(ctx context.Context) error { // This should be uncommon enough such that returning an error // should be okay. At this point, the upload should be mostly // complete, but perhaps the backend became unaccessible. - context.GetLogger(ctx).Errorf("unable to delete layer upload resources %q: %v", dirPath, err) + dcontext.GetLogger(ctx).Errorf("unable to delete layer upload resources %q: %v", dirPath, err) return err } } @@ -383,7 +384,7 @@ func (bw *blobWriter) Reader() (io.ReadCloser, error) { } switch err.(type) { case storagedriver.PathNotFoundError: - context.GetLogger(bw.ctx).Debugf("Nothing found on try %d, sleeping...", try) + dcontext.GetLogger(bw.ctx).Debugf("Nothing found on try %d, sleeping...", try) time.Sleep(1 * time.Second) try++ default: diff --git a/registry/storage/blobwriter_resumable.go b/registry/storage/blobwriter_resumable.go index cc1a833d048..8c9091692e7 100644 --- a/registry/storage/blobwriter_resumable.go +++ b/registry/storage/blobwriter_resumable.go @@ -3,11 +3,11 @@ package storage import ( + "context" "fmt" "path" "strconv" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/sirupsen/logrus" "github.com/stevvooe/resumable" diff --git a/registry/storage/cache/cachecheck/suite.go b/registry/storage/cache/cachecheck/suite.go index 0bbd529570f..b23765e8249 100644 --- a/registry/storage/cache/cachecheck/suite.go +++ b/registry/storage/cache/cachecheck/suite.go @@ -1,11 +1,11 @@ package cachecheck import ( + "context" "reflect" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/cache" "github.com/opencontainers/go-digest" ) diff --git a/registry/storage/cache/cachedblobdescriptorstore.go b/registry/storage/cache/cachedblobdescriptorstore.go index f647616bca4..668eebdad05 100644 --- a/registry/storage/cache/cachedblobdescriptorstore.go +++ b/registry/storage/cache/cachedblobdescriptorstore.go @@ -1,10 +1,11 @@ package cache import ( - "github.com/docker/distribution/context" - "github.com/opencontainers/go-digest" + "context" "github.com/docker/distribution" + dcontext "github.com/docker/distribution/context" + "github.com/opencontainers/go-digest" ) // Metrics is used to hold metric counters @@ -53,7 +54,7 @@ func (cbds *cachedBlobStatter) Stat(ctx context.Context, dgst digest.Digest) (di desc, err := cbds.cache.Stat(ctx, dgst) if err != nil { if err != distribution.ErrBlobUnknown { - context.GetLogger(ctx).Errorf("error retrieving descriptor from cache: %v", err) + dcontext.GetLogger(ctx).Errorf("error retrieving descriptor from cache: %v", err) } goto fallback @@ -73,7 +74,7 @@ fallback: } if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { - context.GetLogger(ctx).Errorf("error adding descriptor %v to cache: %v", desc.Digest, err) + dcontext.GetLogger(ctx).Errorf("error adding descriptor %v to cache: %v", desc.Digest, err) } return desc, err @@ -95,7 +96,7 @@ func (cbds *cachedBlobStatter) Clear(ctx context.Context, dgst digest.Digest) er func (cbds *cachedBlobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error { if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { - context.GetLogger(ctx).Errorf("error adding descriptor %v to cache: %v", desc.Digest, err) + dcontext.GetLogger(ctx).Errorf("error adding descriptor %v to cache: %v", desc.Digest, err) } return nil } diff --git a/registry/storage/cache/memory/memory.go b/registry/storage/cache/memory/memory.go index b2fcaf4e8b1..42d94d9bde6 100644 --- a/registry/storage/cache/memory/memory.go +++ b/registry/storage/cache/memory/memory.go @@ -1,10 +1,10 @@ package memory import ( + "context" "sync" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/cache" "github.com/opencontainers/go-digest" diff --git a/registry/storage/cache/redis/redis.go b/registry/storage/cache/redis/redis.go index 98f0f759bc3..36c6ac602a9 100644 --- a/registry/storage/cache/redis/redis.go +++ b/registry/storage/cache/redis/redis.go @@ -1,10 +1,10 @@ package redis import ( + "context" "fmt" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/cache" "github.com/garyburd/redigo/redis" diff --git a/registry/storage/catalog.go b/registry/storage/catalog.go index 0b59a39ac2b..f3c6fe9e1ed 100644 --- a/registry/storage/catalog.go +++ b/registry/storage/catalog.go @@ -1,12 +1,12 @@ package storage import ( + "context" "errors" "io" "path" "strings" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/driver" ) diff --git a/registry/storage/catalog_test.go b/registry/storage/catalog_test.go index 90dc12cec41..696e024e063 100644 --- a/registry/storage/catalog_test.go +++ b/registry/storage/catalog_test.go @@ -1,13 +1,13 @@ package storage import ( + "context" "fmt" "io" "math/rand" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/cache/memory" "github.com/docker/distribution/registry/storage/driver" diff --git a/registry/storage/driver/azure/azure.go b/registry/storage/driver/azure/azure.go index 45d2b1e5c38..a37a22bdcf8 100644 --- a/registry/storage/driver/azure/azure.go +++ b/registry/storage/driver/azure/azure.go @@ -5,6 +5,7 @@ package azure import ( "bufio" "bytes" + "context" "fmt" "io" "io/ioutil" @@ -12,7 +13,6 @@ import ( "strings" "time" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/factory" diff --git a/registry/storage/driver/base/base.go b/registry/storage/driver/base/base.go index e14f7edb158..1778c6c535d 100644 --- a/registry/storage/driver/base/base.go +++ b/registry/storage/driver/base/base.go @@ -38,9 +38,10 @@ package base import ( + "context" "io" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" ) @@ -79,7 +80,7 @@ func (base *Base) setDriverName(e error) error { // GetContent wraps GetContent of underlying storage driver. func (base *Base) GetContent(ctx context.Context, path string) ([]byte, error) { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.GetContent(%q)", base.Name(), path) if !storagedriver.PathRegexp.MatchString(path) { @@ -92,7 +93,7 @@ func (base *Base) GetContent(ctx context.Context, path string) ([]byte, error) { // PutContent wraps PutContent of underlying storage driver. func (base *Base) PutContent(ctx context.Context, path string, content []byte) error { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.PutContent(%q)", base.Name(), path) if !storagedriver.PathRegexp.MatchString(path) { @@ -104,7 +105,7 @@ func (base *Base) PutContent(ctx context.Context, path string, content []byte) e // Reader wraps Reader of underlying storage driver. func (base *Base) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.Reader(%q, %d)", base.Name(), path, offset) if offset < 0 { @@ -121,7 +122,7 @@ func (base *Base) Reader(ctx context.Context, path string, offset int64) (io.Rea // Writer wraps Writer of underlying storage driver. func (base *Base) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.Writer(%q, %v)", base.Name(), path, append) if !storagedriver.PathRegexp.MatchString(path) { @@ -134,7 +135,7 @@ func (base *Base) Writer(ctx context.Context, path string, append bool) (storage // Stat wraps Stat of underlying storage driver. func (base *Base) Stat(ctx context.Context, path string) (storagedriver.FileInfo, error) { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.Stat(%q)", base.Name(), path) if !storagedriver.PathRegexp.MatchString(path) && path != "/" { @@ -147,7 +148,7 @@ func (base *Base) Stat(ctx context.Context, path string) (storagedriver.FileInfo // List wraps List of underlying storage driver. func (base *Base) List(ctx context.Context, path string) ([]string, error) { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.List(%q)", base.Name(), path) if !storagedriver.PathRegexp.MatchString(path) && path != "/" { @@ -160,7 +161,7 @@ func (base *Base) List(ctx context.Context, path string) ([]string, error) { // Move wraps Move of underlying storage driver. func (base *Base) Move(ctx context.Context, sourcePath string, destPath string) error { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.Move(%q, %q", base.Name(), sourcePath, destPath) if !storagedriver.PathRegexp.MatchString(sourcePath) { @@ -174,7 +175,7 @@ func (base *Base) Move(ctx context.Context, sourcePath string, destPath string) // Delete wraps Delete of underlying storage driver. func (base *Base) Delete(ctx context.Context, path string) error { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.Delete(%q)", base.Name(), path) if !storagedriver.PathRegexp.MatchString(path) { @@ -186,7 +187,7 @@ func (base *Base) Delete(ctx context.Context, path string) error { // URLFor wraps URLFor of underlying storage driver. func (base *Base) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) { - ctx, done := context.WithTrace(ctx) + ctx, done := dcontext.WithTrace(ctx) defer done("%s.URLFor(%q)", base.Name(), path) if !storagedriver.PathRegexp.MatchString(path) { diff --git a/registry/storage/driver/base/regulator.go b/registry/storage/driver/base/regulator.go index 1e929f8368e..97a30ae4dc3 100644 --- a/registry/storage/driver/base/regulator.go +++ b/registry/storage/driver/base/regulator.go @@ -1,10 +1,10 @@ package base import ( + "context" "io" "sync" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" ) diff --git a/registry/storage/driver/filesystem/driver.go b/registry/storage/driver/filesystem/driver.go index 649e2bc2348..71c75fba4a8 100644 --- a/registry/storage/driver/filesystem/driver.go +++ b/registry/storage/driver/filesystem/driver.go @@ -3,6 +3,7 @@ package filesystem import ( "bufio" "bytes" + "context" "fmt" "io" "io/ioutil" @@ -12,7 +13,6 @@ import ( "strconv" "time" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/factory" diff --git a/registry/storage/driver/gcs/gcs.go b/registry/storage/driver/gcs/gcs.go index 8a0be4e9769..dadae79c26a 100644 --- a/registry/storage/driver/gcs/gcs.go +++ b/registry/storage/driver/gcs/gcs.go @@ -16,6 +16,7 @@ package gcs import ( "bytes" + "context" "fmt" "io" "io/ioutil" @@ -29,20 +30,16 @@ import ( "strings" "time" - "golang.org/x/net/context" + storagedriver "github.com/docker/distribution/registry/storage/driver" + "github.com/docker/distribution/registry/storage/driver/base" + "github.com/docker/distribution/registry/storage/driver/factory" + "github.com/sirupsen/logrus" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "golang.org/x/oauth2/jwt" "google.golang.org/api/googleapi" "google.golang.org/cloud" "google.golang.org/cloud/storage" - - "github.com/sirupsen/logrus" - - ctx "github.com/docker/distribution/context" - storagedriver "github.com/docker/distribution/registry/storage/driver" - "github.com/docker/distribution/registry/storage/driver/base" - "github.com/docker/distribution/registry/storage/driver/factory" ) const ( @@ -194,7 +191,7 @@ func (d *driver) Name() string { // GetContent retrieves the content stored at "path" as a []byte. // This should primarily be used for small objects. -func (d *driver) GetContent(context ctx.Context, path string) ([]byte, error) { +func (d *driver) GetContent(context context.Context, path string) ([]byte, error) { gcsContext := d.context(context) name := d.pathToKey(path) var rc io.ReadCloser @@ -220,7 +217,7 @@ func (d *driver) GetContent(context ctx.Context, path string) ([]byte, error) { // PutContent stores the []byte content at a location designated by "path". // This should primarily be used for small objects. -func (d *driver) PutContent(context ctx.Context, path string, contents []byte) error { +func (d *driver) PutContent(context context.Context, path string, contents []byte) error { return retry(func() error { wc := storage.NewWriter(d.context(context), d.bucket, d.pathToKey(path)) wc.ContentType = "application/octet-stream" @@ -231,7 +228,7 @@ func (d *driver) PutContent(context ctx.Context, path string, contents []byte) e // Reader retrieves an io.ReadCloser for the content stored at "path" // with a given byte offset. // May be used to resume reading a stream by providing a nonzero offset. -func (d *driver) Reader(context ctx.Context, path string, offset int64) (io.ReadCloser, error) { +func (d *driver) Reader(context context.Context, path string, offset int64) (io.ReadCloser, error) { res, err := getObject(d.client, d.bucket, d.pathToKey(path), offset) if err != nil { if res != nil { @@ -290,7 +287,7 @@ func getObject(client *http.Client, bucket string, name string, offset int64) (* // Writer returns a FileWriter which will store the content written to it // at the location designated by "path" after the call to Commit. -func (d *driver) Writer(context ctx.Context, path string, append bool) (storagedriver.FileWriter, error) { +func (d *driver) Writer(context context.Context, path string, append bool) (storagedriver.FileWriter, error) { writer := &writer{ client: d.client, bucket: d.bucket, @@ -542,7 +539,7 @@ func retry(req request) error { // Stat retrieves the FileInfo for the given path, including the current // size in bytes and the creation time. -func (d *driver) Stat(context ctx.Context, path string) (storagedriver.FileInfo, error) { +func (d *driver) Stat(context context.Context, path string) (storagedriver.FileInfo, error) { var fi storagedriver.FileInfoFields //try to get as file gcsContext := d.context(context) @@ -588,7 +585,7 @@ func (d *driver) Stat(context ctx.Context, path string) (storagedriver.FileInfo, // List returns a list of the objects that are direct descendants of the //given path. -func (d *driver) List(context ctx.Context, path string) ([]string, error) { +func (d *driver) List(context context.Context, path string) ([]string, error) { var query *storage.Query query = &storage.Query{} query.Delimiter = "/" @@ -626,7 +623,7 @@ func (d *driver) List(context ctx.Context, path string) ([]string, error) { // Move moves an object stored at sourcePath to destPath, removing the // original object. -func (d *driver) Move(context ctx.Context, sourcePath string, destPath string) error { +func (d *driver) Move(context context.Context, sourcePath string, destPath string) error { gcsContext := d.context(context) _, err := storageCopyObject(gcsContext, d.bucket, d.pathToKey(sourcePath), d.bucket, d.pathToKey(destPath), nil) if err != nil { @@ -674,7 +671,7 @@ func (d *driver) listAll(context context.Context, prefix string) ([]string, erro } // Delete recursively deletes all objects stored at "path" and its subpaths. -func (d *driver) Delete(context ctx.Context, path string) error { +func (d *driver) Delete(context context.Context, path string) error { prefix := d.pathToDirKey(path) gcsContext := d.context(context) keys, err := d.listAll(gcsContext, prefix) @@ -749,7 +746,7 @@ func storageCopyObject(context context.Context, srcBucket, srcName string, destB // URLFor returns a URL which may be used to retrieve the content stored at // the given path, possibly using the given options. // Returns ErrUnsupportedMethod if this driver has no privateKey -func (d *driver) URLFor(context ctx.Context, path string, options map[string]interface{}) (string, error) { +func (d *driver) URLFor(context context.Context, path string, options map[string]interface{}) (string, error) { if d.privateKey == nil { return "", storagedriver.ErrUnsupportedMethod{} } @@ -856,7 +853,7 @@ func putChunk(client *http.Client, sessionURI string, chunk []byte, from int64, return bytesPut, err } -func (d *driver) context(context ctx.Context) context.Context { +func (d *driver) context(context context.Context) context.Context { return cloud.WithContext(context, dummyProjectID, d.client) } diff --git a/registry/storage/driver/gcs/gcs_test.go b/registry/storage/driver/gcs/gcs_test.go index f2808d5fc2b..e58216be04e 100644 --- a/registry/storage/driver/gcs/gcs_test.go +++ b/registry/storage/driver/gcs/gcs_test.go @@ -3,12 +3,12 @@ package gcs import ( + "fmt" "io/ioutil" "os" "testing" - "fmt" - ctx "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/testsuites" "golang.org/x/oauth2" @@ -49,7 +49,7 @@ func init() { var email string var privateKey []byte - ts, err = google.DefaultTokenSource(ctx.Background(), storage.ScopeFullControl) + ts, err = google.DefaultTokenSource(dcontext.Background(), storage.ScopeFullControl) if err != nil { // Assume that the file contents are within the environment variable since it exists // but does not contain a valid file path @@ -65,7 +65,7 @@ func init() { if email == "" { panic("Error reading JWT config : missing client_email property") } - ts = jwtConfig.TokenSource(ctx.Background()) + ts = jwtConfig.TokenSource(dcontext.Background()) } gcsDriverConstructor = func(rootDirectory string) (storagedriver.StorageDriver, error) { @@ -74,7 +74,7 @@ func init() { rootDirectory: root, email: email, privateKey: privateKey, - client: oauth2.NewClient(ctx.Background(), ts), + client: oauth2.NewClient(dcontext.Background(), ts), chunkSize: defaultChunkSize, } @@ -104,7 +104,7 @@ func TestCommitEmpty(t *testing.T) { } filename := "/test" - ctx := ctx.Background() + ctx := dcontext.Background() writer, err := driver.Writer(ctx, filename, false) defer driver.Delete(ctx, filename) @@ -150,7 +150,7 @@ func TestCommit(t *testing.T) { } filename := "/test" - ctx := ctx.Background() + ctx := dcontext.Background() contents := make([]byte, defaultChunkSize) writer, err := driver.Writer(ctx, filename, false) @@ -247,7 +247,7 @@ func TestEmptyRootList(t *testing.T) { filename := "/test" contents := []byte("contents") - ctx := ctx.Background() + ctx := dcontext.Background() err = rootedDriver.PutContent(ctx, filename, contents) if err != nil { t.Fatalf("unexpected error creating content: %v", err) @@ -290,7 +290,7 @@ func TestMoveDirectory(t *testing.T) { t.Fatalf("unexpected error creating rooted driver: %v", err) } - ctx := ctx.Background() + ctx := dcontext.Background() contents := []byte("contents") // Create a regular file. err = driver.PutContent(ctx, "/parent/dir/foo", contents) diff --git a/registry/storage/driver/inmemory/driver.go b/registry/storage/driver/inmemory/driver.go index eb2fd1cf42d..14bc3940bb9 100644 --- a/registry/storage/driver/inmemory/driver.go +++ b/registry/storage/driver/inmemory/driver.go @@ -1,13 +1,13 @@ package inmemory import ( + "context" "fmt" "io" "io/ioutil" "sync" "time" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/factory" diff --git a/registry/storage/driver/middleware/cloudfront/middleware.go b/registry/storage/driver/middleware/cloudfront/middleware.go index b0618d1aaa3..61e787a44df 100644 --- a/registry/storage/driver/middleware/cloudfront/middleware.go +++ b/registry/storage/driver/middleware/cloudfront/middleware.go @@ -4,6 +4,7 @@ package middleware import ( + "context" "crypto/x509" "encoding/pem" "fmt" @@ -13,7 +14,7 @@ import ( "time" "github.com/aws/aws-sdk-go/service/cloudfront/sign" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" storagemiddleware "github.com/docker/distribution/registry/storage/driver/middleware" ) @@ -119,7 +120,7 @@ func (lh *cloudFrontStorageMiddleware) URLFor(ctx context.Context, path string, // TODO(endophage): currently only supports S3 keyer, ok := lh.StorageDriver.(S3BucketKeyer) if !ok { - context.GetLogger(ctx).Warn("the CloudFront middleware does not support this backend storage driver") + dcontext.GetLogger(ctx).Warn("the CloudFront middleware does not support this backend storage driver") return lh.StorageDriver.URLFor(ctx, path, options) } diff --git a/registry/storage/driver/middleware/redirect/middleware.go b/registry/storage/driver/middleware/redirect/middleware.go index 20cd7daa756..8f63674c631 100644 --- a/registry/storage/driver/middleware/redirect/middleware.go +++ b/registry/storage/driver/middleware/redirect/middleware.go @@ -1,10 +1,10 @@ package middleware import ( + "context" "fmt" "net/url" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" storagemiddleware "github.com/docker/distribution/registry/storage/driver/middleware" ) diff --git a/registry/storage/driver/oss/oss.go b/registry/storage/driver/oss/oss.go index 6c0c35a5e19..f79e3537237 100644 --- a/registry/storage/driver/oss/oss.go +++ b/registry/storage/driver/oss/oss.go @@ -13,6 +13,7 @@ package oss import ( "bytes" + "context" "fmt" "io" "io/ioutil" @@ -22,8 +23,6 @@ import ( "strings" "time" - "github.com/docker/distribution/context" - "github.com/denverdino/aliyungo/oss" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" diff --git a/registry/storage/driver/oss/oss_test.go b/registry/storage/driver/oss/oss_test.go index fbae5d9ca5c..438d9a48ee2 100644 --- a/registry/storage/driver/oss/oss_test.go +++ b/registry/storage/driver/oss/oss_test.go @@ -4,16 +4,14 @@ package oss import ( "io/ioutil" + "os" + "strconv" + "testing" alioss "github.com/denverdino/aliyungo/oss" "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/testsuites" - //"log" - "os" - "strconv" - "testing" - "gopkg.in/check.v1" ) diff --git a/registry/storage/driver/s3-aws/s3.go b/registry/storage/driver/s3-aws/s3.go index 19407d807f3..33312afcc94 100644 --- a/registry/storage/driver/s3-aws/s3.go +++ b/registry/storage/driver/s3-aws/s3.go @@ -13,6 +13,7 @@ package s3 import ( "bytes" + "context" "fmt" "io" "io/ioutil" @@ -33,7 +34,6 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/client/transport" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" diff --git a/registry/storage/driver/s3-goamz/s3.go b/registry/storage/driver/s3-goamz/s3.go index b16ca49a7ee..4850f6d753f 100644 --- a/registry/storage/driver/s3-goamz/s3.go +++ b/registry/storage/driver/s3-goamz/s3.go @@ -14,6 +14,7 @@ package s3 import ( "bytes" + "context" "fmt" "io" "io/ioutil" @@ -23,14 +24,12 @@ import ( "strings" "time" - "github.com/docker/goamz/aws" - "github.com/docker/goamz/s3" - - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/client/transport" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/factory" + "github.com/docker/goamz/aws" + "github.com/docker/goamz/s3" ) const driverName = "s3goamz" diff --git a/registry/storage/driver/storagedriver.go b/registry/storage/driver/storagedriver.go index 548a17d8461..4b570dd6237 100644 --- a/registry/storage/driver/storagedriver.go +++ b/registry/storage/driver/storagedriver.go @@ -1,13 +1,12 @@ package driver import ( + "context" "fmt" "io" "regexp" "strconv" "strings" - - "github.com/docker/distribution/context" ) // Version is a string representing the storage driver version, of the form diff --git a/registry/storage/driver/swift/swift.go b/registry/storage/driver/swift/swift.go index 4b7aa4e9f24..11a33264be9 100644 --- a/registry/storage/driver/swift/swift.go +++ b/registry/storage/driver/swift/swift.go @@ -18,6 +18,7 @@ package swift import ( "bufio" "bytes" + "context" "crypto/rand" "crypto/sha1" "crypto/tls" @@ -34,7 +35,6 @@ import ( "github.com/mitchellh/mapstructure" "github.com/ncw/swift" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/factory" diff --git a/registry/storage/driver/testdriver/testdriver.go b/registry/storage/driver/testdriver/testdriver.go index 988e5d33bcb..91254627b62 100644 --- a/registry/storage/driver/testdriver/testdriver.go +++ b/registry/storage/driver/testdriver/testdriver.go @@ -1,7 +1,8 @@ package testdriver import ( - "github.com/docker/distribution/context" + "context" + storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/inmemory" diff --git a/registry/storage/driver/testsuites/testsuites.go b/registry/storage/driver/testsuites/testsuites.go index d8afe0c85e8..4f2f1ab0c0f 100644 --- a/registry/storage/driver/testsuites/testsuites.go +++ b/registry/storage/driver/testsuites/testsuites.go @@ -2,6 +2,7 @@ package testsuites import ( "bytes" + "context" "crypto/sha1" "io" "io/ioutil" @@ -15,10 +16,8 @@ import ( "testing" "time" - "gopkg.in/check.v1" - - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" + "gopkg.in/check.v1" ) // Test hooks up gocheck into the "go test" runner. diff --git a/registry/storage/filereader.go b/registry/storage/filereader.go index 3b06c81790c..2050e43d1b7 100644 --- a/registry/storage/filereader.go +++ b/registry/storage/filereader.go @@ -3,12 +3,12 @@ package storage import ( "bufio" "bytes" + "context" "fmt" "io" "io/ioutil" "os" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" ) diff --git a/registry/storage/garbagecollect.go b/registry/storage/garbagecollect.go index 3928989332b..ada48654b45 100644 --- a/registry/storage/garbagecollect.go +++ b/registry/storage/garbagecollect.go @@ -1,10 +1,10 @@ package storage import ( + "context" "fmt" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/driver" "github.com/opencontainers/go-digest" diff --git a/registry/storage/io.go b/registry/storage/io.go index c1be3b77186..f79e7a6f2fd 100644 --- a/registry/storage/io.go +++ b/registry/storage/io.go @@ -1,11 +1,11 @@ package storage import ( + "context" "errors" "io" "io/ioutil" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/driver" ) diff --git a/registry/storage/linkedblobstore.go b/registry/storage/linkedblobstore.go index a1929eed3a1..329163ba1f5 100644 --- a/registry/storage/linkedblobstore.go +++ b/registry/storage/linkedblobstore.go @@ -1,13 +1,14 @@ package storage import ( + "context" "fmt" "net/http" "path" "time" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/uuid" @@ -86,7 +87,7 @@ func (lbs *linkedBlobStore) Put(ctx context.Context, mediaType string, p []byte) // Place the data in the blob store first. desc, err := lbs.blobStore.Put(ctx, mediaType, p) if err != nil { - context.GetLogger(ctx).Errorf("error putting into main store: %v", err) + dcontext.GetLogger(ctx).Errorf("error putting into main store: %v", err) return distribution.Descriptor{}, err } @@ -125,7 +126,7 @@ func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption { // Writer begins a blob write session, returning a handle. func (lbs *linkedBlobStore) Create(ctx context.Context, options ...distribution.BlobCreateOption) (distribution.BlobWriter, error) { - context.GetLogger(ctx).Debug("(*linkedBlobStore).Writer") + dcontext.GetLogger(ctx).Debug("(*linkedBlobStore).Writer") var opts distribution.CreateOptions @@ -174,7 +175,7 @@ func (lbs *linkedBlobStore) Create(ctx context.Context, options ...distribution. } func (lbs *linkedBlobStore) Resume(ctx context.Context, id string) (distribution.BlobWriter, error) { - context.GetLogger(ctx).Debug("(*linkedBlobStore).Resume") + dcontext.GetLogger(ctx).Debug("(*linkedBlobStore).Resume") startedAtPath, err := pathFor(uploadStartedAtPathSpec{ name: lbs.repository.Named().Name(), @@ -411,7 +412,7 @@ func (lbs *linkedBlobStatter) Stat(ctx context.Context, dgst digest.Digest) (dis if target != dgst { // Track when we are doing cross-digest domain lookups. ie, sha512 to sha256. - context.GetLogger(ctx).Warnf("looking up blob with canonical target: %v -> %v", dgst, target) + dcontext.GetLogger(ctx).Warnf("looking up blob with canonical target: %v -> %v", dgst, target) } // TODO(stevvooe): Look up repository local mediatype and replace that on diff --git a/registry/storage/linkedblobstore_test.go b/registry/storage/linkedblobstore_test.go index a059a77819d..85376f715b0 100644 --- a/registry/storage/linkedblobstore_test.go +++ b/registry/storage/linkedblobstore_test.go @@ -1,6 +1,7 @@ package storage import ( + "context" "fmt" "io" "reflect" @@ -8,11 +9,9 @@ import ( "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" - "github.com/opencontainers/go-digest" - "github.com/docker/distribution/reference" "github.com/docker/distribution/testutil" + "github.com/opencontainers/go-digest" ) func TestLinkedBlobStoreCreateWithMountFrom(t *testing.T) { diff --git a/registry/storage/manifestlisthandler.go b/registry/storage/manifestlisthandler.go index aee73b85fc5..085ccccc297 100644 --- a/registry/storage/manifestlisthandler.go +++ b/registry/storage/manifestlisthandler.go @@ -1,11 +1,12 @@ package storage import ( + "context" + "encoding/json" "fmt" - "encoding/json" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/manifest/manifestlist" "github.com/opencontainers/go-digest" ) @@ -20,7 +21,7 @@ type manifestListHandler struct { var _ ManifestHandler = &manifestListHandler{} func (ms *manifestListHandler) Unmarshal(ctx context.Context, dgst digest.Digest, content []byte) (distribution.Manifest, error) { - context.GetLogger(ms.ctx).Debug("(*manifestListHandler).Unmarshal") + dcontext.GetLogger(ms.ctx).Debug("(*manifestListHandler).Unmarshal") var m manifestlist.DeserializedManifestList if err := json.Unmarshal(content, &m); err != nil { @@ -31,7 +32,7 @@ func (ms *manifestListHandler) Unmarshal(ctx context.Context, dgst digest.Digest } func (ms *manifestListHandler) Put(ctx context.Context, manifestList distribution.Manifest, skipDependencyVerification bool) (digest.Digest, error) { - context.GetLogger(ms.ctx).Debug("(*manifestListHandler).Put") + dcontext.GetLogger(ms.ctx).Debug("(*manifestListHandler).Put") m, ok := manifestList.(*manifestlist.DeserializedManifestList) if !ok { @@ -49,7 +50,7 @@ func (ms *manifestListHandler) Put(ctx context.Context, manifestList distributio revision, err := ms.blobStore.Put(ctx, mt, payload) if err != nil { - context.GetLogger(ctx).Errorf("error putting payload into blobstore: %v", err) + dcontext.GetLogger(ctx).Errorf("error putting payload into blobstore: %v", err) return "", err } diff --git a/registry/storage/manifeststore.go b/registry/storage/manifeststore.go index 4cca5157a7b..20e34eb0103 100644 --- a/registry/storage/manifeststore.go +++ b/registry/storage/manifeststore.go @@ -1,11 +1,12 @@ package storage import ( + "context" + "encoding/json" "fmt" - "encoding/json" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/schema1" @@ -53,7 +54,7 @@ type manifestStore struct { var _ distribution.ManifestService = &manifestStore{} func (ms *manifestStore) Exists(ctx context.Context, dgst digest.Digest) (bool, error) { - context.GetLogger(ms.ctx).Debug("(*manifestStore).Exists") + dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Exists") _, err := ms.blobStore.Stat(ms.ctx, dgst) if err != nil { @@ -68,7 +69,7 @@ func (ms *manifestStore) Exists(ctx context.Context, dgst digest.Digest) (bool, } func (ms *manifestStore) Get(ctx context.Context, dgst digest.Digest, options ...distribution.ManifestServiceOption) (distribution.Manifest, error) { - context.GetLogger(ms.ctx).Debug("(*manifestStore).Get") + dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Get") // TODO(stevvooe): Need to check descriptor from above to ensure that the // mediatype is as we expect for the manifest store. @@ -109,7 +110,7 @@ func (ms *manifestStore) Get(ctx context.Context, dgst digest.Digest, options .. } func (ms *manifestStore) Put(ctx context.Context, manifest distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) { - context.GetLogger(ms.ctx).Debug("(*manifestStore).Put") + dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Put") switch manifest.(type) { case *schema1.SignedManifest: @@ -125,7 +126,7 @@ func (ms *manifestStore) Put(ctx context.Context, manifest distribution.Manifest // Delete removes the revision of the specified manifest. func (ms *manifestStore) Delete(ctx context.Context, dgst digest.Digest) error { - context.GetLogger(ms.ctx).Debug("(*manifestStore).Delete") + dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Delete") return ms.blobStore.Delete(ctx, dgst) } diff --git a/registry/storage/manifeststore_test.go b/registry/storage/manifeststore_test.go index e398058be4a..2fad7611da7 100644 --- a/registry/storage/manifeststore_test.go +++ b/registry/storage/manifeststore_test.go @@ -2,12 +2,12 @@ package storage import ( "bytes" + "context" "io" "reflect" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/reference" diff --git a/registry/storage/purgeuploads.go b/registry/storage/purgeuploads.go index d6cae4e7b34..2396e803412 100644 --- a/registry/storage/purgeuploads.go +++ b/registry/storage/purgeuploads.go @@ -1,14 +1,14 @@ package storage import ( + "context" "path" "strings" "time" - "github.com/docker/distribution/context" storageDriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/uuid" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) // uploadData stored the location of temporary files created during a layer upload @@ -30,13 +30,13 @@ func newUploadData() uploadData { // created before olderThan. The list of files deleted and errors // encountered are returned func PurgeUploads(ctx context.Context, driver storageDriver.StorageDriver, olderThan time.Time, actuallyDelete bool) ([]string, []error) { - log.Infof("PurgeUploads starting: olderThan=%s, actuallyDelete=%t", olderThan, actuallyDelete) + logrus.Infof("PurgeUploads starting: olderThan=%s, actuallyDelete=%t", olderThan, actuallyDelete) uploadData, errors := getOutstandingUploads(ctx, driver) var deleted []string for _, uploadData := range uploadData { if uploadData.startedAt.Before(olderThan) { var err error - log.Infof("Upload files in %s have older date (%s) than purge date (%s). Removing upload directory.", + logrus.Infof("Upload files in %s have older date (%s) than purge date (%s). Removing upload directory.", uploadData.containingDir, uploadData.startedAt, olderThan) if actuallyDelete { err = driver.Delete(ctx, uploadData.containingDir) @@ -49,7 +49,7 @@ func PurgeUploads(ctx context.Context, driver storageDriver.StorageDriver, older } } - log.Infof("Purge uploads finished. Num deleted=%d, num errors=%d", len(deleted), len(errors)) + logrus.Infof("Purge uploads finished. Num deleted=%d, num errors=%d", len(deleted), len(errors)) return deleted, errors } diff --git a/registry/storage/purgeuploads_test.go b/registry/storage/purgeuploads_test.go index 3b70f72341b..069f212d52b 100644 --- a/registry/storage/purgeuploads_test.go +++ b/registry/storage/purgeuploads_test.go @@ -1,12 +1,12 @@ package storage import ( + "context" "path" "strings" "testing" "time" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/inmemory" "github.com/docker/distribution/uuid" diff --git a/registry/storage/registry.go b/registry/storage/registry.go index 20525ffb3c3..46b96853982 100644 --- a/registry/storage/registry.go +++ b/registry/storage/registry.go @@ -1,10 +1,10 @@ package storage import ( + "context" "regexp" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/cache" storagedriver "github.com/docker/distribution/registry/storage/driver" diff --git a/registry/storage/schema2manifesthandler.go b/registry/storage/schema2manifesthandler.go index 05c53254ffe..b0ae01ae1d7 100644 --- a/registry/storage/schema2manifesthandler.go +++ b/registry/storage/schema2manifesthandler.go @@ -1,13 +1,14 @@ package storage import ( + "context" "encoding/json" "errors" "fmt" "net/url" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema2" "github.com/opencontainers/go-digest" @@ -30,7 +31,7 @@ type schema2ManifestHandler struct { var _ ManifestHandler = &schema2ManifestHandler{} func (ms *schema2ManifestHandler) Unmarshal(ctx context.Context, dgst digest.Digest, content []byte) (distribution.Manifest, error) { - context.GetLogger(ms.ctx).Debug("(*schema2ManifestHandler).Unmarshal") + dcontext.GetLogger(ms.ctx).Debug("(*schema2ManifestHandler).Unmarshal") var m schema2.DeserializedManifest if err := json.Unmarshal(content, &m); err != nil { @@ -41,7 +42,7 @@ func (ms *schema2ManifestHandler) Unmarshal(ctx context.Context, dgst digest.Dig } func (ms *schema2ManifestHandler) Put(ctx context.Context, manifest distribution.Manifest, skipDependencyVerification bool) (digest.Digest, error) { - context.GetLogger(ms.ctx).Debug("(*schema2ManifestHandler).Put") + dcontext.GetLogger(ms.ctx).Debug("(*schema2ManifestHandler).Put") m, ok := manifest.(*schema2.DeserializedManifest) if !ok { @@ -59,7 +60,7 @@ func (ms *schema2ManifestHandler) Put(ctx context.Context, manifest distribution revision, err := ms.blobStore.Put(ctx, mt, payload) if err != nil { - context.GetLogger(ctx).Errorf("error putting payload into blobstore: %v", err) + dcontext.GetLogger(ctx).Errorf("error putting payload into blobstore: %v", err) return "", err } diff --git a/registry/storage/signedmanifesthandler.go b/registry/storage/signedmanifesthandler.go index 6ca1c6c8cf3..f94ecbea56c 100644 --- a/registry/storage/signedmanifesthandler.go +++ b/registry/storage/signedmanifesthandler.go @@ -1,11 +1,12 @@ package storage import ( + "context" "encoding/json" "fmt" "github.com/docker/distribution" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/reference" "github.com/docker/libtrust" @@ -24,7 +25,7 @@ type signedManifestHandler struct { var _ ManifestHandler = &signedManifestHandler{} func (ms *signedManifestHandler) Unmarshal(ctx context.Context, dgst digest.Digest, content []byte) (distribution.Manifest, error) { - context.GetLogger(ms.ctx).Debug("(*signedManifestHandler).Unmarshal") + dcontext.GetLogger(ms.ctx).Debug("(*signedManifestHandler).Unmarshal") var ( signatures [][]byte @@ -56,7 +57,7 @@ func (ms *signedManifestHandler) Unmarshal(ctx context.Context, dgst digest.Dige } func (ms *signedManifestHandler) Put(ctx context.Context, manifest distribution.Manifest, skipDependencyVerification bool) (digest.Digest, error) { - context.GetLogger(ms.ctx).Debug("(*signedManifestHandler).Put") + dcontext.GetLogger(ms.ctx).Debug("(*signedManifestHandler).Put") sm, ok := manifest.(*schema1.SignedManifest) if !ok { @@ -72,7 +73,7 @@ func (ms *signedManifestHandler) Put(ctx context.Context, manifest distribution. revision, err := ms.blobStore.Put(ctx, mt, payload) if err != nil { - context.GetLogger(ctx).Errorf("error putting payload into blobstore: %v", err) + dcontext.GetLogger(ctx).Errorf("error putting payload into blobstore: %v", err) return "", err } diff --git a/registry/storage/tagstore.go b/registry/storage/tagstore.go index d73278869d9..3fbed6d39a3 100644 --- a/registry/storage/tagstore.go +++ b/registry/storage/tagstore.go @@ -1,10 +1,10 @@ package storage import ( + "context" "path" "github.com/docker/distribution" - "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/opencontainers/go-digest" ) diff --git a/registry/storage/tagstore_test.go b/registry/storage/tagstore_test.go index 396441eec2e..5bfa1451a67 100644 --- a/registry/storage/tagstore_test.go +++ b/registry/storage/tagstore_test.go @@ -1,10 +1,10 @@ package storage import ( + "context" "testing" "github.com/docker/distribution" - "github.com/docker/distribution/context" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/storage/driver/inmemory" ) diff --git a/registry/storage/util.go b/registry/storage/util.go index 773d7ba0be6..8ab235e22df 100644 --- a/registry/storage/util.go +++ b/registry/storage/util.go @@ -1,7 +1,8 @@ package storage import ( - "github.com/docker/distribution/context" + "context" + "github.com/docker/distribution/registry/storage/driver" ) diff --git a/registry/storage/vacuum.go b/registry/storage/vacuum.go index 42c8ef605c4..d2ebc539661 100644 --- a/registry/storage/vacuum.go +++ b/registry/storage/vacuum.go @@ -1,9 +1,10 @@ package storage import ( + "context" "path" - "github.com/docker/distribution/context" + dcontext "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/driver" "github.com/opencontainers/go-digest" ) @@ -39,7 +40,7 @@ func (v Vacuum) RemoveBlob(dgst string) error { return err } - context.GetLogger(v.ctx).Infof("Deleting blob: %s", blobPath) + dcontext.GetLogger(v.ctx).Infof("Deleting blob: %s", blobPath) err = v.driver.Delete(v.ctx, blobPath) if err != nil { @@ -57,7 +58,7 @@ func (v Vacuum) RemoveRepository(repoName string) error { return err } repoDir := path.Join(rootForRepository, repoName) - context.GetLogger(v.ctx).Infof("Deleting repo: %s", repoDir) + dcontext.GetLogger(v.ctx).Infof("Deleting repo: %s", repoDir) err = v.driver.Delete(v.ctx, repoDir) if err != nil { return err diff --git a/registry/storage/walk.go b/registry/storage/walk.go index d979796ebd6..3322d16a6ff 100644 --- a/registry/storage/walk.go +++ b/registry/storage/walk.go @@ -1,11 +1,11 @@ package storage import ( + "context" "errors" "fmt" "sort" - "github.com/docker/distribution/context" storageDriver "github.com/docker/distribution/registry/storage/driver" ) diff --git a/registry/storage/walk_test.go b/registry/storage/walk_test.go index 3d7a4b1b631..ca9caae03f2 100644 --- a/registry/storage/walk_test.go +++ b/registry/storage/walk_test.go @@ -1,11 +1,11 @@ package storage import ( + "context" "fmt" "sort" "testing" - "github.com/docker/distribution/context" "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/inmemory" ) diff --git a/tags.go b/tags.go index 50305659637..f22df2b850e 100644 --- a/tags.go +++ b/tags.go @@ -1,7 +1,7 @@ package distribution import ( - "github.com/docker/distribution/context" + "context" ) // TagService provides access to information about tagged objects.