repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
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", "{", "// TODO(stevvooe): Need a better way to manage the upload state automatically.", "buh", ".", "State", ".", "Name", "=", "buh", ".", "Repository", ".", "Named", "(", ")", ".", "Name", "(", ")", "\n", "buh", ".", "State", ".", "UUID", "=", "buh", ".", "Upload", ".", "ID", "(", ")", "\n", "buh", ".", "Upload", ".", "Close", "(", ")", "\n", "buh", ".", "State", ".", "Offset", "=", "buh", ".", "Upload", ".", "Size", "(", ")", "\n", "buh", ".", "State", ".", "StartedAt", "=", "buh", ".", "Upload", ".", "StartedAt", "(", ")", "\n\n", "token", ",", "err", ":=", "hmacKey", "(", "buh", ".", "Config", ".", "HTTP", ".", "Secret", ")", ".", "packUploadState", "(", "buh", ".", "State", ")", "\n", "if", "err", "!=", "nil", "{", "dcontext", ".", "GetLogger", "(", "buh", ")", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "uploadURL", ",", "err", ":=", "buh", ".", "urlBuilder", ".", "BuildBlobUploadChunkURL", "(", "buh", ".", "Repository", ".", "Named", "(", ")", ",", "buh", ".", "Upload", ".", "ID", "(", ")", ",", "url", ".", "Values", "{", "\"", "\"", ":", "[", "]", "string", "{", "token", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "dcontext", ".", "GetLogger", "(", "buh", ")", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "endRange", ":=", "buh", ".", "Upload", ".", "Size", "(", ")", "\n", "if", "endRange", ">", "0", "{", "endRange", "=", "endRange", "-", "1", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "buh", ".", "UUID", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "uploadURL", ")", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "endRange", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// 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", "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", "." ]
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", "(", "mountDigest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ref", ",", "err", ":=", "reference", ".", "WithName", "(", "fromRepo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "canonical", ",", "err", ":=", "reference", ".", "WithDigest", "(", "ref", ",", "dgst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "storage", ".", "WithMountFrom", "(", "canonical", ")", ",", "nil", "\n", "}" ]
// 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", "canonical", "url", "of", "the", "blob", "." ]
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", ".", "Repository", ".", "Named", "(", ")", ",", "desc", ".", "Digest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "blobURL", ",", "err", ":=", "buh", ".", "urlBuilder", ".", "BuildBlobURL", "(", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "blobURL", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "desc", ".", "Digest", ".", "String", "(", ")", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusCreated", ")", "\n", "return", "nil", "\n", "}" ]
// 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", ".", "ErrManifestVerification", "\n\n", "if", "len", "(", "mnfst", ".", "Name", ")", ">", "reference", ".", "NameTotalLengthMax", "{", "errs", "=", "append", "(", "errs", ",", "distribution", ".", "ErrManifestNameInvalid", "{", "Name", ":", "mnfst", ".", "Name", ",", "Reason", ":", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reference", ".", "NameTotalLengthMax", ")", ",", "}", ")", "\n", "}", "\n\n", "if", "!", "reference", ".", "NameRegexp", ".", "MatchString", "(", "mnfst", ".", "Name", ")", "{", "errs", "=", "append", "(", "errs", ",", "distribution", ".", "ErrManifestNameInvalid", "{", "Name", ":", "mnfst", ".", "Name", ",", "Reason", ":", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ",", "}", ")", "\n", "}", "\n\n", "if", "len", "(", "mnfst", ".", "History", ")", "!=", "len", "(", "mnfst", ".", "FSLayers", ")", "{", "errs", "=", "append", "(", "errs", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "mnfst", ".", "History", ")", ",", "len", "(", "mnfst", ".", "FSLayers", ")", ")", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "schema1", ".", "Verify", "(", "&", "mnfst", ")", ";", "err", "!=", "nil", "{", "switch", "err", "{", "case", "libtrust", ".", "ErrMissingSignatureKey", ",", "libtrust", ".", "ErrInvalidJSONContent", ",", "libtrust", ".", "ErrMissingSignatureKey", ":", "errs", "=", "append", "(", "errs", ",", "distribution", ".", "ErrManifestUnverified", "{", "}", ")", "\n", "default", ":", "if", "err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "// TODO(stevvooe): This should be exported by libtrust", "errs", "=", "append", "(", "errs", ",", "distribution", ".", "ErrManifestUnverified", "{", "}", ")", "\n", "}", "else", "{", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "!", "skipDependencyVerification", "{", "for", "_", ",", "fsLayer", ":=", "range", "mnfst", ".", "References", "(", ")", "{", "_", ",", "err", ":=", "ms", ".", "repository", ".", "Blobs", "(", "ctx", ")", ".", "Stat", "(", "ctx", ",", "fsLayer", ".", "Digest", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "distribution", ".", "ErrBlobUnknown", "{", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n\n", "// On error here, we always append unknown blob errors.", "errs", "=", "append", "(", "errs", ",", "distribution", ".", "ErrManifestBlobUnknown", "{", "Digest", ":", "fsLayer", ".", "Digest", "}", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "errs", ")", "!=", "0", "{", "return", "errs", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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", "policy", "the", "registry", "only", "tries", "to", "store", "valid", "content", "leaving", "trust", "policies", "of", "that", "content", "up", "to", "consumers", "." ]
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", "(", "m", ")", ")", "// make our own copy.", "\n", "for", "k", ",", "v", ":=", "range", "m", "{", "mo", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "return", "stringMapContext", "{", "Context", ":", "ctx", ",", "m", ":", "mo", ",", "}", "\n", "}" ]
// 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", "{", "return", "time", ".", "Since", "(", "startedAt", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
// 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", "is", "helpful", "when", "inferring", "metrics", "related", "to", "context", "execution", "times", "." ]
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", "{", "value", "=", "valuev", "\n", "}", "\n", "return", "value", "\n", "}" ]
// 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", ",", "configMediaType", ":", "configMediaType", ",", "configJSON", ":", "make", "(", "[", "]", "byte", ",", "len", "(", "configJSON", ")", ")", ",", "}", "\n", "copy", "(", "mb", ".", "configJSON", ",", "configJSON", ")", "\n\n", "return", "mb", "\n", "}" ]
// 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", "process", "." ]
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", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "var", "opts", "distribution", ".", "CreateOptions", "\n\n", "for", "_", ",", "option", ":=", "range", "options", "{", "err", ":=", "option", ".", "Apply", "(", "&", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "opts", ".", "Mount", ".", "ShouldMount", "{", "desc", ",", "err", ":=", "lbs", ".", "mount", "(", "ctx", ",", "opts", ".", "Mount", ".", "From", ",", "opts", ".", "Mount", ".", "From", ".", "Digest", "(", ")", ",", "opts", ".", "Mount", ".", "Stat", ")", "\n", "if", "err", "==", "nil", "{", "// Mount successful, no need to initiate an upload session", "return", "nil", ",", "distribution", ".", "ErrBlobMounted", "{", "From", ":", "opts", ".", "Mount", ".", "From", ",", "Descriptor", ":", "desc", "}", "\n", "}", "\n", "}", "\n\n", "uuid", ":=", "uuid", ".", "Generate", "(", ")", ".", "String", "(", ")", "\n", "startedAt", ":=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n\n", "path", ",", "err", ":=", "pathFor", "(", "uploadDataPathSpec", "{", "name", ":", "lbs", ".", "repository", ".", "Named", "(", ")", ".", "Name", "(", ")", ",", "id", ":", "uuid", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "startedAtPath", ",", "err", ":=", "pathFor", "(", "uploadStartedAtPathSpec", "{", "name", ":", "lbs", ".", "repository", ".", "Named", "(", ")", ".", "Name", "(", ")", ",", "id", ":", "uuid", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// 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", "\n", "}", "\n\n", "return", "lbs", ".", "newBlobUpload", "(", "ctx", ",", "uuid", ",", "path", ",", "startedAt", ",", "false", ")", "\n", "}" ]
// 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", ",", "error", ")", "{", "fw", ",", "err", ":=", "lbs", ".", "driver", ".", "Writer", "(", "ctx", ",", "path", ",", "append", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bw", ":=", "&", "blobWriter", "{", "ctx", ":", "ctx", ",", "blobStore", ":", "lbs", ",", "id", ":", "uuid", ",", "startedAt", ":", "startedAt", ",", "digester", ":", "digest", ".", "Canonical", ".", "Digester", "(", ")", ",", "fileWriter", ":", "fw", ",", "driver", ":", "lbs", ".", "driver", ",", "path", ":", "path", ",", "resumableDigestEnabled", ":", "lbs", ".", "resumableDigestEnabled", ",", "}", "\n\n", "return", "bw", ",", "nil", "\n", "}" ]
// 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", "(", "[", "]", "digest", ".", "Digest", "{", "canonical", ".", "Digest", "}", ",", "aliases", "...", ")", "\n\n", "// 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", ")", ")", "\n\n", "// only use the first link", "linkPathFn", ":=", "lbs", ".", "linkPathFns", "[", "0", "]", "\n\n", "for", "_", ",", "dgst", ":=", "range", "dgsts", "{", "if", "_", ",", "seen", ":=", "seenDigests", "[", "dgst", "]", ";", "seen", "{", "continue", "\n", "}", "\n", "seenDigests", "[", "dgst", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "blobLinkPath", ",", "err", ":=", "linkPathFn", "(", "lbs", ".", "repository", ".", "Named", "(", ")", ".", "Name", "(", ")", ",", "dgst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "lbs", ".", "blobStore", ".", "link", "(", "ctx", ",", "blobLinkPath", ",", "canonical", ".", "Digest", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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", ",", "err", ":=", "linkPathFn", "(", "lbs", ".", "repository", ".", "Named", "(", ")", ".", "Name", "(", ")", ",", "dgst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "lbs", ".", "blobStore", ".", "readlink", "(", "ctx", ",", "blobLinkPath", ")", "\n", "}" ]
// 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", "}", ")", "\n", "}" ]
// 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\n", "if", "!", "ok", "{", "return", "ErrorCodeUnknown", ".", "Descriptor", "(", ")", "\n", "}", "\n\n", "return", "d", "\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\n", "if", "!", "ok", "{", "desc", "=", "ErrorCodeUnknown", ".", "Descriptor", "(", ")", "\n", "}", "\n\n", "*", "ec", "=", "desc", ".", "Code", "\n\n", "return", "nil", "\n", "}" ]
// 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", ")", "\n", "}" ]
// 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", "...", ")", "\n", "}" ]
// 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\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\n", "for", "_", ",", "daErr", ":=", "range", "errs", "{", "var", "err", "Error", "\n\n", "switch", "daErr", ":=", "daErr", ".", "(", "type", ")", "{", "case", "ErrorCode", ":", "err", "=", "daErr", ".", "WithDetail", "(", "nil", ")", "\n", "case", "Error", ":", "err", "=", "daErr", "\n", "default", ":", "err", "=", "ErrorCodeUnknown", ".", "WithDetail", "(", "daErr", ")", "\n\n", "}", "\n\n", "// 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", "\n", "if", "msg", "==", "\"", "\"", "{", "msg", "=", "err", ".", "Code", ".", "Message", "(", ")", "\n", "}", "\n\n", "tmpErrs", ".", "Errors", "=", "append", "(", "tmpErrs", ".", "Errors", ",", "Error", "{", "Code", ":", "err", ".", "Code", ",", "Message", ":", "msg", ",", "Detail", ":", "err", ".", "Detail", ",", "}", ")", "\n", "}", "\n\n", "return", "json", ".", "Marshal", "(", "tmpErrs", ")", "\n", "}" ]
// 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", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "sort", ".", "Stable", "(", "sort", ".", "StringSlice", "(", "children", ")", ")", "\n", "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", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "(", "type", ")", "{", "case", "PathNotFoundError", ":", "// repository was removed in between listing and enumeration. Ignore it.", "logrus", ".", "WithField", "(", "\"", "\"", ",", "child", ")", ".", "Infof", "(", "\"", "\"", ")", "\n", "continue", "\n", "default", ":", "return", "err", "\n", "}", "\n", "}", "\n", "err", "=", "f", "(", "fileInfo", ")", "\n", "if", "err", "==", "nil", "&&", "fileInfo", ".", "IsDir", "(", ")", "{", "if", "err", ":=", "WalkFallback", "(", "ctx", ",", "driver", ",", "child", ",", "f", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "if", "err", "==", "ErrSkipDir", "{", "// Stop iteration if it's a file, otherwise noop if it's a directory", "if", "!", "fileInfo", ".", "IsDir", "(", ")", "{", "return", "nil", "\n", "}", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", "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" ]
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\n", "if", "desc", ".", "Size", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "desc", ".", "Size", ")", "\n", "}", "\n\n", "if", "desc", ".", "MediaType", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "desc", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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", "&", "repositoryListener", "{", "Repository", ":", "repo", ",", "listener", ":", "listener", ",", "}", ",", "&", "removerListener", "{", "RepositoryRemover", ":", "remover", ",", "listener", ":", "listener", ",", "}", "\n", "}" ]
// 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", "==", "errDigestNotAvailable", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "ctx", ".", "Errors", "=", "append", "(", "ctx", ".", "Errors", ",", "v2", ".", "ErrorCodeDigestInvalid", ".", "WithDetail", "(", "err", ")", ")", "\n", "}", ")", "\n", "}", "\n\n", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "ctx", ".", "Errors", "=", "append", "(", "ctx", ".", "Errors", ",", "v2", ".", "ErrorCodeDigestInvalid", ".", "WithDetail", "(", "err", ")", ")", "\n", "}", ")", "\n", "}", "\n\n", "blobHandler", ":=", "&", "blobHandler", "{", "Context", ":", "ctx", ",", "Digest", ":", "dgst", ",", "}", "\n\n", "mhandler", ":=", "handlers", ".", "MethodHandler", "{", "\"", "\"", ":", "http", ".", "HandlerFunc", "(", "blobHandler", ".", "GetBlob", ")", ",", "\"", "\"", ":", "http", ".", "HandlerFunc", "(", "blobHandler", ".", "GetBlob", ")", ",", "}", "\n\n", "if", "!", "ctx", ".", "readOnly", "{", "mhandler", "[", "\"", "\"", "]", "=", "http", ".", "HandlerFunc", "(", "blobHandler", ".", "DeleteBlob", ")", "\n", "}", "\n\n", "return", "mhandler", "\n", "}" ]
// 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", "(", "\"", "\"", ")", "\n", "blobs", ":=", "bh", ".", "Repository", ".", "Blobs", "(", "bh", ")", "\n", "desc", ",", "err", ":=", "blobs", ".", "Stat", "(", "bh", ",", "bh", ".", "Digest", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "distribution", ".", "ErrBlobUnknown", "{", "bh", ".", "Errors", "=", "append", "(", "bh", ".", "Errors", ",", "v2", ".", "ErrorCodeBlobUnknown", ".", "WithDetail", "(", "bh", ".", "Digest", ")", ")", "\n", "}", "else", "{", "bh", ".", "Errors", "=", "append", "(", "bh", ".", "Errors", ",", "errcode", ".", "ErrorCodeUnknown", ".", "WithDetail", "(", "err", ")", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "if", "err", ":=", "blobs", ".", "ServeBlob", "(", "bh", ",", "w", ",", "r", ",", "desc", ".", "Digest", ")", ";", "err", "!=", "nil", "{", "context", ".", "GetLogger", "(", "bh", ")", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "bh", ".", "Errors", "=", "append", "(", "bh", ".", "Errors", ",", "errcode", ".", "ErrorCodeUnknown", ".", "WithDetail", "(", "err", ")", ")", "\n", "return", "\n", "}", "\n", "}" ]
// 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", "(", "\"", "\"", ")", "\n\n", "blobs", ":=", "bh", ".", "Repository", ".", "Blobs", "(", "bh", ")", "\n", "err", ":=", "blobs", ".", "Delete", "(", "bh", ",", "bh", ".", "Digest", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", "{", "case", "distribution", ".", "ErrUnsupported", ":", "bh", ".", "Errors", "=", "append", "(", "bh", ".", "Errors", ",", "errcode", ".", "ErrorCodeUnsupported", ")", "\n", "return", "\n", "case", "distribution", ".", "ErrBlobUnknown", ":", "bh", ".", "Errors", "=", "append", "(", "bh", ".", "Errors", ",", "v2", ".", "ErrorCodeBlobUnknown", ")", "\n", "return", "\n", "default", ":", "bh", ".", "Errors", "=", "append", "(", "bh", ".", "Errors", ",", "err", ")", "\n", "context", ".", "GetLogger", "(", "bh", ")", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusAccepted", ")", "\n", "}" ]
// 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", "// store manifest in canonical", "copy", "(", "m", ".", "canonical", ",", "b", ")", "\n\n", "// Unmarshal canonical JSON into Manifest object", "var", "manifest", "Manifest", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "m", ".", "canonical", ",", "&", "manifest", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "manifest", ".", "MediaType", "!=", "\"", "\"", "&&", "manifest", ".", "MediaType", "!=", "v1", ".", "MediaTypeImageManifest", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v1", ".", "MediaTypeImageManifest", ",", "manifest", ".", "MediaType", ")", "\n", "}", "\n\n", "m", ".", "Manifest", "=", "manifest", "\n\n", "return", "nil", "\n", "}" ]
// 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", "[", "string", "]", "*", "schedulerEntry", ")", ",", "driver", ":", "driver", ",", "pathToStateFile", ":", "path", ",", "ctx", ":", "ctx", ",", "stopped", ":", "true", ",", "doneChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "saveTimer", ":", "time", ".", "NewTicker", "(", "indexSaveFrequency", ")", ",", "}", "\n", "}" ]
// 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\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\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", "(", ")", "\n\n", "if", "ttles", ".", "stopped", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ttles", ".", "add", "(", "blobRef", ",", "ttl", ",", "entryTypeBlob", ")", "\n", "return", "nil", "\n", "}" ]
// 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", "(", ")", "\n\n", "if", "ttles", ".", "stopped", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ttles", ".", "add", "(", "manifestRef", ",", "ttl", ",", "entryTypeManifest", ")", "\n", "return", "nil", "\n", "}" ]
// 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\n", "if", "err", ":=", "ttles", ".", "writeState", "(", ")", ";", "err", "!=", "nil", "{", "dcontext", ".", "GetLogger", "(", "ttles", ".", "ctx", ")", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "entry", ":=", "range", "ttles", ".", "entries", "{", "entry", ".", "timer", ".", "Stop", "(", ")", "\n", "}", "\n\n", "close", "(", "ttles", ".", "doneChan", ")", "\n", "ttles", ".", "saveTimer", ".", "Stop", "(", ")", "\n", "ttles", ".", "stopped", "=", "true", "\n", "}" ]
// 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", "}", "\n\n", "return", "&", "htpasswd", "{", "entries", ":", "entries", "}", ",", "nil", "\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", ".", "NewScanner", "(", "rd", ")", "\n", "var", "line", "int", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "line", "++", "// 1-based line numbering", "\n", "t", ":=", "strings", ".", "TrimSpace", "(", "scanner", ".", "Text", "(", ")", ")", "\n\n", "if", "len", "(", "t", ")", "<", "1", "{", "continue", "\n", "}", "\n\n", "// lines that *begin* with a '#' are considered comments", "if", "t", "[", "0", "]", "==", "'#'", "{", "continue", "\n", "}", "\n\n", "i", ":=", "strings", ".", "Index", "(", "t", ",", "\"", "\"", ")", "\n", "if", "i", "<", "0", "||", "i", ">=", "len", "(", "t", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "line", ",", "scanner", ".", "Text", "(", ")", ")", "\n", "}", "\n\n", "entries", "[", "t", "[", ":", "i", "]", "]", "=", "[", "]", "byte", "(", "t", "[", "i", "+", "1", ":", "]", ")", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "entries", ",", "nil", "\n", "}" ]
// 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", "are", "encountered", "or", "if", "the", "reader", "fails", "." ]
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", "(", "\"", "\"", ",", "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", ":=", "ref", ".", "(", "reference", ".", "Tagged", ")", ";", "isTagged", "{", "tag", "=", "tagged", ".", "Tag", "(", ")", "\n", "}", "\n\n", "return", "&", "referenceManifestBuilder", "{", "Manifest", ":", "Manifest", "{", "Versioned", ":", "manifest", ".", "Versioned", "{", "SchemaVersion", ":", "1", ",", "}", ",", "Name", ":", "ref", ".", "Name", "(", ")", ",", "Tag", ":", "tag", ",", "Architecture", ":", "architecture", ",", "}", ",", "pk", ":", "pk", ",", "}", "\n", "}" ]
// 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", ".", "FSLayers", ")", ")", "\n", "for", "i", ":=", "range", "mb", ".", "Manifest", ".", "FSLayers", "{", "layerDigest", ":=", "mb", ".", "Manifest", ".", "FSLayers", "[", "i", "]", ".", "BlobSum", "\n", "history", ":=", "mb", ".", "Manifest", ".", "History", "[", "i", "]", "\n", "ref", ":=", "Reference", "{", "layerDigest", ",", "0", ",", "history", "}", "\n", "refs", "[", "i", "]", "=", "ref", ".", "Descriptor", "(", ")", "\n", "}", "\n", "return", "refs", "\n", "}" ]
// 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", ".", "Size", ",", "}", "\n", "}" ]
// 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", ",", "ErrMalformedToken", "\n", "}", "\n\n", "var", "(", "rawHeader", ",", "rawClaims", "=", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", "\n", "headerJSON", ",", "claimsJSON", "[", "]", "byte", "\n", "err", "error", "\n", ")", "\n\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "if", "headerJSON", ",", "err", "=", "joseBase64UrlDecode", "(", "rawHeader", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "ErrMalformedToken", "\n", "}", "\n\n", "if", "claimsJSON", ",", "err", "=", "joseBase64UrlDecode", "(", "rawClaims", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "ErrMalformedToken", "\n", "}", "\n\n", "token", ":=", "new", "(", "Token", ")", "\n", "token", ".", "Header", "=", "new", "(", "Header", ")", "\n", "token", ".", "Claims", "=", "new", "(", "ClaimSet", ")", "\n\n", "token", ".", "Raw", "=", "strings", ".", "Join", "(", "parts", "[", ":", "2", "]", ",", "TokenSeparator", ")", "\n", "if", "token", ".", "Signature", ",", "err", "=", "joseBase64UrlDecode", "(", "parts", "[", "2", "]", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "ErrMalformedToken", "\n", "}", "\n\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "headerJSON", ",", "token", ".", "Header", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "ErrMalformedToken", "\n", "}", "\n\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "claimsJSON", ",", "token", ".", "Claims", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "ErrMalformedToken", "\n", "}", "\n\n", "return", "token", ",", "nil", "\n", "}" ]
// 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", "{", "// Verify that the Issuer claim is a trusted authority.", "if", "!", "contains", "(", "verifyOpts", ".", "TrustedIssuers", ",", "t", ".", "Claims", ".", "Issuer", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "t", ".", "Claims", ".", "Issuer", ")", "\n", "return", "ErrInvalidToken", "\n", "}", "\n\n", "// Verify that the Audience claim is allowed.", "if", "!", "contains", "(", "verifyOpts", ".", "AcceptedAudiences", ",", "t", ".", "Claims", ".", "Audience", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "t", ".", "Claims", ".", "Audience", ")", "\n", "return", "ErrInvalidToken", "\n", "}", "\n\n", "// Verify that the token is currently usable and not expired.", "currentTime", ":=", "time", ".", "Now", "(", ")", "\n\n", "ExpWithLeeway", ":=", "time", ".", "Unix", "(", "t", ".", "Claims", ".", "Expiration", ",", "0", ")", ".", "Add", "(", "Leeway", ")", "\n", "if", "currentTime", ".", "After", "(", "ExpWithLeeway", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "ExpWithLeeway", ",", "currentTime", ")", "\n", "return", "ErrInvalidToken", "\n", "}", "\n\n", "NotBeforeWithLeeway", ":=", "time", ".", "Unix", "(", "t", ".", "Claims", ".", "NotBefore", ",", "0", ")", ".", "Add", "(", "-", "Leeway", ")", "\n", "if", "currentTime", ".", "Before", "(", "NotBeforeWithLeeway", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "NotBeforeWithLeeway", ",", "currentTime", ")", "\n", "return", "ErrInvalidToken", "\n", "}", "\n\n", "// Verify the token signature.", "if", "len", "(", "t", ".", "Signature", ")", "==", "0", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "ErrInvalidToken", "\n", "}", "\n\n", "// Verify that the signing key is trusted.", "signingKey", ",", "err", ":=", "t", ".", "VerifySigningKey", "(", "verifyOpts", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Info", "(", "err", ")", "\n", "return", "ErrInvalidToken", "\n", "}", "\n\n", "// 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", "(", "\"", "\"", ",", "err", ")", "\n", "return", "ErrInvalidToken", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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\n", "accessSet", ":=", "make", "(", "accessSet", ",", "len", "(", "t", ".", "Claims", ".", "Access", ")", ")", "\n\n", "for", "_", ",", "resourceActions", ":=", "range", "t", ".", "Claims", ".", "Access", "{", "resource", ":=", "auth", ".", "Resource", "{", "Type", ":", "resourceActions", ".", "Type", ",", "Name", ":", "resourceActions", ".", "Name", ",", "}", "\n\n", "set", ",", "exists", ":=", "accessSet", "[", "resource", "]", "\n", "if", "!", "exists", "{", "set", "=", "newActionSet", "(", ")", "\n", "accessSet", "[", "resource", "]", "=", "set", "\n", "}", "\n\n", "for", "_", ",", "action", ":=", "range", "resourceActions", ".", "Actions", "{", "set", ".", "add", "(", "action", ")", "\n", "}", "\n", "}", "\n\n", "return", "accessSet", "\n", "}" ]
// 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", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "p", ",", "err", ":=", "getContent", "(", "ctx", ",", "bs", ".", "driver", ",", "bp", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "(", "type", ")", "{", "case", "driver", ".", "PathNotFoundError", ":", "return", "nil", ",", "distribution", ".", "ErrBlobUnknown", "\n", "}", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "p", ",", "nil", "\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", ".", "FromBytes", "(", "p", ")", "\n", "desc", ",", "err", ":=", "bs", ".", "statter", ".", "Stat", "(", "ctx", ",", "dgst", ")", "\n", "if", "err", "==", "nil", "{", "// content already present", "return", "desc", ",", "nil", "\n", "}", "else", "if", "err", "!=", "distribution", ".", "ErrBlobUnknown", "{", "dcontext", ".", "GetLogger", "(", "ctx", ")", ".", "Errorf", "(", "\"", "\"", ",", "dgst", ",", "err", ")", "\n", "// real error, return it", "return", "distribution", ".", "Descriptor", "{", "}", ",", "err", "\n", "}", "\n\n", "bp", ",", "err", ":=", "bs", ".", "path", "(", "dgst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "distribution", ".", "Descriptor", "{", "}", ",", "err", "\n", "}", "\n\n", "// 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", ":", "\"", "\"", ",", "Digest", ":", "dgst", ",", "}", ",", "bs", ".", "driver", ".", "PutContent", "(", "ctx", ",", "bp", ",", "p", ")", "\n", "}" ]
// 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", "for", "small", "objects", "such", "as", "manifests", ".", "This", "implemented", "as", "a", "convenience", "for", "other", "Put", "implementations" ]
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\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "bp", ",", "nil", "\n", "}" ]
// 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", "{", "// 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", ")", ")", "\n", "}" ]
// 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", "(", "ctx", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "linked", ",", "err", ":=", "digest", ".", "Parse", "(", "string", "(", "content", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "linked", ",", "nil", "\n", "}" ]
// 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", "(", "blobDataPathSpec", "{", "digest", ":", "dgst", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "distribution", ".", "Descriptor", "{", "}", ",", "err", "\n", "}", "\n\n", "fi", ",", "err", ":=", "bs", ".", "driver", ".", "Stat", "(", "ctx", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ":=", "err", ".", "(", "type", ")", "{", "case", "driver", ".", "PathNotFoundError", ":", "return", "distribution", ".", "Descriptor", "{", "}", ",", "distribution", ".", "ErrBlobUnknown", "\n", "default", ":", "return", "distribution", ".", "Descriptor", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n\n", "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", "(", "\"", "\"", ",", "path", ")", "\n", "return", "distribution", ".", "Descriptor", "{", "}", ",", "distribution", ".", "ErrBlobUnknown", "\n", "}", "\n\n", "// 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", ":", "\"", "\"", ",", "Digest", ":", "dgst", ",", "}", ",", "nil", "\n", "}" ]
// 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", "blob", "exists", "and", "is", "available", "." ]
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", "{", "p", ":", "\"", "\"", ",", "mod", ":", "time", ".", "Now", "(", ")", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// 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", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "normalized", ":=", "normalize", "(", "path", ")", "\n", "found", ":=", "d", ".", "root", ".", "find", "(", "normalized", ")", "\n\n", "if", "found", ".", "path", "(", ")", "!=", "normalized", "{", "return", "nil", ",", "storagedriver", ".", "PathNotFoundError", "{", "Path", ":", "path", "}", "\n", "}", "\n\n", "fi", ":=", "storagedriver", ".", "FileInfoFields", "{", "Path", ":", "path", ",", "IsDir", ":", "found", ".", "isdir", "(", ")", ",", "ModTime", ":", "found", ".", "modtime", "(", ")", ",", "}", "\n\n", "if", "!", "fi", ".", "IsDir", "{", "fi", ".", "Size", "=", "int64", "(", "len", "(", "found", ".", "(", "*", "file", ")", ".", "data", ")", ")", "\n", "}", "\n\n", "return", "storagedriver", ".", "FileInfoInternal", "{", "FileInfoFields", ":", "fi", "}", ",", "nil", "\n", "}" ]
// 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\n", "return", "&", "Driver", "{", "baseEmbed", ":", "baseEmbed", "{", "Base", ":", "base", ".", "Base", "{", "StorageDriver", ":", "base", ".", "NewRegulator", "(", "fsDriver", ",", "params", ".", "MaxThreads", ")", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// 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", "*", "http", ".", "Request", ")", "{", "for", "_", ",", "closer", ":=", "range", "closers", "{", "defer", "closer", ".", "Close", "(", ")", "\n", "}", "\n", "handler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// 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", ")", "error", "{", "// Get a channel that tells us if the client disconnects", "clientClosed", ":=", "r", ".", "Context", "(", ")", ".", "Done", "(", ")", "\n", "var", "body", "=", "r", ".", "Body", "\n", "if", "limit", ">", "0", "{", "body", "=", "http", ".", "MaxBytesReader", "(", "responseWriter", ",", "body", ",", "limit", ")", "\n", "}", "\n\n", "// Read in the data, if any.", "copied", ",", "err", ":=", "io", ".", "Copy", "(", "destWriter", ",", "body", ")", "\n", "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", ")", "\n\n", "dcontext", ".", "GetLoggerWithFields", "(", "ctx", ",", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", "{", "\"", "\"", ":", "err", ",", "\"", "\"", ":", "copied", ",", "\"", "\"", ":", "r", ".", "ContentLength", ",", "}", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", ".", "Error", "(", "\"", "\"", "+", "action", ")", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "default", ":", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "dcontext", ".", "GetLogger", "(", "ctx", ")", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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", "a", "400", "error", "to", "keep", "the", "logs", "cleaner", ".", "The", "copy", "will", "be", "limited", "to", "limit", "bytes", "if", "limit", "is", "greater", "than", "zero", "." ]
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", "for", "i", ":=", "range", "m", ".", "Manifests", "{", "dependencies", "[", "i", "]", "=", "m", ".", "Manifests", "[", "i", "]", ".", "Descriptor", "\n", "}", "\n\n", "return", "dependencies", "\n", "}" ]
// 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", "]", ".", "Descriptor", ".", "MediaType", "==", "v1", ".", "MediaTypeImageManifest", "{", "mediaType", "=", "v1", ".", "MediaTypeImageIndex", "\n", "}", "else", "{", "mediaType", "=", "MediaTypeManifestList", "\n", "}", "\n\n", "return", "FromDescriptorsWithMediaType", "(", "descriptors", ",", "mediaType", ")", "\n", "}" ]
// 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", "{", "SchemaVersion", ":", "2", ",", "MediaType", ":", "mediaType", ",", "}", ",", "}", "\n\n", "m", ".", "Manifests", "=", "make", "(", "[", "]", "ManifestDescriptor", ",", "len", "(", "descriptors", ")", ")", "\n", "copy", "(", "m", ".", "Manifests", ",", "descriptors", ")", "\n\n", "deserialized", ":=", "DeserializedManifestList", "{", "ManifestList", ":", "m", ",", "}", "\n\n", "var", "err", "error", "\n", "deserialized", ".", "canonical", ",", "err", "=", "json", ".", "MarshalIndent", "(", "&", "m", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "&", "deserialized", ",", "err", "\n", "}" ]
// 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", "// store manifest list in canonical", "copy", "(", "m", ".", "canonical", ",", "b", ")", "\n\n", "// Unmarshal canonical JSON into ManifestList object", "var", "manifestList", "ManifestList", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "m", ".", "canonical", ",", "&", "manifestList", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "ManifestList", "=", "manifestList", "\n\n", "return", "nil", "\n", "}" ]
// 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", ".", "MediaTypeImageIndex", "\n", "}", "else", "{", "mediaType", "=", "m", ".", "MediaType", "\n", "}", "\n\n", "return", "mediaType", ",", "m", ".", "canonical", ",", "nil", "\n", "}" ]
// 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\n", "return", "handlers", ".", "MethodHandler", "{", "\"", "\"", ":", "http", ".", "HandlerFunc", "(", "tagsHandler", ".", "GetTags", ")", ",", "}", "\n", "}" ]
// 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\n", "tagService", ":=", "th", ".", "Repository", ".", "Tags", "(", "th", ")", "\n", "tags", ",", "err", ":=", "tagService", ".", "All", "(", "th", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ":=", "err", ".", "(", "type", ")", "{", "case", "distribution", ".", "ErrRepositoryUnknown", ":", "th", ".", "Errors", "=", "append", "(", "th", ".", "Errors", ",", "v2", ".", "ErrorCodeNameUnknown", ".", "WithDetail", "(", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "th", ".", "Repository", ".", "Named", "(", ")", ".", "Name", "(", ")", "}", ")", ")", "\n", "case", "errcode", ".", "Error", ":", "th", ".", "Errors", "=", "append", "(", "th", ".", "Errors", ",", "err", ")", "\n", "default", ":", "th", ".", "Errors", "=", "append", "(", "th", ".", "Errors", ",", "errcode", ".", "ErrorCodeUnknown", ".", "WithDetail", "(", "err", ")", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "enc", ":=", "json", ".", "NewEncoder", "(", "w", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "tagsAPIResponse", "{", "Name", ":", "th", ".", "Repository", ".", "Named", "(", ")", ".", "Name", "(", ")", ",", "Tags", ":", "tags", ",", "}", ")", ";", "err", "!=", "nil", "{", "th", ".", "Errors", "=", "append", "(", "th", ".", "Errors", ",", "errcode", ".", "ErrorCodeUnknown", ".", "WithDetail", "(", "err", ")", ")", "\n", "return", "\n", "}", "\n", "}" ]
// 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", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "InvalidStorageDriverError", "{", "name", "}", "\n", "}", "\n", "return", "driverFactory", ".", "Create", "(", "parameters", ")", "\n", "}" ]
// 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", "no", "drivers", "are", "found", "an", "InvalidStorageDriverError", "is", "returned" ]
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", ".", "PathPrefix", "(", "prefix", ")", ".", "Subrouter", "(", ")", "\n", "}", "\n\n", "router", ".", "StrictSlash", "(", "true", ")", "\n\n", "for", "_", ",", "descriptor", ":=", "range", "routeDescriptors", "{", "router", ".", "Path", "(", "descriptor", ".", "Path", ")", ".", "Name", "(", "descriptor", ".", "Name", ")", "\n", "}", "\n\n", "return", "rootRouter", "\n", "}" ]
// 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\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\n", "if", "status", "==", "nil", "{", "tu", ".", "count", "=", "0", "\n", "}", "else", "if", "tu", ".", "count", "<", "tu", ".", "threshold", "{", "tu", ".", "count", "++", "\n", "}", "\n\n", "tu", ".", "status", "=", "status", "\n", "}" ]
// 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", "for", "{", "<-", "t", ".", "C", "\n", "u", ".", "Update", "(", "check", ".", "Check", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "u", "\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", ":=", "time", ".", "NewTicker", "(", "period", ")", "\n", "for", "{", "<-", "t", ".", "C", "\n", "tu", ".", "Update", "(", "check", ".", "Check", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "tu", "\n", "}" ]
// 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", "{", "// TODO(stevvooe) this needs a proper type", "registry", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "registry", ".", "mu", ".", "RUnlock", "(", ")", "\n", "statusKeys", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "k", ",", "v", ":=", "range", "registry", ".", "registeredChecks", "{", "err", ":=", "v", ".", "Check", "(", ")", "\n", "if", "err", "!=", "nil", "{", "statusKeys", "[", "k", "]", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "statusKeys", "\n", "}" ]
// 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", "(", ")", "\n", "defer", "registry", ".", "mu", ".", "Unlock", "(", ")", "\n", "_", ",", "ok", ":=", "registry", ".", "registeredChecks", "[", "name", "]", "\n", "if", "ok", "{", "panic", "(", "\"", "\"", "+", "name", ")", "\n", "}", "\n", "registry", ".", "registeredChecks", "[", "name", "]", "=", "check", "\n", "}" ]
// 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", "==", "\"", "\"", "{", "checks", ":=", "CheckStatus", "(", ")", "\n", "status", ":=", "http", ".", "StatusOK", "\n\n", "// If there is an error, return 503", "if", "len", "(", "checks", ")", "!=", "0", "{", "status", "=", "http", ".", "StatusServiceUnavailable", "\n", "}", "\n\n", "statusResponse", "(", "w", ",", "r", ",", "status", ",", "checks", ")", "\n", "}", "else", "{", "http", ".", "NotFound", "(", "w", ",", "r", ")", "\n", "}", "\n", "}" ]
// 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", ":=", "CheckStatus", "(", ")", "\n", "if", "len", "(", "checks", ")", "!=", "0", "{", "errcode", ".", "ServeJSON", "(", "w", ",", "errcode", ".", "ErrorCodeUnavailable", ".", "WithDetail", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n\n", "handler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "// pass through", "\n", "}", ")", "\n", "}" ]
// 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", "to", "the", "provided", "handler", ".", "Use", "this", "handler", "to", "disable", "a", "web", "application", "when", "the", "health", "checks", "fail", "." ]
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", ")", "\n", "if", "err", "!=", "nil", "{", "context", ".", "GetLogger", "(", "context", ".", "Background", "(", ")", ")", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "p", ",", "err", "=", "json", ".", "Marshal", "(", "struct", "{", "ServerError", "string", "`json:\"server_error\"`", "\n", "}", "{", "ServerError", ":", "\"", "\"", ",", "}", ")", "\n", "status", "=", "http", ".", "StatusInternalServerError", "\n\n", "if", "err", "!=", "nil", "{", "context", ".", "GetLogger", "(", "context", ".", "Background", "(", ")", ")", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprint", "(", "len", "(", "p", ")", ")", ")", "\n", "w", ".", "WriteHeader", "(", "status", ")", "\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "p", ")", ";", "err", "!=", "nil", "{", "context", ".", "GetLogger", "(", "context", ".", "Background", "(", ")", ")", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// 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", ",", "}", "\n", "}" ]
// 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", ",", "err", "\n", "}", "\n\n", "return", "NewURLBuilder", "(", "u", ",", "relative", ")", ",", "nil", "\n", "}" ]
// 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\n", "catalogURL", ",", "err", ":=", "route", ".", "URL", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "appendValuesURL", "(", "catalogURL", ",", "values", "...", ")", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// 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
docker/distribution
registry/api/v2/urls.go
BuildTagsURL
func (ub *URLBuilder) BuildTagsURL(name reference.Named) (string, error) { route := ub.cloneRoute(RouteNameTags) tagsURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return tagsURL.String(), nil }
go
func (ub *URLBuilder) BuildTagsURL(name reference.Named) (string, error) { route := ub.cloneRoute(RouteNameTags) tagsURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return tagsURL.String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildTagsURL", "(", "name", "reference", ".", "Named", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameTags", ")", "\n\n", "tagsURL", ",", "err", ":=", "route", ".", "URL", "(", "\"", "\"", ",", "name", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "tagsURL", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// BuildTagsURL constructs a url to list the tags in the named repository.
[ "BuildTagsURL", "constructs", "a", "url", "to", "list", "the", "tags", "in", "the", "named", "repository", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L131-L140
train
docker/distribution
registry/api/v2/urls.go
BuildManifestURL
func (ub *URLBuilder) BuildManifestURL(ref reference.Named) (string, error) { route := ub.cloneRoute(RouteNameManifest) tagOrDigest := "" switch v := ref.(type) { case reference.Tagged: tagOrDigest = v.Tag() case reference.Digested: tagOrDigest = v.Digest().String() default: return "", fmt.Errorf("reference must have a tag or digest") } manifestURL, err := route.URL("name", ref.Name(), "reference", tagOrDigest) if err != nil { return "", err } return manifestURL.String(), nil }
go
func (ub *URLBuilder) BuildManifestURL(ref reference.Named) (string, error) { route := ub.cloneRoute(RouteNameManifest) tagOrDigest := "" switch v := ref.(type) { case reference.Tagged: tagOrDigest = v.Tag() case reference.Digested: tagOrDigest = v.Digest().String() default: return "", fmt.Errorf("reference must have a tag or digest") } manifestURL, err := route.URL("name", ref.Name(), "reference", tagOrDigest) if err != nil { return "", err } return manifestURL.String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildManifestURL", "(", "ref", "reference", ".", "Named", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameManifest", ")", "\n\n", "tagOrDigest", ":=", "\"", "\"", "\n", "switch", "v", ":=", "ref", ".", "(", "type", ")", "{", "case", "reference", ".", "Tagged", ":", "tagOrDigest", "=", "v", ".", "Tag", "(", ")", "\n", "case", "reference", ".", "Digested", ":", "tagOrDigest", "=", "v", ".", "Digest", "(", ")", ".", "String", "(", ")", "\n", "default", ":", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "manifestURL", ",", "err", ":=", "route", ".", "URL", "(", "\"", "\"", ",", "ref", ".", "Name", "(", ")", ",", "\"", "\"", ",", "tagOrDigest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "manifestURL", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// BuildManifestURL constructs a url for the manifest identified by name and // reference. The argument reference may be either a tag or digest.
[ "BuildManifestURL", "constructs", "a", "url", "for", "the", "manifest", "identified", "by", "name", "and", "reference", ".", "The", "argument", "reference", "may", "be", "either", "a", "tag", "or", "digest", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L144-L163
train
docker/distribution
registry/api/v2/urls.go
BuildBlobURL
func (ub *URLBuilder) BuildBlobURL(ref reference.Canonical) (string, error) { route := ub.cloneRoute(RouteNameBlob) layerURL, err := route.URL("name", ref.Name(), "digest", ref.Digest().String()) if err != nil { return "", err } return layerURL.String(), nil }
go
func (ub *URLBuilder) BuildBlobURL(ref reference.Canonical) (string, error) { route := ub.cloneRoute(RouteNameBlob) layerURL, err := route.URL("name", ref.Name(), "digest", ref.Digest().String()) if err != nil { return "", err } return layerURL.String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildBlobURL", "(", "ref", "reference", ".", "Canonical", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameBlob", ")", "\n\n", "layerURL", ",", "err", ":=", "route", ".", "URL", "(", "\"", "\"", ",", "ref", ".", "Name", "(", ")", ",", "\"", "\"", ",", "ref", ".", "Digest", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "layerURL", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// BuildBlobURL constructs the url for the blob identified by name and dgst.
[ "BuildBlobURL", "constructs", "the", "url", "for", "the", "blob", "identified", "by", "name", "and", "dgst", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L166-L175
train
docker/distribution
registry/api/v2/urls.go
BuildBlobUploadURL
func (ub *URLBuilder) BuildBlobUploadURL(name reference.Named, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUpload) uploadURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
go
func (ub *URLBuilder) BuildBlobUploadURL(name reference.Named, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUpload) uploadURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildBlobUploadURL", "(", "name", "reference", ".", "Named", ",", "values", "...", "url", ".", "Values", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameBlobUpload", ")", "\n\n", "uploadURL", ",", "err", ":=", "route", ".", "URL", "(", "\"", "\"", ",", "name", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "appendValuesURL", "(", "uploadURL", ",", "values", "...", ")", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// BuildBlobUploadURL constructs a url to begin a blob upload in the // repository identified by name.
[ "BuildBlobUploadURL", "constructs", "a", "url", "to", "begin", "a", "blob", "upload", "in", "the", "repository", "identified", "by", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L179-L188
train
docker/distribution
registry/api/v2/urls.go
BuildBlobUploadChunkURL
func (ub *URLBuilder) BuildBlobUploadChunkURL(name reference.Named, uuid string, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUploadChunk) uploadURL, err := route.URL("name", name.Name(), "uuid", uuid) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
go
func (ub *URLBuilder) BuildBlobUploadChunkURL(name reference.Named, uuid string, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUploadChunk) uploadURL, err := route.URL("name", name.Name(), "uuid", uuid) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildBlobUploadChunkURL", "(", "name", "reference", ".", "Named", ",", "uuid", "string", ",", "values", "...", "url", ".", "Values", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameBlobUploadChunk", ")", "\n\n", "uploadURL", ",", "err", ":=", "route", ".", "URL", "(", "\"", "\"", ",", "name", ".", "Name", "(", ")", ",", "\"", "\"", ",", "uuid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "appendValuesURL", "(", "uploadURL", ",", "values", "...", ")", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// BuildBlobUploadChunkURL constructs a url for the upload identified by uuid, // including any url values. This should generally not be used by clients, as // this url is provided by server implementations during the blob upload // process.
[ "BuildBlobUploadChunkURL", "constructs", "a", "url", "for", "the", "upload", "identified", "by", "uuid", "including", "any", "url", "values", ".", "This", "should", "generally", "not", "be", "used", "by", "clients", "as", "this", "url", "is", "provided", "by", "server", "implementations", "during", "the", "blob", "upload", "process", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L194-L203
train
docker/distribution
registry/api/v2/urls.go
cloneRoute
func (ub *URLBuilder) cloneRoute(name string) clonedRoute { route := new(mux.Route) root := new(url.URL) *route = *ub.router.GetRoute(name) // clone the route *root = *ub.root return clonedRoute{Route: route, root: root, relative: ub.relative} }
go
func (ub *URLBuilder) cloneRoute(name string) clonedRoute { route := new(mux.Route) root := new(url.URL) *route = *ub.router.GetRoute(name) // clone the route *root = *ub.root return clonedRoute{Route: route, root: root, relative: ub.relative} }
[ "func", "(", "ub", "*", "URLBuilder", ")", "cloneRoute", "(", "name", "string", ")", "clonedRoute", "{", "route", ":=", "new", "(", "mux", ".", "Route", ")", "\n", "root", ":=", "new", "(", "url", ".", "URL", ")", "\n\n", "*", "route", "=", "*", "ub", ".", "router", ".", "GetRoute", "(", "name", ")", "// clone the route", "\n", "*", "root", "=", "*", "ub", ".", "root", "\n\n", "return", "clonedRoute", "{", "Route", ":", "route", ",", "root", ":", "root", ",", "relative", ":", "ub", ".", "relative", "}", "\n", "}" ]
// clondedRoute returns a clone of the named route from the router. Routes // must be cloned to avoid modifying them during url generation.
[ "clondedRoute", "returns", "a", "clone", "of", "the", "named", "route", "from", "the", "router", ".", "Routes", "must", "be", "cloned", "to", "avoid", "modifying", "them", "during", "url", "generation", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L207-L215
train
docker/distribution
registry/api/v2/urls.go
appendValuesURL
func appendValuesURL(u *url.URL, values ...url.Values) *url.URL { merged := u.Query() for _, v := range values { for k, vv := range v { merged[k] = append(merged[k], vv...) } } u.RawQuery = merged.Encode() return u }
go
func appendValuesURL(u *url.URL, values ...url.Values) *url.URL { merged := u.Query() for _, v := range values { for k, vv := range v { merged[k] = append(merged[k], vv...) } } u.RawQuery = merged.Encode() return u }
[ "func", "appendValuesURL", "(", "u", "*", "url", ".", "URL", ",", "values", "...", "url", ".", "Values", ")", "*", "url", ".", "URL", "{", "merged", ":=", "u", ".", "Query", "(", ")", "\n\n", "for", "_", ",", "v", ":=", "range", "values", "{", "for", "k", ",", "vv", ":=", "range", "v", "{", "merged", "[", "k", "]", "=", "append", "(", "merged", "[", "k", "]", ",", "vv", "...", ")", "\n", "}", "\n", "}", "\n\n", "u", ".", "RawQuery", "=", "merged", ".", "Encode", "(", ")", "\n", "return", "u", "\n", "}" ]
// appendValuesURL appends the parameters to the url.
[ "appendValuesURL", "appends", "the", "parameters", "to", "the", "url", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L243-L254
train
docker/distribution
notifications/http.go
newHTTPSink
func newHTTPSink(u string, timeout time.Duration, headers http.Header, transport *http.Transport, listeners ...httpStatusListener) *httpSink { if transport == nil { transport = http.DefaultTransport.(*http.Transport) } return &httpSink{ url: u, listeners: listeners, client: &http.Client{ Transport: &headerRoundTripper{ Transport: transport, headers: headers, }, Timeout: timeout, }, } }
go
func newHTTPSink(u string, timeout time.Duration, headers http.Header, transport *http.Transport, listeners ...httpStatusListener) *httpSink { if transport == nil { transport = http.DefaultTransport.(*http.Transport) } return &httpSink{ url: u, listeners: listeners, client: &http.Client{ Transport: &headerRoundTripper{ Transport: transport, headers: headers, }, Timeout: timeout, }, } }
[ "func", "newHTTPSink", "(", "u", "string", ",", "timeout", "time", ".", "Duration", ",", "headers", "http", ".", "Header", ",", "transport", "*", "http", ".", "Transport", ",", "listeners", "...", "httpStatusListener", ")", "*", "httpSink", "{", "if", "transport", "==", "nil", "{", "transport", "=", "http", ".", "DefaultTransport", ".", "(", "*", "http", ".", "Transport", ")", "\n", "}", "\n", "return", "&", "httpSink", "{", "url", ":", "u", ",", "listeners", ":", "listeners", ",", "client", ":", "&", "http", ".", "Client", "{", "Transport", ":", "&", "headerRoundTripper", "{", "Transport", ":", "transport", ",", "headers", ":", "headers", ",", "}", ",", "Timeout", ":", "timeout", ",", "}", ",", "}", "\n", "}" ]
// newHTTPSink returns an unreliable, single-flight http sink. Wrap in other // sinks for increased reliability.
[ "newHTTPSink", "returns", "an", "unreliable", "single", "-", "flight", "http", "sink", ".", "Wrap", "in", "other", "sinks", "for", "increased", "reliability", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/http.go#L29-L44
train
docker/distribution
notifications/http.go
Write
func (hs *httpSink) Write(events ...Event) error { hs.mu.Lock() defer hs.mu.Unlock() defer hs.client.Transport.(*headerRoundTripper).CloseIdleConnections() if hs.closed { return ErrSinkClosed } envelope := Envelope{ Events: events, } // TODO(stevvooe): It is not ideal to keep re-encoding the request body on // retry but we are going to do it to keep the code simple. It is likely // we could change the event struct to manage its own buffer. p, err := json.MarshalIndent(envelope, "", " ") if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error marshaling event envelope: %v", hs, err) } body := bytes.NewReader(p) resp, err := hs.client.Post(hs.url, EventsMediaType, body) if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error posting: %v", hs, err) } defer resp.Body.Close() // The notifier will treat any 2xx or 3xx response as accepted by the // endpoint. switch { case resp.StatusCode >= 200 && resp.StatusCode < 400: for _, listener := range hs.listeners { listener.success(resp.StatusCode, events...) } // TODO(stevvooe): This is a little accepting: we may want to support // unsupported media type responses with retries using the correct // media type. There may also be cases that will never work. return nil default: for _, listener := range hs.listeners { listener.failure(resp.StatusCode, events...) } return fmt.Errorf("%v: response status %v unaccepted", hs, resp.Status) } }
go
func (hs *httpSink) Write(events ...Event) error { hs.mu.Lock() defer hs.mu.Unlock() defer hs.client.Transport.(*headerRoundTripper).CloseIdleConnections() if hs.closed { return ErrSinkClosed } envelope := Envelope{ Events: events, } // TODO(stevvooe): It is not ideal to keep re-encoding the request body on // retry but we are going to do it to keep the code simple. It is likely // we could change the event struct to manage its own buffer. p, err := json.MarshalIndent(envelope, "", " ") if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error marshaling event envelope: %v", hs, err) } body := bytes.NewReader(p) resp, err := hs.client.Post(hs.url, EventsMediaType, body) if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error posting: %v", hs, err) } defer resp.Body.Close() // The notifier will treat any 2xx or 3xx response as accepted by the // endpoint. switch { case resp.StatusCode >= 200 && resp.StatusCode < 400: for _, listener := range hs.listeners { listener.success(resp.StatusCode, events...) } // TODO(stevvooe): This is a little accepting: we may want to support // unsupported media type responses with retries using the correct // media type. There may also be cases that will never work. return nil default: for _, listener := range hs.listeners { listener.failure(resp.StatusCode, events...) } return fmt.Errorf("%v: response status %v unaccepted", hs, resp.Status) } }
[ "func", "(", "hs", "*", "httpSink", ")", "Write", "(", "events", "...", "Event", ")", "error", "{", "hs", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "hs", ".", "mu", ".", "Unlock", "(", ")", "\n", "defer", "hs", ".", "client", ".", "Transport", ".", "(", "*", "headerRoundTripper", ")", ".", "CloseIdleConnections", "(", ")", "\n\n", "if", "hs", ".", "closed", "{", "return", "ErrSinkClosed", "\n", "}", "\n\n", "envelope", ":=", "Envelope", "{", "Events", ":", "events", ",", "}", "\n\n", "// TODO(stevvooe): It is not ideal to keep re-encoding the request body on", "// retry but we are going to do it to keep the code simple. It is likely", "// we could change the event struct to manage its own buffer.", "p", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "envelope", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "for", "_", ",", "listener", ":=", "range", "hs", ".", "listeners", "{", "listener", ".", "err", "(", "err", ",", "events", "...", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hs", ",", "err", ")", "\n", "}", "\n\n", "body", ":=", "bytes", ".", "NewReader", "(", "p", ")", "\n", "resp", ",", "err", ":=", "hs", ".", "client", ".", "Post", "(", "hs", ".", "url", ",", "EventsMediaType", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "for", "_", ",", "listener", ":=", "range", "hs", ".", "listeners", "{", "listener", ".", "err", "(", "err", ",", "events", "...", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hs", ",", "err", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "// The notifier will treat any 2xx or 3xx response as accepted by the", "// endpoint.", "switch", "{", "case", "resp", ".", "StatusCode", ">=", "200", "&&", "resp", ".", "StatusCode", "<", "400", ":", "for", "_", ",", "listener", ":=", "range", "hs", ".", "listeners", "{", "listener", ".", "success", "(", "resp", ".", "StatusCode", ",", "events", "...", ")", "\n", "}", "\n\n", "// TODO(stevvooe): This is a little accepting: we may want to support", "// unsupported media type responses with retries using the correct", "// media type. There may also be cases that will never work.", "return", "nil", "\n", "default", ":", "for", "_", ",", "listener", ":=", "range", "hs", ".", "listeners", "{", "listener", ".", "failure", "(", "resp", ".", "StatusCode", ",", "events", "...", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hs", ",", "resp", ".", "Status", ")", "\n", "}", "\n", "}" ]
// Accept makes an attempt to notify the endpoint, returning an error if it // fails. It is the caller's responsibility to retry on error. The events are // accepted or rejected as a group.
[ "Accept", "makes", "an", "attempt", "to", "notify", "the", "endpoint", "returning", "an", "error", "if", "it", "fails", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "retry", "on", "error", ".", "The", "events", "are", "accepted", "or", "rejected", "as", "a", "group", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/http.go#L56-L111
train
docker/distribution
notifications/http.go
Close
func (hs *httpSink) Close() error { hs.mu.Lock() defer hs.mu.Unlock() if hs.closed { return fmt.Errorf("httpsink: already closed") } hs.closed = true return nil }
go
func (hs *httpSink) Close() error { hs.mu.Lock() defer hs.mu.Unlock() if hs.closed { return fmt.Errorf("httpsink: already closed") } hs.closed = true return nil }
[ "func", "(", "hs", "*", "httpSink", ")", "Close", "(", ")", "error", "{", "hs", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "hs", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "hs", ".", "closed", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "hs", ".", "closed", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Close the endpoint
[ "Close", "the", "endpoint" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/http.go#L114-L124
train
docker/distribution
registry/auth/auth.go
WithUser
func WithUser(ctx context.Context, user UserInfo) context.Context { return userInfoContext{ Context: ctx, user: user, } }
go
func WithUser(ctx context.Context, user UserInfo) context.Context { return userInfoContext{ Context: ctx, user: user, } }
[ "func", "WithUser", "(", "ctx", "context", ".", "Context", ",", "user", "UserInfo", ")", "context", ".", "Context", "{", "return", "userInfoContext", "{", "Context", ":", "ctx", ",", "user", ":", "user", ",", "}", "\n", "}" ]
// WithUser returns a context with the authorized user info.
[ "WithUser", "returns", "a", "context", "with", "the", "authorized", "user", "info", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L115-L120
train
docker/distribution
registry/auth/auth.go
WithResources
func WithResources(ctx context.Context, resources []Resource) context.Context { return resourceContext{ Context: ctx, resources: resources, } }
go
func WithResources(ctx context.Context, resources []Resource) context.Context { return resourceContext{ Context: ctx, resources: resources, } }
[ "func", "WithResources", "(", "ctx", "context", ".", "Context", ",", "resources", "[", "]", "Resource", ")", "context", ".", "Context", "{", "return", "resourceContext", "{", "Context", ":", "ctx", ",", "resources", ":", "resources", ",", "}", "\n", "}" ]
// WithResources returns a context with the authorized resources.
[ "WithResources", "returns", "a", "context", "with", "the", "authorized", "resources", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L139-L144
train
docker/distribution
registry/auth/auth.go
AuthorizedResources
func AuthorizedResources(ctx context.Context) []Resource { if resources, ok := ctx.Value(resourceKey{}).([]Resource); ok { return resources } return nil }
go
func AuthorizedResources(ctx context.Context) []Resource { if resources, ok := ctx.Value(resourceKey{}).([]Resource); ok { return resources } return nil }
[ "func", "AuthorizedResources", "(", "ctx", "context", ".", "Context", ")", "[", "]", "Resource", "{", "if", "resources", ",", "ok", ":=", "ctx", ".", "Value", "(", "resourceKey", "{", "}", ")", ".", "(", "[", "]", "Resource", ")", ";", "ok", "{", "return", "resources", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// AuthorizedResources returns the list of resources which have // been authorized for this request.
[ "AuthorizedResources", "returns", "the", "list", "of", "resources", "which", "have", "been", "authorized", "for", "this", "request", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L163-L169
train
docker/distribution
registry/auth/auth.go
GetAccessController
func GetAccessController(name string, options map[string]interface{}) (AccessController, error) { if initFunc, exists := accessControllers[name]; exists { return initFunc(options) } return nil, fmt.Errorf("no access controller registered with name: %s", name) }
go
func GetAccessController(name string, options map[string]interface{}) (AccessController, error) { if initFunc, exists := accessControllers[name]; exists { return initFunc(options) } return nil, fmt.Errorf("no access controller registered with name: %s", name) }
[ "func", "GetAccessController", "(", "name", "string", ",", "options", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "AccessController", ",", "error", ")", "{", "if", "initFunc", ",", "exists", ":=", "accessControllers", "[", "name", "]", ";", "exists", "{", "return", "initFunc", "(", "options", ")", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}" ]
// GetAccessController constructs an AccessController // with the given options using the named backend.
[ "GetAccessController", "constructs", "an", "AccessController", "with", "the", "given", "options", "using", "the", "named", "backend", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L195-L201
train
docker/distribution
reference/normalize.go
ParseNormalizedNamed
func ParseNormalizedNamed(s string) (Named, error) { if ok := anchoredIdentifierRegexp.MatchString(s); ok { return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) } domain, remainder := splitDockerDomain(s) var remoteName string if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { remoteName = remainder[:tagSep] } else { remoteName = remainder } if strings.ToLower(remoteName) != remoteName { return nil, errors.New("invalid reference format: repository name must be lowercase") } ref, err := Parse(domain + "/" + remainder) if err != nil { return nil, err } named, isNamed := ref.(Named) if !isNamed { return nil, fmt.Errorf("reference %s has no name", ref.String()) } return named, nil }
go
func ParseNormalizedNamed(s string) (Named, error) { if ok := anchoredIdentifierRegexp.MatchString(s); ok { return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) } domain, remainder := splitDockerDomain(s) var remoteName string if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { remoteName = remainder[:tagSep] } else { remoteName = remainder } if strings.ToLower(remoteName) != remoteName { return nil, errors.New("invalid reference format: repository name must be lowercase") } ref, err := Parse(domain + "/" + remainder) if err != nil { return nil, err } named, isNamed := ref.(Named) if !isNamed { return nil, fmt.Errorf("reference %s has no name", ref.String()) } return named, nil }
[ "func", "ParseNormalizedNamed", "(", "s", "string", ")", "(", "Named", ",", "error", ")", "{", "if", "ok", ":=", "anchoredIdentifierRegexp", ".", "MatchString", "(", "s", ")", ";", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "domain", ",", "remainder", ":=", "splitDockerDomain", "(", "s", ")", "\n", "var", "remoteName", "string", "\n", "if", "tagSep", ":=", "strings", ".", "IndexRune", "(", "remainder", ",", "':'", ")", ";", "tagSep", ">", "-", "1", "{", "remoteName", "=", "remainder", "[", ":", "tagSep", "]", "\n", "}", "else", "{", "remoteName", "=", "remainder", "\n", "}", "\n", "if", "strings", ".", "ToLower", "(", "remoteName", ")", "!=", "remoteName", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ref", ",", "err", ":=", "Parse", "(", "domain", "+", "\"", "\"", "+", "remainder", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "named", ",", "isNamed", ":=", "ref", ".", "(", "Named", ")", "\n", "if", "!", "isNamed", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ref", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "named", ",", "nil", "\n", "}" ]
// ParseNormalizedNamed parses a string into a named reference // transforming a familiar name from Docker UI to a fully // qualified reference. If the value may be an identifier // use ParseAnyReference.
[ "ParseNormalizedNamed", "parses", "a", "string", "into", "a", "named", "reference", "transforming", "a", "familiar", "name", "from", "Docker", "UI", "to", "a", "fully", "qualified", "reference", ".", "If", "the", "value", "may", "be", "an", "identifier", "use", "ParseAnyReference", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L33-L57
train
docker/distribution
reference/normalize.go
splitDockerDomain
func splitDockerDomain(name string) (domain, remainder string) { i := strings.IndexRune(name, '/') if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") { domain, remainder = defaultDomain, name } else { domain, remainder = name[:i], name[i+1:] } if domain == legacyDefaultDomain { domain = defaultDomain } if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { remainder = officialRepoName + "/" + remainder } return }
go
func splitDockerDomain(name string) (domain, remainder string) { i := strings.IndexRune(name, '/') if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") { domain, remainder = defaultDomain, name } else { domain, remainder = name[:i], name[i+1:] } if domain == legacyDefaultDomain { domain = defaultDomain } if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { remainder = officialRepoName + "/" + remainder } return }
[ "func", "splitDockerDomain", "(", "name", "string", ")", "(", "domain", ",", "remainder", "string", ")", "{", "i", ":=", "strings", ".", "IndexRune", "(", "name", ",", "'/'", ")", "\n", "if", "i", "==", "-", "1", "||", "(", "!", "strings", ".", "ContainsAny", "(", "name", "[", ":", "i", "]", ",", "\"", "\"", ")", "&&", "name", "[", ":", "i", "]", "!=", "\"", "\"", ")", "{", "domain", ",", "remainder", "=", "defaultDomain", ",", "name", "\n", "}", "else", "{", "domain", ",", "remainder", "=", "name", "[", ":", "i", "]", ",", "name", "[", "i", "+", "1", ":", "]", "\n", "}", "\n", "if", "domain", "==", "legacyDefaultDomain", "{", "domain", "=", "defaultDomain", "\n", "}", "\n", "if", "domain", "==", "defaultDomain", "&&", "!", "strings", ".", "ContainsRune", "(", "remainder", ",", "'/'", ")", "{", "remainder", "=", "officialRepoName", "+", "\"", "\"", "+", "remainder", "\n", "}", "\n", "return", "\n", "}" ]
// splitDockerDomain splits a repository name to domain and remotename string. // If no valid domain is found, the default domain is used. Repository name // needs to be already validated before.
[ "splitDockerDomain", "splits", "a", "repository", "name", "to", "domain", "and", "remotename", "string", ".", "If", "no", "valid", "domain", "is", "found", "the", "default", "domain", "is", "used", ".", "Repository", "name", "needs", "to", "be", "already", "validated", "before", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L91-L105
train
docker/distribution
reference/normalize.go
TagNameOnly
func TagNameOnly(ref Named) Named { if IsNameOnly(ref) { namedTagged, err := WithTag(ref, defaultTag) if err != nil { // Default tag must be valid, to create a NamedTagged // type with non-validated input the WithTag function // should be used instead panic(err) } return namedTagged } return ref }
go
func TagNameOnly(ref Named) Named { if IsNameOnly(ref) { namedTagged, err := WithTag(ref, defaultTag) if err != nil { // Default tag must be valid, to create a NamedTagged // type with non-validated input the WithTag function // should be used instead panic(err) } return namedTagged } return ref }
[ "func", "TagNameOnly", "(", "ref", "Named", ")", "Named", "{", "if", "IsNameOnly", "(", "ref", ")", "{", "namedTagged", ",", "err", ":=", "WithTag", "(", "ref", ",", "defaultTag", ")", "\n", "if", "err", "!=", "nil", "{", "// Default tag must be valid, to create a NamedTagged", "// type with non-validated input the WithTag function", "// should be used instead", "panic", "(", "err", ")", "\n", "}", "\n", "return", "namedTagged", "\n", "}", "\n", "return", "ref", "\n", "}" ]
// TagNameOnly adds the default tag "latest" to a reference if it only has // a repo name.
[ "TagNameOnly", "adds", "the", "default", "tag", "latest", "to", "a", "reference", "if", "it", "only", "has", "a", "repo", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L157-L169
train
docker/distribution
reference/normalize.go
ParseAnyReference
func ParseAnyReference(ref string) (Reference, error) { if ok := anchoredIdentifierRegexp.MatchString(ref); ok { return digestReference("sha256:" + ref), nil } if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } return ParseNormalizedNamed(ref) }
go
func ParseAnyReference(ref string) (Reference, error) { if ok := anchoredIdentifierRegexp.MatchString(ref); ok { return digestReference("sha256:" + ref), nil } if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } return ParseNormalizedNamed(ref) }
[ "func", "ParseAnyReference", "(", "ref", "string", ")", "(", "Reference", ",", "error", ")", "{", "if", "ok", ":=", "anchoredIdentifierRegexp", ".", "MatchString", "(", "ref", ")", ";", "ok", "{", "return", "digestReference", "(", "\"", "\"", "+", "ref", ")", ",", "nil", "\n", "}", "\n", "if", "dgst", ",", "err", ":=", "digest", ".", "Parse", "(", "ref", ")", ";", "err", "==", "nil", "{", "return", "digestReference", "(", "dgst", ")", ",", "nil", "\n", "}", "\n\n", "return", "ParseNormalizedNamed", "(", "ref", ")", "\n", "}" ]
// ParseAnyReference parses a reference string as a possible identifier, // full digest, or familiar name.
[ "ParseAnyReference", "parses", "a", "reference", "string", "as", "a", "possible", "identifier", "full", "digest", "or", "familiar", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L173-L182
train
docker/distribution
reference/normalize.go
ParseAnyReferenceWithSet
func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { dgst, err := ds.Lookup(ref) if err == nil { return digestReference(dgst), nil } } else { if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } } return ParseNormalizedNamed(ref) }
go
func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { dgst, err := ds.Lookup(ref) if err == nil { return digestReference(dgst), nil } } else { if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } } return ParseNormalizedNamed(ref) }
[ "func", "ParseAnyReferenceWithSet", "(", "ref", "string", ",", "ds", "*", "digestset", ".", "Set", ")", "(", "Reference", ",", "error", ")", "{", "if", "ok", ":=", "anchoredShortIdentifierRegexp", ".", "MatchString", "(", "ref", ")", ";", "ok", "{", "dgst", ",", "err", ":=", "ds", ".", "Lookup", "(", "ref", ")", "\n", "if", "err", "==", "nil", "{", "return", "digestReference", "(", "dgst", ")", ",", "nil", "\n", "}", "\n", "}", "else", "{", "if", "dgst", ",", "err", ":=", "digest", ".", "Parse", "(", "ref", ")", ";", "err", "==", "nil", "{", "return", "digestReference", "(", "dgst", ")", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "ParseNormalizedNamed", "(", "ref", ")", "\n", "}" ]
// ParseAnyReferenceWithSet parses a reference string as a possible short // identifier to be matched in a digest set, a full digest, or familiar name.
[ "ParseAnyReferenceWithSet", "parses", "a", "reference", "string", "as", "a", "possible", "short", "identifier", "to", "be", "matched", "in", "a", "digest", "set", "a", "full", "digest", "or", "familiar", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L186-L199
train
docker/distribution
registry/api/errcode/register.go
Register
func Register(group string, descriptor ErrorDescriptor) ErrorCode { registerLock.Lock() defer registerLock.Unlock() descriptor.Code = ErrorCode(nextCode) if _, ok := idToDescriptors[descriptor.Value]; ok { panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value)) } if _, ok := errorCodeToDescriptors[descriptor.Code]; ok { panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code)) } groupToDescriptors[group] = append(groupToDescriptors[group], descriptor) errorCodeToDescriptors[descriptor.Code] = descriptor idToDescriptors[descriptor.Value] = descriptor nextCode++ return descriptor.Code }
go
func Register(group string, descriptor ErrorDescriptor) ErrorCode { registerLock.Lock() defer registerLock.Unlock() descriptor.Code = ErrorCode(nextCode) if _, ok := idToDescriptors[descriptor.Value]; ok { panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value)) } if _, ok := errorCodeToDescriptors[descriptor.Code]; ok { panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code)) } groupToDescriptors[group] = append(groupToDescriptors[group], descriptor) errorCodeToDescriptors[descriptor.Code] = descriptor idToDescriptors[descriptor.Value] = descriptor nextCode++ return descriptor.Code }
[ "func", "Register", "(", "group", "string", ",", "descriptor", "ErrorDescriptor", ")", "ErrorCode", "{", "registerLock", ".", "Lock", "(", ")", "\n", "defer", "registerLock", ".", "Unlock", "(", ")", "\n\n", "descriptor", ".", "Code", "=", "ErrorCode", "(", "nextCode", ")", "\n\n", "if", "_", ",", "ok", ":=", "idToDescriptors", "[", "descriptor", ".", "Value", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "descriptor", ".", "Value", ")", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "errorCodeToDescriptors", "[", "descriptor", ".", "Code", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "descriptor", ".", "Code", ")", ")", "\n", "}", "\n\n", "groupToDescriptors", "[", "group", "]", "=", "append", "(", "groupToDescriptors", "[", "group", "]", ",", "descriptor", ")", "\n", "errorCodeToDescriptors", "[", "descriptor", ".", "Code", "]", "=", "descriptor", "\n", "idToDescriptors", "[", "descriptor", ".", "Value", "]", "=", "descriptor", "\n\n", "nextCode", "++", "\n", "return", "descriptor", ".", "Code", "\n", "}" ]
// Register will make the passed-in error known to the environment and // return a new ErrorCode
[ "Register", "will", "make", "the", "passed", "-", "in", "error", "known", "to", "the", "environment", "and", "return", "a", "new", "ErrorCode" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/register.go#L83-L102
train
docker/distribution
registry/api/errcode/register.go
GetGroupNames
func GetGroupNames() []string { keys := []string{} for k := range groupToDescriptors { keys = append(keys, k) } sort.Strings(keys) return keys }
go
func GetGroupNames() []string { keys := []string{} for k := range groupToDescriptors { keys = append(keys, k) } sort.Strings(keys) return keys }
[ "func", "GetGroupNames", "(", ")", "[", "]", "string", "{", "keys", ":=", "[", "]", "string", "{", "}", "\n\n", "for", "k", ":=", "range", "groupToDescriptors", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "return", "keys", "\n", "}" ]
// GetGroupNames returns the list of Error group names that are registered
[ "GetGroupNames", "returns", "the", "list", "of", "Error", "group", "names", "that", "are", "registered" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/register.go#L111-L119
train
docker/distribution
registry/api/errcode/register.go
GetErrorCodeGroup
func GetErrorCodeGroup(name string) []ErrorDescriptor { desc := groupToDescriptors[name] sort.Sort(byValue(desc)) return desc }
go
func GetErrorCodeGroup(name string) []ErrorDescriptor { desc := groupToDescriptors[name] sort.Sort(byValue(desc)) return desc }
[ "func", "GetErrorCodeGroup", "(", "name", "string", ")", "[", "]", "ErrorDescriptor", "{", "desc", ":=", "groupToDescriptors", "[", "name", "]", "\n", "sort", ".", "Sort", "(", "byValue", "(", "desc", ")", ")", "\n", "return", "desc", "\n", "}" ]
// GetErrorCodeGroup returns the named group of error descriptors
[ "GetErrorCodeGroup", "returns", "the", "named", "group", "of", "error", "descriptors" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/register.go#L122-L126
train