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 <stephen.day@docker.com>
This commit is contained in:
Stephen J Day 2017-08-11 15:31:16 -07:00
parent 7a8efe719e
commit 9c88801a12
No known key found for this signature in database
GPG key ID: 67B3DED84EDC823F
90 changed files with 396 additions and 373 deletions

View file

@ -1,13 +1,13 @@
package distribution package distribution
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"time" "time"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )

View file

@ -1,21 +1,16 @@
package context package context
import ( import (
"context"
"sync" "sync"
"github.com/docker/distribution/uuid" "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 // instanceContext is a context that provides only an instance id. It is
// provided as the main background context. // provided as the main background context.
type instanceContext struct { type instanceContext struct {
Context context.Context
id string // id of context, logged as "instance.id" id string // id of context, logged as "instance.id"
once sync.Once // once protect generation of the 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 // Background returns a non-nil, empty Context. The background context
// provides a single key, "instance.id" that is globally unique to the // provides a single key, "instance.id" that is globally unique to the
// process. // process.
func Background() Context { func Background() context.Context {
return background 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 // stringMapContext is a simple context implementation that checks a map for a
// key, falling back to a parent if not present. // key, falling back to a parent if not present.
type stringMapContext struct { type stringMapContext struct {

View file

@ -1,6 +1,7 @@
package context package context
import ( import (
"context"
"errors" "errors"
"net" "net"
"net/http" "net/http"
@ -68,7 +69,7 @@ func RemoteIP(r *http.Request) string {
// is available at "http.request". Other common attributes are available under // is available at "http.request". Other common attributes are available under
// the prefix "http.request.". If a request is already present on the context, // the prefix "http.request.". If a request is already present on the context,
// this method will panic. // 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 { if ctx.Value("http.request") != nil {
// NOTE(stevvooe): This needs to be considered a programming error. It // NOTE(stevvooe): This needs to be considered a programming error. It
// is unlikely that we'd want to have more than one request in // 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 // GetRequest returns the http request in the given context. Returns
// ErrNoRequestContext if the context does not have an http request associated // ErrNoRequestContext if the context does not have an http request associated
// with it. // 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 { if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok {
return r, nil 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 // GetRequestID attempts to resolve the current request id, if possible. An
// error is return if it is not available on the context. // 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") return GetStringValue(ctx, "http.request.id")
} }
// WithResponseWriter returns a new context and response writer that makes // WithResponseWriter returns a new context and response writer that makes
// interesting response statistics available within the context. // 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 { if closeNotifier, ok := w.(http.CloseNotifier); ok {
irwCN := &instrumentedResponseWriterCN{ irwCN := &instrumentedResponseWriterCN{
instrumentedResponseWriter: instrumentedResponseWriter{ instrumentedResponseWriter: instrumentedResponseWriter{
@ -125,7 +126,7 @@ func WithResponseWriter(ctx Context, w http.ResponseWriter) (Context, http.Respo
// GetResponseWriter returns the http.ResponseWriter from the provided // GetResponseWriter returns the http.ResponseWriter from the provided
// context. If not present, ErrNoResponseWriterContext is returned. The // context. If not present, ErrNoResponseWriterContext is returned. The
// returned instance provides instrumentation in the context. // 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") v := ctx.Value("http.response")
rw, ok := v.(http.ResponseWriter) 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 // example, if looking for the variable "name", it can be accessed as
// "vars.name". Implementations that are accessing values need not know that // "vars.name". Implementations that are accessing values need not know that
// the underlying context is implemented with gorilla/mux vars. // 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{ return &muxVarsContext{
Context: ctx, Context: ctx,
vars: getVarsFromRequest(r), 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 // GetRequestLogger returns a logger that contains fields from the request in
// the current context. If the request is not available in the context, no // 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. // 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, return GetLogger(ctx,
"http.request.id", "http.request.id",
"http.request.method", "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 // 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 // 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. // 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, l := getLogrusLogger(ctx,
"http.response.written", "http.response.written",
"http.response.status", "http.response.status",
@ -188,7 +189,7 @@ func GetResponseLogger(ctx Context) Logger {
// httpRequestContext makes information about a request available to context. // httpRequestContext makes information about a request available to context.
type httpRequestContext struct { type httpRequestContext struct {
Context context.Context
startedAt time.Time startedAt time.Time
id string id string
@ -247,7 +248,7 @@ fallback:
} }
type muxVarsContext struct { type muxVarsContext struct {
Context context.Context
vars map[string]string vars map[string]string
} }
@ -282,7 +283,7 @@ type instrumentedResponseWriterCN struct {
// implemented by the parent ResponseWriter. // implemented by the parent ResponseWriter.
type instrumentedResponseWriter struct { type instrumentedResponseWriter struct {
http.ResponseWriter http.ResponseWriter
Context context.Context
mu sync.Mutex mu sync.Mutex
status int status int

View file

@ -1,10 +1,11 @@
package context package context
import ( import (
"context"
"fmt" "fmt"
"runtime"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"runtime"
) )
// Logger provides a leveled-logging interface. // Logger provides a leveled-logging interface.
@ -40,22 +41,24 @@ type Logger interface {
Warnln(args ...interface{}) Warnln(args ...interface{})
} }
type loggerKey struct{}
// WithLogger creates a new context with provided logger. // WithLogger creates a new context with provided logger.
func WithLogger(ctx Context, logger Logger) Context { func WithLogger(ctx context.Context, logger Logger) context.Context {
return WithValue(ctx, "logger", logger) return context.WithValue(ctx, loggerKey{}, logger)
} }
// GetLoggerWithField returns a logger instance with the specified field key // GetLoggerWithField returns a logger instance with the specified field key
// and value without affecting the context. Extra specified keys will be // and value without affecting the context. Extra specified keys will be
// resolved from the context. // 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) return getLogrusLogger(ctx, keys...).WithField(fmt.Sprint(key), value)
} }
// GetLoggerWithFields returns a logger instance with the specified fields // GetLoggerWithFields returns a logger instance with the specified fields
// without affecting the context. Extra specified keys will be resolved from // without affecting the context. Extra specified keys will be resolved from
// the context. // 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. // must convert from interface{} -> interface{} to string -> interface{} for logrus.
lfields := make(logrus.Fields, len(fields)) lfields := make(logrus.Fields, len(fields))
for key, value := range 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 // 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, // a logging key field. If context keys are integer constants, for example,
// its recommended that a String method is implemented. // 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...) 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 // are provided, they will be resolved on the context and included in the
// logger. Only use this function if specific logrus functionality is // logger. Only use this function if specific logrus functionality is
// required. // required.
func getLogrusLogger(ctx Context, keys ...interface{}) *logrus.Entry { func getLogrusLogger(ctx context.Context, keys ...interface{}) *logrus.Entry {
var logger *logrus.Entry var logger *logrus.Entry
// Get a logger, if it is present. // Get a logger, if it is present.
loggerInterface := ctx.Value("logger") loggerInterface := ctx.Value(loggerKey{})
if loggerInterface != nil { if loggerInterface != nil {
if lgr, ok := loggerInterface.(*logrus.Entry); ok { if lgr, ok := loggerInterface.(*logrus.Entry); ok {
logger = lgr logger = lgr

View file

@ -1,6 +1,7 @@
package context package context
import ( import (
"context"
"runtime" "runtime"
"time" "time"
@ -36,7 +37,7 @@ import (
// //
// Notice that the function name is automatically resolved, along with the // 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. // 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 { if ctx == nil {
ctx = Background() 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 // also provides fast lookup for the various attributes that are available on
// the trace. // the trace.
type traced struct { type traced struct {
Context context.Context
id string id string
parent string parent string
start time.Time start time.Time

View file

@ -1,6 +1,7 @@
package context package context
import ( import (
"context"
"runtime" "runtime"
"testing" "testing"
"time" "time"
@ -35,7 +36,7 @@ func TestWithTrace(t *testing.T) {
ctx, done := WithTrace(Background()) ctx, done := WithTrace(Background())
defer done("this will be emitted at end of test") 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", key: "trace.func",
expected: f.Name(), expected: f.Name(),
})) }))
@ -48,7 +49,7 @@ func TestWithTrace(t *testing.T) {
ctx, done := WithTrace(ctx) ctx, done := WithTrace(ctx)
defer done("this should be subordinate to the other trace") defer done("this should be subordinate to the other trace")
time.Sleep(time.Second) time.Sleep(time.Second)
checkContextForValues(t, ctx, append(base, valueTestCase{ checkContextForValues(ctx, t, append(base, valueTestCase{
key: "trace.func", key: "trace.func",
expected: f.Name(), expected: f.Name(),
}, valueTestCase{ }, valueTestCase{
@ -67,8 +68,7 @@ type valueTestCase struct {
notnilorempty bool // just check not empty/not nil 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 { for _, testcase := range values {
v := ctx.Value(testcase.key) v := ctx.Value(testcase.key)
if testcase.notnilorempty { if testcase.notnilorempty {

View file

@ -1,13 +1,14 @@
package context package context
import ( import (
"context"
"time" "time"
) )
// Since looks up key, which should be a time.Time, and returns the duration // 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. // 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. // 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 { if startedAt, ok := ctx.Value(key).(time.Time); ok {
return time.Since(startedAt) 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 // GetStringValue returns a string value from the context. The empty string
// will be returned if not found. // 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 { if valuev, ok := ctx.Value(key).(string); ok {
value = valuev value = valuev
} }

View file

@ -1,16 +1,22 @@
package context package context
import "context"
type versionKey struct{}
func (versionKey) String() string { return "version" }
// WithVersion stores the application version in the context. The new context // WithVersion stores the application version in the context. The new context
// gets a logger to ensure log messages are marked with the application // gets a logger to ensure log messages are marked with the application
// version. // version.
func WithVersion(ctx Context, version string) Context { func WithVersion(ctx context.Context, version string) context.Context {
ctx = WithValue(ctx, "version", version) ctx = context.WithValue(ctx, versionKey{}, version)
// push a new logger onto the stack // 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 // GetVersion returns the application version from the context. An empty
// string may returned if the version was not set on the context. // string may returned if the version was not set on the context.
func GetVersion(ctx Context) string { func GetVersion(ctx context.Context) string {
return GetStringValue(ctx, "version") return GetStringValue(ctx, versionKey{})
} }

View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"context"
"encoding/json" "encoding/json"
"flag" "flag"
"math/rand" "math/rand"
@ -9,7 +10,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/errcode"
"github.com/docker/distribution/registry/auth" "github.com/docker/distribution/registry/auth"
_ "github.com/docker/distribution/registry/auth/htpasswd" _ "github.com/docker/distribution/registry/auth/htpasswd"
@ -85,7 +86,7 @@ func main() {
// TODO: Make configurable // TODO: Make configurable
issuer.Expiration = 15 * time.Minute issuer.Expiration = 15 * time.Minute
ctx := context.Background() ctx := dcontext.Background()
ts := &tokenServer{ ts := &tokenServer{
issuer: issuer, issuer: issuer,
@ -115,23 +116,23 @@ func main() {
// request context from a base context. // request context from a base context.
func handlerWithContext(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) http.Handler { 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) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithRequest(ctx, r) ctx := dcontext.WithRequest(ctx, r)
logger := context.GetRequestLogger(ctx) logger := dcontext.GetRequestLogger(ctx)
ctx = context.WithLogger(ctx, logger) ctx = dcontext.WithLogger(ctx, logger)
handler(ctx, w, r) handler(ctx, w, r)
}) })
} }
func handleError(ctx context.Context, err error, w http.ResponseWriter) { 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 { 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 return
} }
context.GetResponseLogger(ctx).Info("application error") dcontext.GetResponseLogger(ctx).Info("application error")
} }
var refreshCharacters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") var refreshCharacters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
@ -173,13 +174,13 @@ func filterAccessList(ctx context.Context, scope string, requestedAccessList []a
for _, access := range requestedAccessList { for _, access := range requestedAccessList {
if access.Type == "repository" { if access.Type == "repository" {
if !strings.HasPrefix(access.Name, scope) { 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 continue
} }
if enforceRepoClass { if enforceRepoClass {
if class, ok := repositoryClassCache[access.Name]; ok { if class, ok := repositoryClassCache[access.Name]; ok {
if class != access.Class { 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 continue
} }
} else if strings.EqualFold(access.Action, "push") { } 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" { } else if access.Type == "registry" {
if access.Name != "catalog" { 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 continue
} }
// TODO: Limit some actions to "admin" users // TODO: Limit some actions to "admin" users
} else { } else {
context.GetLogger(ctx).Debugf("Skipping unsupported resource type: %s", access.Type) dcontext.GetLogger(ctx).Debugf("Skipping unsupported resource type: %s", access.Type)
continue continue
} }
grantedAccessList = append(grantedAccessList, access) grantedAccessList = append(grantedAccessList, access)
@ -216,7 +217,7 @@ func (grantedAccess) String() string { return "grantedAccess" }
// getToken handles authenticating the request and authorizing access to the // getToken handles authenticating the request and authorizing access to the
// requested scopes. // requested scopes.
func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *http.Request) { 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() params := r.URL.Query()
service := params.Get("service") service := params.Get("service")
@ -242,30 +243,30 @@ func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *h
} }
// Get response context. // Get response context.
ctx, w = context.WithResponseWriter(ctx, w) ctx, w = dcontext.WithResponseWriter(ctx, w)
challenge.SetHeaders(w) challenge.SetHeaders(w)
handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail(challenge.Error()), 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 return
} }
ctx = authorizedCtx ctx = authorizedCtx
username := context.GetStringValue(ctx, "auth.user.name") username := dcontext.GetStringValue(ctx, "auth.user.name")
ctx = context.WithValue(ctx, acctSubject{}, username) 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.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) grantedAccessList := filterAccessList(ctx, username, requestedAccessList)
ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList) 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) token, err := ts.issuer.CreateJWT(username, service, grantedAccessList)
if err != nil { if err != nil {
@ -273,7 +274,7 @@ func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *h
return return
} }
context.GetLogger(ctx).Info("authorized client") dcontext.GetLogger(ctx).Info("authorized client")
response := tokenResponse{ response := tokenResponse{
Token: token, 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") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response) json.NewEncoder(w).Encode(response)
context.GetResponseLogger(ctx).Info("get token complete") dcontext.GetResponseLogger(ctx).Info("get token complete")
} }
type postTokenResponse struct { 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.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.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) grantedAccessList := filterAccessList(ctx, subject, requestedAccessList)
ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList) 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) token, err := ts.issuer.CreateJWT(subject, service, grantedAccessList)
if err != nil { if err != nil {
@ -395,7 +396,7 @@ func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r *
return return
} }
context.GetLogger(ctx).Info("authorized client") dcontext.GetLogger(ctx).Info("authorized client")
response := postTokenResponse{ response := postTokenResponse{
Token: token, Token: token,
@ -416,10 +417,10 @@ func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r *
response.RefreshToken = rToken response.RefreshToken = rToken
} }
ctx, w = context.WithResponseWriter(ctx, w) ctx, w = dcontext.WithResponseWriter(ctx, w)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response) json.NewEncoder(w).Encode(response)
context.GetResponseLogger(ctx).Info("post token complete") dcontext.GetResponseLogger(ctx).Info("post token complete")
} }

View file

@ -1,6 +1,7 @@
package main package main
import ( import (
"context"
"crypto" "crypto"
"crypto/rand" "crypto/rand"
"encoding/base64" "encoding/base64"
@ -11,7 +12,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/auth" "github.com/docker/distribution/registry/auth"
"github.com/docker/distribution/registry/auth/token" "github.com/docker/distribution/registry/auth/token"
"github.com/docker/libtrust" "github.com/docker/libtrust"
@ -27,7 +28,7 @@ func ResolveScopeSpecifiers(ctx context.Context, scopeSpecs []string) []auth.Acc
parts := strings.SplitN(scopeSpecifier, ":", 3) parts := strings.SplitN(scopeSpecifier, ":", 3)
if len(parts) != 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 continue
} }

View file

@ -1,6 +1,7 @@
package schema1 package schema1
import ( import (
"context"
"crypto/sha512" "crypto/sha512"
"encoding/json" "encoding/json"
"errors" "errors"
@ -8,7 +9,6 @@ import (
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/libtrust" "github.com/docker/libtrust"

View file

@ -3,12 +3,13 @@ package schema1
import ( import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"context"
"io" "io"
"reflect" "reflect"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/libtrust" "github.com/docker/libtrust"
"github.com/opencontainers/go-digest" "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 { if err != nil {
t.Fatalf("Build returned error: %v", err) t.Fatalf("Build returned error: %v", err)
} }
// Check that the gzipped empty layer tar was put in the blob store // 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 { if err != nil {
t.Fatal("gzipped empty tar was not put in the blob store") t.Fatal("gzipped empty tar was not put in the blob store")
} }

View file

@ -1,11 +1,11 @@
package schema1 package schema1
import ( import (
"context"
"errors"
"fmt" "fmt"
"errors"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/libtrust" "github.com/docker/libtrust"

View file

@ -1,8 +1,9 @@
package schema2 package schema2
import ( import (
"context"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )

View file

@ -1,11 +1,11 @@
package schema2 package schema2
import ( import (
"context"
"reflect" "reflect"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )

View file

@ -1,10 +1,10 @@
package distribution package distribution
import ( import (
"context"
"fmt" "fmt"
"mime" "mime"
"github.com/docker/distribution/context"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )

View file

@ -1,10 +1,11 @@
package notifications package notifications
import ( import (
"context"
"net/http" "net/http"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/opencontainers/go-digest" "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) err := msl.ManifestService.Delete(ctx, dgst)
if err == nil { if err == nil {
if err := msl.parent.listener.ManifestDeleted(msl.parent.Repository.Named(), dgst); 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...) sm, err := msl.ManifestService.Get(ctx, dgst, options...)
if err == nil { if err == nil {
if err := msl.parent.listener.ManifestPulled(msl.parent.Repository.Named(), sm, options...); 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 == nil {
if err := msl.parent.listener.ManifestPushed(msl.parent.Repository.Named(), sm, options...); 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) p, err := bsl.BlobStore.Get(ctx, dgst)
if err == nil { if err == nil {
if desc, err := bsl.Stat(ctx, dgst); 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 { } else {
if err := bsl.parent.listener.BlobPulled(bsl.parent.Repository.Named(), desc); err != nil { 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) rc, err := bsl.BlobStore.Open(ctx, dgst)
if err == nil { if err == nil {
if desc, err := bsl.Stat(ctx, dgst); 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 { } else {
if err := bsl.parent.listener.BlobPulled(bsl.parent.Repository.Named(), desc); err != nil { 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) err := bsl.BlobStore.ServeBlob(ctx, w, r, dgst)
if err == nil { if err == nil {
if desc, err := bsl.Stat(ctx, dgst); 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 { } else {
if err := bsl.parent.listener.BlobPulled(bsl.parent.Repository.Named(), desc); err != nil { 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) desc, err := bsl.BlobStore.Put(ctx, mediaType, p)
if err == nil { if err == nil {
if err := bsl.parent.listener.BlobPushed(bsl.parent.Repository.Named(), desc); 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) { switch err := err.(type) {
case distribution.ErrBlobMounted: case distribution.ErrBlobMounted:
if err := bsl.parent.listener.BlobMounted(bsl.parent.Repository.Named(), err.Descriptor, err.From); err != nil { 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 return nil, err
} }
@ -179,7 +180,7 @@ func (bsl *blobServiceListener) Delete(ctx context.Context, dgst digest.Digest)
err := bsl.BlobStore.Delete(ctx, dgst) err := bsl.BlobStore.Delete(ctx, dgst)
if err == nil { if err == nil {
if err := bsl.parent.listener.BlobDeleted(bsl.parent.Repository.Named(), dgst); 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) committed, err := bwl.BlobWriter.Commit(ctx, desc)
if err == nil { if err == nil {
if err := bwl.parent.parent.listener.BlobPushed(bwl.parent.parent.Repository.Named(), committed); 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)
} }
} }

View file

@ -1,7 +1,8 @@
package distribution package distribution
import ( import (
"github.com/docker/distribution/context" "context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
) )

View file

@ -33,11 +33,10 @@
package auth package auth
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"github.com/docker/distribution/context"
) )
const ( const (

View file

@ -6,13 +6,14 @@
package htpasswd package htpasswd
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"sync" "sync"
"time" "time"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/auth" "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) { 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 { if err != nil {
return nil, err return nil, err
} }
@ -83,7 +84,7 @@ func (ac *accessController) Authorized(ctx context.Context, accessRecords ...aut
ac.mu.Unlock() ac.mu.Unlock()
if err := localHTPasswd.authenticateUser(username, password); err != nil { 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{ return nil, &challenge{
realm: ac.realm, realm: ac.realm,
err: auth.ErrAuthenticationFailure, err: auth.ErrAuthenticationFailure,

View file

@ -8,11 +8,12 @@
package silly package silly
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/auth" "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, // Authorized simply checks for the existence of the authorization header,
// responding with a bearer challenge if it doesn't exist. // responding with a bearer challenge if it doesn't exist.
func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) { 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 { if err != nil {
return nil, err return nil, err
} }
@ -65,7 +66,11 @@ func (ac *accessController) Authorized(ctx context.Context, accessRecords ...aut
return nil, &challenge 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 { type challenge struct {

View file

@ -1,6 +1,7 @@
package token package token
import ( import (
"context"
"crypto" "crypto"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
@ -11,7 +12,7 @@ import (
"os" "os"
"strings" "strings"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/auth" "github.com/docker/distribution/registry/auth"
"github.com/docker/libtrust" "github.com/docker/libtrust"
) )
@ -221,7 +222,7 @@ func (ac *accessController) Authorized(ctx context.Context, accessItems ...auth.
accessSet: newAccessSet(accessItems...), accessSet: newAccessSet(accessItems...),
} }
req, err := context.GetRequest(ctx) req, err := dcontext.GetRequest(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -2,6 +2,7 @@ package client
import ( import (
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -9,7 +10,6 @@ import (
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
) )
type httpBlobUpload struct { type httpBlobUpload struct {

View file

@ -2,6 +2,7 @@ package client
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -14,7 +15,6 @@ import (
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/api/v2"
"github.com/docker/distribution/registry/client/transport" "github.com/docker/distribution/registry/client/transport"

View file

@ -2,6 +2,7 @@ package handlers
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -21,7 +22,6 @@ import (
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/configuration" "github.com/docker/distribution/configuration"
"github.com/docker/distribution/context"
"github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest"
"github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/manifestlist"
"github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema1"

View file

@ -1,6 +1,7 @@
package handlers package handlers
import ( import (
"context"
cryptorand "crypto/rand" cryptorand "crypto/rand"
"expvar" "expvar"
"fmt" "fmt"
@ -16,7 +17,7 @@ import (
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/configuration" "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"
"github.com/docker/distribution/health/checks" "github.com/docker/distribution/health/checks"
"github.com/docker/distribution/notifications" "github.com/docker/distribution/notifications"
@ -37,8 +38,7 @@ import (
"github.com/docker/libtrust" "github.com/docker/libtrust"
"github.com/garyburd/redigo/redis" "github.com/garyburd/redigo/redis"
"github.com/gorilla/mux" "github.com/gorilla/mux"
log "github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"golang.org/x/net/context"
) )
// randomSecretSize is the number of random bytes to generate if no secret // 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"]) app.driver, err = applyStorageMiddleware(app.driver, config.Middleware["storage"])
if err != nil { if err != nil {
@ -208,7 +208,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App {
} }
} }
if redirectDisabled { if redirectDisabled {
ctxu.GetLogger(app).Infof("backend redirection disabled") dcontext.GetLogger(app).Infof("backend redirection disabled")
} else { } else {
options = append(options, storage.EnableRedirect) options = append(options, storage.EnableRedirect)
} }
@ -269,7 +269,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App {
if err != nil { if err != nil {
panic("could not create registry: " + err.Error()) 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": case "inmemory":
cacheProvider := memorycache.NewInMemoryBlobDescriptorCacheProvider() cacheProvider := memorycache.NewInMemoryBlobDescriptorCacheProvider()
localOptions := append(options, storage.BlobDescriptorCacheProvider(cacheProvider)) localOptions := append(options, storage.BlobDescriptorCacheProvider(cacheProvider))
@ -277,10 +277,10 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App {
if err != nil { if err != nil {
panic("could not create registry: " + err.Error()) 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: default:
if v != "" { 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)) panic(fmt.Sprintf("unable to configure authorization (%s): %v", authType, err))
} }
app.accessController = accessController 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 // configure as a pull through cache
@ -316,7 +316,7 @@ func NewApp(ctx context.Context, config *configuration.Configuration) *App {
panic(err.Error()) panic(err.Error())
} }
app.isCache = true 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 return app
@ -361,7 +361,7 @@ func (app *App) RegisterHealthChecks(healthRegistries ...*health.Registry) {
if interval == 0 { if interval == 0 {
interval = defaultCheckInterval 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)) 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) checker := checks.HTTPChecker(httpChecker.URI, statusCode, httpChecker.Timeout, httpChecker.Headers)
if httpChecker.Threshold != 0 { 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)) healthRegistry.Register(httpChecker.URI, health.PeriodicThresholdChecker(checker, interval, httpChecker.Threshold))
} else { } 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)) 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) checker := checks.TCPChecker(tcpChecker.Addr, tcpChecker.Timeout)
if tcpChecker.Threshold != 0 { 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)) healthRegistry.Register(tcpChecker.Addr, health.PeriodicThresholdChecker(checker, interval, tcpChecker.Threshold))
} else { } 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)) healthRegistry.Register(tcpChecker.Addr, health.PeriodicChecker(checker, interval))
} }
} }
@ -425,11 +425,11 @@ func (app *App) configureEvents(configuration *configuration.Configuration) {
var sinks []notifications.Sink var sinks []notifications.Sink
for _, endpoint := range configuration.Notifications.Endpoints { for _, endpoint := range configuration.Notifications.Endpoints {
if endpoint.Disabled { if endpoint.Disabled {
ctxu.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name) dcontext.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name)
continue 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{ endpoint := notifications.NewEndpoint(endpoint.Name, endpoint.URL, notifications.EndpointConfig{
Timeout: endpoint.Timeout, Timeout: endpoint.Timeout,
Threshold: endpoint.Threshold, Threshold: endpoint.Threshold,
@ -461,7 +461,7 @@ func (app *App) configureEvents(configuration *configuration.Configuration) {
app.events.source = notifications.SourceRecord{ app.events.source = notifications.SourceRecord{
Addr: hostname, 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) { func (app *App) configureRedis(configuration *configuration.Configuration) {
if configuration.Redis.Addr == "" { if configuration.Redis.Addr == "" {
ctxu.GetLogger(app).Infof("redis not configured") dcontext.GetLogger(app).Infof("redis not configured")
return return
} }
@ -479,8 +479,8 @@ func (app *App) configureRedis(configuration *configuration.Configuration) {
ctx := context.WithValue(app, redisStartAtKey{}, time.Now()) ctx := context.WithValue(app, redisStartAtKey{}, time.Now())
done := func(err error) { done := func(err error) {
logger := ctxu.GetLoggerWithField(ctx, "redis.connect.duration", logger := dcontext.GetLoggerWithField(ctx, "redis.connect.duration",
ctxu.Since(ctx, redisStartAtKey{})) dcontext.Since(ctx, redisStartAtKey{}))
if err != nil { if err != nil {
logger.Errorf("redis: error connecting: %v", err) logger.Errorf("redis: error connecting: %v", err)
} else { } else {
@ -494,7 +494,7 @@ func (app *App) configureRedis(configuration *configuration.Configuration) {
configuration.Redis.ReadTimeout, configuration.Redis.ReadTimeout,
configuration.Redis.WriteTimeout) configuration.Redis.WriteTimeout)
if err != nil { 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) configuration.Redis.Addr, err)
done(err) done(err)
return nil, err return nil, err
@ -551,7 +551,7 @@ func (app *App) configureRedis(configuration *configuration.Configuration) {
// configureLogHook prepares logging hook parameters. // configureLogHook prepares logging hook parameters.
func (app *App) configureLogHook(configuration *configuration.Configuration) { func (app *App) configureLogHook(configuration *configuration.Configuration) {
entry, ok := ctxu.GetLogger(app).(*log.Entry) entry, ok := dcontext.GetLogger(app).(*logrus.Entry)
if !ok { if !ok {
// somehow, we are not using logrus // somehow, we are not using logrus
return 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)) panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err))
} }
configuration.HTTP.Secret = string(secretBytes[:]) 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. // Prepare the context with our own little decorations.
ctx := r.Context() ctx := r.Context()
ctx = ctxu.WithRequest(ctx, r) ctx = dcontext.WithRequest(ctx, r)
ctx, w = ctxu.WithResponseWriter(ctx, w) ctx, w = dcontext.WithResponseWriter(ctx, w)
ctx = ctxu.WithLogger(ctx, ctxu.GetRequestLogger(ctx)) ctx = dcontext.WithLogger(ctx, dcontext.GetRequestLogger(ctx))
r = r.WithContext(ctx) r = r.WithContext(ctx)
defer func() { defer func() {
status, ok := ctx.Value("http.response.status").(int) status, ok := ctx.Value("http.response.status").(int)
if ok && status >= 200 && status <= 399 { 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) context := app.context(w, r)
if err := app.authorized(w, r, context); err != nil { 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 return
} }
// Add username to request logging // 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. // sync up context on the request.
r = r.WithContext(context) r = r.WithContext(context)
@ -650,20 +650,20 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler {
if app.nameRequired(r) { if app.nameRequired(r) {
nameRef, err := reference.WithName(getName(context)) nameRef, err := reference.WithName(getName(context))
if err != nil { 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{ context.Errors = append(context.Errors, distribution.ErrRepositoryNameInvalid{
Name: getName(context), Name: getName(context),
Reason: err, Reason: err,
}) })
if err := errcode.ServeJSON(w, context.Errors); err != nil { 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 return
} }
repository, err := app.registry.Repository(context, nameRef) repository, err := app.registry.Repository(context, nameRef)
if err != nil { 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) { switch err := err.(type) {
case distribution.ErrRepositoryUnknown: case distribution.ErrRepositoryUnknown:
@ -675,7 +675,7 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler {
} }
if err := errcode.ServeJSON(w, context.Errors); err != nil { 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 return
} }
@ -687,11 +687,11 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler {
context.Repository, err = applyRepoMiddleware(app, context.Repository, app.Config.Middleware["repository"]) context.Repository, err = applyRepoMiddleware(app, context.Repository, app.Config.Middleware["repository"])
if err != nil { 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)) context.Errors = append(context.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
if err := errcode.ServeJSON(w, context.Errors); err != nil { 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 return
} }
@ -703,7 +703,7 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler {
// for layer upload). // for layer upload).
if context.Errors.Len() > 0 { if context.Errors.Len() > 0 {
if err := errcode.ServeJSON(w, context.Errors); err != nil { 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) app.logError(context, context.Errors)
@ -723,31 +723,31 @@ type errDetailKey struct{}
func (errDetailKey) String() string { return "err.detail" } 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 { for _, e1 := range errors {
var c ctxu.Context var c context.Context
switch e1.(type) { switch e1.(type) {
case errcode.Error: case errcode.Error:
e, _ := e1.(errcode.Error) e, _ := e1.(errcode.Error)
c = ctxu.WithValue(context, errCodeKey{}, e.Code) c = context.WithValue(ctx, errCodeKey{}, e.Code)
c = ctxu.WithValue(c, errMessageKey{}, e.Code.Message()) c = context.WithValue(c, errMessageKey{}, e.Code.Message())
c = ctxu.WithValue(c, errDetailKey{}, e.Detail) c = context.WithValue(c, errDetailKey{}, e.Detail)
case errcode.ErrorCode: case errcode.ErrorCode:
e, _ := e1.(errcode.ErrorCode) e, _ := e1.(errcode.ErrorCode)
c = ctxu.WithValue(context, errCodeKey{}, e) c = context.WithValue(ctx, errCodeKey{}, e)
c = ctxu.WithValue(c, errMessageKey{}, e.Message()) c = context.WithValue(c, errMessageKey{}, e.Message())
default: default:
// just normal go 'error' // just normal go 'error'
c = ctxu.WithValue(context, errCodeKey{}, errcode.ErrorCodeUnknown) c = context.WithValue(ctx, errCodeKey{}, errcode.ErrorCodeUnknown)
c = ctxu.WithValue(c, errMessageKey{}, e1.Error()) c = context.WithValue(c, errMessageKey{}, e1.Error())
} }
c = ctxu.WithLogger(c, ctxu.GetLogger(c, c = dcontext.WithLogger(c, dcontext.GetLogger(c,
errCodeKey{}, errCodeKey{},
errMessageKey{}, errMessageKey{},
errDetailKey{})) 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. // called once per request.
func (app *App) context(w http.ResponseWriter, r *http.Request) *Context { func (app *App) context(w http.ResponseWriter, r *http.Request) *Context {
ctx := r.Context() ctx := r.Context()
ctx = ctxu.WithVars(ctx, r) ctx = dcontext.WithVars(ctx, r)
ctx = ctxu.WithLogger(ctx, ctxu.GetLogger(ctx, ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx,
"vars.name", "vars.name",
"vars.reference", "vars.reference",
"vars.digest", "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. If it succeeds, the context may access the requested
// repository. An error will be returned if access is not available. // repository. An error will be returned if access is not available.
func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Context) error { 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) repo := getName(context)
if app.accessController == nil { 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 // that mistake elsewhere in the code, allowing any operation to
// proceed. // proceed.
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized); err != nil { 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") 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) err.SetHeaders(w)
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized.WithDetail(accessRecords)); err != nil { 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: default:
// This condition is a potential security problem either in // This condition is a potential security problem either in
// the configuration or whatever is backing the access // the configuration or whatever is backing the access
// controller. Just return a bad request with no information // controller. Just return a bad request with no information
// to avoid exposure. The request should not proceed. // 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) w.WriteHeader(http.StatusBadRequest)
} }
return err return err
} }
dcontext.GetLogger(ctx).Info("authorized request")
// TODO(stevvooe): This pattern needs to be cleaned up a bit. One context // 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 // should be replaced by another, rather than replacing the context on a
// mutable object. // mutable object.
@ -851,7 +852,7 @@ func (app *App) eventBridge(ctx *Context, r *http.Request) notifications.Listene
actor := notifications.ActorRecord{ actor := notifications.ActorRecord{
Name: getUserName(ctx, r), 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) 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 // startUploadPurger schedules a goroutine which will periodically
// check upload directories for old files and delete them // 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 { if config["enabled"] == false {
return return
} }

View file

@ -6,7 +6,7 @@ import (
"net/url" "net/url"
"github.com/docker/distribution" "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/reference"
"github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/errcode"
"github.com/docker/distribution/registry/api/v2" "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")) state, err := hmacKey(ctx.Config.HTTP.Secret).unpackUploadState(r.FormValue("_state"))
if err != nil { if err != nil {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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)) 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() { if state.Name != ctx.Repository.Named().Name() {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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)) buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err))
}) })
} }
if state.UUID != buh.UUID { if state.UUID != buh.UUID {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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)) 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) blobs := ctx.Repository.Blobs(buh)
upload, err := blobs.Resume(buh, buh.UUID) upload, err := blobs.Resume(buh, buh.UUID)
if err != nil { 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 { if err == distribution.ErrBlobUploadUnknown {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown.WithDetail(err)) 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 { if size := upload.Size(); size != buh.State.Offset {
defer upload.Close() 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) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err))
upload.Cancel(buh) 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 // 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())) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error()))
return return
} }
@ -218,7 +218,7 @@ func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *ht
return 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())) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error()))
return return
} }
@ -246,7 +246,7 @@ func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *ht
case distribution.ErrBlobInvalidLength, distribution.ErrBlobDigestUnsupported: case distribution.ErrBlobInvalidLength, distribution.ErrBlobDigestUnsupported:
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err))
default: 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)) 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. // Clean up the backend blob data if there was an error.
if err := buh.Upload.Cancel(buh); err != nil { if err := buh.Upload.Cancel(buh); err != nil {
// If the cleanup fails, all we can do is observe and report. // 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 return
@ -275,7 +275,7 @@ func (buh *blobUploadHandler) CancelBlobUpload(w http.ResponseWriter, r *http.Re
w.Header().Set("Docker-Upload-UUID", buh.UUID) w.Header().Set("Docker-Upload-UUID", buh.UUID)
if err := buh.Upload.Cancel(buh); err != nil { 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)) 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) token, err := hmacKey(buh.Config.HTTP.Secret).packUploadState(buh.State)
if err != nil { 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 return err
} }
@ -307,7 +307,7 @@ func (buh *blobUploadHandler) blobUploadResponse(w http.ResponseWriter, r *http.
"_state": []string{token}, "_state": []string{token},
}) })
if err != nil { 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 return err
} }

View file

@ -5,7 +5,7 @@ import (
"net/http" "net/http"
"github.com/docker/distribution" "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/errcode"
"github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/api/v2"
"github.com/docker/distribution/registry/auth" "github.com/docker/distribution/registry/auth"
@ -44,26 +44,26 @@ func (ctx *Context) Value(key interface{}) interface{} {
} }
func getName(ctx context.Context) (name string) { 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) { 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") var errDigestNotAvailable = fmt.Errorf("digest not available in context")
func getDigest(ctx context.Context) (dgst digest.Digest, err error) { func getDigest(ctx context.Context) (dgst digest.Digest, err error) {
dgstStr := ctxu.GetStringValue(ctx, "vars.digest") dgstStr := dcontext.GetStringValue(ctx, "vars.digest")
if dgstStr == "" { if dgstStr == "" {
ctxu.GetLogger(ctx).Errorf("digest not available") dcontext.GetLogger(ctx).Errorf("digest not available")
return "", errDigestNotAvailable return "", errDigestNotAvailable
} }
d, err := digest.Parse(dgstStr) d, err := digest.Parse(dgstStr)
if err != nil { 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 return "", err
} }
@ -71,13 +71,13 @@ func getDigest(ctx context.Context) (dgst digest.Digest, err error) {
} }
func getUploadUUID(ctx context.Context) (uuid string) { 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 // getUserName attempts to resolve a username from the context and request. If
// a username cannot be resolved, the empty string is returned. // a username cannot be resolved, the empty string is returned.
func getUserName(ctx context.Context, r *http.Request) string { 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 // Fallback to request user with basic auth
if username == "" { if username == "" {

View file

@ -1,11 +1,12 @@
package handlers package handlers
import ( import (
"context"
"errors" "errors"
"io" "io"
"net/http" "net/http"
ctxu "github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
) )
// closeResources closes all the provided resources after running the target // 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. // 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. // 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 // Get a channel that tells us if the client disconnects
var clientClosed <-chan bool var clientClosed <-chan bool
if notifier, ok := responseWriter.(http.CloseNotifier); ok { if notifier, ok := responseWriter.(http.CloseNotifier); ok {
clientClosed = notifier.CloseNotify() clientClosed = notifier.CloseNotify()
} else { } 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 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. // instead of showing 0 for the HTTP status.
responseWriter.WriteHeader(499) responseWriter.WriteHeader(499)
ctxu.GetLoggerWithFields(context, map[interface{}]interface{}{ dcontext.GetLoggerWithFields(ctx, map[interface{}]interface{}{
"error": err, "error": err,
"copied": copied, "copied": copied,
"contentLength": r.ContentLength, "contentLength": r.ContentLength,
@ -63,7 +64,7 @@ func copyFullPayload(responseWriter http.ResponseWriter, r *http.Request, destWr
} }
if err != nil { 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 return err
} }

View file

@ -7,7 +7,7 @@ import (
"strings" "strings"
"github.com/docker/distribution" "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/manifestlist"
"github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema1"
"github.com/docker/distribution/manifest/schema2" "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. // GetManifest fetches the image manifest from the storage backend, if it exists.
func (imh *manifestHandler) GetManifest(w http.ResponseWriter, r *http.Request) { 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) manifests, err := imh.Repository.Manifests(imh)
if err != nil { if err != nil {
imh.Errors = append(imh.Errors, err) imh.Errors = append(imh.Errors, err)
@ -143,7 +143,7 @@ func (imh *manifestHandler) GetManifest(w http.ResponseWriter, r *http.Request)
// matching the digest. // matching the digest.
if imh.Tag != "" && isSchema2 && !supportsSchema2 { if imh.Tag != "" && isSchema2 && !supportsSchema2 {
// Rewrite manifest in schema1 format // 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) manifest, err = imh.convertSchema2Manifest(schema2Manifest)
if err != nil { if err != nil {
@ -151,7 +151,7 @@ func (imh *manifestHandler) GetManifest(w http.ResponseWriter, r *http.Request)
} }
} else if imh.Tag != "" && isManifestList && !supportsManifestList { } else if imh.Tag != "" && isManifestList && !supportsManifestList {
// Rewrite manifest in schema1 format // 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 // Find the image manifest corresponding to the default
// platform // platform
@ -252,7 +252,7 @@ func etagMatch(r *http.Request, etag string) bool {
// PutManifest validates and stores a manifest in the registry. // PutManifest validates and stores a manifest in the registry.
func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request) { 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) manifests, err := imh.Repository.Manifests(imh)
if err != nil { if err != nil {
imh.Errors = append(imh.Errors, err) imh.Errors = append(imh.Errors, err)
@ -260,7 +260,7 @@ func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request)
} }
var jsonBuf bytes.Buffer 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 // copyFullPayload reports the error if necessary
imh.Errors = append(imh.Errors, v2.ErrorCodeManifestInvalid.WithDetail(err.Error())) imh.Errors = append(imh.Errors, v2.ErrorCodeManifestInvalid.WithDetail(err.Error()))
return return
@ -275,7 +275,7 @@ func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request)
if imh.Digest != "" { if imh.Digest != "" {
if desc.Digest != 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) imh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid)
return 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 // NOTE(stevvooe): Given the behavior above, this absurdly unlikely to
// happen. We'll log the error here but proceed as if it worked. Worst // happen. We'll log the error here but proceed as if it worked. Worst
// case, we set an empty location header. // 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) 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. // DeleteManifest removes the manifest with the given digest from the registry.
func (imh *manifestHandler) DeleteManifest(w http.ResponseWriter, r *http.Request) { 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) manifests, err := imh.Repository.Manifests(imh)
if err != nil { if err != nil {

View file

@ -1,10 +1,10 @@
package middleware package middleware
import ( import (
"context"
"fmt" "fmt"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage" "github.com/docker/distribution/registry/storage"
) )

View file

@ -1,10 +1,10 @@
package middleware package middleware
import ( import (
"context"
"fmt" "fmt"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
) )
// InitFunc is the type of a RepositoryMiddleware factory function and is // InitFunc is the type of a RepositoryMiddleware factory function and is

View file

@ -1,6 +1,7 @@
package proxy package proxy
import ( import (
"context"
"io" "io"
"net/http" "net/http"
"strconv" "strconv"
@ -8,7 +9,7 @@ import (
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/proxy/scheduler" "github.com/docker/distribution/registry/proxy/scheduler"
"github.com/opencontainers/go-digest" "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 { 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) served, err := pbs.serveLocal(ctx, w, r, dgst)
if err != nil { 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 return err
} }
@ -140,12 +141,12 @@ func (pbs *proxyBlobStore) ServeBlob(ctx context.Context, w http.ResponseWriter,
go func(dgst digest.Digest) { go func(dgst digest.Digest) {
if err := pbs.storeLocal(ctx, dgst); err != nil { 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) blobRef, err := reference.WithDigest(pbs.repositoryName, dgst)
if err != nil { if err != nil {
context.GetLogger(ctx).Errorf("Error creating reference: %s", err) dcontext.GetLogger(ctx).Errorf("Error creating reference: %s", err)
return return
} }

View file

@ -1,6 +1,7 @@
package proxy package proxy
import ( import (
"context"
"io/ioutil" "io/ioutil"
"math/rand" "math/rand"
"net/http" "net/http"
@ -10,7 +11,6 @@ import (
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/proxy/scheduler" "github.com/docker/distribution/registry/proxy/scheduler"
"github.com/docker/distribution/registry/storage" "github.com/docker/distribution/registry/storage"

View file

@ -1,10 +1,11 @@
package proxy package proxy
import ( import (
"context"
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/proxy/scheduler" "github.com/docker/distribution/registry/proxy/scheduler"
"github.com/opencontainers/go-digest" "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 // Schedule the manifest blob for removal
repoBlob, err := reference.WithDigest(pms.repositoryName, dgst) repoBlob, err := reference.WithDigest(pms.repositoryName, dgst)
if err != nil { if err != nil {
context.GetLogger(ctx).Errorf("Error creating reference: %s", err) dcontext.GetLogger(ctx).Errorf("Error creating reference: %s", err)
return nil, err return nil, err
} }

View file

@ -1,12 +1,12 @@
package proxy package proxy
import ( import (
"context"
"io" "io"
"sync" "sync"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest"
"github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema1"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"

View file

@ -1,6 +1,7 @@
package proxy package proxy
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
@ -8,7 +9,7 @@ import (
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/configuration" "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/reference"
"github.com/docker/distribution/registry/client" "github.com/docker/distribution/registry/client"
"github.com/docker/distribution/registry/client/auth" "github.com/docker/distribution/registry/client/auth"
@ -218,7 +219,7 @@ func (r *remoteAuthChallenger) tryEstablishChallenges(ctx context.Context) error
return err 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 return nil
} }

View file

@ -1,8 +1,9 @@
package proxy package proxy
import ( import (
"context"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
) )
// proxyTagService supports local and remote lookup of tags. // proxyTagService supports local and remote lookup of tags.

View file

@ -1,13 +1,13 @@
package proxy package proxy
import ( import (
"context"
"reflect" "reflect"
"sort" "sort"
"sync" "sync"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
) )
type mockTagStore struct { type mockTagStore struct {

View file

@ -1,12 +1,13 @@
package scheduler package scheduler
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"sync" "sync"
"time" "time"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
) )
@ -120,7 +121,7 @@ func (ttles *TTLExpirationScheduler) Start() error {
return fmt.Errorf("Scheduler already started") 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 ttles.stopped = false
// Start timer for each deserialized entry // Start timer for each deserialized entry
@ -142,7 +143,7 @@ func (ttles *TTLExpirationScheduler) Start() error {
err := ttles.writeState() err := ttles.writeState()
if err != nil { 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 { } else {
ttles.indexDirty = false ttles.indexDirty = false
} }
@ -163,7 +164,7 @@ func (ttles *TTLExpirationScheduler) add(r reference.Reference, ttl time.Duratio
Expiry: time.Now().Add(ttl), Expiry: time.Now().Add(ttl),
EntryType: eType, 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 { if oldEntry, present := ttles.entries[entry.Key]; present && oldEntry.timer != nil {
oldEntry.timer.Stop() oldEntry.timer.Stop()
} }
@ -193,10 +194,10 @@ func (ttles *TTLExpirationScheduler) startTimer(entry *schedulerEntry, ttl time.
ref, err := reference.Parse(entry.Key) ref, err := reference.Parse(entry.Key)
if err == nil { if err == nil {
if err := f(ref); 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 { } 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) delete(ttles.entries, entry.Key)
@ -210,7 +211,7 @@ func (ttles *TTLExpirationScheduler) Stop() {
defer ttles.Unlock() defer ttles.Unlock()
if err := ttles.writeState(); err != nil { 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 { for _, entry := range ttles.entries {

View file

@ -1,6 +1,7 @@
package registry package registry
import ( import (
"context"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
@ -14,7 +15,7 @@ import (
logstash "github.com/bshuster-repo/logrus-logstash-hook" logstash "github.com/bshuster-repo/logrus-logstash-hook"
"github.com/bugsnag/bugsnag-go" "github.com/bugsnag/bugsnag-go"
"github.com/docker/distribution/configuration" "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/health"
"github.com/docker/distribution/registry/handlers" "github.com/docker/distribution/registry/handlers"
"github.com/docker/distribution/registry/listener" "github.com/docker/distribution/registry/listener"
@ -34,7 +35,7 @@ var ServeCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
// setup context // setup context
ctx := context.WithVersion(context.Background(), version.Version) ctx := dcontext.WithVersion(dcontext.Background(), version.Version)
config, err := resolveConfiguration(args) config, err := resolveConfiguration(args)
if err != nil { 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 // inject a logger into the uuid library. warns us if there is a problem
// with uuid generation under low entropy. // with uuid generation under low entropy.
uuid.Loggerf = context.GetLogger(ctx).Warnf uuid.Loggerf = dcontext.GetLogger(ctx).Warnf
app := handlers.NewApp(ctx, config) app := handlers.NewApp(ctx, config)
// TODO(aaronl): The global scope of the health checks means NewRegistry // 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() { 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 tlsConf.ClientAuth = tls.RequireAndVerifyClientCert
@ -178,9 +179,9 @@ func (registry *Registry) ListenAndServe() error {
} }
ln = tls.NewListener(ln, tlsConf) 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 { } 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) 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 config.Log.Level == "" && config.Log.Formatter == "" {
// If no config for logging is set, fallback to deprecated "Loglevel". // If no config for logging is set, fallback to deprecated "Loglevel".
log.SetLevel(logLevel(config.Loglevel)) log.SetLevel(logLevel(config.Loglevel))
ctx = context.WithLogger(ctx, context.GetLogger(ctx)) ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx))
return ctx, nil return ctx, nil
} }
@ -270,8 +271,8 @@ func configureLogging(ctx context.Context, config *configuration.Configuration)
fields = append(fields, k) fields = append(fields, k)
} }
ctx = context.WithValues(ctx, config.Log.Fields) ctx = dcontext.WithValues(ctx, config.Log.Fields)
ctx = context.WithLogger(ctx, context.GetLogger(ctx, fields...)) ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, fields...))
} }
return ctx, nil return ctx, nil

View file

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage" "github.com/docker/distribution/registry/storage"
"github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/factory"
"github.com/docker/distribution/version" "github.com/docker/distribution/version"
@ -56,7 +56,7 @@ var GCCmd = &cobra.Command{
os.Exit(1) os.Exit(1)
} }
ctx := context.Background() ctx := dcontext.Background()
ctx, err = configureLogging(ctx, config) ctx, err = configureLogging(ctx, config)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "unable to configure logging with config: %s", err) fmt.Fprintf(os.Stderr, "unable to configure logging with config: %s", err)

View file

@ -2,6 +2,7 @@ package storage
import ( import (
"bytes" "bytes"
"context"
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
"io" "io"
@ -12,7 +13,6 @@ import (
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/cache/memory" "github.com/docker/distribution/registry/storage/cache/memory"
"github.com/docker/distribution/registry/storage/driver/testdriver" "github.com/docker/distribution/registry/storage/driver/testdriver"

View file

@ -1,12 +1,12 @@
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )

View file

@ -1,10 +1,11 @@
package storage package storage
import ( import (
"context"
"path" "path"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )
@ -64,7 +65,7 @@ func (bs *blobStore) Put(ctx context.Context, mediaType string, p []byte) (distr
// content already present // content already present
return desc, nil return desc, nil
} else if err != distribution.ErrBlobUnknown { } 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 // real error, return it
return distribution.Descriptor{}, err 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 // NOTE(stevvooe): This represents a corruption situation. Somehow, we
// calculated a blob path and then detected a directory. We log the // 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. // 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 return distribution.Descriptor{}, distribution.ErrBlobUnknown
} }

View file

@ -1,6 +1,7 @@
package storage package storage
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -8,7 +9,7 @@ import (
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus" "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 // Commit marks the upload as completed, returning a valid descriptor. The
// final size and digest are checked against the first descriptor provided. // final size and digest are checked against the first descriptor provided.
func (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) { 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 { if err := bw.fileWriter.Commit(); err != nil {
return distribution.Descriptor{}, err 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 // Cancel the blob upload process, releasing any resources associated with
// the writer and canceling the operation. // the writer and canceling the operation.
func (bw *blobWriter) Cancel(ctx context.Context) error { 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 { if err := bw.fileWriter.Cancel(); err != nil {
return err return err
} }
if err := bw.Close(); err != nil { 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 { if err := bw.removeResources(ctx); err != nil {
@ -261,7 +262,7 @@ func (bw *blobWriter) validateBlob(ctx context.Context, desc distribution.Descri
} }
if !verified { if !verified {
context.GetLoggerWithFields(ctx, dcontext.GetLoggerWithFields(ctx,
map[interface{}]interface{}{ map[interface{}]interface{}{
"canonical": canonical, "canonical": canonical,
"provided": desc.Digest, "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 // This should be uncommon enough such that returning an error
// should be okay. At this point, the upload should be mostly // should be okay. At this point, the upload should be mostly
// complete, but perhaps the backend became unaccessible. // 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 return err
} }
} }
@ -383,7 +384,7 @@ func (bw *blobWriter) Reader() (io.ReadCloser, error) {
} }
switch err.(type) { switch err.(type) {
case storagedriver.PathNotFoundError: 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) time.Sleep(1 * time.Second)
try++ try++
default: default:

View file

@ -3,11 +3,11 @@
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"path" "path"
"strconv" "strconv"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/stevvooe/resumable" "github.com/stevvooe/resumable"

View file

@ -1,11 +1,11 @@
package cachecheck package cachecheck
import ( import (
"context"
"reflect" "reflect"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/cache" "github.com/docker/distribution/registry/storage/cache"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )

View file

@ -1,10 +1,11 @@
package cache package cache
import ( import (
"github.com/docker/distribution/context" "context"
"github.com/opencontainers/go-digest"
"github.com/docker/distribution" "github.com/docker/distribution"
dcontext "github.com/docker/distribution/context"
"github.com/opencontainers/go-digest"
) )
// Metrics is used to hold metric counters // 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) desc, err := cbds.cache.Stat(ctx, dgst)
if err != nil { if err != nil {
if err != distribution.ErrBlobUnknown { 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 goto fallback
@ -73,7 +74,7 @@ fallback:
} }
if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { 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 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 { func (cbds *cachedBlobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { 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 return nil
} }

View file

@ -1,10 +1,10 @@
package memory package memory
import ( import (
"context"
"sync" "sync"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/cache" "github.com/docker/distribution/registry/storage/cache"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"

View file

@ -1,10 +1,10 @@
package redis package redis
import ( import (
"context"
"fmt" "fmt"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/cache" "github.com/docker/distribution/registry/storage/cache"
"github.com/garyburd/redigo/redis" "github.com/garyburd/redigo/redis"

View file

@ -1,12 +1,12 @@
package storage package storage
import ( import (
"context"
"errors" "errors"
"io" "io"
"path" "path"
"strings" "strings"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
) )

View file

@ -1,13 +1,13 @@
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"math/rand" "math/rand"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/cache/memory" "github.com/docker/distribution/registry/storage/cache/memory"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"

View file

@ -5,6 +5,7 @@ package azure
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -12,7 +13,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/base"
"github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/factory"

View file

@ -38,9 +38,10 @@
package base package base
import ( import (
"context"
"io" "io"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" 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. // GetContent wraps GetContent of underlying storage driver.
func (base *Base) GetContent(ctx context.Context, path string) ([]byte, error) { 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) defer done("%s.GetContent(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(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. // PutContent wraps PutContent of underlying storage driver.
func (base *Base) PutContent(ctx context.Context, path string, content []byte) error { 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) defer done("%s.PutContent(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(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. // Reader wraps Reader of underlying storage driver.
func (base *Base) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) { 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) defer done("%s.Reader(%q, %d)", base.Name(), path, offset)
if offset < 0 { 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. // Writer wraps Writer of underlying storage driver.
func (base *Base) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) { 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) defer done("%s.Writer(%q, %v)", base.Name(), path, append)
if !storagedriver.PathRegexp.MatchString(path) { 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. // Stat wraps Stat of underlying storage driver.
func (base *Base) Stat(ctx context.Context, path string) (storagedriver.FileInfo, error) { 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) defer done("%s.Stat(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(path) && 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. // List wraps List of underlying storage driver.
func (base *Base) List(ctx context.Context, path string) ([]string, error) { 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) defer done("%s.List(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(path) && 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. // Move wraps Move of underlying storage driver.
func (base *Base) Move(ctx context.Context, sourcePath string, destPath string) error { 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) defer done("%s.Move(%q, %q", base.Name(), sourcePath, destPath)
if !storagedriver.PathRegexp.MatchString(sourcePath) { 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. // Delete wraps Delete of underlying storage driver.
func (base *Base) Delete(ctx context.Context, path string) error { 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) defer done("%s.Delete(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(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. // URLFor wraps URLFor of underlying storage driver.
func (base *Base) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) { 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) defer done("%s.URLFor(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(path) { if !storagedriver.PathRegexp.MatchString(path) {

View file

@ -1,10 +1,10 @@
package base package base
import ( import (
"context"
"io" "io"
"sync" "sync"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
) )

View file

@ -3,6 +3,7 @@ package filesystem
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -12,7 +13,6 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/base"
"github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/factory"

View file

@ -16,6 +16,7 @@ package gcs
import ( import (
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -29,20 +30,16 @@ import (
"strings" "strings"
"time" "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"
"golang.org/x/oauth2/google" "golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt" "golang.org/x/oauth2/jwt"
"google.golang.org/api/googleapi" "google.golang.org/api/googleapi"
"google.golang.org/cloud" "google.golang.org/cloud"
"google.golang.org/cloud/storage" "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 ( const (
@ -194,7 +191,7 @@ func (d *driver) Name() string {
// GetContent retrieves the content stored at "path" as a []byte. // GetContent retrieves the content stored at "path" as a []byte.
// This should primarily be used for small objects. // 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) gcsContext := d.context(context)
name := d.pathToKey(path) name := d.pathToKey(path)
var rc io.ReadCloser 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". // PutContent stores the []byte content at a location designated by "path".
// This should primarily be used for small objects. // 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 { return retry(func() error {
wc := storage.NewWriter(d.context(context), d.bucket, d.pathToKey(path)) wc := storage.NewWriter(d.context(context), d.bucket, d.pathToKey(path))
wc.ContentType = "application/octet-stream" 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" // Reader retrieves an io.ReadCloser for the content stored at "path"
// with a given byte offset. // with a given byte offset.
// May be used to resume reading a stream by providing a nonzero 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) res, err := getObject(d.client, d.bucket, d.pathToKey(path), offset)
if err != nil { if err != nil {
if res != 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 // Writer returns a FileWriter which will store the content written to it
// at the location designated by "path" after the call to Commit. // 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{ writer := &writer{
client: d.client, client: d.client,
bucket: d.bucket, bucket: d.bucket,
@ -542,7 +539,7 @@ func retry(req request) error {
// Stat retrieves the FileInfo for the given path, including the current // Stat retrieves the FileInfo for the given path, including the current
// size in bytes and the creation time. // 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 var fi storagedriver.FileInfoFields
//try to get as file //try to get as file
gcsContext := d.context(context) 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 // List returns a list of the objects that are direct descendants of the
//given path. //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 var query *storage.Query
query = &storage.Query{} query = &storage.Query{}
query.Delimiter = "/" 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 // Move moves an object stored at sourcePath to destPath, removing the
// original object. // 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) gcsContext := d.context(context)
_, err := storageCopyObject(gcsContext, d.bucket, d.pathToKey(sourcePath), d.bucket, d.pathToKey(destPath), nil) _, err := storageCopyObject(gcsContext, d.bucket, d.pathToKey(sourcePath), d.bucket, d.pathToKey(destPath), nil)
if err != 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. // 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) prefix := d.pathToDirKey(path)
gcsContext := d.context(context) gcsContext := d.context(context)
keys, err := d.listAll(gcsContext, prefix) 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 // URLFor returns a URL which may be used to retrieve the content stored at
// the given path, possibly using the given options. // the given path, possibly using the given options.
// Returns ErrUnsupportedMethod if this driver has no privateKey // 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 { if d.privateKey == nil {
return "", storagedriver.ErrUnsupportedMethod{} return "", storagedriver.ErrUnsupportedMethod{}
} }
@ -856,7 +853,7 @@ func putChunk(client *http.Client, sessionURI string, chunk []byte, from int64,
return bytesPut, err 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) return cloud.WithContext(context, dummyProjectID, d.client)
} }

View file

@ -3,12 +3,12 @@
package gcs package gcs
import ( import (
"fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"testing" "testing"
"fmt" dcontext "github.com/docker/distribution/context"
ctx "github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/testsuites" "github.com/docker/distribution/registry/storage/driver/testsuites"
"golang.org/x/oauth2" "golang.org/x/oauth2"
@ -49,7 +49,7 @@ func init() {
var email string var email string
var privateKey []byte var privateKey []byte
ts, err = google.DefaultTokenSource(ctx.Background(), storage.ScopeFullControl) ts, err = google.DefaultTokenSource(dcontext.Background(), storage.ScopeFullControl)
if err != nil { if err != nil {
// Assume that the file contents are within the environment variable since it exists // Assume that the file contents are within the environment variable since it exists
// but does not contain a valid file path // but does not contain a valid file path
@ -65,7 +65,7 @@ func init() {
if email == "" { if email == "" {
panic("Error reading JWT config : missing client_email property") 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) { gcsDriverConstructor = func(rootDirectory string) (storagedriver.StorageDriver, error) {
@ -74,7 +74,7 @@ func init() {
rootDirectory: root, rootDirectory: root,
email: email, email: email,
privateKey: privateKey, privateKey: privateKey,
client: oauth2.NewClient(ctx.Background(), ts), client: oauth2.NewClient(dcontext.Background(), ts),
chunkSize: defaultChunkSize, chunkSize: defaultChunkSize,
} }
@ -104,7 +104,7 @@ func TestCommitEmpty(t *testing.T) {
} }
filename := "/test" filename := "/test"
ctx := ctx.Background() ctx := dcontext.Background()
writer, err := driver.Writer(ctx, filename, false) writer, err := driver.Writer(ctx, filename, false)
defer driver.Delete(ctx, filename) defer driver.Delete(ctx, filename)
@ -150,7 +150,7 @@ func TestCommit(t *testing.T) {
} }
filename := "/test" filename := "/test"
ctx := ctx.Background() ctx := dcontext.Background()
contents := make([]byte, defaultChunkSize) contents := make([]byte, defaultChunkSize)
writer, err := driver.Writer(ctx, filename, false) writer, err := driver.Writer(ctx, filename, false)
@ -247,7 +247,7 @@ func TestEmptyRootList(t *testing.T) {
filename := "/test" filename := "/test"
contents := []byte("contents") contents := []byte("contents")
ctx := ctx.Background() ctx := dcontext.Background()
err = rootedDriver.PutContent(ctx, filename, contents) err = rootedDriver.PutContent(ctx, filename, contents)
if err != nil { if err != nil {
t.Fatalf("unexpected error creating content: %v", err) 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) t.Fatalf("unexpected error creating rooted driver: %v", err)
} }
ctx := ctx.Background() ctx := dcontext.Background()
contents := []byte("contents") contents := []byte("contents")
// Create a regular file. // Create a regular file.
err = driver.PutContent(ctx, "/parent/dir/foo", contents) err = driver.PutContent(ctx, "/parent/dir/foo", contents)

View file

@ -1,13 +1,13 @@
package inmemory package inmemory
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"sync" "sync"
"time" "time"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/base"
"github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/factory"

View file

@ -4,6 +4,7 @@
package middleware package middleware
import ( import (
"context"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
@ -13,7 +14,7 @@ import (
"time" "time"
"github.com/aws/aws-sdk-go/service/cloudfront/sign" "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" storagedriver "github.com/docker/distribution/registry/storage/driver"
storagemiddleware "github.com/docker/distribution/registry/storage/driver/middleware" 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 // TODO(endophage): currently only supports S3
keyer, ok := lh.StorageDriver.(S3BucketKeyer) keyer, ok := lh.StorageDriver.(S3BucketKeyer)
if !ok { 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) return lh.StorageDriver.URLFor(ctx, path, options)
} }

View file

@ -1,10 +1,10 @@
package middleware package middleware
import ( import (
"context"
"fmt" "fmt"
"net/url" "net/url"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
storagemiddleware "github.com/docker/distribution/registry/storage/driver/middleware" storagemiddleware "github.com/docker/distribution/registry/storage/driver/middleware"
) )

View file

@ -13,6 +13,7 @@ package oss
import ( import (
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -22,8 +23,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/distribution/context"
"github.com/denverdino/aliyungo/oss" "github.com/denverdino/aliyungo/oss"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/base"

View file

@ -4,16 +4,14 @@ package oss
import ( import (
"io/ioutil" "io/ioutil"
"os"
"strconv"
"testing"
alioss "github.com/denverdino/aliyungo/oss" alioss "github.com/denverdino/aliyungo/oss"
"github.com/docker/distribution/context" "github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/testsuites" "github.com/docker/distribution/registry/storage/driver/testsuites"
//"log"
"os"
"strconv"
"testing"
"gopkg.in/check.v1" "gopkg.in/check.v1"
) )

View file

@ -13,6 +13,7 @@ package s3
import ( import (
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -33,7 +34,6 @@ import (
"github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/client/transport" "github.com/docker/distribution/registry/client/transport"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/base"

View file

@ -14,6 +14,7 @@ package s3
import ( import (
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -23,14 +24,12 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/goamz/aws"
"github.com/docker/goamz/s3"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/client/transport" "github.com/docker/distribution/registry/client/transport"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/base"
"github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/factory"
"github.com/docker/goamz/aws"
"github.com/docker/goamz/s3"
) )
const driverName = "s3goamz" const driverName = "s3goamz"

View file

@ -1,13 +1,12 @@
package driver package driver
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"github.com/docker/distribution/context"
) )
// Version is a string representing the storage driver version, of the form // Version is a string representing the storage driver version, of the form

View file

@ -18,6 +18,7 @@ package swift
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"crypto/rand" "crypto/rand"
"crypto/sha1" "crypto/sha1"
"crypto/tls" "crypto/tls"
@ -34,7 +35,6 @@ import (
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
"github.com/ncw/swift" "github.com/ncw/swift"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/base" "github.com/docker/distribution/registry/storage/driver/base"
"github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/factory"

View file

@ -1,7 +1,8 @@
package testdriver package testdriver
import ( import (
"github.com/docker/distribution/context" "context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/factory" "github.com/docker/distribution/registry/storage/driver/factory"
"github.com/docker/distribution/registry/storage/driver/inmemory" "github.com/docker/distribution/registry/storage/driver/inmemory"

View file

@ -2,6 +2,7 @@ package testsuites
import ( import (
"bytes" "bytes"
"context"
"crypto/sha1" "crypto/sha1"
"io" "io"
"io/ioutil" "io/ioutil"
@ -15,10 +16,8 @@ import (
"testing" "testing"
"time" "time"
"gopkg.in/check.v1"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"gopkg.in/check.v1"
) )
// Test hooks up gocheck into the "go test" runner. // Test hooks up gocheck into the "go test" runner.

View file

@ -3,12 +3,12 @@ package storage
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
) )

View file

@ -1,10 +1,10 @@
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"

View file

@ -1,11 +1,11 @@
package storage package storage
import ( import (
"context"
"errors" "errors"
"io" "io"
"io/ioutil" "io/ioutil"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
) )

View file

@ -1,13 +1,14 @@
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"path" "path"
"time" "time"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/uuid" "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. // Place the data in the blob store first.
desc, err := lbs.blobStore.Put(ctx, mediaType, p) desc, err := lbs.blobStore.Put(ctx, mediaType, p)
if err != nil { 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 return distribution.Descriptor{}, err
} }
@ -125,7 +126,7 @@ func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption {
// Writer begins a blob write session, returning a handle. // Writer begins a blob write session, returning a handle.
func (lbs *linkedBlobStore) Create(ctx context.Context, options ...distribution.BlobCreateOption) (distribution.BlobWriter, error) { 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 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) { 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{ startedAtPath, err := pathFor(uploadStartedAtPathSpec{
name: lbs.repository.Named().Name(), name: lbs.repository.Named().Name(),
@ -411,7 +412,7 @@ func (lbs *linkedBlobStatter) Stat(ctx context.Context, dgst digest.Digest) (dis
if target != dgst { if target != dgst {
// Track when we are doing cross-digest domain lookups. ie, sha512 to sha256. // 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 // TODO(stevvooe): Look up repository local mediatype and replace that on

View file

@ -1,6 +1,7 @@
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"reflect" "reflect"
@ -8,11 +9,9 @@ import (
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/opencontainers/go-digest"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/testutil" "github.com/docker/distribution/testutil"
"github.com/opencontainers/go-digest"
) )
func TestLinkedBlobStoreCreateWithMountFrom(t *testing.T) { func TestLinkedBlobStoreCreateWithMountFrom(t *testing.T) {

View file

@ -1,11 +1,12 @@
package storage package storage
import ( import (
"context"
"encoding/json"
"fmt" "fmt"
"encoding/json"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/manifestlist"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )
@ -20,7 +21,7 @@ type manifestListHandler struct {
var _ ManifestHandler = &manifestListHandler{} var _ ManifestHandler = &manifestListHandler{}
func (ms *manifestListHandler) Unmarshal(ctx context.Context, dgst digest.Digest, content []byte) (distribution.Manifest, error) { 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 var m manifestlist.DeserializedManifestList
if err := json.Unmarshal(content, &m); err != nil { 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) { 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) m, ok := manifestList.(*manifestlist.DeserializedManifestList)
if !ok { if !ok {
@ -49,7 +50,7 @@ func (ms *manifestListHandler) Put(ctx context.Context, manifestList distributio
revision, err := ms.blobStore.Put(ctx, mt, payload) revision, err := ms.blobStore.Put(ctx, mt, payload)
if err != nil { 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 return "", err
} }

View file

@ -1,11 +1,12 @@
package storage package storage
import ( import (
"context"
"encoding/json"
"fmt" "fmt"
"encoding/json"
"github.com/docker/distribution" "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"
"github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/manifestlist"
"github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema1"
@ -53,7 +54,7 @@ type manifestStore struct {
var _ distribution.ManifestService = &manifestStore{} var _ distribution.ManifestService = &manifestStore{}
func (ms *manifestStore) Exists(ctx context.Context, dgst digest.Digest) (bool, error) { 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) _, err := ms.blobStore.Stat(ms.ctx, dgst)
if err != nil { 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) { 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 // TODO(stevvooe): Need to check descriptor from above to ensure that the
// mediatype is as we expect for the manifest store. // 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) { 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) { switch manifest.(type) {
case *schema1.SignedManifest: 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. // Delete removes the revision of the specified manifest.
func (ms *manifestStore) Delete(ctx context.Context, dgst digest.Digest) error { 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) return ms.blobStore.Delete(ctx, dgst)
} }

View file

@ -2,12 +2,12 @@ package storage
import ( import (
"bytes" "bytes"
"context"
"io" "io"
"reflect" "reflect"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest"
"github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema1"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"

View file

@ -1,14 +1,14 @@
package storage package storage
import ( import (
"context"
"path" "path"
"strings" "strings"
"time" "time"
"github.com/docker/distribution/context"
storageDriver "github.com/docker/distribution/registry/storage/driver" storageDriver "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/uuid" "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 // 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 // created before olderThan. The list of files deleted and errors
// encountered are returned // encountered are returned
func PurgeUploads(ctx context.Context, driver storageDriver.StorageDriver, olderThan time.Time, actuallyDelete bool) ([]string, []error) { 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) uploadData, errors := getOutstandingUploads(ctx, driver)
var deleted []string var deleted []string
for _, uploadData := range uploadData { for _, uploadData := range uploadData {
if uploadData.startedAt.Before(olderThan) { if uploadData.startedAt.Before(olderThan) {
var err error 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) uploadData.containingDir, uploadData.startedAt, olderThan)
if actuallyDelete { if actuallyDelete {
err = driver.Delete(ctx, uploadData.containingDir) 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 return deleted, errors
} }

View file

@ -1,12 +1,12 @@
package storage package storage
import ( import (
"context"
"path" "path"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/inmemory" "github.com/docker/distribution/registry/storage/driver/inmemory"
"github.com/docker/distribution/uuid" "github.com/docker/distribution/uuid"

View file

@ -1,10 +1,10 @@
package storage package storage
import ( import (
"context"
"regexp" "regexp"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/cache" "github.com/docker/distribution/registry/storage/cache"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"

View file

@ -1,13 +1,14 @@
package storage package storage
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"net/url" "net/url"
"github.com/docker/distribution" "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/schema1"
"github.com/docker/distribution/manifest/schema2" "github.com/docker/distribution/manifest/schema2"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
@ -30,7 +31,7 @@ type schema2ManifestHandler struct {
var _ ManifestHandler = &schema2ManifestHandler{} var _ ManifestHandler = &schema2ManifestHandler{}
func (ms *schema2ManifestHandler) Unmarshal(ctx context.Context, dgst digest.Digest, content []byte) (distribution.Manifest, error) { 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 var m schema2.DeserializedManifest
if err := json.Unmarshal(content, &m); err != nil { 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) { 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) m, ok := manifest.(*schema2.DeserializedManifest)
if !ok { if !ok {
@ -59,7 +60,7 @@ func (ms *schema2ManifestHandler) Put(ctx context.Context, manifest distribution
revision, err := ms.blobStore.Put(ctx, mt, payload) revision, err := ms.blobStore.Put(ctx, mt, payload)
if err != nil { 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 return "", err
} }

View file

@ -1,11 +1,12 @@
package storage package storage
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/docker/distribution" "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/schema1"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/libtrust" "github.com/docker/libtrust"
@ -24,7 +25,7 @@ type signedManifestHandler struct {
var _ ManifestHandler = &signedManifestHandler{} var _ ManifestHandler = &signedManifestHandler{}
func (ms *signedManifestHandler) Unmarshal(ctx context.Context, dgst digest.Digest, content []byte) (distribution.Manifest, error) { 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 ( var (
signatures [][]byte 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) { 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) sm, ok := manifest.(*schema1.SignedManifest)
if !ok { if !ok {
@ -72,7 +73,7 @@ func (ms *signedManifestHandler) Put(ctx context.Context, manifest distribution.
revision, err := ms.blobStore.Put(ctx, mt, payload) revision, err := ms.blobStore.Put(ctx, mt, payload)
if err != nil { 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 return "", err
} }

View file

@ -1,10 +1,10 @@
package storage package storage
import ( import (
"context"
"path" "path"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
storagedriver "github.com/docker/distribution/registry/storage/driver" storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )

View file

@ -1,10 +1,10 @@
package storage package storage
import ( import (
"context"
"testing" "testing"
"github.com/docker/distribution" "github.com/docker/distribution"
"github.com/docker/distribution/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/distribution/registry/storage/driver/inmemory" "github.com/docker/distribution/registry/storage/driver/inmemory"
) )

View file

@ -1,7 +1,8 @@
package storage package storage
import ( import (
"github.com/docker/distribution/context" "context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
) )

View file

@ -1,9 +1,10 @@
package storage package storage
import ( import (
"context"
"path" "path"
"github.com/docker/distribution/context" dcontext "github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
) )
@ -39,7 +40,7 @@ func (v Vacuum) RemoveBlob(dgst string) error {
return err 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) err = v.driver.Delete(v.ctx, blobPath)
if err != nil { if err != nil {
@ -57,7 +58,7 @@ func (v Vacuum) RemoveRepository(repoName string) error {
return err return err
} }
repoDir := path.Join(rootForRepository, repoName) 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) err = v.driver.Delete(v.ctx, repoDir)
if err != nil { if err != nil {
return err return err

View file

@ -1,11 +1,11 @@
package storage package storage
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"sort" "sort"
"github.com/docker/distribution/context"
storageDriver "github.com/docker/distribution/registry/storage/driver" storageDriver "github.com/docker/distribution/registry/storage/driver"
) )

View file

@ -1,11 +1,11 @@
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"sort" "sort"
"testing" "testing"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver"
"github.com/docker/distribution/registry/storage/driver/inmemory" "github.com/docker/distribution/registry/storage/driver/inmemory"
) )

View file

@ -1,7 +1,7 @@
package distribution package distribution
import ( import (
"github.com/docker/distribution/context" "context"
) )
// TagService provides access to information about tagged objects. // TagService provides access to information about tagged objects.