repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
docker/distribution
registry/storage/tagstore.go
Lookup
func (ts *tagStore) Lookup(ctx context.Context, desc distribution.Descriptor) ([]string, error) { allTags, err := ts.All(ctx) switch err.(type) { case distribution.ErrRepositoryUnknown: // This tag store has been initialized but not yet populated break case nil: break default: return nil, err } var tags []string for _, tag := range allTags { tagLinkPathSpec := manifestTagCurrentPathSpec{ name: ts.repository.Named().Name(), tag: tag, } tagLinkPath, _ := pathFor(tagLinkPathSpec) tagDigest, err := ts.blobStore.readlink(ctx, tagLinkPath) if err != nil { switch err.(type) { case storagedriver.PathNotFoundError: continue } return nil, err } if tagDigest == desc.Digest { tags = append(tags, tag) } } return tags, nil }
go
func (ts *tagStore) Lookup(ctx context.Context, desc distribution.Descriptor) ([]string, error) { allTags, err := ts.All(ctx) switch err.(type) { case distribution.ErrRepositoryUnknown: // This tag store has been initialized but not yet populated break case nil: break default: return nil, err } var tags []string for _, tag := range allTags { tagLinkPathSpec := manifestTagCurrentPathSpec{ name: ts.repository.Named().Name(), tag: tag, } tagLinkPath, _ := pathFor(tagLinkPathSpec) tagDigest, err := ts.blobStore.readlink(ctx, tagLinkPath) if err != nil { switch err.(type) { case storagedriver.PathNotFoundError: continue } return nil, err } if tagDigest == desc.Digest { tags = append(tags, tag) } } return tags, nil }
[ "func", "(", "ts", "*", "tagStore", ")", "Lookup", "(", "ctx", "context", ".", "Context", ",", "desc", "distribution", ".", "Descriptor", ")", "(", "[", "]", "string", ",", "error", ")", "{", "allTags", ",", "err", ":=", "ts", ".", "All", "(", "ctx...
// Lookup recovers a list of tags which refer to this digest. When a manifest is deleted by // digest, tag entries which point to it need to be recovered to avoid dangling tags.
[ "Lookup", "recovers", "a", "list", "of", "tags", "which", "refer", "to", "this", "digest", ".", "When", "a", "manifest", "is", "deleted", "by", "digest", "tag", "entries", "which", "point", "to", "it", "need", "to", "be", "recovered", "to", "avoid", "dan...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/tagstore.go#L144-L179
train
docker/distribution
registry/storage/driver/middleware/storagemiddleware.go
Get
func Get(name string, options map[string]interface{}, storageDriver storagedriver.StorageDriver) (storagedriver.StorageDriver, error) { if storageMiddlewares != nil { if initFunc, exists := storageMiddlewares[name]; exists { return initFunc(storageDriver, options) } } return nil, fmt.Errorf("no storage middleware registered with name: %s", name) }
go
func Get(name string, options map[string]interface{}, storageDriver storagedriver.StorageDriver) (storagedriver.StorageDriver, error) { if storageMiddlewares != nil { if initFunc, exists := storageMiddlewares[name]; exists { return initFunc(storageDriver, options) } } return nil, fmt.Errorf("no storage middleware registered with name: %s", name) }
[ "func", "Get", "(", "name", "string", ",", "options", "map", "[", "string", "]", "interface", "{", "}", ",", "storageDriver", "storagedriver", ".", "StorageDriver", ")", "(", "storagedriver", ".", "StorageDriver", ",", "error", ")", "{", "if", "storageMiddle...
// Get constructs a StorageMiddleware with the given options using the named backend.
[ "Get", "constructs", "a", "StorageMiddleware", "with", "the", "given", "options", "using", "the", "named", "backend", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/storagemiddleware.go#L31-L39
train
docker/distribution
context/http.go
RemoteAddr
func RemoteAddr(r *http.Request) string { if prior := r.Header.Get("X-Forwarded-For"); prior != "" { proxies := strings.Split(prior, ",") if len(proxies) > 0 { remoteAddr := strings.Trim(proxies[0], " ") if parseIP(remoteAddr) != nil { return remoteAddr } } } // X-Real-Ip is less supported, but worth checking in the // absence of X-Forwarded-For if realIP := r.Header.Get("X-Real-Ip"); realIP != "" { if parseIP(realIP) != nil { return realIP } } return r.RemoteAddr }
go
func RemoteAddr(r *http.Request) string { if prior := r.Header.Get("X-Forwarded-For"); prior != "" { proxies := strings.Split(prior, ",") if len(proxies) > 0 { remoteAddr := strings.Trim(proxies[0], " ") if parseIP(remoteAddr) != nil { return remoteAddr } } } // X-Real-Ip is less supported, but worth checking in the // absence of X-Forwarded-For if realIP := r.Header.Get("X-Real-Ip"); realIP != "" { if parseIP(realIP) != nil { return realIP } } return r.RemoteAddr }
[ "func", "RemoteAddr", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "if", "prior", ":=", "r", ".", "Header", ".", "Get", "(", "\"X-Forwarded-For\"", ")", ";", "prior", "!=", "\"\"", "{", "proxies", ":=", "strings", ".", "Split", "(", "pr...
// RemoteAddr extracts the remote address of the request, taking into // account proxy headers.
[ "RemoteAddr", "extracts", "the", "remote", "address", "of", "the", "request", "taking", "into", "account", "proxy", "headers", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L33-L52
train
docker/distribution
context/http.go
RemoteIP
func RemoteIP(r *http.Request) string { addr := RemoteAddr(r) // Try parsing it as "IP:port" if ip, _, err := net.SplitHostPort(addr); err == nil { return ip } return addr }
go
func RemoteIP(r *http.Request) string { addr := RemoteAddr(r) // Try parsing it as "IP:port" if ip, _, err := net.SplitHostPort(addr); err == nil { return ip } return addr }
[ "func", "RemoteIP", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "addr", ":=", "RemoteAddr", "(", "r", ")", "\n", "if", "ip", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "addr", ")", ";", "err", "==", "nil", "{", ...
// RemoteIP extracts the remote IP of the request, taking into // account proxy headers.
[ "RemoteIP", "extracts", "the", "remote", "IP", "of", "the", "request", "taking", "into", "account", "proxy", "headers", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L56-L65
train
docker/distribution
context/http.go
WithRequest
func WithRequest(ctx context.Context, r *http.Request) context.Context { if ctx.Value("http.request") != nil { // NOTE(stevvooe): This needs to be considered a programming error. It // is unlikely that we'd want to have more than one request in // context. panic("only one request per context") } return &httpRequestContext{ Context: ctx, startedAt: time.Now(), id: uuid.Generate().String(), r: r, } }
go
func WithRequest(ctx context.Context, r *http.Request) context.Context { if ctx.Value("http.request") != nil { // NOTE(stevvooe): This needs to be considered a programming error. It // is unlikely that we'd want to have more than one request in // context. panic("only one request per context") } return &httpRequestContext{ Context: ctx, startedAt: time.Now(), id: uuid.Generate().String(), r: r, } }
[ "func", "WithRequest", "(", "ctx", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "context", ".", "Context", "{", "if", "ctx", ".", "Value", "(", "\"http.request\"", ")", "!=", "nil", "{", "panic", "(", "\"only one request per conte...
// WithRequest places the request on the context. The context of the request // is assigned a unique id, available at "http.request.id". The request itself // is available at "http.request". Other common attributes are available under // the prefix "http.request.". If a request is already present on the context, // this method will panic.
[ "WithRequest", "places", "the", "request", "on", "the", "context", ".", "The", "context", "of", "the", "request", "is", "assigned", "a", "unique", "id", "available", "at", "http", ".", "request", ".", "id", ".", "The", "request", "itself", "is", "available...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L72-L86
train
docker/distribution
context/http.go
GetRequest
func GetRequest(ctx context.Context) (*http.Request, error) { if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok { return r, nil } return nil, ErrNoRequestContext }
go
func GetRequest(ctx context.Context) (*http.Request, error) { if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok { return r, nil } return nil, ErrNoRequestContext }
[ "func", "GetRequest", "(", "ctx", "context", ".", "Context", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "if", "r", ",", "ok", ":=", "ctx", ".", "Value", "(", "\"http.request\"", ")", ".", "(", "*", "http", ".", "Request", ")", ...
// GetRequest returns the http request in the given context. Returns // ErrNoRequestContext if the context does not have an http request associated // with it.
[ "GetRequest", "returns", "the", "http", "request", "in", "the", "given", "context", ".", "Returns", "ErrNoRequestContext", "if", "the", "context", "does", "not", "have", "an", "http", "request", "associated", "with", "it", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L91-L96
train
docker/distribution
context/http.go
WithResponseWriter
func WithResponseWriter(ctx context.Context, w http.ResponseWriter) (context.Context, http.ResponseWriter) { irw := instrumentedResponseWriter{ ResponseWriter: w, Context: ctx, } return &irw, &irw }
go
func WithResponseWriter(ctx context.Context, w http.ResponseWriter) (context.Context, http.ResponseWriter) { irw := instrumentedResponseWriter{ ResponseWriter: w, Context: ctx, } return &irw, &irw }
[ "func", "WithResponseWriter", "(", "ctx", "context", ".", "Context", ",", "w", "http", ".", "ResponseWriter", ")", "(", "context", ".", "Context", ",", "http", ".", "ResponseWriter", ")", "{", "irw", ":=", "instrumentedResponseWriter", "{", "ResponseWriter", "...
// WithResponseWriter returns a new context and response writer that makes // interesting response statistics available within the context.
[ "WithResponseWriter", "returns", "a", "new", "context", "and", "response", "writer", "that", "makes", "interesting", "response", "statistics", "available", "within", "the", "context", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L106-L112
train
docker/distribution
context/http.go
GetResponseWriter
func GetResponseWriter(ctx context.Context) (http.ResponseWriter, error) { v := ctx.Value("http.response") rw, ok := v.(http.ResponseWriter) if !ok || rw == nil { return nil, ErrNoResponseWriterContext } return rw, nil }
go
func GetResponseWriter(ctx context.Context) (http.ResponseWriter, error) { v := ctx.Value("http.response") rw, ok := v.(http.ResponseWriter) if !ok || rw == nil { return nil, ErrNoResponseWriterContext } return rw, nil }
[ "func", "GetResponseWriter", "(", "ctx", "context", ".", "Context", ")", "(", "http", ".", "ResponseWriter", ",", "error", ")", "{", "v", ":=", "ctx", ".", "Value", "(", "\"http.response\"", ")", "\n", "rw", ",", "ok", ":=", "v", ".", "(", "http", "....
// GetResponseWriter returns the http.ResponseWriter from the provided // context. If not present, ErrNoResponseWriterContext is returned. The // returned instance provides instrumentation in the context.
[ "GetResponseWriter", "returns", "the", "http", ".", "ResponseWriter", "from", "the", "provided", "context", ".", "If", "not", "present", "ErrNoResponseWriterContext", "is", "returned", ".", "The", "returned", "instance", "provides", "instrumentation", "in", "the", "...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L117-L126
train
docker/distribution
context/http.go
GetResponseLogger
func GetResponseLogger(ctx context.Context) Logger { l := getLogrusLogger(ctx, "http.response.written", "http.response.status", "http.response.contenttype") duration := Since(ctx, "http.request.startedat") if duration > 0 { l = l.WithField("http.response.duration", duration.String()) } return l }
go
func GetResponseLogger(ctx context.Context) Logger { l := getLogrusLogger(ctx, "http.response.written", "http.response.status", "http.response.contenttype") duration := Since(ctx, "http.request.startedat") if duration > 0 { l = l.WithField("http.response.duration", duration.String()) } return l }
[ "func", "GetResponseLogger", "(", "ctx", "context", ".", "Context", ")", "Logger", "{", "l", ":=", "getLogrusLogger", "(", "ctx", ",", "\"http.response.written\"", ",", "\"http.response.status\"", ",", "\"http.response.contenttype\"", ")", "\n", "duration", ":=", "S...
// GetResponseLogger reads the current response stats and builds a logger. // Because the values are read at call time, pushing a logger returned from // this function on the context will lead to missing or invalid data. Only // call this at the end of a request, after the response has been written.
[ "GetResponseLogger", "reads", "the", "current", "response", "stats", "and", "builds", "a", "logger", ".", "Because", "the", "values", "are", "read", "at", "call", "time", "pushing", "a", "logger", "returned", "from", "this", "function", "on", "the", "context",...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L163-L176
train
docker/distribution
registry/client/auth/challenge/authchallenge.go
ResponseChallenges
func ResponseChallenges(resp *http.Response) []Challenge { if resp.StatusCode == http.StatusUnauthorized { // Parse the WWW-Authenticate Header and store the challenges // on this endpoint object. return parseAuthHeader(resp.Header) } return nil }
go
func ResponseChallenges(resp *http.Response) []Challenge { if resp.StatusCode == http.StatusUnauthorized { // Parse the WWW-Authenticate Header and store the challenges // on this endpoint object. return parseAuthHeader(resp.Header) } return nil }
[ "func", "ResponseChallenges", "(", "resp", "*", "http", ".", "Response", ")", "[", "]", "Challenge", "{", "if", "resp", ".", "StatusCode", "==", "http", ".", "StatusUnauthorized", "{", "return", "parseAuthHeader", "(", "resp", ".", "Header", ")", "\n", "}"...
// ResponseChallenges returns a list of authorization challenges // for the given http Response. Challenges are only checked if // the response status code was a 401.
[ "ResponseChallenges", "returns", "a", "list", "of", "authorization", "challenges", "for", "the", "given", "http", "Response", ".", "Challenges", "are", "only", "checked", "if", "the", "response", "status", "code", "was", "a", "401", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/challenge/authchallenge.go#L134-L142
train
docker/distribution
registry/storage/purgeuploads.go
PurgeUploads
func PurgeUploads(ctx context.Context, driver storageDriver.StorageDriver, olderThan time.Time, actuallyDelete bool) ([]string, []error) { logrus.Infof("PurgeUploads starting: olderThan=%s, actuallyDelete=%t", olderThan, actuallyDelete) uploadData, errors := getOutstandingUploads(ctx, driver) var deleted []string for _, uploadData := range uploadData { if uploadData.startedAt.Before(olderThan) { var err error logrus.Infof("Upload files in %s have older date (%s) than purge date (%s). Removing upload directory.", uploadData.containingDir, uploadData.startedAt, olderThan) if actuallyDelete { err = driver.Delete(ctx, uploadData.containingDir) } if err == nil { deleted = append(deleted, uploadData.containingDir) } else { errors = append(errors, err) } } } logrus.Infof("Purge uploads finished. Num deleted=%d, num errors=%d", len(deleted), len(errors)) return deleted, errors }
go
func PurgeUploads(ctx context.Context, driver storageDriver.StorageDriver, olderThan time.Time, actuallyDelete bool) ([]string, []error) { logrus.Infof("PurgeUploads starting: olderThan=%s, actuallyDelete=%t", olderThan, actuallyDelete) uploadData, errors := getOutstandingUploads(ctx, driver) var deleted []string for _, uploadData := range uploadData { if uploadData.startedAt.Before(olderThan) { var err error logrus.Infof("Upload files in %s have older date (%s) than purge date (%s). Removing upload directory.", uploadData.containingDir, uploadData.startedAt, olderThan) if actuallyDelete { err = driver.Delete(ctx, uploadData.containingDir) } if err == nil { deleted = append(deleted, uploadData.containingDir) } else { errors = append(errors, err) } } } logrus.Infof("Purge uploads finished. Num deleted=%d, num errors=%d", len(deleted), len(errors)) return deleted, errors }
[ "func", "PurgeUploads", "(", "ctx", "context", ".", "Context", ",", "driver", "storageDriver", ".", "StorageDriver", ",", "olderThan", "time", ".", "Time", ",", "actuallyDelete", "bool", ")", "(", "[", "]", "string", ",", "[", "]", "error", ")", "{", "lo...
// PurgeUploads deletes files from the upload directory // created before olderThan. The list of files deleted and errors // encountered are returned
[ "PurgeUploads", "deletes", "files", "from", "the", "upload", "directory", "created", "before", "olderThan", ".", "The", "list", "of", "files", "deleted", "and", "errors", "encountered", "are", "returned" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L32-L54
train
docker/distribution
registry/storage/purgeuploads.go
getOutstandingUploads
func getOutstandingUploads(ctx context.Context, driver storageDriver.StorageDriver) (map[string]uploadData, []error) { var errors []error uploads := make(map[string]uploadData) inUploadDir := false root, err := pathFor(repositoriesRootPathSpec{}) if err != nil { return uploads, append(errors, err) } err = driver.Walk(ctx, root, func(fileInfo storageDriver.FileInfo) error { filePath := fileInfo.Path() _, file := path.Split(filePath) if file[0] == '_' { // Reserved directory inUploadDir = (file == "_uploads") if fileInfo.IsDir() && !inUploadDir { return storageDriver.ErrSkipDir } } uuid, isContainingDir := uuidFromPath(filePath) if uuid == "" { // Cannot reliably delete return nil } ud, ok := uploads[uuid] if !ok { ud = newUploadData() } if isContainingDir { ud.containingDir = filePath } if file == "startedat" { if t, err := readStartedAtFile(driver, filePath); err == nil { ud.startedAt = t } else { errors = pushError(errors, filePath, err) } } uploads[uuid] = ud return nil }) if err != nil { errors = pushError(errors, root, err) } return uploads, errors }
go
func getOutstandingUploads(ctx context.Context, driver storageDriver.StorageDriver) (map[string]uploadData, []error) { var errors []error uploads := make(map[string]uploadData) inUploadDir := false root, err := pathFor(repositoriesRootPathSpec{}) if err != nil { return uploads, append(errors, err) } err = driver.Walk(ctx, root, func(fileInfo storageDriver.FileInfo) error { filePath := fileInfo.Path() _, file := path.Split(filePath) if file[0] == '_' { // Reserved directory inUploadDir = (file == "_uploads") if fileInfo.IsDir() && !inUploadDir { return storageDriver.ErrSkipDir } } uuid, isContainingDir := uuidFromPath(filePath) if uuid == "" { // Cannot reliably delete return nil } ud, ok := uploads[uuid] if !ok { ud = newUploadData() } if isContainingDir { ud.containingDir = filePath } if file == "startedat" { if t, err := readStartedAtFile(driver, filePath); err == nil { ud.startedAt = t } else { errors = pushError(errors, filePath, err) } } uploads[uuid] = ud return nil }) if err != nil { errors = pushError(errors, root, err) } return uploads, errors }
[ "func", "getOutstandingUploads", "(", "ctx", "context", ".", "Context", ",", "driver", "storageDriver", ".", "StorageDriver", ")", "(", "map", "[", "string", "]", "uploadData", ",", "[", "]", "error", ")", "{", "var", "errors", "[", "]", "error", "\n", "...
// getOutstandingUploads walks the upload directory, collecting files // which could be eligible for deletion. The only reliable way to // classify the age of a file is with the date stored in the startedAt // file, so gather files by UUID with a date from startedAt.
[ "getOutstandingUploads", "walks", "the", "upload", "directory", "collecting", "files", "which", "could", "be", "eligible", "for", "deletion", ".", "The", "only", "reliable", "way", "to", "classify", "the", "age", "of", "a", "file", "is", "with", "the", "date",...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L60-L112
train
docker/distribution
registry/storage/purgeuploads.go
uuidFromPath
func uuidFromPath(path string) (string, bool) { components := strings.Split(path, "/") for i := len(components) - 1; i >= 0; i-- { if u, err := uuid.Parse(components[i]); err == nil { return u.String(), i == len(components)-1 } } return "", false }
go
func uuidFromPath(path string) (string, bool) { components := strings.Split(path, "/") for i := len(components) - 1; i >= 0; i-- { if u, err := uuid.Parse(components[i]); err == nil { return u.String(), i == len(components)-1 } } return "", false }
[ "func", "uuidFromPath", "(", "path", "string", ")", "(", "string", ",", "bool", ")", "{", "components", ":=", "strings", ".", "Split", "(", "path", ",", "\"/\"", ")", "\n", "for", "i", ":=", "len", "(", "components", ")", "-", "1", ";", "i", ">=", ...
// uuidFromPath extracts the upload UUID from a given path // If the UUID is the last path component, this is the containing // directory for all upload files
[ "uuidFromPath", "extracts", "the", "upload", "UUID", "from", "a", "given", "path", "If", "the", "UUID", "is", "the", "last", "path", "component", "this", "is", "the", "containing", "directory", "for", "all", "upload", "files" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L117-L125
train
docker/distribution
registry/storage/purgeuploads.go
readStartedAtFile
func readStartedAtFile(driver storageDriver.StorageDriver, path string) (time.Time, error) { // todo:(richardscothern) - pass in a context startedAtBytes, err := driver.GetContent(context.Background(), path) if err != nil { return time.Now(), err } startedAt, err := time.Parse(time.RFC3339, string(startedAtBytes)) if err != nil { return time.Now(), err } return startedAt, nil }
go
func readStartedAtFile(driver storageDriver.StorageDriver, path string) (time.Time, error) { // todo:(richardscothern) - pass in a context startedAtBytes, err := driver.GetContent(context.Background(), path) if err != nil { return time.Now(), err } startedAt, err := time.Parse(time.RFC3339, string(startedAtBytes)) if err != nil { return time.Now(), err } return startedAt, nil }
[ "func", "readStartedAtFile", "(", "driver", "storageDriver", ".", "StorageDriver", ",", "path", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "startedAtBytes", ",", "err", ":=", "driver", ".", "GetContent", "(", "context", ".", "Background...
// readStartedAtFile reads the date from an upload's startedAtFile
[ "readStartedAtFile", "reads", "the", "date", "from", "an", "upload", "s", "startedAtFile" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L128-L139
train
docker/distribution
registry/storage/filereader.go
newFileReader
func newFileReader(ctx context.Context, driver storagedriver.StorageDriver, path string, size int64) (*fileReader, error) { return &fileReader{ ctx: ctx, driver: driver, path: path, size: size, }, nil }
go
func newFileReader(ctx context.Context, driver storagedriver.StorageDriver, path string, size int64) (*fileReader, error) { return &fileReader{ ctx: ctx, driver: driver, path: path, size: size, }, nil }
[ "func", "newFileReader", "(", "ctx", "context", ".", "Context", ",", "driver", "storagedriver", ".", "StorageDriver", ",", "path", "string", ",", "size", "int64", ")", "(", "*", "fileReader", ",", "error", ")", "{", "return", "&", "fileReader", "{", "ctx",...
// newFileReader initializes a file reader for the remote file. The reader // takes on the size and path that must be determined externally with a stat // call. The reader operates optimistically, assuming that the file is already // there.
[ "newFileReader", "initializes", "a", "file", "reader", "for", "the", "remote", "file", ".", "The", "reader", "takes", "on", "the", "size", "and", "path", "that", "must", "be", "determined", "externally", "with", "a", "stat", "call", ".", "The", "reader", "...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/filereader.go#L44-L51
train
docker/distribution
registry/storage/filereader.go
reader
func (fr *fileReader) reader() (io.Reader, error) { if fr.err != nil { return nil, fr.err } if fr.rc != nil { return fr.brd, nil } // If we don't have a reader, open one up. rc, err := fr.driver.Reader(fr.ctx, fr.path, fr.offset) if err != nil { switch err := err.(type) { case storagedriver.PathNotFoundError: // NOTE(stevvooe): If the path is not found, we simply return a // reader that returns io.EOF. However, we do not set fr.rc, // allowing future attempts at getting a reader to possibly // succeed if the file turns up later. return ioutil.NopCloser(bytes.NewReader([]byte{})), nil default: return nil, err } } fr.rc = rc if fr.brd == nil { fr.brd = bufio.NewReaderSize(fr.rc, fileReaderBufferSize) } else { fr.brd.Reset(fr.rc) } return fr.brd, nil }
go
func (fr *fileReader) reader() (io.Reader, error) { if fr.err != nil { return nil, fr.err } if fr.rc != nil { return fr.brd, nil } // If we don't have a reader, open one up. rc, err := fr.driver.Reader(fr.ctx, fr.path, fr.offset) if err != nil { switch err := err.(type) { case storagedriver.PathNotFoundError: // NOTE(stevvooe): If the path is not found, we simply return a // reader that returns io.EOF. However, we do not set fr.rc, // allowing future attempts at getting a reader to possibly // succeed if the file turns up later. return ioutil.NopCloser(bytes.NewReader([]byte{})), nil default: return nil, err } } fr.rc = rc if fr.brd == nil { fr.brd = bufio.NewReaderSize(fr.rc, fileReaderBufferSize) } else { fr.brd.Reset(fr.rc) } return fr.brd, nil }
[ "func", "(", "fr", "*", "fileReader", ")", "reader", "(", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "if", "fr", ".", "err", "!=", "nil", "{", "return", "nil", ",", "fr", ".", "err", "\n", "}", "\n", "if", "fr", ".", "rc", "!=", ...
// reader prepares the current reader at the lrs offset, ensuring its buffered // and ready to go.
[ "reader", "prepares", "the", "current", "reader", "at", "the", "lrs", "offset", "ensuring", "its", "buffered", "and", "ready", "to", "go", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/filereader.go#L111-L144
train
docker/distribution
registry/storage/filereader.go
reset
func (fr *fileReader) reset() { if fr.err != nil { return } if fr.rc != nil { fr.rc.Close() fr.rc = nil } }
go
func (fr *fileReader) reset() { if fr.err != nil { return } if fr.rc != nil { fr.rc.Close() fr.rc = nil } }
[ "func", "(", "fr", "*", "fileReader", ")", "reset", "(", ")", "{", "if", "fr", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "fr", ".", "rc", "!=", "nil", "{", "fr", ".", "rc", ".", "Close", "(", ")", "\n", "fr", ".", "rc",...
// resetReader resets the reader, forcing the read method to open up a new // connection and rebuild the buffered reader. This should be called when the // offset and the reader will become out of sync, such as during a seek // operation.
[ "resetReader", "resets", "the", "reader", "forcing", "the", "read", "method", "to", "open", "up", "a", "new", "connection", "and", "rebuild", "the", "buffered", "reader", ".", "This", "should", "be", "called", "when", "the", "offset", "and", "the", "reader",...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/filereader.go#L150-L158
train
docker/distribution
registry/handlers/blobupload.go
StartBlobUpload
func (buh *blobUploadHandler) StartBlobUpload(w http.ResponseWriter, r *http.Request) { var options []distribution.BlobCreateOption fromRepo := r.FormValue("from") mountDigest := r.FormValue("mount") if mountDigest != "" && fromRepo != "" { opt, err := buh.createBlobMountOption(fromRepo, mountDigest) if opt != nil && err == nil { options = append(options, opt) } } blobs := buh.Repository.Blobs(buh) upload, err := blobs.Create(buh, options...) if err != nil { if ebm, ok := err.(distribution.ErrBlobMounted); ok { if err := buh.writeBlobCreatedHeaders(w, ebm.Descriptor); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } } else if err == distribution.ErrUnsupported { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported) } else { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } return } buh.Upload = upload if err := buh.blobUploadResponse(w, r, true); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } w.Header().Set("Docker-Upload-UUID", buh.Upload.ID()) w.WriteHeader(http.StatusAccepted) }
go
func (buh *blobUploadHandler) StartBlobUpload(w http.ResponseWriter, r *http.Request) { var options []distribution.BlobCreateOption fromRepo := r.FormValue("from") mountDigest := r.FormValue("mount") if mountDigest != "" && fromRepo != "" { opt, err := buh.createBlobMountOption(fromRepo, mountDigest) if opt != nil && err == nil { options = append(options, opt) } } blobs := buh.Repository.Blobs(buh) upload, err := blobs.Create(buh, options...) if err != nil { if ebm, ok := err.(distribution.ErrBlobMounted); ok { if err := buh.writeBlobCreatedHeaders(w, ebm.Descriptor); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } } else if err == distribution.ErrUnsupported { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported) } else { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } return } buh.Upload = upload if err := buh.blobUploadResponse(w, r, true); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } w.Header().Set("Docker-Upload-UUID", buh.Upload.ID()) w.WriteHeader(http.StatusAccepted) }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "StartBlobUpload", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "var", "options", "[", "]", "distribution", ".", "BlobCreateOption", "\n", "fromRepo", ":=", "r"...
// StartBlobUpload begins the blob upload process and allocates a server-side // blob writer session, optionally mounting the blob from a separate repository.
[ "StartBlobUpload", "begins", "the", "blob", "upload", "process", "and", "allocates", "a", "server", "-", "side", "blob", "writer", "session", "optionally", "mounting", "the", "blob", "from", "a", "separate", "repository", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L107-L145
train
docker/distribution
registry/handlers/blobupload.go
GetUploadStatus
func (buh *blobUploadHandler) GetUploadStatus(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } // TODO(dmcgowan): Set last argument to false in blobUploadResponse when // resumable upload is supported. This will enable returning a non-zero // range for clients to begin uploading at an offset. if err := buh.blobUploadResponse(w, r, true); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } w.Header().Set("Docker-Upload-UUID", buh.UUID) w.WriteHeader(http.StatusNoContent) }
go
func (buh *blobUploadHandler) GetUploadStatus(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } // TODO(dmcgowan): Set last argument to false in blobUploadResponse when // resumable upload is supported. This will enable returning a non-zero // range for clients to begin uploading at an offset. if err := buh.blobUploadResponse(w, r, true); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } w.Header().Set("Docker-Upload-UUID", buh.UUID) w.WriteHeader(http.StatusNoContent) }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "GetUploadStatus", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "buh", ".", "Upload", "==", "nil", "{", "buh", ".", "Errors", "=", "append", "(", "b...
// GetUploadStatus returns the status of a given upload, identified by id.
[ "GetUploadStatus", "returns", "the", "status", "of", "a", "given", "upload", "identified", "by", "id", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L148-L164
train
docker/distribution
registry/handlers/blobupload.go
PatchBlobData
func (buh *blobUploadHandler) PatchBlobData(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } ct := r.Header.Get("Content-Type") if ct != "" && ct != "application/octet-stream" { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(fmt.Errorf("bad Content-Type"))) // TODO(dmcgowan): encode error return } // TODO(dmcgowan): support Content-Range header to seek and write range if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PATCH"); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error())) return } if err := buh.blobUploadResponse(w, r, false); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } w.WriteHeader(http.StatusAccepted) }
go
func (buh *blobUploadHandler) PatchBlobData(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } ct := r.Header.Get("Content-Type") if ct != "" && ct != "application/octet-stream" { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(fmt.Errorf("bad Content-Type"))) // TODO(dmcgowan): encode error return } // TODO(dmcgowan): support Content-Range header to seek and write range if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PATCH"); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error())) return } if err := buh.blobUploadResponse(w, r, false); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } w.WriteHeader(http.StatusAccepted) }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "PatchBlobData", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "buh", ".", "Upload", "==", "nil", "{", "buh", ".", "Errors", "=", "append", "(", "buh...
// PatchBlobData writes data to an upload.
[ "PatchBlobData", "writes", "data", "to", "an", "upload", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L167-L193
train
docker/distribution
registry/handlers/blobupload.go
PutBlobUploadComplete
func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } dgstStr := r.FormValue("digest") // TODO(stevvooe): Support multiple digest parameters! if dgstStr == "" { // no digest? return error, but allow retry. buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest missing")) return } dgst, err := digest.Parse(dgstStr) if err != nil { // no digest? return error, but allow retry. buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest parsing failed")) return } if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PUT"); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error())) return } desc, err := buh.Upload.Commit(buh, distribution.Descriptor{ Digest: dgst, // TODO(stevvooe): This isn't wildly important yet, but we should // really set the mediatype. For now, we can let the backend take care // of this. }) if err != nil { switch err := err.(type) { case distribution.ErrBlobInvalidDigest: buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err)) case errcode.Error: buh.Errors = append(buh.Errors, err) default: switch err { case distribution.ErrAccessDenied: buh.Errors = append(buh.Errors, errcode.ErrorCodeDenied) case distribution.ErrUnsupported: buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported) case distribution.ErrBlobInvalidLength, distribution.ErrBlobDigestUnsupported: buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) default: dcontext.GetLogger(buh).Errorf("unknown error completing upload: %v", err) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } } // Clean up the backend blob data if there was an error. if err := buh.Upload.Cancel(buh); err != nil { // If the cleanup fails, all we can do is observe and report. dcontext.GetLogger(buh).Errorf("error canceling upload after error: %v", err) } return } if err := buh.writeBlobCreatedHeaders(w, desc); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } }
go
func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } dgstStr := r.FormValue("digest") // TODO(stevvooe): Support multiple digest parameters! if dgstStr == "" { // no digest? return error, but allow retry. buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest missing")) return } dgst, err := digest.Parse(dgstStr) if err != nil { // no digest? return error, but allow retry. buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest parsing failed")) return } if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PUT"); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error())) return } desc, err := buh.Upload.Commit(buh, distribution.Descriptor{ Digest: dgst, // TODO(stevvooe): This isn't wildly important yet, but we should // really set the mediatype. For now, we can let the backend take care // of this. }) if err != nil { switch err := err.(type) { case distribution.ErrBlobInvalidDigest: buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err)) case errcode.Error: buh.Errors = append(buh.Errors, err) default: switch err { case distribution.ErrAccessDenied: buh.Errors = append(buh.Errors, errcode.ErrorCodeDenied) case distribution.ErrUnsupported: buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported) case distribution.ErrBlobInvalidLength, distribution.ErrBlobDigestUnsupported: buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err)) default: dcontext.GetLogger(buh).Errorf("unknown error completing upload: %v", err) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } } // Clean up the backend blob data if there was an error. if err := buh.Upload.Cancel(buh); err != nil { // If the cleanup fails, all we can do is observe and report. dcontext.GetLogger(buh).Errorf("error canceling upload after error: %v", err) } return } if err := buh.writeBlobCreatedHeaders(w, desc); err != nil { buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "PutBlobUploadComplete", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "buh", ".", "Upload", "==", "nil", "{", "buh", ".", "Errors", "=", "append", "("...
// PutBlobUploadComplete takes the final request of a blob upload. The // request may include all the blob data or no blob data. Any data // provided is received and verified. If successful, the blob is linked // into the blob store and 201 Created is returned with the canonical // url of the blob.
[ "PutBlobUploadComplete", "takes", "the", "final", "request", "of", "a", "blob", "upload", ".", "The", "request", "may", "include", "all", "the", "blob", "data", "or", "no", "blob", "data", ".", "Any", "data", "provided", "is", "received", "and", "verified", ...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L200-L267
train
docker/distribution
registry/handlers/blobupload.go
CancelBlobUpload
func (buh *blobUploadHandler) CancelBlobUpload(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } w.Header().Set("Docker-Upload-UUID", buh.UUID) if err := buh.Upload.Cancel(buh); err != nil { dcontext.GetLogger(buh).Errorf("error encountered canceling upload: %v", err) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } w.WriteHeader(http.StatusNoContent) }
go
func (buh *blobUploadHandler) CancelBlobUpload(w http.ResponseWriter, r *http.Request) { if buh.Upload == nil { buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown) return } w.Header().Set("Docker-Upload-UUID", buh.UUID) if err := buh.Upload.Cancel(buh); err != nil { dcontext.GetLogger(buh).Errorf("error encountered canceling upload: %v", err) buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } w.WriteHeader(http.StatusNoContent) }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "CancelBlobUpload", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "buh", ".", "Upload", "==", "nil", "{", "buh", ".", "Errors", "=", "append", "(", "...
// CancelBlobUpload cancels an in-progress upload of a blob.
[ "CancelBlobUpload", "cancels", "an", "in", "-", "progress", "upload", "of", "a", "blob", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L270-L283
train
docker/distribution
registry/handlers/blobupload.go
blobUploadResponse
func (buh *blobUploadHandler) blobUploadResponse(w http.ResponseWriter, r *http.Request, fresh bool) error { // TODO(stevvooe): Need a better way to manage the upload state automatically. buh.State.Name = buh.Repository.Named().Name() buh.State.UUID = buh.Upload.ID() buh.Upload.Close() buh.State.Offset = buh.Upload.Size() buh.State.StartedAt = buh.Upload.StartedAt() token, err := hmacKey(buh.Config.HTTP.Secret).packUploadState(buh.State) if err != nil { dcontext.GetLogger(buh).Infof("error building upload state token: %s", err) return err } uploadURL, err := buh.urlBuilder.BuildBlobUploadChunkURL( buh.Repository.Named(), buh.Upload.ID(), url.Values{ "_state": []string{token}, }) if err != nil { dcontext.GetLogger(buh).Infof("error building upload url: %s", err) return err } endRange := buh.Upload.Size() if endRange > 0 { endRange = endRange - 1 } w.Header().Set("Docker-Upload-UUID", buh.UUID) w.Header().Set("Location", uploadURL) w.Header().Set("Content-Length", "0") w.Header().Set("Range", fmt.Sprintf("0-%d", endRange)) return nil }
go
func (buh *blobUploadHandler) blobUploadResponse(w http.ResponseWriter, r *http.Request, fresh bool) error { // TODO(stevvooe): Need a better way to manage the upload state automatically. buh.State.Name = buh.Repository.Named().Name() buh.State.UUID = buh.Upload.ID() buh.Upload.Close() buh.State.Offset = buh.Upload.Size() buh.State.StartedAt = buh.Upload.StartedAt() token, err := hmacKey(buh.Config.HTTP.Secret).packUploadState(buh.State) if err != nil { dcontext.GetLogger(buh).Infof("error building upload state token: %s", err) return err } uploadURL, err := buh.urlBuilder.BuildBlobUploadChunkURL( buh.Repository.Named(), buh.Upload.ID(), url.Values{ "_state": []string{token}, }) if err != nil { dcontext.GetLogger(buh).Infof("error building upload url: %s", err) return err } endRange := buh.Upload.Size() if endRange > 0 { endRange = endRange - 1 } w.Header().Set("Docker-Upload-UUID", buh.UUID) w.Header().Set("Location", uploadURL) w.Header().Set("Content-Length", "0") w.Header().Set("Range", fmt.Sprintf("0-%d", endRange)) return nil }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "blobUploadResponse", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "fresh", "bool", ")", "error", "{", "buh", ".", "State", ".", "Name", "=", "buh", ".", "Reposi...
// blobUploadResponse provides a standard request for uploading blobs and // chunk responses. This sets the correct headers but the response status is // left to the caller. The fresh argument is used to ensure that new blob // uploads always start at a 0 offset. This allows disabling resumable push by // always returning a 0 offset on check status.
[ "blobUploadResponse", "provides", "a", "standard", "request", "for", "uploading", "blobs", "and", "chunk", "responses", ".", "This", "sets", "the", "correct", "headers", "but", "the", "response", "status", "is", "left", "to", "the", "caller", ".", "The", "fres...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L290-L326
train
docker/distribution
registry/handlers/blobupload.go
createBlobMountOption
func (buh *blobUploadHandler) createBlobMountOption(fromRepo, mountDigest string) (distribution.BlobCreateOption, error) { dgst, err := digest.Parse(mountDigest) if err != nil { return nil, err } ref, err := reference.WithName(fromRepo) if err != nil { return nil, err } canonical, err := reference.WithDigest(ref, dgst) if err != nil { return nil, err } return storage.WithMountFrom(canonical), nil }
go
func (buh *blobUploadHandler) createBlobMountOption(fromRepo, mountDigest string) (distribution.BlobCreateOption, error) { dgst, err := digest.Parse(mountDigest) if err != nil { return nil, err } ref, err := reference.WithName(fromRepo) if err != nil { return nil, err } canonical, err := reference.WithDigest(ref, dgst) if err != nil { return nil, err } return storage.WithMountFrom(canonical), nil }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "createBlobMountOption", "(", "fromRepo", ",", "mountDigest", "string", ")", "(", "distribution", ".", "BlobCreateOption", ",", "error", ")", "{", "dgst", ",", "err", ":=", "digest", ".", "Parse", "(", "moun...
// mountBlob attempts to mount a blob from another repository by its digest. If // successful, the blob is linked into the blob store and 201 Created is // returned with the canonical url of the blob.
[ "mountBlob", "attempts", "to", "mount", "a", "blob", "from", "another", "repository", "by", "its", "digest", ".", "If", "successful", "the", "blob", "is", "linked", "into", "the", "blob", "store", "and", "201", "Created", "is", "returned", "with", "the", "...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L331-L348
train
docker/distribution
registry/handlers/blobupload.go
writeBlobCreatedHeaders
func (buh *blobUploadHandler) writeBlobCreatedHeaders(w http.ResponseWriter, desc distribution.Descriptor) error { ref, err := reference.WithDigest(buh.Repository.Named(), desc.Digest) if err != nil { return err } blobURL, err := buh.urlBuilder.BuildBlobURL(ref) if err != nil { return err } w.Header().Set("Location", blobURL) w.Header().Set("Content-Length", "0") w.Header().Set("Docker-Content-Digest", desc.Digest.String()) w.WriteHeader(http.StatusCreated) return nil }
go
func (buh *blobUploadHandler) writeBlobCreatedHeaders(w http.ResponseWriter, desc distribution.Descriptor) error { ref, err := reference.WithDigest(buh.Repository.Named(), desc.Digest) if err != nil { return err } blobURL, err := buh.urlBuilder.BuildBlobURL(ref) if err != nil { return err } w.Header().Set("Location", blobURL) w.Header().Set("Content-Length", "0") w.Header().Set("Docker-Content-Digest", desc.Digest.String()) w.WriteHeader(http.StatusCreated) return nil }
[ "func", "(", "buh", "*", "blobUploadHandler", ")", "writeBlobCreatedHeaders", "(", "w", "http", ".", "ResponseWriter", ",", "desc", "distribution", ".", "Descriptor", ")", "error", "{", "ref", ",", "err", ":=", "reference", ".", "WithDigest", "(", "buh", "."...
// writeBlobCreatedHeaders writes the standard headers describing a newly // created blob. A 201 Created is written as well as the canonical URL and // blob digest.
[ "writeBlobCreatedHeaders", "writes", "the", "standard", "headers", "describing", "a", "newly", "created", "blob", ".", "A", "201", "Created", "is", "written", "as", "well", "as", "the", "canonical", "URL", "and", "blob", "digest", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L353-L368
train
docker/distribution
registry/storage/signedmanifesthandler.go
verifyManifest
func (ms *signedManifestHandler) verifyManifest(ctx context.Context, mnfst schema1.SignedManifest, skipDependencyVerification bool) error { var errs distribution.ErrManifestVerification if len(mnfst.Name) > reference.NameTotalLengthMax { errs = append(errs, distribution.ErrManifestNameInvalid{ Name: mnfst.Name, Reason: fmt.Errorf("manifest name must not be more than %v characters", reference.NameTotalLengthMax), }) } if !reference.NameRegexp.MatchString(mnfst.Name) { errs = append(errs, distribution.ErrManifestNameInvalid{ Name: mnfst.Name, Reason: fmt.Errorf("invalid manifest name format"), }) } if len(mnfst.History) != len(mnfst.FSLayers) { errs = append(errs, fmt.Errorf("mismatched history and fslayer cardinality %d != %d", len(mnfst.History), len(mnfst.FSLayers))) } if _, err := schema1.Verify(&mnfst); err != nil { switch err { case libtrust.ErrMissingSignatureKey, libtrust.ErrInvalidJSONContent, libtrust.ErrMissingSignatureKey: errs = append(errs, distribution.ErrManifestUnverified{}) default: if err.Error() == "invalid signature" { // TODO(stevvooe): This should be exported by libtrust errs = append(errs, distribution.ErrManifestUnverified{}) } else { errs = append(errs, err) } } } if !skipDependencyVerification { for _, fsLayer := range mnfst.References() { _, err := ms.repository.Blobs(ctx).Stat(ctx, fsLayer.Digest) if err != nil { if err != distribution.ErrBlobUnknown { errs = append(errs, err) } // On error here, we always append unknown blob errors. errs = append(errs, distribution.ErrManifestBlobUnknown{Digest: fsLayer.Digest}) } } } if len(errs) != 0 { return errs } return nil }
go
func (ms *signedManifestHandler) verifyManifest(ctx context.Context, mnfst schema1.SignedManifest, skipDependencyVerification bool) error { var errs distribution.ErrManifestVerification if len(mnfst.Name) > reference.NameTotalLengthMax { errs = append(errs, distribution.ErrManifestNameInvalid{ Name: mnfst.Name, Reason: fmt.Errorf("manifest name must not be more than %v characters", reference.NameTotalLengthMax), }) } if !reference.NameRegexp.MatchString(mnfst.Name) { errs = append(errs, distribution.ErrManifestNameInvalid{ Name: mnfst.Name, Reason: fmt.Errorf("invalid manifest name format"), }) } if len(mnfst.History) != len(mnfst.FSLayers) { errs = append(errs, fmt.Errorf("mismatched history and fslayer cardinality %d != %d", len(mnfst.History), len(mnfst.FSLayers))) } if _, err := schema1.Verify(&mnfst); err != nil { switch err { case libtrust.ErrMissingSignatureKey, libtrust.ErrInvalidJSONContent, libtrust.ErrMissingSignatureKey: errs = append(errs, distribution.ErrManifestUnverified{}) default: if err.Error() == "invalid signature" { // TODO(stevvooe): This should be exported by libtrust errs = append(errs, distribution.ErrManifestUnverified{}) } else { errs = append(errs, err) } } } if !skipDependencyVerification { for _, fsLayer := range mnfst.References() { _, err := ms.repository.Blobs(ctx).Stat(ctx, fsLayer.Digest) if err != nil { if err != distribution.ErrBlobUnknown { errs = append(errs, err) } // On error here, we always append unknown blob errors. errs = append(errs, distribution.ErrManifestBlobUnknown{Digest: fsLayer.Digest}) } } } if len(errs) != 0 { return errs } return nil }
[ "func", "(", "ms", "*", "signedManifestHandler", ")", "verifyManifest", "(", "ctx", "context", ".", "Context", ",", "mnfst", "schema1", ".", "SignedManifest", ",", "skipDependencyVerification", "bool", ")", "error", "{", "var", "errs", "distribution", ".", "ErrM...
// verifyManifest ensures that the manifest content is valid from the // perspective of the registry. It ensures that the signature is valid for the // enclosed payload. As a policy, the registry only tries to store valid // content, leaving trust policies of that content up to consumers.
[ "verifyManifest", "ensures", "that", "the", "manifest", "content", "is", "valid", "from", "the", "perspective", "of", "the", "registry", ".", "It", "ensures", "that", "the", "signature", "is", "valid", "for", "the", "enclosed", "payload", ".", "As", "a", "po...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/signedmanifesthandler.go#L87-L142
train
docker/distribution
context/context.go
WithValues
func WithValues(ctx context.Context, m map[string]interface{}) context.Context { mo := make(map[string]interface{}, len(m)) // make our own copy. for k, v := range m { mo[k] = v } return stringMapContext{ Context: ctx, m: mo, } }
go
func WithValues(ctx context.Context, m map[string]interface{}) context.Context { mo := make(map[string]interface{}, len(m)) // make our own copy. for k, v := range m { mo[k] = v } return stringMapContext{ Context: ctx, m: mo, } }
[ "func", "WithValues", "(", "ctx", "context", ".", "Context", ",", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "context", ".", "Context", "{", "mo", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "("...
// WithValues returns a context that proxies lookups through a map. Only // supports string keys.
[ "WithValues", "returns", "a", "context", "that", "proxies", "lookups", "through", "a", "map", ".", "Only", "supports", "string", "keys", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/context.go#L53-L63
train
docker/distribution
context/util.go
Since
func Since(ctx context.Context, key interface{}) time.Duration { if startedAt, ok := ctx.Value(key).(time.Time); ok { return time.Since(startedAt) } return 0 }
go
func Since(ctx context.Context, key interface{}) time.Duration { if startedAt, ok := ctx.Value(key).(time.Time); ok { return time.Since(startedAt) } return 0 }
[ "func", "Since", "(", "ctx", "context", ".", "Context", ",", "key", "interface", "{", "}", ")", "time", ".", "Duration", "{", "if", "startedAt", ",", "ok", ":=", "ctx", ".", "Value", "(", "key", ")", ".", "(", "time", ".", "Time", ")", ";", "ok",...
// Since looks up key, which should be a time.Time, and returns the duration // since that time. If the key is not found, the value returned will be zero. // This is helpful when inferring metrics related to context execution times.
[ "Since", "looks", "up", "key", "which", "should", "be", "a", "time", ".", "Time", "and", "returns", "the", "duration", "since", "that", "time", ".", "If", "the", "key", "is", "not", "found", "the", "value", "returned", "will", "be", "zero", ".", "This"...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/util.go#L11-L16
train
docker/distribution
context/util.go
GetStringValue
func GetStringValue(ctx context.Context, key interface{}) (value string) { if valuev, ok := ctx.Value(key).(string); ok { value = valuev } return value }
go
func GetStringValue(ctx context.Context, key interface{}) (value string) { if valuev, ok := ctx.Value(key).(string); ok { value = valuev } return value }
[ "func", "GetStringValue", "(", "ctx", "context", ".", "Context", ",", "key", "interface", "{", "}", ")", "(", "value", "string", ")", "{", "if", "valuev", ",", "ok", ":=", "ctx", ".", "Value", "(", "key", ")", ".", "(", "string", ")", ";", "ok", ...
// GetStringValue returns a string value from the context. The empty string // will be returned if not found.
[ "GetStringValue", "returns", "a", "string", "value", "from", "the", "context", ".", "The", "empty", "string", "will", "be", "returned", "if", "not", "found", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/util.go#L20-L25
train
docker/distribution
manifest/schema2/builder.go
NewManifestBuilder
func NewManifestBuilder(bs distribution.BlobService, configMediaType string, configJSON []byte) distribution.ManifestBuilder { mb := &builder{ bs: bs, configMediaType: configMediaType, configJSON: make([]byte, len(configJSON)), } copy(mb.configJSON, configJSON) return mb }
go
func NewManifestBuilder(bs distribution.BlobService, configMediaType string, configJSON []byte) distribution.ManifestBuilder { mb := &builder{ bs: bs, configMediaType: configMediaType, configJSON: make([]byte, len(configJSON)), } copy(mb.configJSON, configJSON) return mb }
[ "func", "NewManifestBuilder", "(", "bs", "distribution", ".", "BlobService", ",", "configMediaType", "string", ",", "configJSON", "[", "]", "byte", ")", "distribution", ".", "ManifestBuilder", "{", "mb", ":=", "&", "builder", "{", "bs", ":", "bs", ",", "conf...
// NewManifestBuilder is used to build new manifests for the current schema // version. It takes a BlobService so it can publish the configuration blob // as part of the Build process.
[ "NewManifestBuilder", "is", "used", "to", "build", "new", "manifests", "for", "the", "current", "schema", "version", ".", "It", "takes", "a", "BlobService", "so", "it", "can", "publish", "the", "configuration", "blob", "as", "part", "of", "the", "Build", "pr...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema2/builder.go#L29-L38
train
docker/distribution
registry/storage/linkedblobstore.go
Create
func (lbs *linkedBlobStore) Create(ctx context.Context, options ...distribution.BlobCreateOption) (distribution.BlobWriter, error) { dcontext.GetLogger(ctx).Debug("(*linkedBlobStore).Writer") var opts distribution.CreateOptions for _, option := range options { err := option.Apply(&opts) if err != nil { return nil, err } } if opts.Mount.ShouldMount { desc, err := lbs.mount(ctx, opts.Mount.From, opts.Mount.From.Digest(), opts.Mount.Stat) if err == nil { // Mount successful, no need to initiate an upload session return nil, distribution.ErrBlobMounted{From: opts.Mount.From, Descriptor: desc} } } uuid := uuid.Generate().String() startedAt := time.Now().UTC() path, err := pathFor(uploadDataPathSpec{ name: lbs.repository.Named().Name(), id: uuid, }) if err != nil { return nil, err } startedAtPath, err := pathFor(uploadStartedAtPathSpec{ name: lbs.repository.Named().Name(), id: uuid, }) if err != nil { return nil, err } // Write a startedat file for this upload if err := lbs.blobStore.driver.PutContent(ctx, startedAtPath, []byte(startedAt.Format(time.RFC3339))); err != nil { return nil, err } return lbs.newBlobUpload(ctx, uuid, path, startedAt, false) }
go
func (lbs *linkedBlobStore) Create(ctx context.Context, options ...distribution.BlobCreateOption) (distribution.BlobWriter, error) { dcontext.GetLogger(ctx).Debug("(*linkedBlobStore).Writer") var opts distribution.CreateOptions for _, option := range options { err := option.Apply(&opts) if err != nil { return nil, err } } if opts.Mount.ShouldMount { desc, err := lbs.mount(ctx, opts.Mount.From, opts.Mount.From.Digest(), opts.Mount.Stat) if err == nil { // Mount successful, no need to initiate an upload session return nil, distribution.ErrBlobMounted{From: opts.Mount.From, Descriptor: desc} } } uuid := uuid.Generate().String() startedAt := time.Now().UTC() path, err := pathFor(uploadDataPathSpec{ name: lbs.repository.Named().Name(), id: uuid, }) if err != nil { return nil, err } startedAtPath, err := pathFor(uploadStartedAtPathSpec{ name: lbs.repository.Named().Name(), id: uuid, }) if err != nil { return nil, err } // Write a startedat file for this upload if err := lbs.blobStore.driver.PutContent(ctx, startedAtPath, []byte(startedAt.Format(time.RFC3339))); err != nil { return nil, err } return lbs.newBlobUpload(ctx, uuid, path, startedAt, false) }
[ "func", "(", "lbs", "*", "linkedBlobStore", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "options", "...", "distribution", ".", "BlobCreateOption", ")", "(", "distribution", ".", "BlobWriter", ",", "error", ")", "{", "dcontext", ".", "GetLogger...
// Writer begins a blob write session, returning a handle.
[ "Writer", "begins", "a", "blob", "write", "session", "returning", "a", "handle", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/linkedblobstore.go#L128-L175
train
docker/distribution
registry/storage/linkedblobstore.go
newBlobUpload
func (lbs *linkedBlobStore) newBlobUpload(ctx context.Context, uuid, path string, startedAt time.Time, append bool) (distribution.BlobWriter, error) { fw, err := lbs.driver.Writer(ctx, path, append) if err != nil { return nil, err } bw := &blobWriter{ ctx: ctx, blobStore: lbs, id: uuid, startedAt: startedAt, digester: digest.Canonical.Digester(), fileWriter: fw, driver: lbs.driver, path: path, resumableDigestEnabled: lbs.resumableDigestEnabled, } return bw, nil }
go
func (lbs *linkedBlobStore) newBlobUpload(ctx context.Context, uuid, path string, startedAt time.Time, append bool) (distribution.BlobWriter, error) { fw, err := lbs.driver.Writer(ctx, path, append) if err != nil { return nil, err } bw := &blobWriter{ ctx: ctx, blobStore: lbs, id: uuid, startedAt: startedAt, digester: digest.Canonical.Digester(), fileWriter: fw, driver: lbs.driver, path: path, resumableDigestEnabled: lbs.resumableDigestEnabled, } return bw, nil }
[ "func", "(", "lbs", "*", "linkedBlobStore", ")", "newBlobUpload", "(", "ctx", "context", ".", "Context", ",", "uuid", ",", "path", "string", ",", "startedAt", "time", ".", "Time", ",", "append", "bool", ")", "(", "distribution", ".", "BlobWriter", ",", "...
// newBlobUpload allocates a new upload controller with the given state.
[ "newBlobUpload", "allocates", "a", "new", "upload", "controller", "with", "the", "given", "state", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/linkedblobstore.go#L308-L327
train
docker/distribution
registry/storage/linkedblobstore.go
linkBlob
func (lbs *linkedBlobStore) linkBlob(ctx context.Context, canonical distribution.Descriptor, aliases ...digest.Digest) error { dgsts := append([]digest.Digest{canonical.Digest}, aliases...) // TODO(stevvooe): Need to write out mediatype for only canonical hash // since we don't care about the aliases. They are generally unused except // for tarsum but those versions don't care about mediatype. // Don't make duplicate links. seenDigests := make(map[digest.Digest]struct{}, len(dgsts)) // only use the first link linkPathFn := lbs.linkPathFns[0] for _, dgst := range dgsts { if _, seen := seenDigests[dgst]; seen { continue } seenDigests[dgst] = struct{}{} blobLinkPath, err := linkPathFn(lbs.repository.Named().Name(), dgst) if err != nil { return err } if err := lbs.blobStore.link(ctx, blobLinkPath, canonical.Digest); err != nil { return err } } return nil }
go
func (lbs *linkedBlobStore) linkBlob(ctx context.Context, canonical distribution.Descriptor, aliases ...digest.Digest) error { dgsts := append([]digest.Digest{canonical.Digest}, aliases...) // TODO(stevvooe): Need to write out mediatype for only canonical hash // since we don't care about the aliases. They are generally unused except // for tarsum but those versions don't care about mediatype. // Don't make duplicate links. seenDigests := make(map[digest.Digest]struct{}, len(dgsts)) // only use the first link linkPathFn := lbs.linkPathFns[0] for _, dgst := range dgsts { if _, seen := seenDigests[dgst]; seen { continue } seenDigests[dgst] = struct{}{} blobLinkPath, err := linkPathFn(lbs.repository.Named().Name(), dgst) if err != nil { return err } if err := lbs.blobStore.link(ctx, blobLinkPath, canonical.Digest); err != nil { return err } } return nil }
[ "func", "(", "lbs", "*", "linkedBlobStore", ")", "linkBlob", "(", "ctx", "context", ".", "Context", ",", "canonical", "distribution", ".", "Descriptor", ",", "aliases", "...", "digest", ".", "Digest", ")", "error", "{", "dgsts", ":=", "append", "(", "[", ...
// linkBlob links a valid, written blob into the registry under the named // repository for the upload controller.
[ "linkBlob", "links", "a", "valid", "written", "blob", "into", "the", "registry", "under", "the", "named", "repository", "for", "the", "upload", "controller", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/linkedblobstore.go#L331-L361
train
docker/distribution
registry/storage/linkedblobstore.go
resolveWithLinkFunc
func (lbs *linkedBlobStatter) resolveWithLinkFunc(ctx context.Context, dgst digest.Digest, linkPathFn linkPathFunc) (digest.Digest, error) { blobLinkPath, err := linkPathFn(lbs.repository.Named().Name(), dgst) if err != nil { return "", err } return lbs.blobStore.readlink(ctx, blobLinkPath) }
go
func (lbs *linkedBlobStatter) resolveWithLinkFunc(ctx context.Context, dgst digest.Digest, linkPathFn linkPathFunc) (digest.Digest, error) { blobLinkPath, err := linkPathFn(lbs.repository.Named().Name(), dgst) if err != nil { return "", err } return lbs.blobStore.readlink(ctx, blobLinkPath) }
[ "func", "(", "lbs", "*", "linkedBlobStatter", ")", "resolveWithLinkFunc", "(", "ctx", "context", ".", "Context", ",", "dgst", "digest", ".", "Digest", ",", "linkPathFn", "linkPathFunc", ")", "(", "digest", ".", "Digest", ",", "error", ")", "{", "blobLinkPath...
// resolveTargetWithFunc allows us to read a link to a resource with different // linkPathFuncs to let us try a few different paths before returning not // found.
[ "resolveTargetWithFunc", "allows", "us", "to", "read", "a", "link", "to", "a", "resource", "with", "different", "linkPathFuncs", "to", "let", "us", "try", "a", "few", "different", "paths", "before", "returning", "not", "found", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/linkedblobstore.go#L443-L450
train
docker/distribution
registry/storage/linkedblobstore.go
blobLinkPath
func blobLinkPath(name string, dgst digest.Digest) (string, error) { return pathFor(layerLinkPathSpec{name: name, digest: dgst}) }
go
func blobLinkPath(name string, dgst digest.Digest) (string, error) { return pathFor(layerLinkPathSpec{name: name, digest: dgst}) }
[ "func", "blobLinkPath", "(", "name", "string", ",", "dgst", "digest", ".", "Digest", ")", "(", "string", ",", "error", ")", "{", "return", "pathFor", "(", "layerLinkPathSpec", "{", "name", ":", "name", ",", "digest", ":", "dgst", "}", ")", "\n", "}" ]
// blobLinkPath provides the path to the blob link, also known as layers.
[ "blobLinkPath", "provides", "the", "path", "to", "the", "blob", "link", "also", "known", "as", "layers", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/linkedblobstore.go#L458-L460
train
docker/distribution
registry/storage/linkedblobstore.go
manifestRevisionLinkPath
func manifestRevisionLinkPath(name string, dgst digest.Digest) (string, error) { return pathFor(manifestRevisionLinkPathSpec{name: name, revision: dgst}) }
go
func manifestRevisionLinkPath(name string, dgst digest.Digest) (string, error) { return pathFor(manifestRevisionLinkPathSpec{name: name, revision: dgst}) }
[ "func", "manifestRevisionLinkPath", "(", "name", "string", ",", "dgst", "digest", ".", "Digest", ")", "(", "string", ",", "error", ")", "{", "return", "pathFor", "(", "manifestRevisionLinkPathSpec", "{", "name", ":", "name", ",", "revision", ":", "dgst", "}"...
// manifestRevisionLinkPath provides the path to the manifest revision link.
[ "manifestRevisionLinkPath", "provides", "the", "path", "to", "the", "manifest", "revision", "link", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/linkedblobstore.go#L463-L465
train
docker/distribution
registry/api/errcode/errors.go
Descriptor
func (ec ErrorCode) Descriptor() ErrorDescriptor { d, ok := errorCodeToDescriptors[ec] if !ok { return ErrorCodeUnknown.Descriptor() } return d }
go
func (ec ErrorCode) Descriptor() ErrorDescriptor { d, ok := errorCodeToDescriptors[ec] if !ok { return ErrorCodeUnknown.Descriptor() } return d }
[ "func", "(", "ec", "ErrorCode", ")", "Descriptor", "(", ")", "ErrorDescriptor", "{", "d", ",", "ok", ":=", "errorCodeToDescriptors", "[", "ec", "]", "\n", "if", "!", "ok", "{", "return", "ErrorCodeUnknown", ".", "Descriptor", "(", ")", "\n", "}", "\n", ...
// Descriptor returns the descriptor for the error code.
[ "Descriptor", "returns", "the", "descriptor", "for", "the", "error", "code", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L33-L41
train
docker/distribution
registry/api/errcode/errors.go
UnmarshalText
func (ec *ErrorCode) UnmarshalText(text []byte) error { desc, ok := idToDescriptors[string(text)] if !ok { desc = ErrorCodeUnknown.Descriptor() } *ec = desc.Code return nil }
go
func (ec *ErrorCode) UnmarshalText(text []byte) error { desc, ok := idToDescriptors[string(text)] if !ok { desc = ErrorCodeUnknown.Descriptor() } *ec = desc.Code return nil }
[ "func", "(", "ec", "*", "ErrorCode", ")", "UnmarshalText", "(", "text", "[", "]", "byte", ")", "error", "{", "desc", ",", "ok", ":=", "idToDescriptors", "[", "string", "(", "text", ")", "]", "\n", "if", "!", "ok", "{", "desc", "=", "ErrorCodeUnknown"...
// UnmarshalText decodes the form generated by MarshalText.
[ "UnmarshalText", "decodes", "the", "form", "generated", "by", "MarshalText", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L60-L70
train
docker/distribution
registry/api/errcode/errors.go
WithMessage
func (ec ErrorCode) WithMessage(message string) Error { return Error{ Code: ec, Message: message, } }
go
func (ec ErrorCode) WithMessage(message string) Error { return Error{ Code: ec, Message: message, } }
[ "func", "(", "ec", "ErrorCode", ")", "WithMessage", "(", "message", "string", ")", "Error", "{", "return", "Error", "{", "Code", ":", "ec", ",", "Message", ":", "message", ",", "}", "\n", "}" ]
// WithMessage creates a new Error struct based on the passed-in info and // overrides the Message property.
[ "WithMessage", "creates", "a", "new", "Error", "struct", "based", "on", "the", "passed", "-", "in", "info", "and", "overrides", "the", "Message", "property", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L74-L79
train
docker/distribution
registry/api/errcode/errors.go
WithDetail
func (ec ErrorCode) WithDetail(detail interface{}) Error { return Error{ Code: ec, Message: ec.Message(), }.WithDetail(detail) }
go
func (ec ErrorCode) WithDetail(detail interface{}) Error { return Error{ Code: ec, Message: ec.Message(), }.WithDetail(detail) }
[ "func", "(", "ec", "ErrorCode", ")", "WithDetail", "(", "detail", "interface", "{", "}", ")", "Error", "{", "return", "Error", "{", "Code", ":", "ec", ",", "Message", ":", "ec", ".", "Message", "(", ")", ",", "}", ".", "WithDetail", "(", "detail", ...
// WithDetail creates a new Error struct based on the passed-in info and // set the Detail property appropriately
[ "WithDetail", "creates", "a", "new", "Error", "struct", "based", "on", "the", "passed", "-", "in", "info", "and", "set", "the", "Detail", "property", "appropriately" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L83-L88
train
docker/distribution
registry/api/errcode/errors.go
WithArgs
func (ec ErrorCode) WithArgs(args ...interface{}) Error { return Error{ Code: ec, Message: ec.Message(), }.WithArgs(args...) }
go
func (ec ErrorCode) WithArgs(args ...interface{}) Error { return Error{ Code: ec, Message: ec.Message(), }.WithArgs(args...) }
[ "func", "(", "ec", "ErrorCode", ")", "WithArgs", "(", "args", "...", "interface", "{", "}", ")", "Error", "{", "return", "Error", "{", "Code", ":", "ec", ",", "Message", ":", "ec", ".", "Message", "(", ")", ",", "}", ".", "WithArgs", "(", "args", ...
// WithArgs creates a new Error struct and sets the Args slice
[ "WithArgs", "creates", "a", "new", "Error", "struct", "and", "sets", "the", "Args", "slice" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L91-L96
train
docker/distribution
registry/api/errcode/errors.go
WithDetail
func (e Error) WithDetail(detail interface{}) Error { return Error{ Code: e.Code, Message: e.Message, Detail: detail, } }
go
func (e Error) WithDetail(detail interface{}) Error { return Error{ Code: e.Code, Message: e.Message, Detail: detail, } }
[ "func", "(", "e", "Error", ")", "WithDetail", "(", "detail", "interface", "{", "}", ")", "Error", "{", "return", "Error", "{", "Code", ":", "e", ".", "Code", ",", "Message", ":", "e", ".", "Message", ",", "Detail", ":", "detail", ",", "}", "\n", ...
// WithDetail will return a new Error, based on the current one, but with // some Detail info added
[ "WithDetail", "will", "return", "a", "new", "Error", "based", "on", "the", "current", "one", "but", "with", "some", "Detail", "info", "added" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L122-L128
train
docker/distribution
registry/api/errcode/errors.go
ParseErrorCode
func ParseErrorCode(value string) ErrorCode { ed, ok := idToDescriptors[value] if ok { return ed.Code } return ErrorCodeUnknown }
go
func ParseErrorCode(value string) ErrorCode { ed, ok := idToDescriptors[value] if ok { return ed.Code } return ErrorCodeUnknown }
[ "func", "ParseErrorCode", "(", "value", "string", ")", "ErrorCode", "{", "ed", ",", "ok", ":=", "idToDescriptors", "[", "value", "]", "\n", "if", "ok", "{", "return", "ed", ".", "Code", "\n", "}", "\n", "return", "ErrorCodeUnknown", "\n", "}" ]
// ParseErrorCode returns the value by the string error code. // `ErrorCodeUnknown` will be returned if the error is not known.
[ "ParseErrorCode", "returns", "the", "value", "by", "the", "string", "error", "code", ".", "ErrorCodeUnknown", "will", "be", "returned", "if", "the", "error", "is", "not", "known", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L165-L172
train
docker/distribution
registry/api/errcode/errors.go
MarshalJSON
func (errs Errors) MarshalJSON() ([]byte, error) { var tmpErrs struct { Errors []Error `json:"errors,omitempty"` } for _, daErr := range errs { var err Error switch daErr := daErr.(type) { case ErrorCode: err = daErr.WithDetail(nil) case Error: err = daErr default: err = ErrorCodeUnknown.WithDetail(daErr) } // If the Error struct was setup and they forgot to set the // Message field (meaning its "") then grab it from the ErrCode msg := err.Message if msg == "" { msg = err.Code.Message() } tmpErrs.Errors = append(tmpErrs.Errors, Error{ Code: err.Code, Message: msg, Detail: err.Detail, }) } return json.Marshal(tmpErrs) }
go
func (errs Errors) MarshalJSON() ([]byte, error) { var tmpErrs struct { Errors []Error `json:"errors,omitempty"` } for _, daErr := range errs { var err Error switch daErr := daErr.(type) { case ErrorCode: err = daErr.WithDetail(nil) case Error: err = daErr default: err = ErrorCodeUnknown.WithDetail(daErr) } // If the Error struct was setup and they forgot to set the // Message field (meaning its "") then grab it from the ErrCode msg := err.Message if msg == "" { msg = err.Code.Message() } tmpErrs.Errors = append(tmpErrs.Errors, Error{ Code: err.Code, Message: msg, Detail: err.Detail, }) } return json.Marshal(tmpErrs) }
[ "func", "(", "errs", "Errors", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "tmpErrs", "struct", "{", "Errors", "[", "]", "Error", "`json:\"errors,omitempty\"`", "\n", "}", "\n", "for", "_", ",", "daErr", ":=", ...
// MarshalJSON converts slice of error, ErrorCode or Error into a // slice of Error - then serializes
[ "MarshalJSON", "converts", "slice", "of", "error", "ErrorCode", "or", "Error", "into", "a", "slice", "of", "Error", "-", "then", "serializes" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/errors.go#L202-L235
train
docker/distribution
registry/client/transport/transport.go
NewTransport
func NewTransport(base http.RoundTripper, modifiers ...RequestModifier) http.RoundTripper { return &transport{ Modifiers: modifiers, Base: base, } }
go
func NewTransport(base http.RoundTripper, modifiers ...RequestModifier) http.RoundTripper { return &transport{ Modifiers: modifiers, Base: base, } }
[ "func", "NewTransport", "(", "base", "http", ".", "RoundTripper", ",", "modifiers", "...", "RequestModifier", ")", "http", ".", "RoundTripper", "{", "return", "&", "transport", "{", "Modifiers", ":", "modifiers", ",", "Base", ":", "base", ",", "}", "\n", "...
// NewTransport creates a new transport which will apply modifiers to // the request on a RoundTrip call.
[ "NewTransport", "creates", "a", "new", "transport", "which", "will", "apply", "modifiers", "to", "the", "request", "on", "a", "RoundTrip", "call", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/transport/transport.go#L33-L38
train
docker/distribution
registry/storage/driver/walk.go
WalkFallback
func WalkFallback(ctx context.Context, driver StorageDriver, from string, f WalkFn) error { children, err := driver.List(ctx, from) if err != nil { return err } sort.Stable(sort.StringSlice(children)) for _, child := range children { // TODO(stevvooe): Calling driver.Stat for every entry is quite // expensive when running against backends with a slow Stat // implementation, such as s3. This is very likely a serious // performance bottleneck. fileInfo, err := driver.Stat(ctx, child) if err != nil { switch err.(type) { case PathNotFoundError: // repository was removed in between listing and enumeration. Ignore it. logrus.WithField("path", child).Infof("ignoring deleted path") continue default: return err } } err = f(fileInfo) if err == nil && fileInfo.IsDir() { if err := WalkFallback(ctx, driver, child, f); err != nil { return err } } else if err == ErrSkipDir { // Stop iteration if it's a file, otherwise noop if it's a directory if !fileInfo.IsDir() { return nil } } else if err != nil { return err } } return nil }
go
func WalkFallback(ctx context.Context, driver StorageDriver, from string, f WalkFn) error { children, err := driver.List(ctx, from) if err != nil { return err } sort.Stable(sort.StringSlice(children)) for _, child := range children { // TODO(stevvooe): Calling driver.Stat for every entry is quite // expensive when running against backends with a slow Stat // implementation, such as s3. This is very likely a serious // performance bottleneck. fileInfo, err := driver.Stat(ctx, child) if err != nil { switch err.(type) { case PathNotFoundError: // repository was removed in between listing and enumeration. Ignore it. logrus.WithField("path", child).Infof("ignoring deleted path") continue default: return err } } err = f(fileInfo) if err == nil && fileInfo.IsDir() { if err := WalkFallback(ctx, driver, child, f); err != nil { return err } } else if err == ErrSkipDir { // Stop iteration if it's a file, otherwise noop if it's a directory if !fileInfo.IsDir() { return nil } } else if err != nil { return err } } return nil }
[ "func", "WalkFallback", "(", "ctx", "context", ".", "Context", ",", "driver", "StorageDriver", ",", "from", "string", ",", "f", "WalkFn", ")", "error", "{", "children", ",", "err", ":=", "driver", ".", "List", "(", "ctx", ",", "from", ")", "\n", "if", ...
// WalkFallback traverses a filesystem defined within driver, starting // from the given path, calling f on each file. It uses the List method and Stat to drive itself. // If the returned error from the WalkFn is ErrSkipDir and fileInfo refers // to a directory, the directory will not be entered and Walk // will continue the traversal. If fileInfo refers to a normal file, processing stops
[ "WalkFallback", "traverses", "a", "filesystem", "defined", "within", "driver", "starting", "from", "the", "given", "path", "calling", "f", "on", "each", "file", ".", "It", "uses", "the", "List", "method", "and", "Stat", "to", "drive", "itself", ".", "If", ...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/walk.go#L24-L61
train
docker/distribution
registry/storage/cache/cache.go
ValidateDescriptor
func ValidateDescriptor(desc distribution.Descriptor) error { if err := desc.Digest.Validate(); err != nil { return err } if desc.Size < 0 { return fmt.Errorf("cache: invalid length in descriptor: %v < 0", desc.Size) } if desc.MediaType == "" { return fmt.Errorf("cache: empty mediatype on descriptor: %v", desc) } return nil }
go
func ValidateDescriptor(desc distribution.Descriptor) error { if err := desc.Digest.Validate(); err != nil { return err } if desc.Size < 0 { return fmt.Errorf("cache: invalid length in descriptor: %v < 0", desc.Size) } if desc.MediaType == "" { return fmt.Errorf("cache: empty mediatype on descriptor: %v", desc) } return nil }
[ "func", "ValidateDescriptor", "(", "desc", "distribution", ".", "Descriptor", ")", "error", "{", "if", "err", ":=", "desc", ".", "Digest", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "desc", ".", "...
// ValidateDescriptor provides a helper function to ensure that caches have // common criteria for admitting descriptors.
[ "ValidateDescriptor", "provides", "a", "helper", "function", "to", "ensure", "that", "caches", "have", "common", "criteria", "for", "admitting", "descriptors", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/cache.go#L21-L35
train
docker/distribution
notifications/listener.go
Listen
func Listen(repo distribution.Repository, remover distribution.RepositoryRemover, listener Listener) (distribution.Repository, distribution.RepositoryRemover) { return &repositoryListener{ Repository: repo, listener: listener, }, &removerListener{ RepositoryRemover: remover, listener: listener, } }
go
func Listen(repo distribution.Repository, remover distribution.RepositoryRemover, listener Listener) (distribution.Repository, distribution.RepositoryRemover) { return &repositoryListener{ Repository: repo, listener: listener, }, &removerListener{ RepositoryRemover: remover, listener: listener, } }
[ "func", "Listen", "(", "repo", "distribution", ".", "Repository", ",", "remover", "distribution", ".", "RepositoryRemover", ",", "listener", "Listener", ")", "(", "distribution", ".", "Repository", ",", "distribution", ".", "RepositoryRemover", ")", "{", "return",...
// Listen dispatches events on the repository to the listener.
[ "Listen", "dispatches", "events", "on", "the", "repository", "to", "the", "listener", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/listener.go#L53-L61
train
docker/distribution
registry/handlers/blob.go
blobDispatcher
func blobDispatcher(ctx *Context, r *http.Request) http.Handler { dgst, err := getDigest(ctx) if err != nil { if err == errDigestNotAvailable { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx.Errors = append(ctx.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err)) }) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx.Errors = append(ctx.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err)) }) } blobHandler := &blobHandler{ Context: ctx, Digest: dgst, } mhandler := handlers.MethodHandler{ "GET": http.HandlerFunc(blobHandler.GetBlob), "HEAD": http.HandlerFunc(blobHandler.GetBlob), } if !ctx.readOnly { mhandler["DELETE"] = http.HandlerFunc(blobHandler.DeleteBlob) } return mhandler }
go
func blobDispatcher(ctx *Context, r *http.Request) http.Handler { dgst, err := getDigest(ctx) if err != nil { if err == errDigestNotAvailable { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx.Errors = append(ctx.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err)) }) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx.Errors = append(ctx.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err)) }) } blobHandler := &blobHandler{ Context: ctx, Digest: dgst, } mhandler := handlers.MethodHandler{ "GET": http.HandlerFunc(blobHandler.GetBlob), "HEAD": http.HandlerFunc(blobHandler.GetBlob), } if !ctx.readOnly { mhandler["DELETE"] = http.HandlerFunc(blobHandler.DeleteBlob) } return mhandler }
[ "func", "blobDispatcher", "(", "ctx", "*", "Context", ",", "r", "*", "http", ".", "Request", ")", "http", ".", "Handler", "{", "dgst", ",", "err", ":=", "getDigest", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "errDiges...
// blobDispatcher uses the request context to build a blobHandler.
[ "blobDispatcher", "uses", "the", "request", "context", "to", "build", "a", "blobHandler", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blob.go#L15-L45
train
docker/distribution
registry/handlers/blob.go
GetBlob
func (bh *blobHandler) GetBlob(w http.ResponseWriter, r *http.Request) { context.GetLogger(bh).Debug("GetBlob") blobs := bh.Repository.Blobs(bh) desc, err := blobs.Stat(bh, bh.Digest) if err != nil { if err == distribution.ErrBlobUnknown { bh.Errors = append(bh.Errors, v2.ErrorCodeBlobUnknown.WithDetail(bh.Digest)) } else { bh.Errors = append(bh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } return } if err := blobs.ServeBlob(bh, w, r, desc.Digest); err != nil { context.GetLogger(bh).Debugf("unexpected error getting blob HTTP handler: %v", err) bh.Errors = append(bh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } }
go
func (bh *blobHandler) GetBlob(w http.ResponseWriter, r *http.Request) { context.GetLogger(bh).Debug("GetBlob") blobs := bh.Repository.Blobs(bh) desc, err := blobs.Stat(bh, bh.Digest) if err != nil { if err == distribution.ErrBlobUnknown { bh.Errors = append(bh.Errors, v2.ErrorCodeBlobUnknown.WithDetail(bh.Digest)) } else { bh.Errors = append(bh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } return } if err := blobs.ServeBlob(bh, w, r, desc.Digest); err != nil { context.GetLogger(bh).Debugf("unexpected error getting blob HTTP handler: %v", err) bh.Errors = append(bh.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } }
[ "func", "(", "bh", "*", "blobHandler", ")", "GetBlob", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "context", ".", "GetLogger", "(", "bh", ")", ".", "Debug", "(", "\"GetBlob\"", ")", "\n", "blobs", ":=", ...
// GetBlob fetches the binary data from backend storage returns it in the // response.
[ "GetBlob", "fetches", "the", "binary", "data", "from", "backend", "storage", "returns", "it", "in", "the", "response", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blob.go#L56-L74
train
docker/distribution
registry/handlers/blob.go
DeleteBlob
func (bh *blobHandler) DeleteBlob(w http.ResponseWriter, r *http.Request) { context.GetLogger(bh).Debug("DeleteBlob") blobs := bh.Repository.Blobs(bh) err := blobs.Delete(bh, bh.Digest) if err != nil { switch err { case distribution.ErrUnsupported: bh.Errors = append(bh.Errors, errcode.ErrorCodeUnsupported) return case distribution.ErrBlobUnknown: bh.Errors = append(bh.Errors, v2.ErrorCodeBlobUnknown) return default: bh.Errors = append(bh.Errors, err) context.GetLogger(bh).Errorf("Unknown error deleting blob: %s", err.Error()) return } } w.Header().Set("Content-Length", "0") w.WriteHeader(http.StatusAccepted) }
go
func (bh *blobHandler) DeleteBlob(w http.ResponseWriter, r *http.Request) { context.GetLogger(bh).Debug("DeleteBlob") blobs := bh.Repository.Blobs(bh) err := blobs.Delete(bh, bh.Digest) if err != nil { switch err { case distribution.ErrUnsupported: bh.Errors = append(bh.Errors, errcode.ErrorCodeUnsupported) return case distribution.ErrBlobUnknown: bh.Errors = append(bh.Errors, v2.ErrorCodeBlobUnknown) return default: bh.Errors = append(bh.Errors, err) context.GetLogger(bh).Errorf("Unknown error deleting blob: %s", err.Error()) return } } w.Header().Set("Content-Length", "0") w.WriteHeader(http.StatusAccepted) }
[ "func", "(", "bh", "*", "blobHandler", ")", "DeleteBlob", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "context", ".", "GetLogger", "(", "bh", ")", ".", "Debug", "(", "\"DeleteBlob\"", ")", "\n", "blobs", ...
// DeleteBlob deletes a layer blob
[ "DeleteBlob", "deletes", "a", "layer", "blob" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blob.go#L77-L99
train
docker/distribution
manifest/ocischema/manifest.go
UnmarshalJSON
func (m *DeserializedManifest) UnmarshalJSON(b []byte) error { m.canonical = make([]byte, len(b)) // store manifest in canonical copy(m.canonical, b) // Unmarshal canonical JSON into Manifest object var manifest Manifest if err := json.Unmarshal(m.canonical, &manifest); err != nil { return err } if manifest.MediaType != "" && manifest.MediaType != v1.MediaTypeImageManifest { return fmt.Errorf("if present, mediaType in manifest should be '%s' not '%s'", v1.MediaTypeImageManifest, manifest.MediaType) } m.Manifest = manifest return nil }
go
func (m *DeserializedManifest) UnmarshalJSON(b []byte) error { m.canonical = make([]byte, len(b)) // store manifest in canonical copy(m.canonical, b) // Unmarshal canonical JSON into Manifest object var manifest Manifest if err := json.Unmarshal(m.canonical, &manifest); err != nil { return err } if manifest.MediaType != "" && manifest.MediaType != v1.MediaTypeImageManifest { return fmt.Errorf("if present, mediaType in manifest should be '%s' not '%s'", v1.MediaTypeImageManifest, manifest.MediaType) } m.Manifest = manifest return nil }
[ "func", "(", "m", "*", "DeserializedManifest", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "m", ".", "canonical", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "b", ")", ")", "\n", "copy", "(", "m", ".", "canonical...
// UnmarshalJSON populates a new Manifest struct from JSON data.
[ "UnmarshalJSON", "populates", "a", "new", "Manifest", "struct", "from", "JSON", "data", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/ocischema/manifest.go#L89-L108
train
docker/distribution
registry/proxy/scheduler/scheduler.go
New
func New(ctx context.Context, driver driver.StorageDriver, path string) *TTLExpirationScheduler { return &TTLExpirationScheduler{ entries: make(map[string]*schedulerEntry), driver: driver, pathToStateFile: path, ctx: ctx, stopped: true, doneChan: make(chan struct{}), saveTimer: time.NewTicker(indexSaveFrequency), } }
go
func New(ctx context.Context, driver driver.StorageDriver, path string) *TTLExpirationScheduler { return &TTLExpirationScheduler{ entries: make(map[string]*schedulerEntry), driver: driver, pathToStateFile: path, ctx: ctx, stopped: true, doneChan: make(chan struct{}), saveTimer: time.NewTicker(indexSaveFrequency), } }
[ "func", "New", "(", "ctx", "context", ".", "Context", ",", "driver", "driver", ".", "StorageDriver", ",", "path", "string", ")", "*", "TTLExpirationScheduler", "{", "return", "&", "TTLExpirationScheduler", "{", "entries", ":", "make", "(", "map", "[", "strin...
// New returns a new instance of the scheduler
[ "New", "returns", "a", "new", "instance", "of", "the", "scheduler" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/scheduler/scheduler.go#L35-L45
train
docker/distribution
registry/proxy/scheduler/scheduler.go
OnBlobExpire
func (ttles *TTLExpirationScheduler) OnBlobExpire(f expiryFunc) { ttles.Lock() defer ttles.Unlock() ttles.onBlobExpire = f }
go
func (ttles *TTLExpirationScheduler) OnBlobExpire(f expiryFunc) { ttles.Lock() defer ttles.Unlock() ttles.onBlobExpire = f }
[ "func", "(", "ttles", "*", "TTLExpirationScheduler", ")", "OnBlobExpire", "(", "f", "expiryFunc", ")", "{", "ttles", ".", "Lock", "(", ")", "\n", "defer", "ttles", ".", "Unlock", "(", ")", "\n", "ttles", ".", "onBlobExpire", "=", "f", "\n", "}" ]
// OnBlobExpire is called when a scheduled blob's TTL expires
[ "OnBlobExpire", "is", "called", "when", "a", "scheduled", "blob", "s", "TTL", "expires" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/scheduler/scheduler.go#L69-L74
train
docker/distribution
registry/proxy/scheduler/scheduler.go
OnManifestExpire
func (ttles *TTLExpirationScheduler) OnManifestExpire(f expiryFunc) { ttles.Lock() defer ttles.Unlock() ttles.onManifestExpire = f }
go
func (ttles *TTLExpirationScheduler) OnManifestExpire(f expiryFunc) { ttles.Lock() defer ttles.Unlock() ttles.onManifestExpire = f }
[ "func", "(", "ttles", "*", "TTLExpirationScheduler", ")", "OnManifestExpire", "(", "f", "expiryFunc", ")", "{", "ttles", ".", "Lock", "(", ")", "\n", "defer", "ttles", ".", "Unlock", "(", ")", "\n", "ttles", ".", "onManifestExpire", "=", "f", "\n", "}" ]
// OnManifestExpire is called when a scheduled manifest's TTL expires
[ "OnManifestExpire", "is", "called", "when", "a", "scheduled", "manifest", "s", "TTL", "expires" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/scheduler/scheduler.go#L77-L82
train
docker/distribution
registry/proxy/scheduler/scheduler.go
AddBlob
func (ttles *TTLExpirationScheduler) AddBlob(blobRef reference.Canonical, ttl time.Duration) error { ttles.Lock() defer ttles.Unlock() if ttles.stopped { return fmt.Errorf("scheduler not started") } ttles.add(blobRef, ttl, entryTypeBlob) return nil }
go
func (ttles *TTLExpirationScheduler) AddBlob(blobRef reference.Canonical, ttl time.Duration) error { ttles.Lock() defer ttles.Unlock() if ttles.stopped { return fmt.Errorf("scheduler not started") } ttles.add(blobRef, ttl, entryTypeBlob) return nil }
[ "func", "(", "ttles", "*", "TTLExpirationScheduler", ")", "AddBlob", "(", "blobRef", "reference", ".", "Canonical", ",", "ttl", "time", ".", "Duration", ")", "error", "{", "ttles", ".", "Lock", "(", ")", "\n", "defer", "ttles", ".", "Unlock", "(", ")", ...
// AddBlob schedules a blob cleanup after ttl expires
[ "AddBlob", "schedules", "a", "blob", "cleanup", "after", "ttl", "expires" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/scheduler/scheduler.go#L85-L95
train
docker/distribution
registry/proxy/scheduler/scheduler.go
AddManifest
func (ttles *TTLExpirationScheduler) AddManifest(manifestRef reference.Canonical, ttl time.Duration) error { ttles.Lock() defer ttles.Unlock() if ttles.stopped { return fmt.Errorf("scheduler not started") } ttles.add(manifestRef, ttl, entryTypeManifest) return nil }
go
func (ttles *TTLExpirationScheduler) AddManifest(manifestRef reference.Canonical, ttl time.Duration) error { ttles.Lock() defer ttles.Unlock() if ttles.stopped { return fmt.Errorf("scheduler not started") } ttles.add(manifestRef, ttl, entryTypeManifest) return nil }
[ "func", "(", "ttles", "*", "TTLExpirationScheduler", ")", "AddManifest", "(", "manifestRef", "reference", ".", "Canonical", ",", "ttl", "time", ".", "Duration", ")", "error", "{", "ttles", ".", "Lock", "(", ")", "\n", "defer", "ttles", ".", "Unlock", "(", ...
// AddManifest schedules a manifest cleanup after ttl expires
[ "AddManifest", "schedules", "a", "manifest", "cleanup", "after", "ttl", "expires" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/scheduler/scheduler.go#L98-L108
train
docker/distribution
registry/proxy/scheduler/scheduler.go
Stop
func (ttles *TTLExpirationScheduler) Stop() { ttles.Lock() defer ttles.Unlock() if err := ttles.writeState(); err != nil { dcontext.GetLogger(ttles.ctx).Errorf("Error writing scheduler state: %s", err) } for _, entry := range ttles.entries { entry.timer.Stop() } close(ttles.doneChan) ttles.saveTimer.Stop() ttles.stopped = true }
go
func (ttles *TTLExpirationScheduler) Stop() { ttles.Lock() defer ttles.Unlock() if err := ttles.writeState(); err != nil { dcontext.GetLogger(ttles.ctx).Errorf("Error writing scheduler state: %s", err) } for _, entry := range ttles.entries { entry.timer.Stop() } close(ttles.doneChan) ttles.saveTimer.Stop() ttles.stopped = true }
[ "func", "(", "ttles", "*", "TTLExpirationScheduler", ")", "Stop", "(", ")", "{", "ttles", ".", "Lock", "(", ")", "\n", "defer", "ttles", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "ttles", ".", "writeState", "(", ")", ";", "err", "!=", "nil"...
// Stop stops the scheduler.
[ "Stop", "stops", "the", "scheduler", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/scheduler/scheduler.go#L209-L224
train
docker/distribution
registry/auth/htpasswd/htpasswd.go
newHTPasswd
func newHTPasswd(rd io.Reader) (*htpasswd, error) { entries, err := parseHTPasswd(rd) if err != nil { return nil, err } return &htpasswd{entries: entries}, nil }
go
func newHTPasswd(rd io.Reader) (*htpasswd, error) { entries, err := parseHTPasswd(rd) if err != nil { return nil, err } return &htpasswd{entries: entries}, nil }
[ "func", "newHTPasswd", "(", "rd", "io", ".", "Reader", ")", "(", "*", "htpasswd", ",", "error", ")", "{", "entries", ",", "err", ":=", "parseHTPasswd", "(", "rd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "...
// newHTPasswd parses the reader and returns an htpasswd or an error.
[ "newHTPasswd", "parses", "the", "reader", "and", "returns", "an", "htpasswd", "or", "an", "error", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/htpasswd/htpasswd.go#L21-L28
train
docker/distribution
registry/auth/htpasswd/htpasswd.go
parseHTPasswd
func parseHTPasswd(rd io.Reader) (map[string][]byte, error) { entries := map[string][]byte{} scanner := bufio.NewScanner(rd) var line int for scanner.Scan() { line++ // 1-based line numbering t := strings.TrimSpace(scanner.Text()) if len(t) < 1 { continue } // lines that *begin* with a '#' are considered comments if t[0] == '#' { continue } i := strings.Index(t, ":") if i < 0 || i >= len(t) { return nil, fmt.Errorf("htpasswd: invalid entry at line %d: %q", line, scanner.Text()) } entries[t[:i]] = []byte(t[i+1:]) } if err := scanner.Err(); err != nil { return nil, err } return entries, nil }
go
func parseHTPasswd(rd io.Reader) (map[string][]byte, error) { entries := map[string][]byte{} scanner := bufio.NewScanner(rd) var line int for scanner.Scan() { line++ // 1-based line numbering t := strings.TrimSpace(scanner.Text()) if len(t) < 1 { continue } // lines that *begin* with a '#' are considered comments if t[0] == '#' { continue } i := strings.Index(t, ":") if i < 0 || i >= len(t) { return nil, fmt.Errorf("htpasswd: invalid entry at line %d: %q", line, scanner.Text()) } entries[t[:i]] = []byte(t[i+1:]) } if err := scanner.Err(); err != nil { return nil, err } return entries, nil }
[ "func", "parseHTPasswd", "(", "rd", "io", ".", "Reader", ")", "(", "map", "[", "string", "]", "[", "]", "byte", ",", "error", ")", "{", "entries", ":=", "map", "[", "string", "]", "[", "]", "byte", "{", "}", "\n", "scanner", ":=", "bufio", ".", ...
// parseHTPasswd parses the contents of htpasswd. This will read all the // entries in the file, whether or not they are needed. An error is returned // if a syntax errors are encountered or if the reader fails.
[ "parseHTPasswd", "parses", "the", "contents", "of", "htpasswd", ".", "This", "will", "read", "all", "the", "entries", "in", "the", "file", "whether", "or", "not", "they", "are", "needed", ".", "An", "error", "is", "returned", "if", "a", "syntax", "errors",...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/htpasswd/htpasswd.go#L52-L82
train
docker/distribution
registry/storage/error.go
pushError
func pushError(errors []error, path string, err error) []error { return append(errors, fmt.Errorf("%s: %s", path, err)) }
go
func pushError(errors []error, path string, err error) []error { return append(errors, fmt.Errorf("%s: %s", path, err)) }
[ "func", "pushError", "(", "errors", "[", "]", "error", ",", "path", "string", ",", "err", "error", ")", "[", "]", "error", "{", "return", "append", "(", "errors", ",", "fmt", ".", "Errorf", "(", "\"%s: %s\"", ",", "path", ",", "err", ")", ")", "\n"...
// pushError formats an error type given a path and an error // and pushes it to a slice of errors
[ "pushError", "formats", "an", "error", "type", "given", "a", "path", "and", "an", "error", "and", "pushes", "it", "to", "a", "slice", "of", "errors" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/error.go#L7-L9
train
docker/distribution
manifest/schema1/reference_builder.go
NewReferenceManifestBuilder
func NewReferenceManifestBuilder(pk libtrust.PrivateKey, ref reference.Named, architecture string) distribution.ManifestBuilder { tag := "" if tagged, isTagged := ref.(reference.Tagged); isTagged { tag = tagged.Tag() } return &referenceManifestBuilder{ Manifest: Manifest{ Versioned: manifest.Versioned{ SchemaVersion: 1, }, Name: ref.Name(), Tag: tag, Architecture: architecture, }, pk: pk, } }
go
func NewReferenceManifestBuilder(pk libtrust.PrivateKey, ref reference.Named, architecture string) distribution.ManifestBuilder { tag := "" if tagged, isTagged := ref.(reference.Tagged); isTagged { tag = tagged.Tag() } return &referenceManifestBuilder{ Manifest: Manifest{ Versioned: manifest.Versioned{ SchemaVersion: 1, }, Name: ref.Name(), Tag: tag, Architecture: architecture, }, pk: pk, } }
[ "func", "NewReferenceManifestBuilder", "(", "pk", "libtrust", ".", "PrivateKey", ",", "ref", "reference", ".", "Named", ",", "architecture", "string", ")", "distribution", ".", "ManifestBuilder", "{", "tag", ":=", "\"\"", "\n", "if", "tagged", ",", "isTagged", ...
// NewReferenceManifestBuilder is used to build new manifests for the current // schema version using schema1 dependencies.
[ "NewReferenceManifestBuilder", "is", "used", "to", "build", "new", "manifests", "for", "the", "current", "schema", "version", "using", "schema1", "dependencies", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/reference_builder.go#L24-L41
train
docker/distribution
manifest/schema1/reference_builder.go
References
func (mb *referenceManifestBuilder) References() []distribution.Descriptor { refs := make([]distribution.Descriptor, len(mb.Manifest.FSLayers)) for i := range mb.Manifest.FSLayers { layerDigest := mb.Manifest.FSLayers[i].BlobSum history := mb.Manifest.History[i] ref := Reference{layerDigest, 0, history} refs[i] = ref.Descriptor() } return refs }
go
func (mb *referenceManifestBuilder) References() []distribution.Descriptor { refs := make([]distribution.Descriptor, len(mb.Manifest.FSLayers)) for i := range mb.Manifest.FSLayers { layerDigest := mb.Manifest.FSLayers[i].BlobSum history := mb.Manifest.History[i] ref := Reference{layerDigest, 0, history} refs[i] = ref.Descriptor() } return refs }
[ "func", "(", "mb", "*", "referenceManifestBuilder", ")", "References", "(", ")", "[", "]", "distribution", ".", "Descriptor", "{", "refs", ":=", "make", "(", "[", "]", "distribution", ".", "Descriptor", ",", "len", "(", "mb", ".", "Manifest", ".", "FSLay...
// References returns the current references added to this builder
[ "References", "returns", "the", "current", "references", "added", "to", "this", "builder" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/reference_builder.go#L72-L81
train
docker/distribution
manifest/schema1/reference_builder.go
Descriptor
func (r Reference) Descriptor() distribution.Descriptor { return distribution.Descriptor{ MediaType: MediaTypeManifestLayer, Digest: r.Digest, Size: r.Size, } }
go
func (r Reference) Descriptor() distribution.Descriptor { return distribution.Descriptor{ MediaType: MediaTypeManifestLayer, Digest: r.Digest, Size: r.Size, } }
[ "func", "(", "r", "Reference", ")", "Descriptor", "(", ")", "distribution", ".", "Descriptor", "{", "return", "distribution", ".", "Descriptor", "{", "MediaType", ":", "MediaTypeManifestLayer", ",", "Digest", ":", "r", ".", "Digest", ",", "Size", ":", "r", ...
// Descriptor describes a reference
[ "Descriptor", "describes", "a", "reference" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/reference_builder.go#L92-L98
train
docker/distribution
registry/auth/token/token.go
NewToken
func NewToken(rawToken string) (*Token, error) { parts := strings.Split(rawToken, TokenSeparator) if len(parts) != 3 { return nil, ErrMalformedToken } var ( rawHeader, rawClaims = parts[0], parts[1] headerJSON, claimsJSON []byte err error ) defer func() { if err != nil { log.Infof("error while unmarshalling raw token: %s", err) } }() if headerJSON, err = joseBase64UrlDecode(rawHeader); err != nil { err = fmt.Errorf("unable to decode header: %s", err) return nil, ErrMalformedToken } if claimsJSON, err = joseBase64UrlDecode(rawClaims); err != nil { err = fmt.Errorf("unable to decode claims: %s", err) return nil, ErrMalformedToken } token := new(Token) token.Header = new(Header) token.Claims = new(ClaimSet) token.Raw = strings.Join(parts[:2], TokenSeparator) if token.Signature, err = joseBase64UrlDecode(parts[2]); err != nil { err = fmt.Errorf("unable to decode signature: %s", err) return nil, ErrMalformedToken } if err = json.Unmarshal(headerJSON, token.Header); err != nil { return nil, ErrMalformedToken } if err = json.Unmarshal(claimsJSON, token.Claims); err != nil { return nil, ErrMalformedToken } return token, nil }
go
func NewToken(rawToken string) (*Token, error) { parts := strings.Split(rawToken, TokenSeparator) if len(parts) != 3 { return nil, ErrMalformedToken } var ( rawHeader, rawClaims = parts[0], parts[1] headerJSON, claimsJSON []byte err error ) defer func() { if err != nil { log.Infof("error while unmarshalling raw token: %s", err) } }() if headerJSON, err = joseBase64UrlDecode(rawHeader); err != nil { err = fmt.Errorf("unable to decode header: %s", err) return nil, ErrMalformedToken } if claimsJSON, err = joseBase64UrlDecode(rawClaims); err != nil { err = fmt.Errorf("unable to decode claims: %s", err) return nil, ErrMalformedToken } token := new(Token) token.Header = new(Header) token.Claims = new(ClaimSet) token.Raw = strings.Join(parts[:2], TokenSeparator) if token.Signature, err = joseBase64UrlDecode(parts[2]); err != nil { err = fmt.Errorf("unable to decode signature: %s", err) return nil, ErrMalformedToken } if err = json.Unmarshal(headerJSON, token.Header); err != nil { return nil, ErrMalformedToken } if err = json.Unmarshal(claimsJSON, token.Claims); err != nil { return nil, ErrMalformedToken } return token, nil }
[ "func", "NewToken", "(", "rawToken", "string", ")", "(", "*", "Token", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "rawToken", ",", "TokenSeparator", ")", "\n", "if", "len", "(", "parts", ")", "!=", "3", "{", "return", "nil",...
// NewToken parses the given raw token string // and constructs an unverified JSON Web Token.
[ "NewToken", "parses", "the", "given", "raw", "token", "string", "and", "constructs", "an", "unverified", "JSON", "Web", "Token", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/token.go#L85-L132
train
docker/distribution
registry/auth/token/token.go
Verify
func (t *Token) Verify(verifyOpts VerifyOptions) error { // Verify that the Issuer claim is a trusted authority. if !contains(verifyOpts.TrustedIssuers, t.Claims.Issuer) { log.Infof("token from untrusted issuer: %q", t.Claims.Issuer) return ErrInvalidToken } // Verify that the Audience claim is allowed. if !contains(verifyOpts.AcceptedAudiences, t.Claims.Audience) { log.Infof("token intended for another audience: %q", t.Claims.Audience) return ErrInvalidToken } // Verify that the token is currently usable and not expired. currentTime := time.Now() ExpWithLeeway := time.Unix(t.Claims.Expiration, 0).Add(Leeway) if currentTime.After(ExpWithLeeway) { log.Infof("token not to be used after %s - currently %s", ExpWithLeeway, currentTime) return ErrInvalidToken } NotBeforeWithLeeway := time.Unix(t.Claims.NotBefore, 0).Add(-Leeway) if currentTime.Before(NotBeforeWithLeeway) { log.Infof("token not to be used before %s - currently %s", NotBeforeWithLeeway, currentTime) return ErrInvalidToken } // Verify the token signature. if len(t.Signature) == 0 { log.Info("token has no signature") return ErrInvalidToken } // Verify that the signing key is trusted. signingKey, err := t.VerifySigningKey(verifyOpts) if err != nil { log.Info(err) return ErrInvalidToken } // Finally, verify the signature of the token using the key which signed it. if err := signingKey.Verify(strings.NewReader(t.Raw), t.Header.SigningAlg, t.Signature); err != nil { log.Infof("unable to verify token signature: %s", err) return ErrInvalidToken } return nil }
go
func (t *Token) Verify(verifyOpts VerifyOptions) error { // Verify that the Issuer claim is a trusted authority. if !contains(verifyOpts.TrustedIssuers, t.Claims.Issuer) { log.Infof("token from untrusted issuer: %q", t.Claims.Issuer) return ErrInvalidToken } // Verify that the Audience claim is allowed. if !contains(verifyOpts.AcceptedAudiences, t.Claims.Audience) { log.Infof("token intended for another audience: %q", t.Claims.Audience) return ErrInvalidToken } // Verify that the token is currently usable and not expired. currentTime := time.Now() ExpWithLeeway := time.Unix(t.Claims.Expiration, 0).Add(Leeway) if currentTime.After(ExpWithLeeway) { log.Infof("token not to be used after %s - currently %s", ExpWithLeeway, currentTime) return ErrInvalidToken } NotBeforeWithLeeway := time.Unix(t.Claims.NotBefore, 0).Add(-Leeway) if currentTime.Before(NotBeforeWithLeeway) { log.Infof("token not to be used before %s - currently %s", NotBeforeWithLeeway, currentTime) return ErrInvalidToken } // Verify the token signature. if len(t.Signature) == 0 { log.Info("token has no signature") return ErrInvalidToken } // Verify that the signing key is trusted. signingKey, err := t.VerifySigningKey(verifyOpts) if err != nil { log.Info(err) return ErrInvalidToken } // Finally, verify the signature of the token using the key which signed it. if err := signingKey.Verify(strings.NewReader(t.Raw), t.Header.SigningAlg, t.Signature); err != nil { log.Infof("unable to verify token signature: %s", err) return ErrInvalidToken } return nil }
[ "func", "(", "t", "*", "Token", ")", "Verify", "(", "verifyOpts", "VerifyOptions", ")", "error", "{", "if", "!", "contains", "(", "verifyOpts", ".", "TrustedIssuers", ",", "t", ".", "Claims", ".", "Issuer", ")", "{", "log", ".", "Infof", "(", "\"token ...
// Verify attempts to verify this token using the given options. // Returns a nil error if the token is valid.
[ "Verify", "attempts", "to", "verify", "this", "token", "using", "the", "given", "options", ".", "Returns", "a", "nil", "error", "if", "the", "token", "is", "valid", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/token.go#L136-L184
train
docker/distribution
registry/auth/token/token.go
accessSet
func (t *Token) accessSet() accessSet { if t.Claims == nil { return nil } accessSet := make(accessSet, len(t.Claims.Access)) for _, resourceActions := range t.Claims.Access { resource := auth.Resource{ Type: resourceActions.Type, Name: resourceActions.Name, } set, exists := accessSet[resource] if !exists { set = newActionSet() accessSet[resource] = set } for _, action := range resourceActions.Actions { set.add(action) } } return accessSet }
go
func (t *Token) accessSet() accessSet { if t.Claims == nil { return nil } accessSet := make(accessSet, len(t.Claims.Access)) for _, resourceActions := range t.Claims.Access { resource := auth.Resource{ Type: resourceActions.Type, Name: resourceActions.Name, } set, exists := accessSet[resource] if !exists { set = newActionSet() accessSet[resource] = set } for _, action := range resourceActions.Actions { set.add(action) } } return accessSet }
[ "func", "(", "t", "*", "Token", ")", "accessSet", "(", ")", "accessSet", "{", "if", "t", ".", "Claims", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "accessSet", ":=", "make", "(", "accessSet", ",", "len", "(", "t", ".", "Claims", ".", "Ac...
// accessSet returns a set of actions available for the resource // actions listed in the `access` section of this token.
[ "accessSet", "returns", "a", "set", "of", "actions", "available", "for", "the", "resource", "actions", "listed", "in", "the", "access", "section", "of", "this", "token", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/token.go#L326-L351
train
docker/distribution
registry/storage/blobstore.go
Get
func (bs *blobStore) Get(ctx context.Context, dgst digest.Digest) ([]byte, error) { bp, err := bs.path(dgst) if err != nil { return nil, err } p, err := getContent(ctx, bs.driver, bp) if err != nil { switch err.(type) { case driver.PathNotFoundError: return nil, distribution.ErrBlobUnknown } return nil, err } return p, nil }
go
func (bs *blobStore) Get(ctx context.Context, dgst digest.Digest) ([]byte, error) { bp, err := bs.path(dgst) if err != nil { return nil, err } p, err := getContent(ctx, bs.driver, bp) if err != nil { switch err.(type) { case driver.PathNotFoundError: return nil, distribution.ErrBlobUnknown } return nil, err } return p, nil }
[ "func", "(", "bs", "*", "blobStore", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "dgst", "digest", ".", "Digest", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "bp", ",", "err", ":=", "bs", ".", "path", "(", "dgst", ")", "\n",...
// Get implements the BlobReadService.Get call.
[ "Get", "implements", "the", "BlobReadService", ".", "Get", "call", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobstore.go#L25-L42
train
docker/distribution
registry/storage/blobstore.go
Put
func (bs *blobStore) Put(ctx context.Context, mediaType string, p []byte) (distribution.Descriptor, error) { dgst := digest.FromBytes(p) desc, err := bs.statter.Stat(ctx, dgst) if err == nil { // content already present return desc, nil } else if err != distribution.ErrBlobUnknown { dcontext.GetLogger(ctx).Errorf("blobStore: error stating content (%v): %v", dgst, err) // real error, return it return distribution.Descriptor{}, err } bp, err := bs.path(dgst) if err != nil { return distribution.Descriptor{}, err } // TODO(stevvooe): Write out mediatype here, as well. return distribution.Descriptor{ Size: int64(len(p)), // NOTE(stevvooe): The central blob store firewalls media types from // other users. The caller should look this up and override the value // for the specific repository. MediaType: "application/octet-stream", Digest: dgst, }, bs.driver.PutContent(ctx, bp, p) }
go
func (bs *blobStore) Put(ctx context.Context, mediaType string, p []byte) (distribution.Descriptor, error) { dgst := digest.FromBytes(p) desc, err := bs.statter.Stat(ctx, dgst) if err == nil { // content already present return desc, nil } else if err != distribution.ErrBlobUnknown { dcontext.GetLogger(ctx).Errorf("blobStore: error stating content (%v): %v", dgst, err) // real error, return it return distribution.Descriptor{}, err } bp, err := bs.path(dgst) if err != nil { return distribution.Descriptor{}, err } // TODO(stevvooe): Write out mediatype here, as well. return distribution.Descriptor{ Size: int64(len(p)), // NOTE(stevvooe): The central blob store firewalls media types from // other users. The caller should look this up and override the value // for the specific repository. MediaType: "application/octet-stream", Digest: dgst, }, bs.driver.PutContent(ctx, bp, p) }
[ "func", "(", "bs", "*", "blobStore", ")", "Put", "(", "ctx", "context", ".", "Context", ",", "mediaType", "string", ",", "p", "[", "]", "byte", ")", "(", "distribution", ".", "Descriptor", ",", "error", ")", "{", "dgst", ":=", "digest", ".", "FromByt...
// Put stores the content p in the blob store, calculating the digest. If the // content is already present, only the digest will be returned. This should // only be used for small objects, such as manifests. This implemented as a convenience for other Put implementations
[ "Put", "stores", "the", "content", "p", "in", "the", "blob", "store", "calculating", "the", "digest", ".", "If", "the", "content", "is", "already", "present", "only", "the", "digest", "will", "be", "returned", ".", "This", "should", "only", "be", "used", ...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobstore.go#L61-L88
train
docker/distribution
registry/storage/blobstore.go
path
func (bs *blobStore) path(dgst digest.Digest) (string, error) { bp, err := pathFor(blobDataPathSpec{ digest: dgst, }) if err != nil { return "", err } return bp, nil }
go
func (bs *blobStore) path(dgst digest.Digest) (string, error) { bp, err := pathFor(blobDataPathSpec{ digest: dgst, }) if err != nil { return "", err } return bp, nil }
[ "func", "(", "bs", "*", "blobStore", ")", "path", "(", "dgst", "digest", ".", "Digest", ")", "(", "string", ",", "error", ")", "{", "bp", ",", "err", ":=", "pathFor", "(", "blobDataPathSpec", "{", "digest", ":", "dgst", ",", "}", ")", "\n", "if", ...
// path returns the canonical path for the blob identified by digest. The blob // may or may not exist.
[ "path", "returns", "the", "canonical", "path", "for", "the", "blob", "identified", "by", "digest", ".", "The", "blob", "may", "or", "may", "not", "exist", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobstore.go#L120-L130
train
docker/distribution
registry/storage/blobstore.go
link
func (bs *blobStore) link(ctx context.Context, path string, dgst digest.Digest) error { // The contents of the "link" file are the exact string contents of the // digest, which is specified in that package. return bs.driver.PutContent(ctx, path, []byte(dgst)) }
go
func (bs *blobStore) link(ctx context.Context, path string, dgst digest.Digest) error { // The contents of the "link" file are the exact string contents of the // digest, which is specified in that package. return bs.driver.PutContent(ctx, path, []byte(dgst)) }
[ "func", "(", "bs", "*", "blobStore", ")", "link", "(", "ctx", "context", ".", "Context", ",", "path", "string", ",", "dgst", "digest", ".", "Digest", ")", "error", "{", "return", "bs", ".", "driver", ".", "PutContent", "(", "ctx", ",", "path", ",", ...
// link links the path to the provided digest by writing the digest into the // target file. Caller must ensure that the blob actually exists.
[ "link", "links", "the", "path", "to", "the", "provided", "digest", "by", "writing", "the", "digest", "into", "the", "target", "file", ".", "Caller", "must", "ensure", "that", "the", "blob", "actually", "exists", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobstore.go#L134-L138
train
docker/distribution
registry/storage/blobstore.go
readlink
func (bs *blobStore) readlink(ctx context.Context, path string) (digest.Digest, error) { content, err := bs.driver.GetContent(ctx, path) if err != nil { return "", err } linked, err := digest.Parse(string(content)) if err != nil { return "", err } return linked, nil }
go
func (bs *blobStore) readlink(ctx context.Context, path string) (digest.Digest, error) { content, err := bs.driver.GetContent(ctx, path) if err != nil { return "", err } linked, err := digest.Parse(string(content)) if err != nil { return "", err } return linked, nil }
[ "func", "(", "bs", "*", "blobStore", ")", "readlink", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "digest", ".", "Digest", ",", "error", ")", "{", "content", ",", "err", ":=", "bs", ".", "driver", ".", "GetContent", "(", ...
// readlink returns the linked digest at path.
[ "readlink", "returns", "the", "linked", "digest", "at", "path", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobstore.go#L141-L153
train
docker/distribution
registry/storage/blobstore.go
Stat
func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { path, err := pathFor(blobDataPathSpec{ digest: dgst, }) if err != nil { return distribution.Descriptor{}, err } fi, err := bs.driver.Stat(ctx, path) if err != nil { switch err := err.(type) { case driver.PathNotFoundError: return distribution.Descriptor{}, distribution.ErrBlobUnknown default: return distribution.Descriptor{}, err } } if fi.IsDir() { // NOTE(stevvooe): This represents a corruption situation. Somehow, we // calculated a blob path and then detected a directory. We log the // error and then error on the side of not knowing about the blob. dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path) return distribution.Descriptor{}, distribution.ErrBlobUnknown } // TODO(stevvooe): Add method to resolve the mediatype. We can store and // cache a "global" media type for the blob, even if a specific repo has a // mediatype that overrides the main one. return distribution.Descriptor{ Size: fi.Size(), // NOTE(stevvooe): The central blob store firewalls media types from // other users. The caller should look this up and override the value // for the specific repository. MediaType: "application/octet-stream", Digest: dgst, }, nil }
go
func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { path, err := pathFor(blobDataPathSpec{ digest: dgst, }) if err != nil { return distribution.Descriptor{}, err } fi, err := bs.driver.Stat(ctx, path) if err != nil { switch err := err.(type) { case driver.PathNotFoundError: return distribution.Descriptor{}, distribution.ErrBlobUnknown default: return distribution.Descriptor{}, err } } if fi.IsDir() { // NOTE(stevvooe): This represents a corruption situation. Somehow, we // calculated a blob path and then detected a directory. We log the // error and then error on the side of not knowing about the blob. dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path) return distribution.Descriptor{}, distribution.ErrBlobUnknown } // TODO(stevvooe): Add method to resolve the mediatype. We can store and // cache a "global" media type for the blob, even if a specific repo has a // mediatype that overrides the main one. return distribution.Descriptor{ Size: fi.Size(), // NOTE(stevvooe): The central blob store firewalls media types from // other users. The caller should look this up and override the value // for the specific repository. MediaType: "application/octet-stream", Digest: dgst, }, nil }
[ "func", "(", "bs", "*", "blobStatter", ")", "Stat", "(", "ctx", "context", ".", "Context", ",", "dgst", "digest", ".", "Digest", ")", "(", "distribution", ".", "Descriptor", ",", "error", ")", "{", "path", ",", "err", ":=", "pathFor", "(", "blobDataPat...
// Stat implements BlobStatter.Stat by returning the descriptor for the blob // in the main blob store. If this method returns successfully, there is // strong guarantee that the blob exists and is available.
[ "Stat", "implements", "BlobStatter", ".", "Stat", "by", "returning", "the", "descriptor", "for", "the", "blob", "in", "the", "main", "blob", "store", ".", "If", "this", "method", "returns", "successfully", "there", "is", "strong", "guarantee", "that", "the", ...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobstore.go#L164-L204
train
docker/distribution
registry/storage/driver/inmemory/driver.go
New
func New() *Driver { return &Driver{ baseEmbed: baseEmbed{ Base: base.Base{ StorageDriver: &driver{ root: &dir{ common: common{ p: "/", mod: time.Now(), }, }, }, }, }, } }
go
func New() *Driver { return &Driver{ baseEmbed: baseEmbed{ Base: base.Base{ StorageDriver: &driver{ root: &dir{ common: common{ p: "/", mod: time.Now(), }, }, }, }, }, } }
[ "func", "New", "(", ")", "*", "Driver", "{", "return", "&", "Driver", "{", "baseEmbed", ":", "baseEmbed", "{", "Base", ":", "base", ".", "Base", "{", "StorageDriver", ":", "&", "driver", "{", "root", ":", "&", "dir", "{", "common", ":", "common", "...
// New constructs a new Driver.
[ "New", "constructs", "a", "new", "Driver", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/driver.go#L48-L63
train
docker/distribution
registry/storage/driver/inmemory/driver.go
Stat
func (d *driver) Stat(ctx context.Context, path string) (storagedriver.FileInfo, error) { d.mutex.RLock() defer d.mutex.RUnlock() normalized := normalize(path) found := d.root.find(normalized) if found.path() != normalized { return nil, storagedriver.PathNotFoundError{Path: path} } fi := storagedriver.FileInfoFields{ Path: path, IsDir: found.isdir(), ModTime: found.modtime(), } if !fi.IsDir { fi.Size = int64(len(found.(*file).data)) } return storagedriver.FileInfoInternal{FileInfoFields: fi}, nil }
go
func (d *driver) Stat(ctx context.Context, path string) (storagedriver.FileInfo, error) { d.mutex.RLock() defer d.mutex.RUnlock() normalized := normalize(path) found := d.root.find(normalized) if found.path() != normalized { return nil, storagedriver.PathNotFoundError{Path: path} } fi := storagedriver.FileInfoFields{ Path: path, IsDir: found.isdir(), ModTime: found.modtime(), } if !fi.IsDir { fi.Size = int64(len(found.(*file).data)) } return storagedriver.FileInfoInternal{FileInfoFields: fi}, nil }
[ "func", "(", "d", "*", "driver", ")", "Stat", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "storagedriver", ".", "FileInfo", ",", "error", ")", "{", "d", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "m...
// Stat returns info about the provided path.
[ "Stat", "returns", "info", "about", "the", "provided", "path", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/driver.go#L154-L176
train
docker/distribution
registry/storage/driver/filesystem/driver.go
New
func New(params DriverParameters) *Driver { fsDriver := &driver{rootDirectory: params.RootDirectory} return &Driver{ baseEmbed: baseEmbed{ Base: base.Base{ StorageDriver: base.NewRegulator(fsDriver, params.MaxThreads), }, }, } }
go
func New(params DriverParameters) *Driver { fsDriver := &driver{rootDirectory: params.RootDirectory} return &Driver{ baseEmbed: baseEmbed{ Base: base.Base{ StorageDriver: base.NewRegulator(fsDriver, params.MaxThreads), }, }, } }
[ "func", "New", "(", "params", "DriverParameters", ")", "*", "Driver", "{", "fsDriver", ":=", "&", "driver", "{", "rootDirectory", ":", "params", ".", "RootDirectory", "}", "\n", "return", "&", "Driver", "{", "baseEmbed", ":", "baseEmbed", "{", "Base", ":",...
// New constructs a new Driver with a given rootDirectory
[ "New", "constructs", "a", "new", "Driver", "with", "a", "given", "rootDirectory" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/filesystem/driver.go#L100-L110
train
docker/distribution
registry/storage/driver/filesystem/driver.go
fullPath
func (d *driver) fullPath(subPath string) string { return path.Join(d.rootDirectory, subPath) }
go
func (d *driver) fullPath(subPath string) string { return path.Join(d.rootDirectory, subPath) }
[ "func", "(", "d", "*", "driver", ")", "fullPath", "(", "subPath", "string", ")", "string", "{", "return", "path", ".", "Join", "(", "d", ".", "rootDirectory", ",", "subPath", ")", "\n", "}" ]
// fullPath returns the absolute path of a key within the Driver's storage.
[ "fullPath", "returns", "the", "absolute", "path", "of", "a", "key", "within", "the", "Driver", "s", "storage", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/filesystem/driver.go#L299-L301
train
docker/distribution
registry/handlers/helpers.go
closeResources
func closeResources(handler http.Handler, closers ...io.Closer) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for _, closer := range closers { defer closer.Close() } handler.ServeHTTP(w, r) }) }
go
func closeResources(handler http.Handler, closers ...io.Closer) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for _, closer := range closers { defer closer.Close() } handler.ServeHTTP(w, r) }) }
[ "func", "closeResources", "(", "handler", "http", ".", "Handler", ",", "closers", "...", "io", ".", "Closer", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "...
// closeResources closes all the provided resources after running the target // handler.
[ "closeResources", "closes", "all", "the", "provided", "resources", "after", "running", "the", "target", "handler", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/helpers.go#L14-L21
train
docker/distribution
registry/handlers/helpers.go
copyFullPayload
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 clientClosed := r.Context().Done() var body = r.Body if limit > 0 { body = http.MaxBytesReader(responseWriter, body, limit) } // Read in the data, if any. copied, err := io.Copy(destWriter, body) if clientClosed != nil && (err != nil || (r.ContentLength > 0 && copied < r.ContentLength)) { // Didn't receive as much content as expected. Did the client // disconnect during the request? If so, avoid returning a 400 // error to keep the logs cleaner. select { case <-clientClosed: // Set the response code to "499 Client Closed Request" // Even though the connection has already been closed, // this causes the logger to pick up a 499 error // instead of showing 0 for the HTTP status. responseWriter.WriteHeader(499) dcontext.GetLoggerWithFields(ctx, map[interface{}]interface{}{ "error": err, "copied": copied, "contentLength": r.ContentLength, }, "error", "copied", "contentLength").Error("client disconnected during " + action) return errors.New("client disconnected") default: } } if err != nil { dcontext.GetLogger(ctx).Errorf("unknown error reading request payload: %v", err) return err } return nil }
go
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 clientClosed := r.Context().Done() var body = r.Body if limit > 0 { body = http.MaxBytesReader(responseWriter, body, limit) } // Read in the data, if any. copied, err := io.Copy(destWriter, body) if clientClosed != nil && (err != nil || (r.ContentLength > 0 && copied < r.ContentLength)) { // Didn't receive as much content as expected. Did the client // disconnect during the request? If so, avoid returning a 400 // error to keep the logs cleaner. select { case <-clientClosed: // Set the response code to "499 Client Closed Request" // Even though the connection has already been closed, // this causes the logger to pick up a 499 error // instead of showing 0 for the HTTP status. responseWriter.WriteHeader(499) dcontext.GetLoggerWithFields(ctx, map[interface{}]interface{}{ "error": err, "copied": copied, "contentLength": r.ContentLength, }, "error", "copied", "contentLength").Error("client disconnected during " + action) return errors.New("client disconnected") default: } } if err != nil { dcontext.GetLogger(ctx).Errorf("unknown error reading request payload: %v", err) return err } return nil }
[ "func", "copyFullPayload", "(", "ctx", "context", ".", "Context", ",", "responseWriter", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "destWriter", "io", ".", "Writer", ",", "limit", "int64", ",", "action", "string", ")", "err...
// copyFullPayload copies the payload of an HTTP request to destWriter. If it // receives less content than expected, and the client disconnected during the // 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.
[ "copyFullPayload", "copies", "the", "payload", "of", "an", "HTTP", "request", "to", "destWriter", ".", "If", "it", "receives", "less", "content", "than", "expected", "and", "the", "client", "disconnected", "during", "the", "upload", "it", "avoids", "sending", ...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/helpers.go#L28-L66
train
docker/distribution
manifest/manifestlist/manifestlist.go
References
func (m ManifestList) References() []distribution.Descriptor { dependencies := make([]distribution.Descriptor, len(m.Manifests)) for i := range m.Manifests { dependencies[i] = m.Manifests[i].Descriptor } return dependencies }
go
func (m ManifestList) References() []distribution.Descriptor { dependencies := make([]distribution.Descriptor, len(m.Manifests)) for i := range m.Manifests { dependencies[i] = m.Manifests[i].Descriptor } return dependencies }
[ "func", "(", "m", "ManifestList", ")", "References", "(", ")", "[", "]", "distribution", ".", "Descriptor", "{", "dependencies", ":=", "make", "(", "[", "]", "distribution", ".", "Descriptor", ",", "len", "(", "m", ".", "Manifests", ")", ")", "\n", "fo...
// References returns the distribution descriptors for the referenced image // manifests.
[ "References", "returns", "the", "distribution", "descriptors", "for", "the", "referenced", "image", "manifests", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/manifestlist/manifestlist.go#L125-L132
train
docker/distribution
manifest/manifestlist/manifestlist.go
FromDescriptors
func FromDescriptors(descriptors []ManifestDescriptor) (*DeserializedManifestList, error) { var mediaType string if len(descriptors) > 0 && descriptors[0].Descriptor.MediaType == v1.MediaTypeImageManifest { mediaType = v1.MediaTypeImageIndex } else { mediaType = MediaTypeManifestList } return FromDescriptorsWithMediaType(descriptors, mediaType) }
go
func FromDescriptors(descriptors []ManifestDescriptor) (*DeserializedManifestList, error) { var mediaType string if len(descriptors) > 0 && descriptors[0].Descriptor.MediaType == v1.MediaTypeImageManifest { mediaType = v1.MediaTypeImageIndex } else { mediaType = MediaTypeManifestList } return FromDescriptorsWithMediaType(descriptors, mediaType) }
[ "func", "FromDescriptors", "(", "descriptors", "[", "]", "ManifestDescriptor", ")", "(", "*", "DeserializedManifestList", ",", "error", ")", "{", "var", "mediaType", "string", "\n", "if", "len", "(", "descriptors", ")", ">", "0", "&&", "descriptors", "[", "0...
// FromDescriptors takes a slice of descriptors, and returns a // DeserializedManifestList which contains the resulting manifest list // and its JSON representation.
[ "FromDescriptors", "takes", "a", "slice", "of", "descriptors", "and", "returns", "a", "DeserializedManifestList", "which", "contains", "the", "resulting", "manifest", "list", "and", "its", "JSON", "representation", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/manifestlist/manifestlist.go#L146-L155
train
docker/distribution
manifest/manifestlist/manifestlist.go
FromDescriptorsWithMediaType
func FromDescriptorsWithMediaType(descriptors []ManifestDescriptor, mediaType string) (*DeserializedManifestList, error) { m := ManifestList{ Versioned: manifest.Versioned{ SchemaVersion: 2, MediaType: mediaType, }, } m.Manifests = make([]ManifestDescriptor, len(descriptors)) copy(m.Manifests, descriptors) deserialized := DeserializedManifestList{ ManifestList: m, } var err error deserialized.canonical, err = json.MarshalIndent(&m, "", " ") return &deserialized, err }
go
func FromDescriptorsWithMediaType(descriptors []ManifestDescriptor, mediaType string) (*DeserializedManifestList, error) { m := ManifestList{ Versioned: manifest.Versioned{ SchemaVersion: 2, MediaType: mediaType, }, } m.Manifests = make([]ManifestDescriptor, len(descriptors)) copy(m.Manifests, descriptors) deserialized := DeserializedManifestList{ ManifestList: m, } var err error deserialized.canonical, err = json.MarshalIndent(&m, "", " ") return &deserialized, err }
[ "func", "FromDescriptorsWithMediaType", "(", "descriptors", "[", "]", "ManifestDescriptor", ",", "mediaType", "string", ")", "(", "*", "DeserializedManifestList", ",", "error", ")", "{", "m", ":=", "ManifestList", "{", "Versioned", ":", "manifest", ".", "Versioned...
// FromDescriptorsWithMediaType is for testing purposes, it's useful to be able to specify the media type explicitly
[ "FromDescriptorsWithMediaType", "is", "for", "testing", "purposes", "it", "s", "useful", "to", "be", "able", "to", "specify", "the", "media", "type", "explicitly" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/manifestlist/manifestlist.go#L158-L176
train
docker/distribution
manifest/manifestlist/manifestlist.go
UnmarshalJSON
func (m *DeserializedManifestList) UnmarshalJSON(b []byte) error { m.canonical = make([]byte, len(b)) // store manifest list in canonical copy(m.canonical, b) // Unmarshal canonical JSON into ManifestList object var manifestList ManifestList if err := json.Unmarshal(m.canonical, &manifestList); err != nil { return err } m.ManifestList = manifestList return nil }
go
func (m *DeserializedManifestList) UnmarshalJSON(b []byte) error { m.canonical = make([]byte, len(b)) // store manifest list in canonical copy(m.canonical, b) // Unmarshal canonical JSON into ManifestList object var manifestList ManifestList if err := json.Unmarshal(m.canonical, &manifestList); err != nil { return err } m.ManifestList = manifestList return nil }
[ "func", "(", "m", "*", "DeserializedManifestList", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "m", ".", "canonical", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "b", ")", ")", "\n", "copy", "(", "m", ".", "canon...
// UnmarshalJSON populates a new ManifestList struct from JSON data.
[ "UnmarshalJSON", "populates", "a", "new", "ManifestList", "struct", "from", "JSON", "data", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/manifestlist/manifestlist.go#L179-L193
train
docker/distribution
manifest/manifestlist/manifestlist.go
Payload
func (m DeserializedManifestList) Payload() (string, []byte, error) { var mediaType string if m.MediaType == "" { mediaType = v1.MediaTypeImageIndex } else { mediaType = m.MediaType } return mediaType, m.canonical, nil }
go
func (m DeserializedManifestList) Payload() (string, []byte, error) { var mediaType string if m.MediaType == "" { mediaType = v1.MediaTypeImageIndex } else { mediaType = m.MediaType } return mediaType, m.canonical, nil }
[ "func", "(", "m", "DeserializedManifestList", ")", "Payload", "(", ")", "(", "string", ",", "[", "]", "byte", ",", "error", ")", "{", "var", "mediaType", "string", "\n", "if", "m", ".", "MediaType", "==", "\"\"", "{", "mediaType", "=", "v1", ".", "Me...
// Payload returns the raw content of the manifest list. The contents can be // used to calculate the content identifier.
[ "Payload", "returns", "the", "raw", "content", "of", "the", "manifest", "list", ".", "The", "contents", "can", "be", "used", "to", "calculate", "the", "content", "identifier", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/manifestlist/manifestlist.go#L207-L216
train
docker/distribution
registry/handlers/tags.go
tagsDispatcher
func tagsDispatcher(ctx *Context, r *http.Request) http.Handler { tagsHandler := &tagsHandler{ Context: ctx, } return handlers.MethodHandler{ "GET": http.HandlerFunc(tagsHandler.GetTags), } }
go
func tagsDispatcher(ctx *Context, r *http.Request) http.Handler { tagsHandler := &tagsHandler{ Context: ctx, } return handlers.MethodHandler{ "GET": http.HandlerFunc(tagsHandler.GetTags), } }
[ "func", "tagsDispatcher", "(", "ctx", "*", "Context", ",", "r", "*", "http", ".", "Request", ")", "http", ".", "Handler", "{", "tagsHandler", ":=", "&", "tagsHandler", "{", "Context", ":", "ctx", ",", "}", "\n", "return", "handlers", ".", "MethodHandler"...
// tagsDispatcher constructs the tags handler api endpoint.
[ "tagsDispatcher", "constructs", "the", "tags", "handler", "api", "endpoint", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/tags.go#L14-L22
train
docker/distribution
registry/handlers/tags.go
GetTags
func (th *tagsHandler) GetTags(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() tagService := th.Repository.Tags(th) tags, err := tagService.All(th) if err != nil { switch err := err.(type) { case distribution.ErrRepositoryUnknown: th.Errors = append(th.Errors, v2.ErrorCodeNameUnknown.WithDetail(map[string]string{"name": th.Repository.Named().Name()})) case errcode.Error: th.Errors = append(th.Errors, err) default: th.Errors = append(th.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } return } w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) if err := enc.Encode(tagsAPIResponse{ Name: th.Repository.Named().Name(), Tags: tags, }); err != nil { th.Errors = append(th.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } }
go
func (th *tagsHandler) GetTags(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() tagService := th.Repository.Tags(th) tags, err := tagService.All(th) if err != nil { switch err := err.(type) { case distribution.ErrRepositoryUnknown: th.Errors = append(th.Errors, v2.ErrorCodeNameUnknown.WithDetail(map[string]string{"name": th.Repository.Named().Name()})) case errcode.Error: th.Errors = append(th.Errors, err) default: th.Errors = append(th.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) } return } w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) if err := enc.Encode(tagsAPIResponse{ Name: th.Repository.Named().Name(), Tags: tags, }); err != nil { th.Errors = append(th.Errors, errcode.ErrorCodeUnknown.WithDetail(err)) return } }
[ "func", "(", "th", "*", "tagsHandler", ")", "GetTags", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n", "tagService", ":=", "th", ".", "Repository", "...
// GetTags returns a json list of tags for a specific image name.
[ "GetTags", "returns", "a", "json", "list", "of", "tags", "for", "a", "specific", "image", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/tags.go#L35-L62
train
docker/distribution
registry/storage/driver/factory/factory.go
Create
func Create(name string, parameters map[string]interface{}) (storagedriver.StorageDriver, error) { driverFactory, ok := driverFactories[name] if !ok { return nil, InvalidStorageDriverError{name} } return driverFactory.Create(parameters) }
go
func Create(name string, parameters map[string]interface{}) (storagedriver.StorageDriver, error) { driverFactory, ok := driverFactories[name] if !ok { return nil, InvalidStorageDriverError{name} } return driverFactory.Create(parameters) }
[ "func", "Create", "(", "name", "string", ",", "parameters", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "storagedriver", ".", "StorageDriver", ",", "error", ")", "{", "driverFactory", ",", "ok", ":=", "driverFactories", "[", "name", "]", ...
// Create a new storagedriver.StorageDriver with the given name and // parameters. To use a driver, the StorageDriverFactory must first be // registered with the given name. If no drivers are found, an // InvalidStorageDriverError is returned
[ "Create", "a", "new", "storagedriver", ".", "StorageDriver", "with", "the", "given", "name", "and", "parameters", ".", "To", "use", "a", "driver", "the", "StorageDriverFactory", "must", "first", "be", "registered", "with", "the", "given", "name", ".", "If", ...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/factory/factory.go#L49-L55
train
docker/distribution
registry/api/v2/routes.go
RouterWithPrefix
func RouterWithPrefix(prefix string) *mux.Router { rootRouter := mux.NewRouter() router := rootRouter if prefix != "" { router = router.PathPrefix(prefix).Subrouter() } router.StrictSlash(true) for _, descriptor := range routeDescriptors { router.Path(descriptor.Path).Name(descriptor.Name) } return rootRouter }
go
func RouterWithPrefix(prefix string) *mux.Router { rootRouter := mux.NewRouter() router := rootRouter if prefix != "" { router = router.PathPrefix(prefix).Subrouter() } router.StrictSlash(true) for _, descriptor := range routeDescriptors { router.Path(descriptor.Path).Name(descriptor.Name) } return rootRouter }
[ "func", "RouterWithPrefix", "(", "prefix", "string", ")", "*", "mux", ".", "Router", "{", "rootRouter", ":=", "mux", ".", "NewRouter", "(", ")", "\n", "router", ":=", "rootRouter", "\n", "if", "prefix", "!=", "\"\"", "{", "router", "=", "router", ".", ...
// RouterWithPrefix builds a gorilla router with a configured prefix // on all routes.
[ "RouterWithPrefix", "builds", "a", "gorilla", "router", "with", "a", "configured", "prefix", "on", "all", "routes", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/routes.go#L26-L40
train
docker/distribution
health/health.go
Update
func (u *updater) Update(status error) { u.mu.Lock() defer u.mu.Unlock() u.status = status }
go
func (u *updater) Update(status error) { u.mu.Lock() defer u.mu.Unlock() u.status = status }
[ "func", "(", "u", "*", "updater", ")", "Update", "(", "status", "error", ")", "{", "u", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "u", ".", "mu", ".", "Unlock", "(", ")", "\n", "u", ".", "status", "=", "status", "\n", "}" ]
// Update implements the Updater interface, allowing asynchronous access to // the status of a Checker.
[ "Update", "implements", "the", "Updater", "interface", "allowing", "asynchronous", "access", "to", "the", "status", "of", "a", "Checker", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L78-L83
train
docker/distribution
health/health.go
Update
func (tu *thresholdUpdater) Update(status error) { tu.mu.Lock() defer tu.mu.Unlock() if status == nil { tu.count = 0 } else if tu.count < tu.threshold { tu.count++ } tu.status = status }
go
func (tu *thresholdUpdater) Update(status error) { tu.mu.Lock() defer tu.mu.Unlock() if status == nil { tu.count = 0 } else if tu.count < tu.threshold { tu.count++ } tu.status = status }
[ "func", "(", "tu", "*", "thresholdUpdater", ")", "Update", "(", "status", "error", ")", "{", "tu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tu", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "status", "==", "nil", "{", "tu", ".", "co...
// thresholdUpdater implements the Updater interface, allowing asynchronous // access to the status of a Checker.
[ "thresholdUpdater", "implements", "the", "Updater", "interface", "allowing", "asynchronous", "access", "to", "the", "status", "of", "a", "Checker", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L115-L126
train
docker/distribution
health/health.go
PeriodicChecker
func PeriodicChecker(check Checker, period time.Duration) Checker { u := NewStatusUpdater() go func() { t := time.NewTicker(period) for { <-t.C u.Update(check.Check()) } }() return u }
go
func PeriodicChecker(check Checker, period time.Duration) Checker { u := NewStatusUpdater() go func() { t := time.NewTicker(period) for { <-t.C u.Update(check.Check()) } }() return u }
[ "func", "PeriodicChecker", "(", "check", "Checker", ",", "period", "time", ".", "Duration", ")", "Checker", "{", "u", ":=", "NewStatusUpdater", "(", ")", "\n", "go", "func", "(", ")", "{", "t", ":=", "time", ".", "NewTicker", "(", "period", ")", "\n", ...
// PeriodicChecker wraps an updater to provide a periodic checker
[ "PeriodicChecker", "wraps", "an", "updater", "to", "provide", "a", "periodic", "checker" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L134-L145
train
docker/distribution
health/health.go
PeriodicThresholdChecker
func PeriodicThresholdChecker(check Checker, period time.Duration, threshold int) Checker { tu := NewThresholdStatusUpdater(threshold) go func() { t := time.NewTicker(period) for { <-t.C tu.Update(check.Check()) } }() return tu }
go
func PeriodicThresholdChecker(check Checker, period time.Duration, threshold int) Checker { tu := NewThresholdStatusUpdater(threshold) go func() { t := time.NewTicker(period) for { <-t.C tu.Update(check.Check()) } }() return tu }
[ "func", "PeriodicThresholdChecker", "(", "check", "Checker", ",", "period", "time", ".", "Duration", ",", "threshold", "int", ")", "Checker", "{", "tu", ":=", "NewThresholdStatusUpdater", "(", "threshold", ")", "\n", "go", "func", "(", ")", "{", "t", ":=", ...
// PeriodicThresholdChecker wraps an updater to provide a periodic checker that // uses a threshold before it changes status
[ "PeriodicThresholdChecker", "wraps", "an", "updater", "to", "provide", "a", "periodic", "checker", "that", "uses", "a", "threshold", "before", "it", "changes", "status" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L149-L160
train
docker/distribution
health/health.go
CheckStatus
func (registry *Registry) CheckStatus() map[string]string { // TODO(stevvooe) this needs a proper type registry.mu.RLock() defer registry.mu.RUnlock() statusKeys := make(map[string]string) for k, v := range registry.registeredChecks { err := v.Check() if err != nil { statusKeys[k] = err.Error() } } return statusKeys }
go
func (registry *Registry) CheckStatus() map[string]string { // TODO(stevvooe) this needs a proper type registry.mu.RLock() defer registry.mu.RUnlock() statusKeys := make(map[string]string) for k, v := range registry.registeredChecks { err := v.Check() if err != nil { statusKeys[k] = err.Error() } } return statusKeys }
[ "func", "(", "registry", "*", "Registry", ")", "CheckStatus", "(", ")", "map", "[", "string", "]", "string", "{", "registry", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "registry", ".", "mu", ".", "RUnlock", "(", ")", "\n", "statusKeys", ":=",...
// CheckStatus returns a map with all the current health check errors
[ "CheckStatus", "returns", "a", "map", "with", "all", "the", "current", "health", "check", "errors" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L163-L175
train
docker/distribution
health/health.go
Register
func (registry *Registry) Register(name string, check Checker) { if registry == nil { registry = DefaultRegistry } registry.mu.Lock() defer registry.mu.Unlock() _, ok := registry.registeredChecks[name] if ok { panic("Check already exists: " + name) } registry.registeredChecks[name] = check }
go
func (registry *Registry) Register(name string, check Checker) { if registry == nil { registry = DefaultRegistry } registry.mu.Lock() defer registry.mu.Unlock() _, ok := registry.registeredChecks[name] if ok { panic("Check already exists: " + name) } registry.registeredChecks[name] = check }
[ "func", "(", "registry", "*", "Registry", ")", "Register", "(", "name", "string", ",", "check", "Checker", ")", "{", "if", "registry", "==", "nil", "{", "registry", "=", "DefaultRegistry", "\n", "}", "\n", "registry", ".", "mu", ".", "Lock", "(", ")", ...
// Register associates the checker with the provided name.
[ "Register", "associates", "the", "checker", "with", "the", "provided", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L184-L195
train
docker/distribution
health/health.go
StatusHandler
func StatusHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { checks := CheckStatus() status := http.StatusOK // If there is an error, return 503 if len(checks) != 0 { status = http.StatusServiceUnavailable } statusResponse(w, r, status, checks) } else { http.NotFound(w, r) } }
go
func StatusHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { checks := CheckStatus() status := http.StatusOK // If there is an error, return 503 if len(checks) != 0 { status = http.StatusServiceUnavailable } statusResponse(w, r, status, checks) } else { http.NotFound(w, r) } }
[ "func", "StatusHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "==", "\"GET\"", "{", "checks", ":=", "CheckStatus", "(", ")", "\n", "status", ":=", "http", ".", "StatusOK", ...
// StatusHandler returns a JSON blob with all the currently registered Health Checks // and their corresponding status. // Returns 503 if any Error status exists, 200 otherwise
[ "StatusHandler", "returns", "a", "JSON", "blob", "with", "all", "the", "currently", "registered", "Health", "Checks", "and", "their", "corresponding", "status", ".", "Returns", "503", "if", "any", "Error", "status", "exists", "200", "otherwise" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L242-L256
train
docker/distribution
health/health.go
Handler
func Handler(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { checks := CheckStatus() if len(checks) != 0 { errcode.ServeJSON(w, errcode.ErrorCodeUnavailable. WithDetail("health check failed: please see /debug/health")) return } handler.ServeHTTP(w, r) // pass through }) }
go
func Handler(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { checks := CheckStatus() if len(checks) != 0 { errcode.ServeJSON(w, errcode.ErrorCodeUnavailable. WithDetail("health check failed: please see /debug/health")) return } handler.ServeHTTP(w, r) // pass through }) }
[ "func", "Handler", "(", "handler", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "checks", ":=", ...
// Handler returns a handler that will return 503 response code if the health // checks have failed. If everything is okay with the health checks, the // handler will pass through to the provided handler. Use this handler to // disable a web application when the health checks fail.
[ "Handler", "returns", "a", "handler", "that", "will", "return", "503", "response", "code", "if", "the", "health", "checks", "have", "failed", ".", "If", "everything", "is", "okay", "with", "the", "health", "checks", "the", "handler", "will", "pass", "through...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L262-L273
train
docker/distribution
health/health.go
statusResponse
func statusResponse(w http.ResponseWriter, r *http.Request, status int, checks map[string]string) { p, err := json.Marshal(checks) if err != nil { context.GetLogger(context.Background()).Errorf("error serializing health status: %v", err) p, err = json.Marshal(struct { ServerError string `json:"server_error"` }{ ServerError: "Could not parse error message", }) status = http.StatusInternalServerError if err != nil { context.GetLogger(context.Background()).Errorf("error serializing health status failure message: %v", err) return } } w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Length", fmt.Sprint(len(p))) w.WriteHeader(status) if _, err := w.Write(p); err != nil { context.GetLogger(context.Background()).Errorf("error writing health status response body: %v", err) } }
go
func statusResponse(w http.ResponseWriter, r *http.Request, status int, checks map[string]string) { p, err := json.Marshal(checks) if err != nil { context.GetLogger(context.Background()).Errorf("error serializing health status: %v", err) p, err = json.Marshal(struct { ServerError string `json:"server_error"` }{ ServerError: "Could not parse error message", }) status = http.StatusInternalServerError if err != nil { context.GetLogger(context.Background()).Errorf("error serializing health status failure message: %v", err) return } } w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Length", fmt.Sprint(len(p))) w.WriteHeader(status) if _, err := w.Write(p); err != nil { context.GetLogger(context.Background()).Errorf("error writing health status response body: %v", err) } }
[ "func", "statusResponse", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "status", "int", ",", "checks", "map", "[", "string", "]", "string", ")", "{", "p", ",", "err", ":=", "json", ".", "Marshal", "(", "checks"...
// statusResponse completes the request with a response describing the health // of the service.
[ "statusResponse", "completes", "the", "request", "with", "a", "response", "describing", "the", "health", "of", "the", "service", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/health.go#L277-L300
train
docker/distribution
registry/api/v2/urls.go
NewURLBuilder
func NewURLBuilder(root *url.URL, relative bool) *URLBuilder { return &URLBuilder{ root: root, router: Router(), relative: relative, } }
go
func NewURLBuilder(root *url.URL, relative bool) *URLBuilder { return &URLBuilder{ root: root, router: Router(), relative: relative, } }
[ "func", "NewURLBuilder", "(", "root", "*", "url", ".", "URL", ",", "relative", "bool", ")", "*", "URLBuilder", "{", "return", "&", "URLBuilder", "{", "root", ":", "root", ",", "router", ":", "Router", "(", ")", ",", "relative", ":", "relative", ",", ...
// NewURLBuilder creates a URLBuilder with provided root url object.
[ "NewURLBuilder", "creates", "a", "URLBuilder", "with", "provided", "root", "url", "object", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L27-L33
train
docker/distribution
registry/api/v2/urls.go
NewURLBuilderFromString
func NewURLBuilderFromString(root string, relative bool) (*URLBuilder, error) { u, err := url.Parse(root) if err != nil { return nil, err } return NewURLBuilder(u, relative), nil }
go
func NewURLBuilderFromString(root string, relative bool) (*URLBuilder, error) { u, err := url.Parse(root) if err != nil { return nil, err } return NewURLBuilder(u, relative), nil }
[ "func", "NewURLBuilderFromString", "(", "root", "string", ",", "relative", "bool", ")", "(", "*", "URLBuilder", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil"...
// NewURLBuilderFromString workes identically to NewURLBuilder except it takes // a string argument for the root, returning an error if it is not a valid // url.
[ "NewURLBuilderFromString", "workes", "identically", "to", "NewURLBuilder", "except", "it", "takes", "a", "string", "argument", "for", "the", "root", "returning", "an", "error", "if", "it", "is", "not", "a", "valid", "url", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L38-L45
train
docker/distribution
registry/api/v2/urls.go
BuildCatalogURL
func (ub *URLBuilder) BuildCatalogURL(values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameCatalog) catalogURL, err := route.URL() if err != nil { return "", err } return appendValuesURL(catalogURL, values...).String(), nil }
go
func (ub *URLBuilder) BuildCatalogURL(values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameCatalog) catalogURL, err := route.URL() if err != nil { return "", err } return appendValuesURL(catalogURL, values...).String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildCatalogURL", "(", "values", "...", "url", ".", "Values", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameCatalog", ")", "\n", "catalogURL", ",", "err", ...
// BuildCatalogURL constructs a url get a catalog of repositories
[ "BuildCatalogURL", "constructs", "a", "url", "get", "a", "catalog", "of", "repositories" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L119-L128
train