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/storage/driver/base/regulator.go
|
URLFor
|
func (r *regulator) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
r.enter()
defer r.exit()
return r.StorageDriver.URLFor(ctx, path, options)
}
|
go
|
func (r *regulator) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
r.enter()
defer r.exit()
return r.StorageDriver.URLFor(ctx, path, options)
}
|
[
"func",
"(",
"r",
"*",
"regulator",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"r",
".",
"enter",
"(",
")",
"\n",
"defer",
"r",
".",
"exit",
"(",
")",
"\n\n",
"return",
"r",
".",
"StorageDriver",
".",
"URLFor",
"(",
"ctx",
",",
"path",
",",
"options",
")",
"\n",
"}"
] |
// URLFor returns a URL which may be used to retrieve the content stored at
// the given path, possibly using the given options.
// May return an ErrUnsupportedMethod in certain StorageDriver
// implementations.
|
[
"URLFor",
"returns",
"a",
"URL",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"content",
"stored",
"at",
"the",
"given",
"path",
"possibly",
"using",
"the",
"given",
"options",
".",
"May",
"return",
"an",
"ErrUnsupportedMethod",
"in",
"certain",
"StorageDriver",
"implementations",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/regulator.go#L179-L184
|
train
|
docker/distribution
|
registry/storage/driver/swift/swift.go
|
URLFor
|
func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if d.SecretKey == "" {
return "", storagedriver.ErrUnsupportedMethod{}
}
methodString := "GET"
method, ok := options["method"]
if ok {
if methodString, ok = method.(string); !ok {
return "", storagedriver.ErrUnsupportedMethod{}
}
}
if methodString == "HEAD" {
// A "HEAD" request on a temporary URL is allowed if the
// signature was generated with "GET", "POST" or "PUT"
methodString = "GET"
}
supported := false
for _, method := range d.TempURLMethods {
if method == methodString {
supported = true
break
}
}
if !supported {
return "", storagedriver.ErrUnsupportedMethod{}
}
expiresTime := time.Now().Add(20 * time.Minute)
expires, ok := options["expiry"]
if ok {
et, ok := expires.(time.Time)
if ok {
expiresTime = et
}
}
tempURL := d.Conn.ObjectTempUrl(d.Container, d.swiftPath(path), d.SecretKey, methodString, expiresTime)
if d.AccessKey != "" {
// On HP Cloud, the signature must be in the form of tenant_id:access_key:signature
url, _ := url.Parse(tempURL)
query := url.Query()
query.Set("temp_url_sig", fmt.Sprintf("%s:%s:%s", d.Conn.TenantId, d.AccessKey, query.Get("temp_url_sig")))
url.RawQuery = query.Encode()
tempURL = url.String()
}
return tempURL, nil
}
|
go
|
func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if d.SecretKey == "" {
return "", storagedriver.ErrUnsupportedMethod{}
}
methodString := "GET"
method, ok := options["method"]
if ok {
if methodString, ok = method.(string); !ok {
return "", storagedriver.ErrUnsupportedMethod{}
}
}
if methodString == "HEAD" {
// A "HEAD" request on a temporary URL is allowed if the
// signature was generated with "GET", "POST" or "PUT"
methodString = "GET"
}
supported := false
for _, method := range d.TempURLMethods {
if method == methodString {
supported = true
break
}
}
if !supported {
return "", storagedriver.ErrUnsupportedMethod{}
}
expiresTime := time.Now().Add(20 * time.Minute)
expires, ok := options["expiry"]
if ok {
et, ok := expires.(time.Time)
if ok {
expiresTime = et
}
}
tempURL := d.Conn.ObjectTempUrl(d.Container, d.swiftPath(path), d.SecretKey, methodString, expiresTime)
if d.AccessKey != "" {
// On HP Cloud, the signature must be in the form of tenant_id:access_key:signature
url, _ := url.Parse(tempURL)
query := url.Query()
query.Set("temp_url_sig", fmt.Sprintf("%s:%s:%s", d.Conn.TenantId, d.AccessKey, query.Get("temp_url_sig")))
url.RawQuery = query.Encode()
tempURL = url.String()
}
return tempURL, nil
}
|
[
"func",
"(",
"d",
"*",
"driver",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"d",
".",
"SecretKey",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"storagedriver",
".",
"ErrUnsupportedMethod",
"{",
"}",
"\n",
"}",
"\n\n",
"methodString",
":=",
"\"",
"\"",
"\n",
"method",
",",
"ok",
":=",
"options",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"if",
"methodString",
",",
"ok",
"=",
"method",
".",
"(",
"string",
")",
";",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"storagedriver",
".",
"ErrUnsupportedMethod",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"methodString",
"==",
"\"",
"\"",
"{",
"// A \"HEAD\" request on a temporary URL is allowed if the",
"// signature was generated with \"GET\", \"POST\" or \"PUT\"",
"methodString",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"supported",
":=",
"false",
"\n",
"for",
"_",
",",
"method",
":=",
"range",
"d",
".",
"TempURLMethods",
"{",
"if",
"method",
"==",
"methodString",
"{",
"supported",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"supported",
"{",
"return",
"\"",
"\"",
",",
"storagedriver",
".",
"ErrUnsupportedMethod",
"{",
"}",
"\n",
"}",
"\n\n",
"expiresTime",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"20",
"*",
"time",
".",
"Minute",
")",
"\n",
"expires",
",",
"ok",
":=",
"options",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"et",
",",
"ok",
":=",
"expires",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"if",
"ok",
"{",
"expiresTime",
"=",
"et",
"\n",
"}",
"\n",
"}",
"\n\n",
"tempURL",
":=",
"d",
".",
"Conn",
".",
"ObjectTempUrl",
"(",
"d",
".",
"Container",
",",
"d",
".",
"swiftPath",
"(",
"path",
")",
",",
"d",
".",
"SecretKey",
",",
"methodString",
",",
"expiresTime",
")",
"\n\n",
"if",
"d",
".",
"AccessKey",
"!=",
"\"",
"\"",
"{",
"// On HP Cloud, the signature must be in the form of tenant_id:access_key:signature",
"url",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"tempURL",
")",
"\n",
"query",
":=",
"url",
".",
"Query",
"(",
")",
"\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d",
".",
"Conn",
".",
"TenantId",
",",
"d",
".",
"AccessKey",
",",
"query",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
")",
"\n",
"url",
".",
"RawQuery",
"=",
"query",
".",
"Encode",
"(",
")",
"\n",
"tempURL",
"=",
"url",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"tempURL",
",",
"nil",
"\n",
"}"
] |
// URLFor returns a URL which may be used to retrieve the content stored at the given path.
|
[
"URLFor",
"returns",
"a",
"URL",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"content",
"stored",
"at",
"the",
"given",
"path",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/swift/swift.go#L606-L658
|
train
|
docker/distribution
|
manifest/schema2/manifest.go
|
References
|
func (m Manifest) References() []distribution.Descriptor {
references := make([]distribution.Descriptor, 0, 1+len(m.Layers))
references = append(references, m.Config)
references = append(references, m.Layers...)
return references
}
|
go
|
func (m Manifest) References() []distribution.Descriptor {
references := make([]distribution.Descriptor, 0, 1+len(m.Layers))
references = append(references, m.Config)
references = append(references, m.Layers...)
return references
}
|
[
"func",
"(",
"m",
"Manifest",
")",
"References",
"(",
")",
"[",
"]",
"distribution",
".",
"Descriptor",
"{",
"references",
":=",
"make",
"(",
"[",
"]",
"distribution",
".",
"Descriptor",
",",
"0",
",",
"1",
"+",
"len",
"(",
"m",
".",
"Layers",
")",
")",
"\n",
"references",
"=",
"append",
"(",
"references",
",",
"m",
".",
"Config",
")",
"\n",
"references",
"=",
"append",
"(",
"references",
",",
"m",
".",
"Layers",
"...",
")",
"\n",
"return",
"references",
"\n",
"}"
] |
// References returns the descriptors of this manifests references.
|
[
"References",
"returns",
"the",
"descriptors",
"of",
"this",
"manifests",
"references",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema2/manifest.go#L75-L80
|
train
|
docker/distribution
|
manifest/schema2/manifest.go
|
FromStruct
|
func FromStruct(m Manifest) (*DeserializedManifest, error) {
var deserialized DeserializedManifest
deserialized.Manifest = m
var err error
deserialized.canonical, err = json.MarshalIndent(&m, "", " ")
return &deserialized, err
}
|
go
|
func FromStruct(m Manifest) (*DeserializedManifest, error) {
var deserialized DeserializedManifest
deserialized.Manifest = m
var err error
deserialized.canonical, err = json.MarshalIndent(&m, "", " ")
return &deserialized, err
}
|
[
"func",
"FromStruct",
"(",
"m",
"Manifest",
")",
"(",
"*",
"DeserializedManifest",
",",
"error",
")",
"{",
"var",
"deserialized",
"DeserializedManifest",
"\n",
"deserialized",
".",
"Manifest",
"=",
"m",
"\n\n",
"var",
"err",
"error",
"\n",
"deserialized",
".",
"canonical",
",",
"err",
"=",
"json",
".",
"MarshalIndent",
"(",
"&",
"m",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"&",
"deserialized",
",",
"err",
"\n",
"}"
] |
// FromStruct takes a Manifest structure, marshals it to JSON, and returns a
// DeserializedManifest which contains the manifest and its JSON representation.
|
[
"FromStruct",
"takes",
"a",
"Manifest",
"structure",
"marshals",
"it",
"to",
"JSON",
"and",
"returns",
"a",
"DeserializedManifest",
"which",
"contains",
"the",
"manifest",
"and",
"its",
"JSON",
"representation",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema2/manifest.go#L98-L105
|
train
|
docker/distribution
|
manifest/schema2/manifest.go
|
MarshalJSON
|
func (m *DeserializedManifest) MarshalJSON() ([]byte, error) {
if len(m.canonical) > 0 {
return m.canonical, nil
}
return nil, errors.New("JSON representation not initialized in DeserializedManifest")
}
|
go
|
func (m *DeserializedManifest) MarshalJSON() ([]byte, error) {
if len(m.canonical) > 0 {
return m.canonical, nil
}
return nil, errors.New("JSON representation not initialized in DeserializedManifest")
}
|
[
"func",
"(",
"m",
"*",
"DeserializedManifest",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"m",
".",
"canonical",
")",
">",
"0",
"{",
"return",
"m",
".",
"canonical",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// MarshalJSON returns the contents of canonical. If canonical is empty,
// marshals the inner contents.
|
[
"MarshalJSON",
"returns",
"the",
"contents",
"of",
"canonical",
".",
"If",
"canonical",
"is",
"empty",
"marshals",
"the",
"inner",
"contents",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema2/manifest.go#L132-L138
|
train
|
docker/distribution
|
registry/storage/blobwriter_resumable.go
|
resumeDigest
|
func (bw *blobWriter) resumeDigest(ctx context.Context) error {
if !bw.resumableDigestEnabled {
return errResumableDigestNotAvailable
}
h, ok := bw.digester.Hash().(encoding.BinaryUnmarshaler)
if !ok {
return errResumableDigestNotAvailable
}
offset := bw.fileWriter.Size()
if offset == bw.written {
// State of digester is already at the requested offset.
return nil
}
// List hash states from storage backend.
var hashStateMatch hashStateEntry
hashStates, err := bw.getStoredHashStates(ctx)
if err != nil {
return fmt.Errorf("unable to get stored hash states with offset %d: %s", offset, err)
}
// Find the highest stored hashState with offset equal to
// the requested offset.
for _, hashState := range hashStates {
if hashState.offset == offset {
hashStateMatch = hashState
break // Found an exact offset match.
}
}
if hashStateMatch.offset == 0 {
// No need to load any state, just reset the hasher.
h.(hash.Hash).Reset()
} else {
storedState, err := bw.driver.GetContent(ctx, hashStateMatch.path)
if err != nil {
return err
}
if err = h.UnmarshalBinary(storedState); err != nil {
return err
}
bw.written = hashStateMatch.offset
}
// Mind the gap.
if gapLen := offset - bw.written; gapLen > 0 {
return errResumableDigestNotAvailable
}
return nil
}
|
go
|
func (bw *blobWriter) resumeDigest(ctx context.Context) error {
if !bw.resumableDigestEnabled {
return errResumableDigestNotAvailable
}
h, ok := bw.digester.Hash().(encoding.BinaryUnmarshaler)
if !ok {
return errResumableDigestNotAvailable
}
offset := bw.fileWriter.Size()
if offset == bw.written {
// State of digester is already at the requested offset.
return nil
}
// List hash states from storage backend.
var hashStateMatch hashStateEntry
hashStates, err := bw.getStoredHashStates(ctx)
if err != nil {
return fmt.Errorf("unable to get stored hash states with offset %d: %s", offset, err)
}
// Find the highest stored hashState with offset equal to
// the requested offset.
for _, hashState := range hashStates {
if hashState.offset == offset {
hashStateMatch = hashState
break // Found an exact offset match.
}
}
if hashStateMatch.offset == 0 {
// No need to load any state, just reset the hasher.
h.(hash.Hash).Reset()
} else {
storedState, err := bw.driver.GetContent(ctx, hashStateMatch.path)
if err != nil {
return err
}
if err = h.UnmarshalBinary(storedState); err != nil {
return err
}
bw.written = hashStateMatch.offset
}
// Mind the gap.
if gapLen := offset - bw.written; gapLen > 0 {
return errResumableDigestNotAvailable
}
return nil
}
|
[
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"resumeDigest",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"!",
"bw",
".",
"resumableDigestEnabled",
"{",
"return",
"errResumableDigestNotAvailable",
"\n",
"}",
"\n\n",
"h",
",",
"ok",
":=",
"bw",
".",
"digester",
".",
"Hash",
"(",
")",
".",
"(",
"encoding",
".",
"BinaryUnmarshaler",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errResumableDigestNotAvailable",
"\n",
"}",
"\n\n",
"offset",
":=",
"bw",
".",
"fileWriter",
".",
"Size",
"(",
")",
"\n",
"if",
"offset",
"==",
"bw",
".",
"written",
"{",
"// State of digester is already at the requested offset.",
"return",
"nil",
"\n",
"}",
"\n\n",
"// List hash states from storage backend.",
"var",
"hashStateMatch",
"hashStateEntry",
"\n",
"hashStates",
",",
"err",
":=",
"bw",
".",
"getStoredHashStates",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"offset",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Find the highest stored hashState with offset equal to",
"// the requested offset.",
"for",
"_",
",",
"hashState",
":=",
"range",
"hashStates",
"{",
"if",
"hashState",
".",
"offset",
"==",
"offset",
"{",
"hashStateMatch",
"=",
"hashState",
"\n",
"break",
"// Found an exact offset match.",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"hashStateMatch",
".",
"offset",
"==",
"0",
"{",
"// No need to load any state, just reset the hasher.",
"h",
".",
"(",
"hash",
".",
"Hash",
")",
".",
"Reset",
"(",
")",
"\n",
"}",
"else",
"{",
"storedState",
",",
"err",
":=",
"bw",
".",
"driver",
".",
"GetContent",
"(",
"ctx",
",",
"hashStateMatch",
".",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"h",
".",
"UnmarshalBinary",
"(",
"storedState",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"bw",
".",
"written",
"=",
"hashStateMatch",
".",
"offset",
"\n",
"}",
"\n\n",
"// Mind the gap.",
"if",
"gapLen",
":=",
"offset",
"-",
"bw",
".",
"written",
";",
"gapLen",
">",
"0",
"{",
"return",
"errResumableDigestNotAvailable",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// resumeDigest attempts to restore the state of the internal hash function
// by loading the most recent saved hash state equal to the current size of the blob.
|
[
"resumeDigest",
"attempts",
"to",
"restore",
"the",
"state",
"of",
"the",
"internal",
"hash",
"function",
"by",
"loading",
"the",
"most",
"recent",
"saved",
"hash",
"state",
"equal",
"to",
"the",
"current",
"size",
"of",
"the",
"blob",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter_resumable.go#L19-L72
|
train
|
docker/distribution
|
registry/storage/blobwriter_resumable.go
|
getStoredHashStates
|
func (bw *blobWriter) getStoredHashStates(ctx context.Context) ([]hashStateEntry, error) {
uploadHashStatePathPrefix, err := pathFor(uploadHashStatePathSpec{
name: bw.blobStore.repository.Named().String(),
id: bw.id,
alg: bw.digester.Digest().Algorithm(),
list: true,
})
if err != nil {
return nil, err
}
paths, err := bw.blobStore.driver.List(ctx, uploadHashStatePathPrefix)
if err != nil {
if _, ok := err.(storagedriver.PathNotFoundError); !ok {
return nil, err
}
// Treat PathNotFoundError as no entries.
paths = nil
}
hashStateEntries := make([]hashStateEntry, 0, len(paths))
for _, p := range paths {
pathSuffix := path.Base(p)
// The suffix should be the offset.
offset, err := strconv.ParseInt(pathSuffix, 0, 64)
if err != nil {
logrus.Errorf("unable to parse offset from upload state path %q: %s", p, err)
}
hashStateEntries = append(hashStateEntries, hashStateEntry{offset: offset, path: p})
}
return hashStateEntries, nil
}
|
go
|
func (bw *blobWriter) getStoredHashStates(ctx context.Context) ([]hashStateEntry, error) {
uploadHashStatePathPrefix, err := pathFor(uploadHashStatePathSpec{
name: bw.blobStore.repository.Named().String(),
id: bw.id,
alg: bw.digester.Digest().Algorithm(),
list: true,
})
if err != nil {
return nil, err
}
paths, err := bw.blobStore.driver.List(ctx, uploadHashStatePathPrefix)
if err != nil {
if _, ok := err.(storagedriver.PathNotFoundError); !ok {
return nil, err
}
// Treat PathNotFoundError as no entries.
paths = nil
}
hashStateEntries := make([]hashStateEntry, 0, len(paths))
for _, p := range paths {
pathSuffix := path.Base(p)
// The suffix should be the offset.
offset, err := strconv.ParseInt(pathSuffix, 0, 64)
if err != nil {
logrus.Errorf("unable to parse offset from upload state path %q: %s", p, err)
}
hashStateEntries = append(hashStateEntries, hashStateEntry{offset: offset, path: p})
}
return hashStateEntries, nil
}
|
[
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"getStoredHashStates",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"hashStateEntry",
",",
"error",
")",
"{",
"uploadHashStatePathPrefix",
",",
"err",
":=",
"pathFor",
"(",
"uploadHashStatePathSpec",
"{",
"name",
":",
"bw",
".",
"blobStore",
".",
"repository",
".",
"Named",
"(",
")",
".",
"String",
"(",
")",
",",
"id",
":",
"bw",
".",
"id",
",",
"alg",
":",
"bw",
".",
"digester",
".",
"Digest",
"(",
")",
".",
"Algorithm",
"(",
")",
",",
"list",
":",
"true",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"paths",
",",
"err",
":=",
"bw",
".",
"blobStore",
".",
"driver",
".",
"List",
"(",
"ctx",
",",
"uploadHashStatePathPrefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"storagedriver",
".",
"PathNotFoundError",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Treat PathNotFoundError as no entries.",
"paths",
"=",
"nil",
"\n",
"}",
"\n\n",
"hashStateEntries",
":=",
"make",
"(",
"[",
"]",
"hashStateEntry",
",",
"0",
",",
"len",
"(",
"paths",
")",
")",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"paths",
"{",
"pathSuffix",
":=",
"path",
".",
"Base",
"(",
"p",
")",
"\n",
"// The suffix should be the offset.",
"offset",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"pathSuffix",
",",
"0",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
",",
"err",
")",
"\n",
"}",
"\n\n",
"hashStateEntries",
"=",
"append",
"(",
"hashStateEntries",
",",
"hashStateEntry",
"{",
"offset",
":",
"offset",
",",
"path",
":",
"p",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"hashStateEntries",
",",
"nil",
"\n",
"}"
] |
// getStoredHashStates returns a slice of hashStateEntries for this upload.
|
[
"getStoredHashStates",
"returns",
"a",
"slice",
"of",
"hashStateEntries",
"for",
"this",
"upload",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter_resumable.go#L80-L115
|
train
|
docker/distribution
|
registry/storage/catalog.go
|
Repositories
|
func (reg *registry) Repositories(ctx context.Context, repos []string, last string) (n int, err error) {
var finishedWalk bool
var foundRepos []string
if len(repos) == 0 {
return 0, errors.New("no space in slice")
}
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return 0, err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
err := handleRepository(fileInfo, root, last, func(repoPath string) error {
foundRepos = append(foundRepos, repoPath)
return nil
})
if err != nil {
return err
}
// if we've filled our array, no need to walk any further
if len(foundRepos) == len(repos) {
finishedWalk = true
return driver.ErrSkipDir
}
return nil
})
n = copy(repos, foundRepos)
if err != nil {
return n, err
} else if !finishedWalk {
// We didn't fill buffer. No more records are available.
return n, io.EOF
}
return n, err
}
|
go
|
func (reg *registry) Repositories(ctx context.Context, repos []string, last string) (n int, err error) {
var finishedWalk bool
var foundRepos []string
if len(repos) == 0 {
return 0, errors.New("no space in slice")
}
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return 0, err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
err := handleRepository(fileInfo, root, last, func(repoPath string) error {
foundRepos = append(foundRepos, repoPath)
return nil
})
if err != nil {
return err
}
// if we've filled our array, no need to walk any further
if len(foundRepos) == len(repos) {
finishedWalk = true
return driver.ErrSkipDir
}
return nil
})
n = copy(repos, foundRepos)
if err != nil {
return n, err
} else if !finishedWalk {
// We didn't fill buffer. No more records are available.
return n, io.EOF
}
return n, err
}
|
[
"func",
"(",
"reg",
"*",
"registry",
")",
"Repositories",
"(",
"ctx",
"context",
".",
"Context",
",",
"repos",
"[",
"]",
"string",
",",
"last",
"string",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"var",
"finishedWalk",
"bool",
"\n",
"var",
"foundRepos",
"[",
"]",
"string",
"\n\n",
"if",
"len",
"(",
"repos",
")",
"==",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"root",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"reg",
".",
"blobStore",
".",
"driver",
".",
"Walk",
"(",
"ctx",
",",
"root",
",",
"func",
"(",
"fileInfo",
"driver",
".",
"FileInfo",
")",
"error",
"{",
"err",
":=",
"handleRepository",
"(",
"fileInfo",
",",
"root",
",",
"last",
",",
"func",
"(",
"repoPath",
"string",
")",
"error",
"{",
"foundRepos",
"=",
"append",
"(",
"foundRepos",
",",
"repoPath",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// if we've filled our array, no need to walk any further",
"if",
"len",
"(",
"foundRepos",
")",
"==",
"len",
"(",
"repos",
")",
"{",
"finishedWalk",
"=",
"true",
"\n",
"return",
"driver",
".",
"ErrSkipDir",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"n",
"=",
"copy",
"(",
"repos",
",",
"foundRepos",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n",
",",
"err",
"\n",
"}",
"else",
"if",
"!",
"finishedWalk",
"{",
"// We didn't fill buffer. No more records are available.",
"return",
"n",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n\n",
"return",
"n",
",",
"err",
"\n",
"}"
] |
// Returns a list, or partial list, of repositories in the registry.
// Because it's a quite expensive operation, it should only be used when building up
// an initial set of repositories.
|
[
"Returns",
"a",
"list",
"or",
"partial",
"list",
"of",
"repositories",
"in",
"the",
"registry",
".",
"Because",
"it",
"s",
"a",
"quite",
"expensive",
"operation",
"it",
"should",
"only",
"be",
"used",
"when",
"building",
"up",
"an",
"initial",
"set",
"of",
"repositories",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L17-L58
|
train
|
docker/distribution
|
registry/storage/catalog.go
|
Enumerate
|
func (reg *registry) Enumerate(ctx context.Context, ingester func(string) error) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
return handleRepository(fileInfo, root, "", ingester)
})
return err
}
|
go
|
func (reg *registry) Enumerate(ctx context.Context, ingester func(string) error) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
err = reg.blobStore.driver.Walk(ctx, root, func(fileInfo driver.FileInfo) error {
return handleRepository(fileInfo, root, "", ingester)
})
return err
}
|
[
"func",
"(",
"reg",
"*",
"registry",
")",
"Enumerate",
"(",
"ctx",
"context",
".",
"Context",
",",
"ingester",
"func",
"(",
"string",
")",
"error",
")",
"error",
"{",
"root",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"reg",
".",
"blobStore",
".",
"driver",
".",
"Walk",
"(",
"ctx",
",",
"root",
",",
"func",
"(",
"fileInfo",
"driver",
".",
"FileInfo",
")",
"error",
"{",
"return",
"handleRepository",
"(",
"fileInfo",
",",
"root",
",",
"\"",
"\"",
",",
"ingester",
")",
"\n",
"}",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// Enumerate applies ingester to each repository
|
[
"Enumerate",
"applies",
"ingester",
"to",
"each",
"repository"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L61-L72
|
train
|
docker/distribution
|
registry/storage/catalog.go
|
Remove
|
func (reg *registry) Remove(ctx context.Context, name reference.Named) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(root, name.Name())
return reg.driver.Delete(ctx, repoDir)
}
|
go
|
func (reg *registry) Remove(ctx context.Context, name reference.Named) error {
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(root, name.Name())
return reg.driver.Delete(ctx, repoDir)
}
|
[
"func",
"(",
"reg",
"*",
"registry",
")",
"Remove",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"reference",
".",
"Named",
")",
"error",
"{",
"root",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"repoDir",
":=",
"path",
".",
"Join",
"(",
"root",
",",
"name",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"reg",
".",
"driver",
".",
"Delete",
"(",
"ctx",
",",
"repoDir",
")",
"\n",
"}"
] |
// Remove removes a repository from storage
|
[
"Remove",
"removes",
"a",
"repository",
"from",
"storage"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L75-L82
|
train
|
docker/distribution
|
registry/storage/catalog.go
|
compareReplaceInline
|
func compareReplaceInline(s1, s2 string, old, new byte) int {
// TODO(stevvooe): We are missing an optimization when the s1 and s2 have
// the exact same slice header. It will make the code unsafe but can
// provide some extra performance.
l := len(s1)
if len(s2) < l {
l = len(s2)
}
for i := 0; i < l; i++ {
c1, c2 := s1[i], s2[i]
if c1 == old {
c1 = new
}
if c2 == old {
c2 = new
}
if c1 < c2 {
return -1
}
if c1 > c2 {
return +1
}
}
if len(s1) < len(s2) {
return -1
}
if len(s1) > len(s2) {
return +1
}
return 0
}
|
go
|
func compareReplaceInline(s1, s2 string, old, new byte) int {
// TODO(stevvooe): We are missing an optimization when the s1 and s2 have
// the exact same slice header. It will make the code unsafe but can
// provide some extra performance.
l := len(s1)
if len(s2) < l {
l = len(s2)
}
for i := 0; i < l; i++ {
c1, c2 := s1[i], s2[i]
if c1 == old {
c1 = new
}
if c2 == old {
c2 = new
}
if c1 < c2 {
return -1
}
if c1 > c2 {
return +1
}
}
if len(s1) < len(s2) {
return -1
}
if len(s1) > len(s2) {
return +1
}
return 0
}
|
[
"func",
"compareReplaceInline",
"(",
"s1",
",",
"s2",
"string",
",",
"old",
",",
"new",
"byte",
")",
"int",
"{",
"// TODO(stevvooe): We are missing an optimization when the s1 and s2 have",
"// the exact same slice header. It will make the code unsafe but can",
"// provide some extra performance.",
"l",
":=",
"len",
"(",
"s1",
")",
"\n",
"if",
"len",
"(",
"s2",
")",
"<",
"l",
"{",
"l",
"=",
"len",
"(",
"s2",
")",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
"{",
"c1",
",",
"c2",
":=",
"s1",
"[",
"i",
"]",
",",
"s2",
"[",
"i",
"]",
"\n",
"if",
"c1",
"==",
"old",
"{",
"c1",
"=",
"new",
"\n",
"}",
"\n\n",
"if",
"c2",
"==",
"old",
"{",
"c2",
"=",
"new",
"\n",
"}",
"\n\n",
"if",
"c1",
"<",
"c2",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n\n",
"if",
"c1",
">",
"c2",
"{",
"return",
"+",
"1",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"s1",
")",
"<",
"len",
"(",
"s2",
")",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"s1",
")",
">",
"len",
"(",
"s2",
")",
"{",
"return",
"+",
"1",
"\n",
"}",
"\n\n",
"return",
"0",
"\n",
"}"
] |
// compareReplaceInline modifies runtime.cmpstring to replace old with new
// during a byte-wise comparison.
|
[
"compareReplaceInline",
"modifies",
"runtime",
".",
"cmpstring",
"to",
"replace",
"old",
"with",
"new",
"during",
"a",
"byte",
"-",
"wise",
"comparison",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L95-L133
|
train
|
docker/distribution
|
registry/storage/catalog.go
|
handleRepository
|
func handleRepository(fileInfo driver.FileInfo, root, last string, fn func(repoPath string) error) error {
filePath := fileInfo.Path()
// lop the base path off
repo := filePath[len(root)+1:]
_, file := path.Split(repo)
if file == "_layers" {
repo = strings.TrimSuffix(repo, "/_layers")
if lessPath(last, repo) {
if err := fn(repo); err != nil {
return err
}
}
return driver.ErrSkipDir
} else if strings.HasPrefix(file, "_") {
return driver.ErrSkipDir
}
return nil
}
|
go
|
func handleRepository(fileInfo driver.FileInfo, root, last string, fn func(repoPath string) error) error {
filePath := fileInfo.Path()
// lop the base path off
repo := filePath[len(root)+1:]
_, file := path.Split(repo)
if file == "_layers" {
repo = strings.TrimSuffix(repo, "/_layers")
if lessPath(last, repo) {
if err := fn(repo); err != nil {
return err
}
}
return driver.ErrSkipDir
} else if strings.HasPrefix(file, "_") {
return driver.ErrSkipDir
}
return nil
}
|
[
"func",
"handleRepository",
"(",
"fileInfo",
"driver",
".",
"FileInfo",
",",
"root",
",",
"last",
"string",
",",
"fn",
"func",
"(",
"repoPath",
"string",
")",
"error",
")",
"error",
"{",
"filePath",
":=",
"fileInfo",
".",
"Path",
"(",
")",
"\n\n",
"// lop the base path off",
"repo",
":=",
"filePath",
"[",
"len",
"(",
"root",
")",
"+",
"1",
":",
"]",
"\n\n",
"_",
",",
"file",
":=",
"path",
".",
"Split",
"(",
"repo",
")",
"\n",
"if",
"file",
"==",
"\"",
"\"",
"{",
"repo",
"=",
"strings",
".",
"TrimSuffix",
"(",
"repo",
",",
"\"",
"\"",
")",
"\n",
"if",
"lessPath",
"(",
"last",
",",
"repo",
")",
"{",
"if",
"err",
":=",
"fn",
"(",
"repo",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"driver",
".",
"ErrSkipDir",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"file",
",",
"\"",
"\"",
")",
"{",
"return",
"driver",
".",
"ErrSkipDir",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// handleRepository calls function fn with a repository path if fileInfo
// has a path of a repository under root and that it is lexographically
// after last. Otherwise, it will return ErrSkipDir. This should be used
// with Walk to do handling with repositories in a storage.
|
[
"handleRepository",
"calls",
"function",
"fn",
"with",
"a",
"repository",
"path",
"if",
"fileInfo",
"has",
"a",
"path",
"of",
"a",
"repository",
"under",
"root",
"and",
"that",
"it",
"is",
"lexographically",
"after",
"last",
".",
"Otherwise",
"it",
"will",
"return",
"ErrSkipDir",
".",
"This",
"should",
"be",
"used",
"with",
"Walk",
"to",
"do",
"handling",
"with",
"repositories",
"in",
"a",
"storage",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/catalog.go#L139-L159
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/middleware.go
|
URLFor
|
func (lh *cloudFrontStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
// TODO(endophage): currently only supports S3
keyer, ok := lh.StorageDriver.(S3BucketKeyer)
if !ok {
dcontext.GetLogger(ctx).Warn("the CloudFront middleware does not support this backend storage driver")
return lh.StorageDriver.URLFor(ctx, path, options)
}
if eligibleForS3(ctx, lh.awsIPs) {
return lh.StorageDriver.URLFor(ctx, path, options)
}
// Get signed cloudfront url.
cfURL, err := lh.urlSigner.Sign(lh.baseURL+keyer.S3BucketKey(path), time.Now().Add(lh.duration))
if err != nil {
return "", err
}
return cfURL, nil
}
|
go
|
func (lh *cloudFrontStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
// TODO(endophage): currently only supports S3
keyer, ok := lh.StorageDriver.(S3BucketKeyer)
if !ok {
dcontext.GetLogger(ctx).Warn("the CloudFront middleware does not support this backend storage driver")
return lh.StorageDriver.URLFor(ctx, path, options)
}
if eligibleForS3(ctx, lh.awsIPs) {
return lh.StorageDriver.URLFor(ctx, path, options)
}
// Get signed cloudfront url.
cfURL, err := lh.urlSigner.Sign(lh.baseURL+keyer.S3BucketKey(path), time.Now().Add(lh.duration))
if err != nil {
return "", err
}
return cfURL, nil
}
|
[
"func",
"(",
"lh",
"*",
"cloudFrontStorageMiddleware",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"// TODO(endophage): currently only supports S3",
"keyer",
",",
"ok",
":=",
"lh",
".",
"StorageDriver",
".",
"(",
"S3BucketKeyer",
")",
"\n",
"if",
"!",
"ok",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"lh",
".",
"StorageDriver",
".",
"URLFor",
"(",
"ctx",
",",
"path",
",",
"options",
")",
"\n",
"}",
"\n\n",
"if",
"eligibleForS3",
"(",
"ctx",
",",
"lh",
".",
"awsIPs",
")",
"{",
"return",
"lh",
".",
"StorageDriver",
".",
"URLFor",
"(",
"ctx",
",",
"path",
",",
"options",
")",
"\n",
"}",
"\n\n",
"// Get signed cloudfront url.",
"cfURL",
",",
"err",
":=",
"lh",
".",
"urlSigner",
".",
"Sign",
"(",
"lh",
".",
"baseURL",
"+",
"keyer",
".",
"S3BucketKey",
"(",
"path",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"lh",
".",
"duration",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"cfURL",
",",
"nil",
"\n",
"}"
] |
// URLFor attempts to find a url which may be used to retrieve the file at the given path.
// Returns an error if the file cannot be found.
|
[
"URLFor",
"attempts",
"to",
"find",
"a",
"url",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"file",
"at",
"the",
"given",
"path",
".",
"Returns",
"an",
"error",
"if",
"the",
"file",
"cannot",
"be",
"found",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/middleware.go#L187-L205
|
train
|
docker/distribution
|
registry/storage/paths.go
|
digestFromPath
|
func digestFromPath(digestPath string) (digest.Digest, error) {
digestPath = strings.TrimSuffix(digestPath, "/data")
dir, hex := path.Split(digestPath)
dir = path.Dir(dir)
dir, next := path.Split(dir)
// next is either the algorithm OR the first two characters in the hex string
var algo string
if next == hex[:2] {
algo = path.Base(dir)
} else {
algo = next
}
dgst := digest.NewDigestFromHex(algo, hex)
return dgst, dgst.Validate()
}
|
go
|
func digestFromPath(digestPath string) (digest.Digest, error) {
digestPath = strings.TrimSuffix(digestPath, "/data")
dir, hex := path.Split(digestPath)
dir = path.Dir(dir)
dir, next := path.Split(dir)
// next is either the algorithm OR the first two characters in the hex string
var algo string
if next == hex[:2] {
algo = path.Base(dir)
} else {
algo = next
}
dgst := digest.NewDigestFromHex(algo, hex)
return dgst, dgst.Validate()
}
|
[
"func",
"digestFromPath",
"(",
"digestPath",
"string",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"digestPath",
"=",
"strings",
".",
"TrimSuffix",
"(",
"digestPath",
",",
"\"",
"\"",
")",
"\n",
"dir",
",",
"hex",
":=",
"path",
".",
"Split",
"(",
"digestPath",
")",
"\n",
"dir",
"=",
"path",
".",
"Dir",
"(",
"dir",
")",
"\n",
"dir",
",",
"next",
":=",
"path",
".",
"Split",
"(",
"dir",
")",
"\n\n",
"// next is either the algorithm OR the first two characters in the hex string",
"var",
"algo",
"string",
"\n",
"if",
"next",
"==",
"hex",
"[",
":",
"2",
"]",
"{",
"algo",
"=",
"path",
".",
"Base",
"(",
"dir",
")",
"\n",
"}",
"else",
"{",
"algo",
"=",
"next",
"\n",
"}",
"\n\n",
"dgst",
":=",
"digest",
".",
"NewDigestFromHex",
"(",
"algo",
",",
"hex",
")",
"\n",
"return",
"dgst",
",",
"dgst",
".",
"Validate",
"(",
")",
"\n",
"}"
] |
// Reconstructs a digest from a path
|
[
"Reconstructs",
"a",
"digest",
"from",
"a",
"path"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/paths.go#L460-L477
|
train
|
docker/distribution
|
registry/storage/blobwriter.go
|
Commit
|
func (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Commit")
if err := bw.fileWriter.Commit(); err != nil {
return distribution.Descriptor{}, err
}
bw.Close()
desc.Size = bw.Size()
canonical, err := bw.validateBlob(ctx, desc)
if err != nil {
return distribution.Descriptor{}, err
}
if err := bw.moveBlob(ctx, canonical); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.blobStore.linkBlob(ctx, canonical, desc.Digest); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.removeResources(ctx); err != nil {
return distribution.Descriptor{}, err
}
err = bw.blobStore.blobAccessController.SetDescriptor(ctx, canonical.Digest, canonical)
if err != nil {
return distribution.Descriptor{}, err
}
bw.committed = true
return canonical, nil
}
|
go
|
func (bw *blobWriter) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Commit")
if err := bw.fileWriter.Commit(); err != nil {
return distribution.Descriptor{}, err
}
bw.Close()
desc.Size = bw.Size()
canonical, err := bw.validateBlob(ctx, desc)
if err != nil {
return distribution.Descriptor{}, err
}
if err := bw.moveBlob(ctx, canonical); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.blobStore.linkBlob(ctx, canonical, desc.Digest); err != nil {
return distribution.Descriptor{}, err
}
if err := bw.removeResources(ctx); err != nil {
return distribution.Descriptor{}, err
}
err = bw.blobStore.blobAccessController.SetDescriptor(ctx, canonical.Digest, canonical)
if err != nil {
return distribution.Descriptor{}, err
}
bw.committed = true
return canonical, nil
}
|
[
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"Commit",
"(",
"ctx",
"context",
".",
"Context",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
":=",
"bw",
".",
"fileWriter",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"bw",
".",
"Close",
"(",
")",
"\n",
"desc",
".",
"Size",
"=",
"bw",
".",
"Size",
"(",
")",
"\n\n",
"canonical",
",",
"err",
":=",
"bw",
".",
"validateBlob",
"(",
"ctx",
",",
"desc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"bw",
".",
"moveBlob",
"(",
"ctx",
",",
"canonical",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"bw",
".",
"blobStore",
".",
"linkBlob",
"(",
"ctx",
",",
"canonical",
",",
"desc",
".",
"Digest",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"bw",
".",
"removeResources",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"bw",
".",
"blobStore",
".",
"blobAccessController",
".",
"SetDescriptor",
"(",
"ctx",
",",
"canonical",
".",
"Digest",
",",
"canonical",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"bw",
".",
"committed",
"=",
"true",
"\n",
"return",
"canonical",
",",
"nil",
"\n",
"}"
] |
// Commit marks the upload as completed, returning a valid descriptor. The
// final size and digest are checked against the first descriptor provided.
|
[
"Commit",
"marks",
"the",
"upload",
"as",
"completed",
"returning",
"a",
"valid",
"descriptor",
".",
"The",
"final",
"size",
"and",
"digest",
"are",
"checked",
"against",
"the",
"first",
"descriptor",
"provided",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L59-L93
|
train
|
docker/distribution
|
registry/storage/blobwriter.go
|
Cancel
|
func (bw *blobWriter) Cancel(ctx context.Context) error {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Cancel")
if err := bw.fileWriter.Cancel(); err != nil {
return err
}
if err := bw.Close(); err != nil {
dcontext.GetLogger(ctx).Errorf("error closing blobwriter: %s", err)
}
return bw.removeResources(ctx)
}
|
go
|
func (bw *blobWriter) Cancel(ctx context.Context) error {
dcontext.GetLogger(ctx).Debug("(*blobWriter).Cancel")
if err := bw.fileWriter.Cancel(); err != nil {
return err
}
if err := bw.Close(); err != nil {
dcontext.GetLogger(ctx).Errorf("error closing blobwriter: %s", err)
}
return bw.removeResources(ctx)
}
|
[
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"Cancel",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"bw",
".",
"fileWriter",
".",
"Cancel",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"bw",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"bw",
".",
"removeResources",
"(",
"ctx",
")",
"\n",
"}"
] |
// Cancel the blob upload process, releasing any resources associated with
// the writer and canceling the operation.
|
[
"Cancel",
"the",
"blob",
"upload",
"process",
"releasing",
"any",
"resources",
"associated",
"with",
"the",
"writer",
"and",
"canceling",
"the",
"operation",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L97-L108
|
train
|
docker/distribution
|
registry/storage/blobwriter.go
|
moveBlob
|
func (bw *blobWriter) moveBlob(ctx context.Context, desc distribution.Descriptor) error {
blobPath, err := pathFor(blobDataPathSpec{
digest: desc.Digest,
})
if err != nil {
return err
}
// Check for existence
if _, err := bw.blobStore.driver.Stat(ctx, blobPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // ensure that it doesn't exist.
default:
return err
}
} else {
// If the path exists, we can assume that the content has already
// been uploaded, since the blob storage is content-addressable.
// While it may be corrupted, detection of such corruption belongs
// elsewhere.
return nil
}
// If no data was received, we may not actually have a file on disk. Check
// the size here and write a zero-length file to blobPath if this is the
// case. For the most part, this should only ever happen with zero-length
// blobs.
if _, err := bw.blobStore.driver.Stat(ctx, bw.path); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
// HACK(stevvooe): This is slightly dangerous: if we verify above,
// get a hash, then the underlying file is deleted, we risk moving
// a zero-length blob into a nonzero-length blob location. To
// prevent this horrid thing, we employ the hack of only allowing
// to this happen for the digest of an empty blob.
if desc.Digest == digestSha256Empty {
return bw.blobStore.driver.PutContent(ctx, blobPath, []byte{})
}
// We let this fail during the move below.
logrus.
WithField("upload.id", bw.ID()).
WithField("digest", desc.Digest).Warnf("attempted to move zero-length content with non-zero digest")
default:
return err // unrelated error
}
}
// TODO(stevvooe): We should also write the mediatype when executing this move.
return bw.blobStore.driver.Move(ctx, bw.path, blobPath)
}
|
go
|
func (bw *blobWriter) moveBlob(ctx context.Context, desc distribution.Descriptor) error {
blobPath, err := pathFor(blobDataPathSpec{
digest: desc.Digest,
})
if err != nil {
return err
}
// Check for existence
if _, err := bw.blobStore.driver.Stat(ctx, blobPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // ensure that it doesn't exist.
default:
return err
}
} else {
// If the path exists, we can assume that the content has already
// been uploaded, since the blob storage is content-addressable.
// While it may be corrupted, detection of such corruption belongs
// elsewhere.
return nil
}
// If no data was received, we may not actually have a file on disk. Check
// the size here and write a zero-length file to blobPath if this is the
// case. For the most part, this should only ever happen with zero-length
// blobs.
if _, err := bw.blobStore.driver.Stat(ctx, bw.path); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
// HACK(stevvooe): This is slightly dangerous: if we verify above,
// get a hash, then the underlying file is deleted, we risk moving
// a zero-length blob into a nonzero-length blob location. To
// prevent this horrid thing, we employ the hack of only allowing
// to this happen for the digest of an empty blob.
if desc.Digest == digestSha256Empty {
return bw.blobStore.driver.PutContent(ctx, blobPath, []byte{})
}
// We let this fail during the move below.
logrus.
WithField("upload.id", bw.ID()).
WithField("digest", desc.Digest).Warnf("attempted to move zero-length content with non-zero digest")
default:
return err // unrelated error
}
}
// TODO(stevvooe): We should also write the mediatype when executing this move.
return bw.blobStore.driver.Move(ctx, bw.path, blobPath)
}
|
[
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"moveBlob",
"(",
"ctx",
"context",
".",
"Context",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"error",
"{",
"blobPath",
",",
"err",
":=",
"pathFor",
"(",
"blobDataPathSpec",
"{",
"digest",
":",
"desc",
".",
"Digest",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Check for existence",
"if",
"_",
",",
"err",
":=",
"bw",
".",
"blobStore",
".",
"driver",
".",
"Stat",
"(",
"ctx",
",",
"blobPath",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"break",
"// ensure that it doesn't exist.",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// If the path exists, we can assume that the content has already",
"// been uploaded, since the blob storage is content-addressable.",
"// While it may be corrupted, detection of such corruption belongs",
"// elsewhere.",
"return",
"nil",
"\n",
"}",
"\n\n",
"// If no data was received, we may not actually have a file on disk. Check",
"// the size here and write a zero-length file to blobPath if this is the",
"// case. For the most part, this should only ever happen with zero-length",
"// blobs.",
"if",
"_",
",",
"err",
":=",
"bw",
".",
"blobStore",
".",
"driver",
".",
"Stat",
"(",
"ctx",
",",
"bw",
".",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"// HACK(stevvooe): This is slightly dangerous: if we verify above,",
"// get a hash, then the underlying file is deleted, we risk moving",
"// a zero-length blob into a nonzero-length blob location. To",
"// prevent this horrid thing, we employ the hack of only allowing",
"// to this happen for the digest of an empty blob.",
"if",
"desc",
".",
"Digest",
"==",
"digestSha256Empty",
"{",
"return",
"bw",
".",
"blobStore",
".",
"driver",
".",
"PutContent",
"(",
"ctx",
",",
"blobPath",
",",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"}",
"\n\n",
"// We let this fail during the move below.",
"logrus",
".",
"WithField",
"(",
"\"",
"\"",
",",
"bw",
".",
"ID",
"(",
")",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"desc",
".",
"Digest",
")",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"default",
":",
"return",
"err",
"// unrelated error",
"\n",
"}",
"\n",
"}",
"\n\n",
"// TODO(stevvooe): We should also write the mediatype when executing this move.",
"return",
"bw",
".",
"blobStore",
".",
"driver",
".",
"Move",
"(",
"ctx",
",",
"bw",
".",
"path",
",",
"blobPath",
")",
"\n",
"}"
] |
// moveBlob moves the data into its final, hash-qualified destination,
// identified by dgst. The layer should be validated before commencing the
// move.
|
[
"moveBlob",
"moves",
"the",
"data",
"into",
"its",
"final",
"hash",
"-",
"qualified",
"destination",
"identified",
"by",
"dgst",
".",
"The",
"layer",
"should",
"be",
"validated",
"before",
"commencing",
"the",
"move",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L295-L348
|
train
|
docker/distribution
|
registry/storage/blobwriter.go
|
removeResources
|
func (bw *blobWriter) removeResources(ctx context.Context) error {
dataPath, err := pathFor(uploadDataPathSpec{
name: bw.blobStore.repository.Named().Name(),
id: bw.id,
})
if err != nil {
return err
}
// Resolve and delete the containing directory, which should include any
// upload related files.
dirPath := path.Dir(dataPath)
if err := bw.blobStore.driver.Delete(ctx, dirPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // already gone!
default:
// This should be uncommon enough such that returning an error
// should be okay. At this point, the upload should be mostly
// complete, but perhaps the backend became unaccessible.
dcontext.GetLogger(ctx).Errorf("unable to delete layer upload resources %q: %v", dirPath, err)
return err
}
}
return nil
}
|
go
|
func (bw *blobWriter) removeResources(ctx context.Context) error {
dataPath, err := pathFor(uploadDataPathSpec{
name: bw.blobStore.repository.Named().Name(),
id: bw.id,
})
if err != nil {
return err
}
// Resolve and delete the containing directory, which should include any
// upload related files.
dirPath := path.Dir(dataPath)
if err := bw.blobStore.driver.Delete(ctx, dirPath); err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
break // already gone!
default:
// This should be uncommon enough such that returning an error
// should be okay. At this point, the upload should be mostly
// complete, but perhaps the backend became unaccessible.
dcontext.GetLogger(ctx).Errorf("unable to delete layer upload resources %q: %v", dirPath, err)
return err
}
}
return nil
}
|
[
"func",
"(",
"bw",
"*",
"blobWriter",
")",
"removeResources",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"dataPath",
",",
"err",
":=",
"pathFor",
"(",
"uploadDataPathSpec",
"{",
"name",
":",
"bw",
".",
"blobStore",
".",
"repository",
".",
"Named",
"(",
")",
".",
"Name",
"(",
")",
",",
"id",
":",
"bw",
".",
"id",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Resolve and delete the containing directory, which should include any",
"// upload related files.",
"dirPath",
":=",
"path",
".",
"Dir",
"(",
"dataPath",
")",
"\n",
"if",
"err",
":=",
"bw",
".",
"blobStore",
".",
"driver",
".",
"Delete",
"(",
"ctx",
",",
"dirPath",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"break",
"// already gone!",
"\n",
"default",
":",
"// This should be uncommon enough such that returning an error",
"// should be okay. At this point, the upload should be mostly",
"// complete, but perhaps the backend became unaccessible.",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dirPath",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// removeResources should clean up all resources associated with the upload
// instance. An error will be returned if the clean up cannot proceed. If the
// resources are already not present, no error will be returned.
|
[
"removeResources",
"should",
"clean",
"up",
"all",
"resources",
"associated",
"with",
"the",
"upload",
"instance",
".",
"An",
"error",
"will",
"be",
"returned",
"if",
"the",
"clean",
"up",
"cannot",
"proceed",
".",
"If",
"the",
"resources",
"are",
"already",
"not",
"present",
"no",
"error",
"will",
"be",
"returned",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/blobwriter.go#L353-L380
|
train
|
docker/distribution
|
manifest/schema1/verify.go
|
Verify
|
func Verify(sm *SignedManifest) ([]libtrust.PublicKey, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
logrus.WithField("err", err).Debugf("(*SignedManifest).Verify")
return nil, err
}
return js.Verify()
}
|
go
|
func Verify(sm *SignedManifest) ([]libtrust.PublicKey, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
logrus.WithField("err", err).Debugf("(*SignedManifest).Verify")
return nil, err
}
return js.Verify()
}
|
[
"func",
"Verify",
"(",
"sm",
"*",
"SignedManifest",
")",
"(",
"[",
"]",
"libtrust",
".",
"PublicKey",
",",
"error",
")",
"{",
"js",
",",
"err",
":=",
"libtrust",
".",
"ParsePrettySignature",
"(",
"sm",
".",
"all",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"js",
".",
"Verify",
"(",
")",
"\n",
"}"
] |
// Verify verifies the signature of the signed manifest returning the public
// keys used during signing.
|
[
"Verify",
"verifies",
"the",
"signature",
"of",
"the",
"signed",
"manifest",
"returning",
"the",
"public",
"keys",
"used",
"during",
"signing",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/verify.go#L12-L20
|
train
|
docker/distribution
|
manifest/schema1/verify.go
|
VerifyChains
|
func VerifyChains(sm *SignedManifest, ca *x509.CertPool) ([][]*x509.Certificate, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
return nil, err
}
return js.VerifyChains(ca)
}
|
go
|
func VerifyChains(sm *SignedManifest, ca *x509.CertPool) ([][]*x509.Certificate, error) {
js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
if err != nil {
return nil, err
}
return js.VerifyChains(ca)
}
|
[
"func",
"VerifyChains",
"(",
"sm",
"*",
"SignedManifest",
",",
"ca",
"*",
"x509",
".",
"CertPool",
")",
"(",
"[",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"js",
",",
"err",
":=",
"libtrust",
".",
"ParsePrettySignature",
"(",
"sm",
".",
"all",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"js",
".",
"VerifyChains",
"(",
"ca",
")",
"\n",
"}"
] |
// VerifyChains verifies the signature of the signed manifest against the
// certificate pool returning the list of verified chains. Signatures without
// an x509 chain are not checked.
|
[
"VerifyChains",
"verifies",
"the",
"signature",
"of",
"the",
"signed",
"manifest",
"against",
"the",
"certificate",
"pool",
"returning",
"the",
"list",
"of",
"verified",
"chains",
".",
"Signatures",
"without",
"an",
"x509",
"chain",
"are",
"not",
"checked",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/verify.go#L25-L32
|
train
|
docker/distribution
|
registry/proxy/proxyauth.go
|
configureAuth
|
func configureAuth(username, password, remoteURL string) (auth.CredentialStore, error) {
creds := map[string]userpass{}
authURLs, err := getAuthURLs(remoteURL)
if err != nil {
return nil, err
}
for _, url := range authURLs {
context.GetLogger(context.Background()).Infof("Discovered token authentication URL: %s", url)
creds[url] = userpass{
username: username,
password: password,
}
}
return credentials{creds: creds}, nil
}
|
go
|
func configureAuth(username, password, remoteURL string) (auth.CredentialStore, error) {
creds := map[string]userpass{}
authURLs, err := getAuthURLs(remoteURL)
if err != nil {
return nil, err
}
for _, url := range authURLs {
context.GetLogger(context.Background()).Infof("Discovered token authentication URL: %s", url)
creds[url] = userpass{
username: username,
password: password,
}
}
return credentials{creds: creds}, nil
}
|
[
"func",
"configureAuth",
"(",
"username",
",",
"password",
",",
"remoteURL",
"string",
")",
"(",
"auth",
".",
"CredentialStore",
",",
"error",
")",
"{",
"creds",
":=",
"map",
"[",
"string",
"]",
"userpass",
"{",
"}",
"\n\n",
"authURLs",
",",
"err",
":=",
"getAuthURLs",
"(",
"remoteURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"url",
":=",
"range",
"authURLs",
"{",
"context",
".",
"GetLogger",
"(",
"context",
".",
"Background",
"(",
")",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"creds",
"[",
"url",
"]",
"=",
"userpass",
"{",
"username",
":",
"username",
",",
"password",
":",
"password",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"credentials",
"{",
"creds",
":",
"creds",
"}",
",",
"nil",
"\n",
"}"
] |
// configureAuth stores credentials for challenge responses
|
[
"configureAuth",
"stores",
"credentials",
"for",
"challenge",
"responses"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxyauth.go#L38-L55
|
train
|
docker/distribution
|
registry/storage/driver/inmemory/mfs.go
|
add
|
func (d *dir) add(n node) {
if d.children == nil {
d.children = make(map[string]node)
}
d.children[n.name()] = n
d.mod = time.Now()
}
|
go
|
func (d *dir) add(n node) {
if d.children == nil {
d.children = make(map[string]node)
}
d.children[n.name()] = n
d.mod = time.Now()
}
|
[
"func",
"(",
"d",
"*",
"dir",
")",
"add",
"(",
"n",
"node",
")",
"{",
"if",
"d",
".",
"children",
"==",
"nil",
"{",
"d",
".",
"children",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"node",
")",
"\n",
"}",
"\n\n",
"d",
".",
"children",
"[",
"n",
".",
"name",
"(",
")",
"]",
"=",
"n",
"\n",
"d",
".",
"mod",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}"
] |
// add places the node n into dir d.
|
[
"add",
"places",
"the",
"node",
"n",
"into",
"dir",
"d",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L42-L49
|
train
|
docker/distribution
|
registry/storage/driver/inmemory/mfs.go
|
mkfile
|
func (d *dir) mkfile(p string) (*file, error) {
n := d.find(p)
if n.path() == p {
if n.isdir() {
return nil, errIsDir
}
return n.(*file), nil
}
dirpath, filename := path.Split(p)
// Make any non-existent directories
n, err := d.mkdirs(dirpath)
if err != nil {
return nil, err
}
dd := n.(*dir)
n = &file{
common: common{
p: path.Join(dd.path(), filename),
mod: time.Now(),
},
}
dd.add(n)
return n.(*file), nil
}
|
go
|
func (d *dir) mkfile(p string) (*file, error) {
n := d.find(p)
if n.path() == p {
if n.isdir() {
return nil, errIsDir
}
return n.(*file), nil
}
dirpath, filename := path.Split(p)
// Make any non-existent directories
n, err := d.mkdirs(dirpath)
if err != nil {
return nil, err
}
dd := n.(*dir)
n = &file{
common: common{
p: path.Join(dd.path(), filename),
mod: time.Now(),
},
}
dd.add(n)
return n.(*file), nil
}
|
[
"func",
"(",
"d",
"*",
"dir",
")",
"mkfile",
"(",
"p",
"string",
")",
"(",
"*",
"file",
",",
"error",
")",
"{",
"n",
":=",
"d",
".",
"find",
"(",
"p",
")",
"\n",
"if",
"n",
".",
"path",
"(",
")",
"==",
"p",
"{",
"if",
"n",
".",
"isdir",
"(",
")",
"{",
"return",
"nil",
",",
"errIsDir",
"\n",
"}",
"\n\n",
"return",
"n",
".",
"(",
"*",
"file",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"dirpath",
",",
"filename",
":=",
"path",
".",
"Split",
"(",
"p",
")",
"\n",
"// Make any non-existent directories",
"n",
",",
"err",
":=",
"d",
".",
"mkdirs",
"(",
"dirpath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"dd",
":=",
"n",
".",
"(",
"*",
"dir",
")",
"\n",
"n",
"=",
"&",
"file",
"{",
"common",
":",
"common",
"{",
"p",
":",
"path",
".",
"Join",
"(",
"dd",
".",
"path",
"(",
")",
",",
"filename",
")",
",",
"mod",
":",
"time",
".",
"Now",
"(",
")",
",",
"}",
",",
"}",
"\n\n",
"dd",
".",
"add",
"(",
"n",
")",
"\n",
"return",
"n",
".",
"(",
"*",
"file",
")",
",",
"nil",
"\n",
"}"
] |
// mkfile or return the existing one. returns an error if it exists and is a
// directory. Essentially, this is open or create.
|
[
"mkfile",
"or",
"return",
"the",
"existing",
"one",
".",
"returns",
"an",
"error",
"if",
"it",
"exists",
"and",
"is",
"a",
"directory",
".",
"Essentially",
"this",
"is",
"open",
"or",
"create",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L111-L138
|
train
|
docker/distribution
|
registry/storage/driver/inmemory/mfs.go
|
mkdirs
|
func (d *dir) mkdirs(p string) (*dir, error) {
p = normalize(p)
n := d.find(p)
if !n.isdir() {
// Found something there
return nil, errIsNotDir
}
if n.path() == p {
return n.(*dir), nil
}
dd := n.(*dir)
relative := strings.Trim(strings.TrimPrefix(p, n.path()), "/")
if relative == "" {
return dd, nil
}
components := strings.Split(relative, "/")
for _, component := range components {
d, err := dd.mkdir(component)
if err != nil {
// This should actually never happen, since there are no children.
return nil, err
}
dd = d
}
return dd, nil
}
|
go
|
func (d *dir) mkdirs(p string) (*dir, error) {
p = normalize(p)
n := d.find(p)
if !n.isdir() {
// Found something there
return nil, errIsNotDir
}
if n.path() == p {
return n.(*dir), nil
}
dd := n.(*dir)
relative := strings.Trim(strings.TrimPrefix(p, n.path()), "/")
if relative == "" {
return dd, nil
}
components := strings.Split(relative, "/")
for _, component := range components {
d, err := dd.mkdir(component)
if err != nil {
// This should actually never happen, since there are no children.
return nil, err
}
dd = d
}
return dd, nil
}
|
[
"func",
"(",
"d",
"*",
"dir",
")",
"mkdirs",
"(",
"p",
"string",
")",
"(",
"*",
"dir",
",",
"error",
")",
"{",
"p",
"=",
"normalize",
"(",
"p",
")",
"\n\n",
"n",
":=",
"d",
".",
"find",
"(",
"p",
")",
"\n\n",
"if",
"!",
"n",
".",
"isdir",
"(",
")",
"{",
"// Found something there",
"return",
"nil",
",",
"errIsNotDir",
"\n",
"}",
"\n\n",
"if",
"n",
".",
"path",
"(",
")",
"==",
"p",
"{",
"return",
"n",
".",
"(",
"*",
"dir",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"dd",
":=",
"n",
".",
"(",
"*",
"dir",
")",
"\n\n",
"relative",
":=",
"strings",
".",
"Trim",
"(",
"strings",
".",
"TrimPrefix",
"(",
"p",
",",
"n",
".",
"path",
"(",
")",
")",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"relative",
"==",
"\"",
"\"",
"{",
"return",
"dd",
",",
"nil",
"\n",
"}",
"\n\n",
"components",
":=",
"strings",
".",
"Split",
"(",
"relative",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"component",
":=",
"range",
"components",
"{",
"d",
",",
"err",
":=",
"dd",
".",
"mkdir",
"(",
"component",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// This should actually never happen, since there are no children.",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dd",
"=",
"d",
"\n",
"}",
"\n\n",
"return",
"dd",
",",
"nil",
"\n",
"}"
] |
// mkdirs creates any missing directory entries in p and returns the result.
|
[
"mkdirs",
"creates",
"any",
"missing",
"directory",
"entries",
"in",
"p",
"and",
"returns",
"the",
"result",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L141-L175
|
train
|
docker/distribution
|
registry/storage/driver/inmemory/mfs.go
|
mkdir
|
func (d *dir) mkdir(name string) (*dir, error) {
if name == "" {
return nil, fmt.Errorf("invalid dirname")
}
_, ok := d.children[name]
if ok {
return nil, errExists
}
child := &dir{
common: common{
p: path.Join(d.path(), name),
mod: time.Now(),
},
}
d.add(child)
d.mod = time.Now()
return child, nil
}
|
go
|
func (d *dir) mkdir(name string) (*dir, error) {
if name == "" {
return nil, fmt.Errorf("invalid dirname")
}
_, ok := d.children[name]
if ok {
return nil, errExists
}
child := &dir{
common: common{
p: path.Join(d.path(), name),
mod: time.Now(),
},
}
d.add(child)
d.mod = time.Now()
return child, nil
}
|
[
"func",
"(",
"d",
"*",
"dir",
")",
"mkdir",
"(",
"name",
"string",
")",
"(",
"*",
"dir",
",",
"error",
")",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"_",
",",
"ok",
":=",
"d",
".",
"children",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
"return",
"nil",
",",
"errExists",
"\n",
"}",
"\n\n",
"child",
":=",
"&",
"dir",
"{",
"common",
":",
"common",
"{",
"p",
":",
"path",
".",
"Join",
"(",
"d",
".",
"path",
"(",
")",
",",
"name",
")",
",",
"mod",
":",
"time",
".",
"Now",
"(",
")",
",",
"}",
",",
"}",
"\n",
"d",
".",
"add",
"(",
"child",
")",
"\n",
"d",
".",
"mod",
"=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"return",
"child",
",",
"nil",
"\n",
"}"
] |
// mkdir creates a child directory under d with the given name.
|
[
"mkdir",
"creates",
"a",
"child",
"directory",
"under",
"d",
"with",
"the",
"given",
"name",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/inmemory/mfs.go#L178-L198
|
train
|
docker/distribution
|
registry/client/repository.go
|
checkHTTPRedirect
|
func checkHTTPRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if len(via) > 0 {
for headerName, headerVals := range via[0].Header {
if headerName != "Accept" && headerName != "Range" {
continue
}
for _, val := range headerVals {
// Don't add to redirected request if redirected
// request already has a header with the same
// name and value.
hasValue := false
for _, existingVal := range req.Header[headerName] {
if existingVal == val {
hasValue = true
break
}
}
if !hasValue {
req.Header.Add(headerName, val)
}
}
}
}
return nil
}
|
go
|
func checkHTTPRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if len(via) > 0 {
for headerName, headerVals := range via[0].Header {
if headerName != "Accept" && headerName != "Range" {
continue
}
for _, val := range headerVals {
// Don't add to redirected request if redirected
// request already has a header with the same
// name and value.
hasValue := false
for _, existingVal := range req.Header[headerName] {
if existingVal == val {
hasValue = true
break
}
}
if !hasValue {
req.Header.Add(headerName, val)
}
}
}
}
return nil
}
|
[
"func",
"checkHTTPRedirect",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"via",
"[",
"]",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"if",
"len",
"(",
"via",
")",
">=",
"10",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"via",
")",
">",
"0",
"{",
"for",
"headerName",
",",
"headerVals",
":=",
"range",
"via",
"[",
"0",
"]",
".",
"Header",
"{",
"if",
"headerName",
"!=",
"\"",
"\"",
"&&",
"headerName",
"!=",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"val",
":=",
"range",
"headerVals",
"{",
"// Don't add to redirected request if redirected",
"// request already has a header with the same",
"// name and value.",
"hasValue",
":=",
"false",
"\n",
"for",
"_",
",",
"existingVal",
":=",
"range",
"req",
".",
"Header",
"[",
"headerName",
"]",
"{",
"if",
"existingVal",
"==",
"val",
"{",
"hasValue",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"hasValue",
"{",
"req",
".",
"Header",
".",
"Add",
"(",
"headerName",
",",
"val",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// checkHTTPRedirect is a callback that can manipulate redirected HTTP
// requests. It is used to preserve Accept and Range headers.
|
[
"checkHTTPRedirect",
"is",
"a",
"callback",
"that",
"can",
"manipulate",
"redirected",
"HTTP",
"requests",
".",
"It",
"is",
"used",
"to",
"preserve",
"Accept",
"and",
"Range",
"headers",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L33-L62
|
train
|
docker/distribution
|
registry/client/repository.go
|
NewRegistry
|
func NewRegistry(baseURL string, transport http.RoundTripper) (Registry, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
Timeout: 1 * time.Minute,
CheckRedirect: checkHTTPRedirect,
}
return ®istry{
client: client,
ub: ub,
}, nil
}
|
go
|
func NewRegistry(baseURL string, transport http.RoundTripper) (Registry, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
Timeout: 1 * time.Minute,
CheckRedirect: checkHTTPRedirect,
}
return ®istry{
client: client,
ub: ub,
}, nil
}
|
[
"func",
"NewRegistry",
"(",
"baseURL",
"string",
",",
"transport",
"http",
".",
"RoundTripper",
")",
"(",
"Registry",
",",
"error",
")",
"{",
"ub",
",",
"err",
":=",
"v2",
".",
"NewURLBuilderFromString",
"(",
"baseURL",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"transport",
",",
"Timeout",
":",
"1",
"*",
"time",
".",
"Minute",
",",
"CheckRedirect",
":",
"checkHTTPRedirect",
",",
"}",
"\n\n",
"return",
"&",
"registry",
"{",
"client",
":",
"client",
",",
"ub",
":",
"ub",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewRegistry creates a registry namespace which can be used to get a listing of repositories
|
[
"NewRegistry",
"creates",
"a",
"registry",
"namespace",
"which",
"can",
"be",
"used",
"to",
"get",
"a",
"listing",
"of",
"repositories"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L65-L81
|
train
|
docker/distribution
|
registry/client/repository.go
|
Repositories
|
func (r *registry) Repositories(ctx context.Context, entries []string, last string) (int, error) {
var numFilled int
var returnErr error
values := buildCatalogValues(len(entries), last)
u, err := r.ub.BuildCatalogURL(values)
if err != nil {
return 0, err
}
resp, err := r.client.Get(u)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
var ctlg struct {
Repositories []string `json:"repositories"`
}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&ctlg); err != nil {
return 0, err
}
for cnt := range ctlg.Repositories {
entries[cnt] = ctlg.Repositories[cnt]
}
numFilled = len(ctlg.Repositories)
link := resp.Header.Get("Link")
if link == "" {
returnErr = io.EOF
}
} else {
return 0, HandleErrorResponse(resp)
}
return numFilled, returnErr
}
|
go
|
func (r *registry) Repositories(ctx context.Context, entries []string, last string) (int, error) {
var numFilled int
var returnErr error
values := buildCatalogValues(len(entries), last)
u, err := r.ub.BuildCatalogURL(values)
if err != nil {
return 0, err
}
resp, err := r.client.Get(u)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
var ctlg struct {
Repositories []string `json:"repositories"`
}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&ctlg); err != nil {
return 0, err
}
for cnt := range ctlg.Repositories {
entries[cnt] = ctlg.Repositories[cnt]
}
numFilled = len(ctlg.Repositories)
link := resp.Header.Get("Link")
if link == "" {
returnErr = io.EOF
}
} else {
return 0, HandleErrorResponse(resp)
}
return numFilled, returnErr
}
|
[
"func",
"(",
"r",
"*",
"registry",
")",
"Repositories",
"(",
"ctx",
"context",
".",
"Context",
",",
"entries",
"[",
"]",
"string",
",",
"last",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"numFilled",
"int",
"\n",
"var",
"returnErr",
"error",
"\n\n",
"values",
":=",
"buildCatalogValues",
"(",
"len",
"(",
"entries",
")",
",",
"last",
")",
"\n",
"u",
",",
"err",
":=",
"r",
".",
"ub",
".",
"BuildCatalogURL",
"(",
"values",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"r",
".",
"client",
".",
"Get",
"(",
"u",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"SuccessStatus",
"(",
"resp",
".",
"StatusCode",
")",
"{",
"var",
"ctlg",
"struct",
"{",
"Repositories",
"[",
"]",
"string",
"`json:\"repositories\"`",
"\n",
"}",
"\n",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
"\n\n",
"if",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"ctlg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"cnt",
":=",
"range",
"ctlg",
".",
"Repositories",
"{",
"entries",
"[",
"cnt",
"]",
"=",
"ctlg",
".",
"Repositories",
"[",
"cnt",
"]",
"\n",
"}",
"\n",
"numFilled",
"=",
"len",
"(",
"ctlg",
".",
"Repositories",
")",
"\n\n",
"link",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"link",
"==",
"\"",
"\"",
"{",
"returnErr",
"=",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"0",
",",
"HandleErrorResponse",
"(",
"resp",
")",
"\n",
"}",
"\n\n",
"return",
"numFilled",
",",
"returnErr",
"\n",
"}"
] |
// Repositories returns a lexigraphically sorted catalog given a base URL. The 'entries' slice will be filled up to the size
// of the slice, starting at the value provided in 'last'. The number of entries will be returned along with io.EOF if there
// are no more entries
|
[
"Repositories",
"returns",
"a",
"lexigraphically",
"sorted",
"catalog",
"given",
"a",
"base",
"URL",
".",
"The",
"entries",
"slice",
"will",
"be",
"filled",
"up",
"to",
"the",
"size",
"of",
"the",
"slice",
"starting",
"at",
"the",
"value",
"provided",
"in",
"last",
".",
"The",
"number",
"of",
"entries",
"will",
"be",
"returned",
"along",
"with",
"io",
".",
"EOF",
"if",
"there",
"are",
"no",
"more",
"entries"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L91-L131
|
train
|
docker/distribution
|
registry/client/repository.go
|
NewRepository
|
func NewRepository(name reference.Named, baseURL string, transport http.RoundTripper) (distribution.Repository, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
CheckRedirect: checkHTTPRedirect,
// TODO(dmcgowan): create cookie jar
}
return &repository{
client: client,
ub: ub,
name: name,
}, nil
}
|
go
|
func NewRepository(name reference.Named, baseURL string, transport http.RoundTripper) (distribution.Repository, error) {
ub, err := v2.NewURLBuilderFromString(baseURL, false)
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
CheckRedirect: checkHTTPRedirect,
// TODO(dmcgowan): create cookie jar
}
return &repository{
client: client,
ub: ub,
name: name,
}, nil
}
|
[
"func",
"NewRepository",
"(",
"name",
"reference",
".",
"Named",
",",
"baseURL",
"string",
",",
"transport",
"http",
".",
"RoundTripper",
")",
"(",
"distribution",
".",
"Repository",
",",
"error",
")",
"{",
"ub",
",",
"err",
":=",
"v2",
".",
"NewURLBuilderFromString",
"(",
"baseURL",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"transport",
",",
"CheckRedirect",
":",
"checkHTTPRedirect",
",",
"// TODO(dmcgowan): create cookie jar",
"}",
"\n\n",
"return",
"&",
"repository",
"{",
"client",
":",
"client",
",",
"ub",
":",
"ub",
",",
"name",
":",
"name",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewRepository creates a new Repository for the given repository name and base URL.
|
[
"NewRepository",
"creates",
"a",
"new",
"Repository",
"for",
"the",
"given",
"repository",
"name",
"and",
"base",
"URL",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L134-L151
|
train
|
docker/distribution
|
registry/client/repository.go
|
Get
|
func (t *tags) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
ref, err := reference.WithTag(t.name, tag)
if err != nil {
return distribution.Descriptor{}, err
}
u, err := t.ub.BuildManifestURL(ref)
if err != nil {
return distribution.Descriptor{}, err
}
newRequest := func(method string) (*http.Response, error) {
req, err := http.NewRequest(method, u, nil)
if err != nil {
return nil, err
}
for _, t := range distribution.ManifestMediaTypes() {
req.Header.Add("Accept", t)
}
resp, err := t.client.Do(req)
return resp, err
}
resp, err := newRequest("HEAD")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 200 && resp.StatusCode < 400 && len(resp.Header.Get("Docker-Content-Digest")) > 0:
// if the response is a success AND a Docker-Content-Digest can be retrieved from the headers
return descriptorFromResponse(resp)
default:
// if the response is an error - there will be no body to decode.
// Issue a GET request:
// - for data from a server that does not handle HEAD
// - to get error details in case of a failure
resp, err = newRequest("GET")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
return descriptorFromResponse(resp)
}
return distribution.Descriptor{}, HandleErrorResponse(resp)
}
}
|
go
|
func (t *tags) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
ref, err := reference.WithTag(t.name, tag)
if err != nil {
return distribution.Descriptor{}, err
}
u, err := t.ub.BuildManifestURL(ref)
if err != nil {
return distribution.Descriptor{}, err
}
newRequest := func(method string) (*http.Response, error) {
req, err := http.NewRequest(method, u, nil)
if err != nil {
return nil, err
}
for _, t := range distribution.ManifestMediaTypes() {
req.Header.Add("Accept", t)
}
resp, err := t.client.Do(req)
return resp, err
}
resp, err := newRequest("HEAD")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 200 && resp.StatusCode < 400 && len(resp.Header.Get("Docker-Content-Digest")) > 0:
// if the response is a success AND a Docker-Content-Digest can be retrieved from the headers
return descriptorFromResponse(resp)
default:
// if the response is an error - there will be no body to decode.
// Issue a GET request:
// - for data from a server that does not handle HEAD
// - to get error details in case of a failure
resp, err = newRequest("GET")
if err != nil {
return distribution.Descriptor{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
return descriptorFromResponse(resp)
}
return distribution.Descriptor{}, HandleErrorResponse(resp)
}
}
|
[
"func",
"(",
"t",
"*",
"tags",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"ref",
",",
"err",
":=",
"reference",
".",
"WithTag",
"(",
"t",
".",
"name",
",",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"u",
",",
"err",
":=",
"t",
".",
"ub",
".",
"BuildManifestURL",
"(",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"newRequest",
":=",
"func",
"(",
"method",
"string",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"u",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"distribution",
".",
"ManifestMediaTypes",
"(",
")",
"{",
"req",
".",
"Header",
".",
"Add",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"t",
".",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"return",
"resp",
",",
"err",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"newRequest",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"switch",
"{",
"case",
"resp",
".",
"StatusCode",
">=",
"200",
"&&",
"resp",
".",
"StatusCode",
"<",
"400",
"&&",
"len",
"(",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
">",
"0",
":",
"// if the response is a success AND a Docker-Content-Digest can be retrieved from the headers",
"return",
"descriptorFromResponse",
"(",
"resp",
")",
"\n",
"default",
":",
"// if the response is an error - there will be no body to decode.",
"// Issue a GET request:",
"// - for data from a server that does not handle HEAD",
"// - to get error details in case of a failure",
"resp",
",",
"err",
"=",
"newRequest",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
">=",
"200",
"&&",
"resp",
".",
"StatusCode",
"<",
"400",
"{",
"return",
"descriptorFromResponse",
"(",
"resp",
")",
"\n",
"}",
"\n",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"HandleErrorResponse",
"(",
"resp",
")",
"\n",
"}",
"\n",
"}"
] |
// Get issues a HEAD request for a Manifest against its named endpoint in order
// to construct a descriptor for the tag. If the registry doesn't support HEADing
// a manifest, fallback to GET.
|
[
"Get",
"issues",
"a",
"HEAD",
"request",
"for",
"a",
"Manifest",
"against",
"its",
"named",
"endpoint",
"in",
"order",
"to",
"construct",
"a",
"descriptor",
"for",
"the",
"tag",
".",
"If",
"the",
"registry",
"doesn",
"t",
"support",
"HEADing",
"a",
"manifest",
"fallback",
"to",
"GET",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L299-L348
|
train
|
docker/distribution
|
registry/client/repository.go
|
Put
|
func (ms *manifests) Put(ctx context.Context, m distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) {
ref := ms.name
var tagged bool
for _, option := range options {
if opt, ok := option.(distribution.WithTagOption); ok {
var err error
ref, err = reference.WithTag(ref, opt.Tag)
if err != nil {
return "", err
}
tagged = true
} else {
err := option.Apply(ms)
if err != nil {
return "", err
}
}
}
mediaType, p, err := m.Payload()
if err != nil {
return "", err
}
if !tagged {
// generate a canonical digest and Put by digest
_, d, err := distribution.UnmarshalManifest(mediaType, p)
if err != nil {
return "", err
}
ref, err = reference.WithDigest(ref, d.Digest)
if err != nil {
return "", err
}
}
manifestURL, err := ms.ub.BuildManifestURL(ref)
if err != nil {
return "", err
}
putRequest, err := http.NewRequest("PUT", manifestURL, bytes.NewReader(p))
if err != nil {
return "", err
}
putRequest.Header.Set("Content-Type", mediaType)
resp, err := ms.client.Do(putRequest)
if err != nil {
return "", err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
dgstHeader := resp.Header.Get("Docker-Content-Digest")
dgst, err := digest.Parse(dgstHeader)
if err != nil {
return "", err
}
return dgst, nil
}
return "", HandleErrorResponse(resp)
}
|
go
|
func (ms *manifests) Put(ctx context.Context, m distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) {
ref := ms.name
var tagged bool
for _, option := range options {
if opt, ok := option.(distribution.WithTagOption); ok {
var err error
ref, err = reference.WithTag(ref, opt.Tag)
if err != nil {
return "", err
}
tagged = true
} else {
err := option.Apply(ms)
if err != nil {
return "", err
}
}
}
mediaType, p, err := m.Payload()
if err != nil {
return "", err
}
if !tagged {
// generate a canonical digest and Put by digest
_, d, err := distribution.UnmarshalManifest(mediaType, p)
if err != nil {
return "", err
}
ref, err = reference.WithDigest(ref, d.Digest)
if err != nil {
return "", err
}
}
manifestURL, err := ms.ub.BuildManifestURL(ref)
if err != nil {
return "", err
}
putRequest, err := http.NewRequest("PUT", manifestURL, bytes.NewReader(p))
if err != nil {
return "", err
}
putRequest.Header.Set("Content-Type", mediaType)
resp, err := ms.client.Do(putRequest)
if err != nil {
return "", err
}
defer resp.Body.Close()
if SuccessStatus(resp.StatusCode) {
dgstHeader := resp.Header.Get("Docker-Content-Digest")
dgst, err := digest.Parse(dgstHeader)
if err != nil {
return "", err
}
return dgst, nil
}
return "", HandleErrorResponse(resp)
}
|
[
"func",
"(",
"ms",
"*",
"manifests",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"m",
"distribution",
".",
"Manifest",
",",
"options",
"...",
"distribution",
".",
"ManifestServiceOption",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"ref",
":=",
"ms",
".",
"name",
"\n",
"var",
"tagged",
"bool",
"\n\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"if",
"opt",
",",
"ok",
":=",
"option",
".",
"(",
"distribution",
".",
"WithTagOption",
")",
";",
"ok",
"{",
"var",
"err",
"error",
"\n",
"ref",
",",
"err",
"=",
"reference",
".",
"WithTag",
"(",
"ref",
",",
"opt",
".",
"Tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"tagged",
"=",
"true",
"\n",
"}",
"else",
"{",
"err",
":=",
"option",
".",
"Apply",
"(",
"ms",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"mediaType",
",",
"p",
",",
"err",
":=",
"m",
".",
"Payload",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"tagged",
"{",
"// generate a canonical digest and Put by digest",
"_",
",",
"d",
",",
"err",
":=",
"distribution",
".",
"UnmarshalManifest",
"(",
"mediaType",
",",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"ref",
",",
"err",
"=",
"reference",
".",
"WithDigest",
"(",
"ref",
",",
"d",
".",
"Digest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"manifestURL",
",",
"err",
":=",
"ms",
".",
"ub",
".",
"BuildManifestURL",
"(",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"putRequest",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"manifestURL",
",",
"bytes",
".",
"NewReader",
"(",
"p",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"putRequest",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"mediaType",
")",
"\n\n",
"resp",
",",
"err",
":=",
"ms",
".",
"client",
".",
"Do",
"(",
"putRequest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"SuccessStatus",
"(",
"resp",
".",
"StatusCode",
")",
"{",
"dgstHeader",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"dgst",
",",
"err",
":=",
"digest",
".",
"Parse",
"(",
"dgstHeader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"dgst",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"HandleErrorResponse",
"(",
"resp",
")",
"\n",
"}"
] |
// Put puts a manifest. A tag can be specified using an options parameter which uses some shared state to hold the
// tag name in order to build the correct upload URL.
|
[
"Put",
"puts",
"a",
"manifest",
".",
"A",
"tag",
"can",
"be",
"specified",
"using",
"an",
"options",
"parameter",
"which",
"uses",
"some",
"shared",
"state",
"to",
"hold",
"the",
"tag",
"name",
"in",
"order",
"to",
"build",
"the",
"correct",
"upload",
"URL",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L514-L579
|
train
|
docker/distribution
|
registry/client/repository.go
|
WithMountFrom
|
func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption {
return optionFunc(func(v interface{}) error {
opts, ok := v.(*distribution.CreateOptions)
if !ok {
return fmt.Errorf("unexpected options type: %T", v)
}
opts.Mount.ShouldMount = true
opts.Mount.From = ref
return nil
})
}
|
go
|
func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption {
return optionFunc(func(v interface{}) error {
opts, ok := v.(*distribution.CreateOptions)
if !ok {
return fmt.Errorf("unexpected options type: %T", v)
}
opts.Mount.ShouldMount = true
opts.Mount.From = ref
return nil
})
}
|
[
"func",
"WithMountFrom",
"(",
"ref",
"reference",
".",
"Canonical",
")",
"distribution",
".",
"BlobCreateOption",
"{",
"return",
"optionFunc",
"(",
"func",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"opts",
",",
"ok",
":=",
"v",
".",
"(",
"*",
"distribution",
".",
"CreateOptions",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n\n",
"opts",
".",
"Mount",
".",
"ShouldMount",
"=",
"true",
"\n",
"opts",
".",
"Mount",
".",
"From",
"=",
"ref",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// WithMountFrom returns a BlobCreateOption which designates that the blob should be
// mounted from the given canonical reference.
|
[
"WithMountFrom",
"returns",
"a",
"BlobCreateOption",
"which",
"designates",
"that",
"the",
"blob",
"should",
"be",
"mounted",
"from",
"the",
"given",
"canonical",
"reference",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/repository.go#L704-L716
|
train
|
docker/distribution
|
registry/client/auth/session.go
|
String
|
func (rs RepositoryScope) String() string {
repoType := "repository"
// Keep existing format for image class to maintain backwards compatibility
// with authorization servers which do not support the expanded grammar.
if rs.Class != "" && rs.Class != "image" {
repoType = fmt.Sprintf("%s(%s)", repoType, rs.Class)
}
return fmt.Sprintf("%s:%s:%s", repoType, rs.Repository, strings.Join(rs.Actions, ","))
}
|
go
|
func (rs RepositoryScope) String() string {
repoType := "repository"
// Keep existing format for image class to maintain backwards compatibility
// with authorization servers which do not support the expanded grammar.
if rs.Class != "" && rs.Class != "image" {
repoType = fmt.Sprintf("%s(%s)", repoType, rs.Class)
}
return fmt.Sprintf("%s:%s:%s", repoType, rs.Repository, strings.Join(rs.Actions, ","))
}
|
[
"func",
"(",
"rs",
"RepositoryScope",
")",
"String",
"(",
")",
"string",
"{",
"repoType",
":=",
"\"",
"\"",
"\n",
"// Keep existing format for image class to maintain backwards compatibility",
"// with authorization servers which do not support the expanded grammar.",
"if",
"rs",
".",
"Class",
"!=",
"\"",
"\"",
"&&",
"rs",
".",
"Class",
"!=",
"\"",
"\"",
"{",
"repoType",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"repoType",
",",
"rs",
".",
"Class",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"repoType",
",",
"rs",
".",
"Repository",
",",
"strings",
".",
"Join",
"(",
"rs",
".",
"Actions",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] |
// String returns the string representation of the repository
// using the scope grammar
|
[
"String",
"returns",
"the",
"string",
"representation",
"of",
"the",
"repository",
"using",
"the",
"scope",
"grammar"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L155-L163
|
train
|
docker/distribution
|
registry/client/auth/session.go
|
String
|
func (rs RegistryScope) String() string {
return fmt.Sprintf("registry:%s:%s", rs.Name, strings.Join(rs.Actions, ","))
}
|
go
|
func (rs RegistryScope) String() string {
return fmt.Sprintf("registry:%s:%s", rs.Name, strings.Join(rs.Actions, ","))
}
|
[
"func",
"(",
"rs",
"RegistryScope",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rs",
".",
"Name",
",",
"strings",
".",
"Join",
"(",
"rs",
".",
"Actions",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] |
// String returns the string representation of the user
// using the scope grammar
|
[
"String",
"returns",
"the",
"string",
"representation",
"of",
"the",
"user",
"using",
"the",
"scope",
"grammar"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L174-L176
|
train
|
docker/distribution
|
registry/client/auth/session.go
|
NewTokenHandler
|
func NewTokenHandler(transport http.RoundTripper, creds CredentialStore, scope string, actions ...string) AuthenticationHandler {
// Create options...
return NewTokenHandlerWithOptions(TokenHandlerOptions{
Transport: transport,
Credentials: creds,
Scopes: []Scope{
RepositoryScope{
Repository: scope,
Actions: actions,
},
},
})
}
|
go
|
func NewTokenHandler(transport http.RoundTripper, creds CredentialStore, scope string, actions ...string) AuthenticationHandler {
// Create options...
return NewTokenHandlerWithOptions(TokenHandlerOptions{
Transport: transport,
Credentials: creds,
Scopes: []Scope{
RepositoryScope{
Repository: scope,
Actions: actions,
},
},
})
}
|
[
"func",
"NewTokenHandler",
"(",
"transport",
"http",
".",
"RoundTripper",
",",
"creds",
"CredentialStore",
",",
"scope",
"string",
",",
"actions",
"...",
"string",
")",
"AuthenticationHandler",
"{",
"// Create options...",
"return",
"NewTokenHandlerWithOptions",
"(",
"TokenHandlerOptions",
"{",
"Transport",
":",
"transport",
",",
"Credentials",
":",
"creds",
",",
"Scopes",
":",
"[",
"]",
"Scope",
"{",
"RepositoryScope",
"{",
"Repository",
":",
"scope",
",",
"Actions",
":",
"actions",
",",
"}",
",",
"}",
",",
"}",
")",
"\n",
"}"
] |
// NewTokenHandler creates a new AuthenicationHandler which supports
// fetching tokens from a remote token server.
|
[
"NewTokenHandler",
"creates",
"a",
"new",
"AuthenicationHandler",
"which",
"supports",
"fetching",
"tokens",
"from",
"a",
"remote",
"token",
"server",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L210-L222
|
train
|
docker/distribution
|
registry/client/auth/session.go
|
NewTokenHandlerWithOptions
|
func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
handler := &tokenHandler{
transport: options.Transport,
creds: options.Credentials,
offlineAccess: options.OfflineAccess,
forceOAuth: options.ForceOAuth,
clientID: options.ClientID,
scopes: options.Scopes,
clock: realClock{},
logger: options.Logger,
}
return handler
}
|
go
|
func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
handler := &tokenHandler{
transport: options.Transport,
creds: options.Credentials,
offlineAccess: options.OfflineAccess,
forceOAuth: options.ForceOAuth,
clientID: options.ClientID,
scopes: options.Scopes,
clock: realClock{},
logger: options.Logger,
}
return handler
}
|
[
"func",
"NewTokenHandlerWithOptions",
"(",
"options",
"TokenHandlerOptions",
")",
"AuthenticationHandler",
"{",
"handler",
":=",
"&",
"tokenHandler",
"{",
"transport",
":",
"options",
".",
"Transport",
",",
"creds",
":",
"options",
".",
"Credentials",
",",
"offlineAccess",
":",
"options",
".",
"OfflineAccess",
",",
"forceOAuth",
":",
"options",
".",
"ForceOAuth",
",",
"clientID",
":",
"options",
".",
"ClientID",
",",
"scopes",
":",
"options",
".",
"Scopes",
",",
"clock",
":",
"realClock",
"{",
"}",
",",
"logger",
":",
"options",
".",
"Logger",
",",
"}",
"\n\n",
"return",
"handler",
"\n",
"}"
] |
// NewTokenHandlerWithOptions creates a new token handler using the provided
// options structure.
|
[
"NewTokenHandlerWithOptions",
"creates",
"a",
"new",
"token",
"handler",
"using",
"the",
"provided",
"options",
"structure",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/session.go#L226-L239
|
train
|
docker/distribution
|
registry/proxy/proxymetrics.go
|
BlobPull
|
func (pmc *proxyMetricsCollector) BlobPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.blobMetrics.Misses, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPulled, bytesPulled)
}
|
go
|
func (pmc *proxyMetricsCollector) BlobPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.blobMetrics.Misses, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPulled, bytesPulled)
}
|
[
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"BlobPull",
"(",
"bytesPulled",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"blobMetrics",
".",
"Misses",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"blobMetrics",
".",
"BytesPulled",
",",
"bytesPulled",
")",
"\n",
"}"
] |
// BlobPull tracks metrics about blobs pulled into the cache
|
[
"BlobPull",
"tracks",
"metrics",
"about",
"blobs",
"pulled",
"into",
"the",
"cache"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L24-L27
|
train
|
docker/distribution
|
registry/proxy/proxymetrics.go
|
BlobPush
|
func (pmc *proxyMetricsCollector) BlobPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.blobMetrics.Requests, 1)
atomic.AddUint64(&pmc.blobMetrics.Hits, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPushed, bytesPushed)
}
|
go
|
func (pmc *proxyMetricsCollector) BlobPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.blobMetrics.Requests, 1)
atomic.AddUint64(&pmc.blobMetrics.Hits, 1)
atomic.AddUint64(&pmc.blobMetrics.BytesPushed, bytesPushed)
}
|
[
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"BlobPush",
"(",
"bytesPushed",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"blobMetrics",
".",
"Requests",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"blobMetrics",
".",
"Hits",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"blobMetrics",
".",
"BytesPushed",
",",
"bytesPushed",
")",
"\n",
"}"
] |
// BlobPush tracks metrics about blobs pushed to clients
|
[
"BlobPush",
"tracks",
"metrics",
"about",
"blobs",
"pushed",
"to",
"clients"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L30-L34
|
train
|
docker/distribution
|
registry/proxy/proxymetrics.go
|
ManifestPull
|
func (pmc *proxyMetricsCollector) ManifestPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Misses, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPulled, bytesPulled)
}
|
go
|
func (pmc *proxyMetricsCollector) ManifestPull(bytesPulled uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Misses, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPulled, bytesPulled)
}
|
[
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"ManifestPull",
"(",
"bytesPulled",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"manifestMetrics",
".",
"Misses",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"manifestMetrics",
".",
"BytesPulled",
",",
"bytesPulled",
")",
"\n",
"}"
] |
// ManifestPull tracks metrics related to Manifests pulled into the cache
|
[
"ManifestPull",
"tracks",
"metrics",
"related",
"to",
"Manifests",
"pulled",
"into",
"the",
"cache"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L37-L40
|
train
|
docker/distribution
|
registry/proxy/proxymetrics.go
|
ManifestPush
|
func (pmc *proxyMetricsCollector) ManifestPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Requests, 1)
atomic.AddUint64(&pmc.manifestMetrics.Hits, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPushed, bytesPushed)
}
|
go
|
func (pmc *proxyMetricsCollector) ManifestPush(bytesPushed uint64) {
atomic.AddUint64(&pmc.manifestMetrics.Requests, 1)
atomic.AddUint64(&pmc.manifestMetrics.Hits, 1)
atomic.AddUint64(&pmc.manifestMetrics.BytesPushed, bytesPushed)
}
|
[
"func",
"(",
"pmc",
"*",
"proxyMetricsCollector",
")",
"ManifestPush",
"(",
"bytesPushed",
"uint64",
")",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"manifestMetrics",
".",
"Requests",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"manifestMetrics",
".",
"Hits",
",",
"1",
")",
"\n",
"atomic",
".",
"AddUint64",
"(",
"&",
"pmc",
".",
"manifestMetrics",
".",
"BytesPushed",
",",
"bytesPushed",
")",
"\n",
"}"
] |
// ManifestPush tracks metrics about manifests pushed to clients
|
[
"ManifestPush",
"tracks",
"metrics",
"about",
"manifests",
"pushed",
"to",
"clients"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxymetrics.go#L43-L47
|
train
|
docker/distribution
|
registry/storage/driver/middleware/alicdn/middleware.go
|
URLFor
|
func (ac *aliCDNStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if ac.StorageDriver.Name() != "oss" {
dcontext.GetLogger(ctx).Warn("the AliCDN middleware does not support this backend storage driver")
return ac.StorageDriver.URLFor(ctx, path, options)
}
acURL, err := ac.urlSigner.Sign(ac.baseURL+path, time.Now().Add(ac.duration))
if err != nil {
return "", err
}
return acURL, nil
}
|
go
|
func (ac *aliCDNStorageMiddleware) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
if ac.StorageDriver.Name() != "oss" {
dcontext.GetLogger(ctx).Warn("the AliCDN middleware does not support this backend storage driver")
return ac.StorageDriver.URLFor(ctx, path, options)
}
acURL, err := ac.urlSigner.Sign(ac.baseURL+path, time.Now().Add(ac.duration))
if err != nil {
return "", err
}
return acURL, nil
}
|
[
"func",
"(",
"ac",
"*",
"aliCDNStorageMiddleware",
")",
"URLFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"ac",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"!=",
"\"",
"\"",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"ac",
".",
"StorageDriver",
".",
"URLFor",
"(",
"ctx",
",",
"path",
",",
"options",
")",
"\n",
"}",
"\n",
"acURL",
",",
"err",
":=",
"ac",
".",
"urlSigner",
".",
"Sign",
"(",
"ac",
".",
"baseURL",
"+",
"path",
",",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"ac",
".",
"duration",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"acURL",
",",
"nil",
"\n",
"}"
] |
// URLFor attempts to find a url which may be used to retrieve the file at the given path.
|
[
"URLFor",
"attempts",
"to",
"find",
"a",
"url",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"file",
"at",
"the",
"given",
"path",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/alicdn/middleware.go#L100-L111
|
train
|
docker/distribution
|
health/api/api.go
|
DownHandler
|
func DownHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(errors.New("manual Check"))
} else {
w.WriteHeader(http.StatusNotFound)
}
}
|
go
|
func DownHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(errors.New("manual Check"))
} else {
w.WriteHeader(http.StatusNotFound)
}
}
|
[
"func",
"DownHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"\"",
"\"",
"{",
"updater",
".",
"Update",
"(",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"\n",
"}"
] |
// DownHandler registers a manual_http_status that always returns an Error
|
[
"DownHandler",
"registers",
"a",
"manual_http_status",
"that",
"always",
"returns",
"an",
"Error"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/api/api.go#L15-L21
|
train
|
docker/distribution
|
health/api/api.go
|
UpHandler
|
func UpHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(nil)
} else {
w.WriteHeader(http.StatusNotFound)
}
}
|
go
|
func UpHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
updater.Update(nil)
} else {
w.WriteHeader(http.StatusNotFound)
}
}
|
[
"func",
"UpHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"\"",
"\"",
"{",
"updater",
".",
"Update",
"(",
"nil",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"\n",
"}"
] |
// UpHandler registers a manual_http_status that always returns nil
|
[
"UpHandler",
"registers",
"a",
"manual_http_status",
"that",
"always",
"returns",
"nil"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/api/api.go#L24-L30
|
train
|
docker/distribution
|
health/api/api.go
|
init
|
func init() {
health.Register("manual_http_status", updater)
http.HandleFunc("/debug/health/down", DownHandler)
http.HandleFunc("/debug/health/up", UpHandler)
}
|
go
|
func init() {
health.Register("manual_http_status", updater)
http.HandleFunc("/debug/health/down", DownHandler)
http.HandleFunc("/debug/health/up", UpHandler)
}
|
[
"func",
"init",
"(",
")",
"{",
"health",
".",
"Register",
"(",
"\"",
"\"",
",",
"updater",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"DownHandler",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"UpHandler",
")",
"\n",
"}"
] |
// init sets up the two endpoints to bring the service up and down
|
[
"init",
"sets",
"up",
"the",
"two",
"endpoints",
"to",
"bring",
"the",
"service",
"up",
"and",
"down"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/api/api.go#L33-L37
|
train
|
docker/distribution
|
health/checks/checks.go
|
HTTPChecker
|
func HTTPChecker(r string, statusCode int, timeout time.Duration, headers http.Header) health.Checker {
return health.CheckFunc(func() error {
client := http.Client{
Timeout: timeout,
}
req, err := http.NewRequest("HEAD", r, nil)
if err != nil {
return errors.New("error creating request: " + r)
}
for headerName, headerValues := range headers {
for _, headerValue := range headerValues {
req.Header.Add(headerName, headerValue)
}
}
response, err := client.Do(req)
if err != nil {
return errors.New("error while checking: " + r)
}
if response.StatusCode != statusCode {
return errors.New("downstream service returned unexpected status: " + strconv.Itoa(response.StatusCode))
}
return nil
})
}
|
go
|
func HTTPChecker(r string, statusCode int, timeout time.Duration, headers http.Header) health.Checker {
return health.CheckFunc(func() error {
client := http.Client{
Timeout: timeout,
}
req, err := http.NewRequest("HEAD", r, nil)
if err != nil {
return errors.New("error creating request: " + r)
}
for headerName, headerValues := range headers {
for _, headerValue := range headerValues {
req.Header.Add(headerName, headerValue)
}
}
response, err := client.Do(req)
if err != nil {
return errors.New("error while checking: " + r)
}
if response.StatusCode != statusCode {
return errors.New("downstream service returned unexpected status: " + strconv.Itoa(response.StatusCode))
}
return nil
})
}
|
[
"func",
"HTTPChecker",
"(",
"r",
"string",
",",
"statusCode",
"int",
",",
"timeout",
"time",
".",
"Duration",
",",
"headers",
"http",
".",
"Header",
")",
"health",
".",
"Checker",
"{",
"return",
"health",
".",
"CheckFunc",
"(",
"func",
"(",
")",
"error",
"{",
"client",
":=",
"http",
".",
"Client",
"{",
"Timeout",
":",
"timeout",
",",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"r",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"r",
")",
"\n",
"}",
"\n",
"for",
"headerName",
",",
"headerValues",
":=",
"range",
"headers",
"{",
"for",
"_",
",",
"headerValue",
":=",
"range",
"headerValues",
"{",
"req",
".",
"Header",
".",
"Add",
"(",
"headerName",
",",
"headerValue",
")",
"\n",
"}",
"\n",
"}",
"\n",
"response",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"r",
")",
"\n",
"}",
"\n",
"if",
"response",
".",
"StatusCode",
"!=",
"statusCode",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"response",
".",
"StatusCode",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// HTTPChecker does a HEAD request and verifies that the HTTP status code
// returned matches statusCode.
|
[
"HTTPChecker",
"does",
"a",
"HEAD",
"request",
"and",
"verifies",
"that",
"the",
"HTTP",
"status",
"code",
"returned",
"matches",
"statusCode",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/checks/checks.go#L38-L61
|
train
|
docker/distribution
|
health/checks/checks.go
|
TCPChecker
|
func TCPChecker(addr string, timeout time.Duration) health.Checker {
return health.CheckFunc(func() error {
conn, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
return errors.New("connection to " + addr + " failed")
}
conn.Close()
return nil
})
}
|
go
|
func TCPChecker(addr string, timeout time.Duration) health.Checker {
return health.CheckFunc(func() error {
conn, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
return errors.New("connection to " + addr + " failed")
}
conn.Close()
return nil
})
}
|
[
"func",
"TCPChecker",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"health",
".",
"Checker",
"{",
"return",
"health",
".",
"CheckFunc",
"(",
"func",
"(",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"DialTimeout",
"(",
"\"",
"\"",
",",
"addr",
",",
"timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"addr",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// TCPChecker attempts to open a TCP connection.
|
[
"TCPChecker",
"attempts",
"to",
"open",
"a",
"TCP",
"connection",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/health/checks/checks.go#L64-L73
|
train
|
docker/distribution
|
registry/storage/manifeststore.go
|
Delete
|
func (ms *manifestStore) Delete(ctx context.Context, dgst digest.Digest) error {
dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Delete")
return ms.blobStore.Delete(ctx, dgst)
}
|
go
|
func (ms *manifestStore) Delete(ctx context.Context, dgst digest.Digest) error {
dcontext.GetLogger(ms.ctx).Debug("(*manifestStore).Delete")
return ms.blobStore.Delete(ctx, dgst)
}
|
[
"func",
"(",
"ms",
"*",
"manifestStore",
")",
"Delete",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"error",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ms",
".",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"ms",
".",
"blobStore",
".",
"Delete",
"(",
"ctx",
",",
"dgst",
")",
"\n",
"}"
] |
// Delete removes the revision of the specified manifest.
|
[
"Delete",
"removes",
"the",
"revision",
"of",
"the",
"specified",
"manifest",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/manifeststore.go#L147-L150
|
train
|
docker/distribution
|
registry/middleware/registry/middleware.go
|
Register
|
func Register(name string, initFunc InitFunc) error {
if middlewares == nil {
middlewares = make(map[string]InitFunc)
}
if _, exists := middlewares[name]; exists {
return fmt.Errorf("name already registered: %s", name)
}
middlewares[name] = initFunc
return nil
}
|
go
|
func Register(name string, initFunc InitFunc) error {
if middlewares == nil {
middlewares = make(map[string]InitFunc)
}
if _, exists := middlewares[name]; exists {
return fmt.Errorf("name already registered: %s", name)
}
middlewares[name] = initFunc
return nil
}
|
[
"func",
"Register",
"(",
"name",
"string",
",",
"initFunc",
"InitFunc",
")",
"error",
"{",
"if",
"middlewares",
"==",
"nil",
"{",
"middlewares",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"InitFunc",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"exists",
":=",
"middlewares",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"middlewares",
"[",
"name",
"]",
"=",
"initFunc",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Register is used to register an InitFunc for
// a RegistryMiddleware backend with the given name.
|
[
"Register",
"is",
"used",
"to",
"register",
"an",
"InitFunc",
"for",
"a",
"RegistryMiddleware",
"backend",
"with",
"the",
"given",
"name",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/middleware/registry/middleware.go#L20-L31
|
train
|
docker/distribution
|
registry/middleware/registry/middleware.go
|
Get
|
func Get(ctx context.Context, name string, options map[string]interface{}, registry distribution.Namespace) (distribution.Namespace, error) {
if middlewares != nil {
if initFunc, exists := middlewares[name]; exists {
return initFunc(ctx, registry, options)
}
}
return nil, fmt.Errorf("no registry middleware registered with name: %s", name)
}
|
go
|
func Get(ctx context.Context, name string, options map[string]interface{}, registry distribution.Namespace) (distribution.Namespace, error) {
if middlewares != nil {
if initFunc, exists := middlewares[name]; exists {
return initFunc(ctx, registry, options)
}
}
return nil, fmt.Errorf("no registry middleware registered with name: %s", name)
}
|
[
"func",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"registry",
"distribution",
".",
"Namespace",
")",
"(",
"distribution",
".",
"Namespace",
",",
"error",
")",
"{",
"if",
"middlewares",
"!=",
"nil",
"{",
"if",
"initFunc",
",",
"exists",
":=",
"middlewares",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"initFunc",
"(",
"ctx",
",",
"registry",
",",
"options",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
] |
// Get constructs a RegistryMiddleware with the given options using the named backend.
|
[
"Get",
"constructs",
"a",
"RegistryMiddleware",
"with",
"the",
"given",
"options",
"using",
"the",
"named",
"backend",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/middleware/registry/middleware.go#L34-L42
|
train
|
docker/distribution
|
registry/middleware/registry/middleware.go
|
RegisterOptions
|
func RegisterOptions(options ...storage.RegistryOption) error {
registryoptions = append(registryoptions, options...)
return nil
}
|
go
|
func RegisterOptions(options ...storage.RegistryOption) error {
registryoptions = append(registryoptions, options...)
return nil
}
|
[
"func",
"RegisterOptions",
"(",
"options",
"...",
"storage",
".",
"RegistryOption",
")",
"error",
"{",
"registryoptions",
"=",
"append",
"(",
"registryoptions",
",",
"options",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// RegisterOptions adds more options to RegistryOption list. Options get applied before
// any other configuration-based options.
|
[
"RegisterOptions",
"adds",
"more",
"options",
"to",
"RegistryOption",
"list",
".",
"Options",
"get",
"applied",
"before",
"any",
"other",
"configuration",
"-",
"based",
"options",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/middleware/registry/middleware.go#L46-L49
|
train
|
docker/distribution
|
reference/reference.go
|
Domain
|
func Domain(named Named) string {
if r, ok := named.(namedRepository); ok {
return r.Domain()
}
domain, _ := splitDomain(named.Name())
return domain
}
|
go
|
func Domain(named Named) string {
if r, ok := named.(namedRepository); ok {
return r.Domain()
}
domain, _ := splitDomain(named.Name())
return domain
}
|
[
"func",
"Domain",
"(",
"named",
"Named",
")",
"string",
"{",
"if",
"r",
",",
"ok",
":=",
"named",
".",
"(",
"namedRepository",
")",
";",
"ok",
"{",
"return",
"r",
".",
"Domain",
"(",
")",
"\n",
"}",
"\n",
"domain",
",",
"_",
":=",
"splitDomain",
"(",
"named",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"domain",
"\n",
"}"
] |
// Domain returns the domain part of the Named reference
|
[
"Domain",
"returns",
"the",
"domain",
"part",
"of",
"the",
"Named",
"reference"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/reference.go#L149-L155
|
train
|
docker/distribution
|
reference/reference.go
|
Path
|
func Path(named Named) (name string) {
if r, ok := named.(namedRepository); ok {
return r.Path()
}
_, path := splitDomain(named.Name())
return path
}
|
go
|
func Path(named Named) (name string) {
if r, ok := named.(namedRepository); ok {
return r.Path()
}
_, path := splitDomain(named.Name())
return path
}
|
[
"func",
"Path",
"(",
"named",
"Named",
")",
"(",
"name",
"string",
")",
"{",
"if",
"r",
",",
"ok",
":=",
"named",
".",
"(",
"namedRepository",
")",
";",
"ok",
"{",
"return",
"r",
".",
"Path",
"(",
")",
"\n",
"}",
"\n",
"_",
",",
"path",
":=",
"splitDomain",
"(",
"named",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"path",
"\n",
"}"
] |
// Path returns the name without the domain part of the Named reference
|
[
"Path",
"returns",
"the",
"name",
"without",
"the",
"domain",
"part",
"of",
"the",
"Named",
"reference"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/reference.go#L158-L164
|
train
|
docker/distribution
|
reference/reference.go
|
TrimNamed
|
func TrimNamed(ref Named) Named {
domain, path := SplitHostname(ref)
return repository{
domain: domain,
path: path,
}
}
|
go
|
func TrimNamed(ref Named) Named {
domain, path := SplitHostname(ref)
return repository{
domain: domain,
path: path,
}
}
|
[
"func",
"TrimNamed",
"(",
"ref",
"Named",
")",
"Named",
"{",
"domain",
",",
"path",
":=",
"SplitHostname",
"(",
"ref",
")",
"\n",
"return",
"repository",
"{",
"domain",
":",
"domain",
",",
"path",
":",
"path",
",",
"}",
"\n",
"}"
] |
// TrimNamed removes any tag or digest from the named reference.
|
[
"TrimNamed",
"removes",
"any",
"tag",
"or",
"digest",
"from",
"the",
"named",
"reference",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/reference.go#L322-L328
|
train
|
docker/distribution
|
registry/storage/cache/cachecheck/suite.go
|
CheckBlobDescriptorCache
|
func CheckBlobDescriptorCache(t *testing.T, provider cache.BlobDescriptorCacheProvider) {
ctx := context.Background()
checkBlobDescriptorCacheEmptyRepository(ctx, t, provider)
checkBlobDescriptorCacheSetAndRead(ctx, t, provider)
checkBlobDescriptorCacheClear(ctx, t, provider)
}
|
go
|
func CheckBlobDescriptorCache(t *testing.T, provider cache.BlobDescriptorCacheProvider) {
ctx := context.Background()
checkBlobDescriptorCacheEmptyRepository(ctx, t, provider)
checkBlobDescriptorCacheSetAndRead(ctx, t, provider)
checkBlobDescriptorCacheClear(ctx, t, provider)
}
|
[
"func",
"CheckBlobDescriptorCache",
"(",
"t",
"*",
"testing",
".",
"T",
",",
"provider",
"cache",
".",
"BlobDescriptorCacheProvider",
")",
"{",
"ctx",
":=",
"context",
".",
"Background",
"(",
")",
"\n\n",
"checkBlobDescriptorCacheEmptyRepository",
"(",
"ctx",
",",
"t",
",",
"provider",
")",
"\n",
"checkBlobDescriptorCacheSetAndRead",
"(",
"ctx",
",",
"t",
",",
"provider",
")",
"\n",
"checkBlobDescriptorCacheClear",
"(",
"ctx",
",",
"t",
",",
"provider",
")",
"\n",
"}"
] |
// CheckBlobDescriptorCache takes a cache implementation through a common set
// of operations. If adding new tests, please add them here so new
// implementations get the benefit. This should be used for unit tests.
|
[
"CheckBlobDescriptorCache",
"takes",
"a",
"cache",
"implementation",
"through",
"a",
"common",
"set",
"of",
"operations",
".",
"If",
"adding",
"new",
"tests",
"please",
"add",
"them",
"here",
"so",
"new",
"implementations",
"get",
"the",
"benefit",
".",
"This",
"should",
"be",
"used",
"for",
"unit",
"tests",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/cachecheck/suite.go#L16-L22
|
train
|
docker/distribution
|
registry/storage/vacuum.go
|
RemoveBlob
|
func (v Vacuum) RemoveBlob(dgst string) error {
d, err := digest.Parse(dgst)
if err != nil {
return err
}
blobPath, err := pathFor(blobPathSpec{digest: d})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("Deleting blob: %s", blobPath)
err = v.driver.Delete(v.ctx, blobPath)
if err != nil {
return err
}
return nil
}
|
go
|
func (v Vacuum) RemoveBlob(dgst string) error {
d, err := digest.Parse(dgst)
if err != nil {
return err
}
blobPath, err := pathFor(blobPathSpec{digest: d})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("Deleting blob: %s", blobPath)
err = v.driver.Delete(v.ctx, blobPath)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"v",
"Vacuum",
")",
"RemoveBlob",
"(",
"dgst",
"string",
")",
"error",
"{",
"d",
",",
"err",
":=",
"digest",
".",
"Parse",
"(",
"dgst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"blobPath",
",",
"err",
":=",
"pathFor",
"(",
"blobPathSpec",
"{",
"digest",
":",
"d",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"dcontext",
".",
"GetLogger",
"(",
"v",
".",
"ctx",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"blobPath",
")",
"\n\n",
"err",
"=",
"v",
".",
"driver",
".",
"Delete",
"(",
"v",
".",
"ctx",
",",
"blobPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// RemoveBlob removes a blob from the filesystem
|
[
"RemoveBlob",
"removes",
"a",
"blob",
"from",
"the",
"filesystem"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/vacuum.go#L32-L51
|
train
|
docker/distribution
|
registry/storage/vacuum.go
|
RemoveManifest
|
func (v Vacuum) RemoveManifest(name string, dgst digest.Digest, tags []string) error {
// remove a tag manifest reference, in case of not found continue to next one
for _, tag := range tags {
tagsPath, err := pathFor(manifestTagIndexEntryPathSpec{name: name, revision: dgst, tag: tag})
if err != nil {
return err
}
_, err = v.driver.Stat(v.ctx, tagsPath)
if err != nil {
switch err := err.(type) {
case driver.PathNotFoundError:
continue
default:
return err
}
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest tag reference: %s", tagsPath)
err = v.driver.Delete(v.ctx, tagsPath)
if err != nil {
return err
}
}
manifestPath, err := pathFor(manifestRevisionPathSpec{name: name, revision: dgst})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest: %s", manifestPath)
return v.driver.Delete(v.ctx, manifestPath)
}
|
go
|
func (v Vacuum) RemoveManifest(name string, dgst digest.Digest, tags []string) error {
// remove a tag manifest reference, in case of not found continue to next one
for _, tag := range tags {
tagsPath, err := pathFor(manifestTagIndexEntryPathSpec{name: name, revision: dgst, tag: tag})
if err != nil {
return err
}
_, err = v.driver.Stat(v.ctx, tagsPath)
if err != nil {
switch err := err.(type) {
case driver.PathNotFoundError:
continue
default:
return err
}
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest tag reference: %s", tagsPath)
err = v.driver.Delete(v.ctx, tagsPath)
if err != nil {
return err
}
}
manifestPath, err := pathFor(manifestRevisionPathSpec{name: name, revision: dgst})
if err != nil {
return err
}
dcontext.GetLogger(v.ctx).Infof("deleting manifest: %s", manifestPath)
return v.driver.Delete(v.ctx, manifestPath)
}
|
[
"func",
"(",
"v",
"Vacuum",
")",
"RemoveManifest",
"(",
"name",
"string",
",",
"dgst",
"digest",
".",
"Digest",
",",
"tags",
"[",
"]",
"string",
")",
"error",
"{",
"// remove a tag manifest reference, in case of not found continue to next one",
"for",
"_",
",",
"tag",
":=",
"range",
"tags",
"{",
"tagsPath",
",",
"err",
":=",
"pathFor",
"(",
"manifestTagIndexEntryPathSpec",
"{",
"name",
":",
"name",
",",
"revision",
":",
"dgst",
",",
"tag",
":",
"tag",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"v",
".",
"driver",
".",
"Stat",
"(",
"v",
".",
"ctx",
",",
"tagsPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"driver",
".",
"PathNotFoundError",
":",
"continue",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"dcontext",
".",
"GetLogger",
"(",
"v",
".",
"ctx",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"tagsPath",
")",
"\n",
"err",
"=",
"v",
".",
"driver",
".",
"Delete",
"(",
"v",
".",
"ctx",
",",
"tagsPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"manifestPath",
",",
"err",
":=",
"pathFor",
"(",
"manifestRevisionPathSpec",
"{",
"name",
":",
"name",
",",
"revision",
":",
"dgst",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"dcontext",
".",
"GetLogger",
"(",
"v",
".",
"ctx",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"manifestPath",
")",
"\n",
"return",
"v",
".",
"driver",
".",
"Delete",
"(",
"v",
".",
"ctx",
",",
"manifestPath",
")",
"\n",
"}"
] |
// RemoveManifest removes a manifest from the filesystem
|
[
"RemoveManifest",
"removes",
"a",
"manifest",
"from",
"the",
"filesystem"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/vacuum.go#L54-L85
|
train
|
docker/distribution
|
registry/storage/vacuum.go
|
RemoveRepository
|
func (v Vacuum) RemoveRepository(repoName string) error {
rootForRepository, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(rootForRepository, repoName)
dcontext.GetLogger(v.ctx).Infof("Deleting repo: %s", repoDir)
err = v.driver.Delete(v.ctx, repoDir)
if err != nil {
return err
}
return nil
}
|
go
|
func (v Vacuum) RemoveRepository(repoName string) error {
rootForRepository, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return err
}
repoDir := path.Join(rootForRepository, repoName)
dcontext.GetLogger(v.ctx).Infof("Deleting repo: %s", repoDir)
err = v.driver.Delete(v.ctx, repoDir)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"v",
"Vacuum",
")",
"RemoveRepository",
"(",
"repoName",
"string",
")",
"error",
"{",
"rootForRepository",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"repoDir",
":=",
"path",
".",
"Join",
"(",
"rootForRepository",
",",
"repoName",
")",
"\n",
"dcontext",
".",
"GetLogger",
"(",
"v",
".",
"ctx",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"repoDir",
")",
"\n",
"err",
"=",
"v",
".",
"driver",
".",
"Delete",
"(",
"v",
".",
"ctx",
",",
"repoDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// RemoveRepository removes a repository directory from the
// filesystem
|
[
"RemoveRepository",
"removes",
"a",
"repository",
"directory",
"from",
"the",
"filesystem"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/vacuum.go#L89-L102
|
train
|
docker/distribution
|
registry/proxy/proxytagservice.go
|
Get
|
func (pt proxyTagService) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
err := pt.authChallenger.tryEstablishChallenges(ctx)
if err == nil {
desc, err := pt.remoteTags.Get(ctx, tag)
if err == nil {
err := pt.localTags.Tag(ctx, tag, desc)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
}
desc, err := pt.localTags.Get(ctx, tag)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
|
go
|
func (pt proxyTagService) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
err := pt.authChallenger.tryEstablishChallenges(ctx)
if err == nil {
desc, err := pt.remoteTags.Get(ctx, tag)
if err == nil {
err := pt.localTags.Tag(ctx, tag, desc)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
}
desc, err := pt.localTags.Get(ctx, tag)
if err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
|
[
"func",
"(",
"pt",
"proxyTagService",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"err",
":=",
"pt",
".",
"authChallenger",
".",
"tryEstablishChallenges",
"(",
"ctx",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"desc",
",",
"err",
":=",
"pt",
".",
"remoteTags",
".",
"Get",
"(",
"ctx",
",",
"tag",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
":=",
"pt",
".",
"localTags",
".",
"Tag",
"(",
"ctx",
",",
"tag",
",",
"desc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"desc",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"desc",
",",
"err",
":=",
"pt",
".",
"localTags",
".",
"Get",
"(",
"ctx",
",",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"desc",
",",
"nil",
"\n",
"}"
] |
// Get attempts to get the most recent digest for the tag by checking the remote
// tag service first and then caching it locally. If the remote is unavailable
// the local association is returned
|
[
"Get",
"attempts",
"to",
"get",
"the",
"most",
"recent",
"digest",
"for",
"the",
"tag",
"by",
"checking",
"the",
"remote",
"tag",
"service",
"first",
"and",
"then",
"caching",
"it",
"locally",
".",
"If",
"the",
"remote",
"is",
"unavailable",
"the",
"local",
"association",
"is",
"returned"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxytagservice.go#L21-L39
|
train
|
docker/distribution
|
configuration/configuration.go
|
UnmarshalYAML
|
func (version *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {
var versionString string
err := unmarshal(&versionString)
if err != nil {
return err
}
newVersion := Version(versionString)
if _, err := newVersion.major(); err != nil {
return err
}
if _, err := newVersion.minor(); err != nil {
return err
}
*version = newVersion
return nil
}
|
go
|
func (version *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {
var versionString string
err := unmarshal(&versionString)
if err != nil {
return err
}
newVersion := Version(versionString)
if _, err := newVersion.major(); err != nil {
return err
}
if _, err := newVersion.minor(); err != nil {
return err
}
*version = newVersion
return nil
}
|
[
"func",
"(",
"version",
"*",
"Version",
")",
"UnmarshalYAML",
"(",
"unmarshal",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"var",
"versionString",
"string",
"\n",
"err",
":=",
"unmarshal",
"(",
"&",
"versionString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"newVersion",
":=",
"Version",
"(",
"versionString",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"newVersion",
".",
"major",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"newVersion",
".",
"minor",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"*",
"version",
"=",
"newVersion",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalYAML implements the yaml.Unmarshaler interface
// Unmarshals a string of the form X.Y into a Version, validating that X and Y can represent unsigned integers
|
[
"UnmarshalYAML",
"implements",
"the",
"yaml",
".",
"Unmarshaler",
"interface",
"Unmarshals",
"a",
"string",
"of",
"the",
"form",
"X",
".",
"Y",
"into",
"a",
"Version",
"validating",
"that",
"X",
"and",
"Y",
"can",
"represent",
"unsigned",
"integers"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/configuration/configuration.go#L353-L371
|
train
|
docker/distribution
|
configuration/configuration.go
|
UnmarshalYAML
|
func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {
var loglevelString string
err := unmarshal(&loglevelString)
if err != nil {
return err
}
loglevelString = strings.ToLower(loglevelString)
switch loglevelString {
case "error", "warn", "info", "debug":
default:
return fmt.Errorf("invalid loglevel %s Must be one of [error, warn, info, debug]", loglevelString)
}
*loglevel = Loglevel(loglevelString)
return nil
}
|
go
|
func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {
var loglevelString string
err := unmarshal(&loglevelString)
if err != nil {
return err
}
loglevelString = strings.ToLower(loglevelString)
switch loglevelString {
case "error", "warn", "info", "debug":
default:
return fmt.Errorf("invalid loglevel %s Must be one of [error, warn, info, debug]", loglevelString)
}
*loglevel = Loglevel(loglevelString)
return nil
}
|
[
"func",
"(",
"loglevel",
"*",
"Loglevel",
")",
"UnmarshalYAML",
"(",
"unmarshal",
"func",
"(",
"interface",
"{",
"}",
")",
"error",
")",
"error",
"{",
"var",
"loglevelString",
"string",
"\n",
"err",
":=",
"unmarshal",
"(",
"&",
"loglevelString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"loglevelString",
"=",
"strings",
".",
"ToLower",
"(",
"loglevelString",
")",
"\n",
"switch",
"loglevelString",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"loglevelString",
")",
"\n",
"}",
"\n\n",
"*",
"loglevel",
"=",
"Loglevel",
"(",
"loglevelString",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalYAML implements the yaml.Umarshaler interface
// Unmarshals a string into a Loglevel, lowercasing the string and validating that it represents a
// valid loglevel
|
[
"UnmarshalYAML",
"implements",
"the",
"yaml",
".",
"Umarshaler",
"interface",
"Unmarshals",
"a",
"string",
"into",
"a",
"Loglevel",
"lowercasing",
"the",
"string",
"and",
"validating",
"that",
"it",
"represents",
"a",
"valid",
"loglevel"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/configuration/configuration.go#L383-L399
|
train
|
docker/distribution
|
configuration/configuration.go
|
Type
|
func (storage Storage) Type() string {
var storageType []string
// Return only key in this map
for k := range storage {
switch k {
case "maintenance":
// allow configuration of maintenance
case "cache":
// allow configuration of caching
case "delete":
// allow configuration of delete
case "redirect":
// allow configuration of redirect
default:
storageType = append(storageType, k)
}
}
if len(storageType) > 1 {
panic("multiple storage drivers specified in configuration or environment: " + strings.Join(storageType, ", "))
}
if len(storageType) == 1 {
return storageType[0]
}
return ""
}
|
go
|
func (storage Storage) Type() string {
var storageType []string
// Return only key in this map
for k := range storage {
switch k {
case "maintenance":
// allow configuration of maintenance
case "cache":
// allow configuration of caching
case "delete":
// allow configuration of delete
case "redirect":
// allow configuration of redirect
default:
storageType = append(storageType, k)
}
}
if len(storageType) > 1 {
panic("multiple storage drivers specified in configuration or environment: " + strings.Join(storageType, ", "))
}
if len(storageType) == 1 {
return storageType[0]
}
return ""
}
|
[
"func",
"(",
"storage",
"Storage",
")",
"Type",
"(",
")",
"string",
"{",
"var",
"storageType",
"[",
"]",
"string",
"\n\n",
"// Return only key in this map",
"for",
"k",
":=",
"range",
"storage",
"{",
"switch",
"k",
"{",
"case",
"\"",
"\"",
":",
"// allow configuration of maintenance",
"case",
"\"",
"\"",
":",
"// allow configuration of caching",
"case",
"\"",
"\"",
":",
"// allow configuration of delete",
"case",
"\"",
"\"",
":",
"// allow configuration of redirect",
"default",
":",
"storageType",
"=",
"append",
"(",
"storageType",
",",
"k",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"storageType",
")",
">",
"1",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"storageType",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"storageType",
")",
"==",
"1",
"{",
"return",
"storageType",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// Type returns the storage driver type, such as filesystem or s3
|
[
"Type",
"returns",
"the",
"storage",
"driver",
"type",
"such",
"as",
"filesystem",
"or",
"s3"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/configuration/configuration.go#L408-L433
|
train
|
docker/distribution
|
uuid/uuid.go
|
Generate
|
func Generate() (u UUID) {
const (
// ensures we backoff for less than 450ms total. Use the following to
// select new value, in units of 10ms:
// n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2
maxretries = 9
backoff = time.Millisecond * 10
)
var (
totalBackoff time.Duration
count int
retries int
)
for {
// This should never block but the read may fail. Because of this,
// we just try to read the random number generator until we get
// something. This is a very rare condition but may happen.
b := time.Duration(retries) * backoff
time.Sleep(b)
totalBackoff += b
n, err := io.ReadFull(rand.Reader, u[count:])
if err != nil {
if retryOnError(err) && retries < maxretries {
count += n
retries++
Loggerf("error generating version 4 uuid, retrying: %v", err)
continue
}
// Any other errors represent a system problem. What did someone
// do to /dev/urandom?
panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err))
}
break
}
u[6] = (u[6] & 0x0f) | 0x40 // set version byte
u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b}
return u
}
|
go
|
func Generate() (u UUID) {
const (
// ensures we backoff for less than 450ms total. Use the following to
// select new value, in units of 10ms:
// n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2
maxretries = 9
backoff = time.Millisecond * 10
)
var (
totalBackoff time.Duration
count int
retries int
)
for {
// This should never block but the read may fail. Because of this,
// we just try to read the random number generator until we get
// something. This is a very rare condition but may happen.
b := time.Duration(retries) * backoff
time.Sleep(b)
totalBackoff += b
n, err := io.ReadFull(rand.Reader, u[count:])
if err != nil {
if retryOnError(err) && retries < maxretries {
count += n
retries++
Loggerf("error generating version 4 uuid, retrying: %v", err)
continue
}
// Any other errors represent a system problem. What did someone
// do to /dev/urandom?
panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err))
}
break
}
u[6] = (u[6] & 0x0f) | 0x40 // set version byte
u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b}
return u
}
|
[
"func",
"Generate",
"(",
")",
"(",
"u",
"UUID",
")",
"{",
"const",
"(",
"// ensures we backoff for less than 450ms total. Use the following to",
"// select new value, in units of 10ms:",
"// \tn*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2",
"maxretries",
"=",
"9",
"\n",
"backoff",
"=",
"time",
".",
"Millisecond",
"*",
"10",
"\n",
")",
"\n\n",
"var",
"(",
"totalBackoff",
"time",
".",
"Duration",
"\n",
"count",
"int",
"\n",
"retries",
"int",
"\n",
")",
"\n\n",
"for",
"{",
"// This should never block but the read may fail. Because of this,",
"// we just try to read the random number generator until we get",
"// something. This is a very rare condition but may happen.",
"b",
":=",
"time",
".",
"Duration",
"(",
"retries",
")",
"*",
"backoff",
"\n",
"time",
".",
"Sleep",
"(",
"b",
")",
"\n",
"totalBackoff",
"+=",
"b",
"\n\n",
"n",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"rand",
".",
"Reader",
",",
"u",
"[",
"count",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"retryOnError",
"(",
"err",
")",
"&&",
"retries",
"<",
"maxretries",
"{",
"count",
"+=",
"n",
"\n",
"retries",
"++",
"\n",
"Loggerf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Any other errors represent a system problem. What did someone",
"// do to /dev/urandom?",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"totalBackoff",
".",
"String",
"(",
")",
",",
"err",
")",
")",
"\n",
"}",
"\n\n",
"break",
"\n",
"}",
"\n\n",
"u",
"[",
"6",
"]",
"=",
"(",
"u",
"[",
"6",
"]",
"&",
"0x0f",
")",
"|",
"0x40",
"// set version byte",
"\n",
"u",
"[",
"8",
"]",
"=",
"(",
"u",
"[",
"8",
"]",
"&",
"0x3f",
")",
"|",
"0x80",
"// set high order byte 0b10{8,9,a,b}",
"\n\n",
"return",
"u",
"\n",
"}"
] |
// Generate creates a new, version 4 uuid.
|
[
"Generate",
"creates",
"a",
"new",
"version",
"4",
"uuid",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/uuid/uuid.go#L40-L84
|
train
|
docker/distribution
|
uuid/uuid.go
|
Parse
|
func Parse(s string) (u UUID, err error) {
if len(s) != 36 {
return UUID{}, ErrUUIDInvalid
}
// create stack addresses for each section of the uuid.
p := make([][]byte, 5)
if _, err := fmt.Sscanf(s, format, &p[0], &p[1], &p[2], &p[3], &p[4]); err != nil {
return u, err
}
copy(u[0:4], p[0])
copy(u[4:6], p[1])
copy(u[6:8], p[2])
copy(u[8:10], p[3])
copy(u[10:16], p[4])
return
}
|
go
|
func Parse(s string) (u UUID, err error) {
if len(s) != 36 {
return UUID{}, ErrUUIDInvalid
}
// create stack addresses for each section of the uuid.
p := make([][]byte, 5)
if _, err := fmt.Sscanf(s, format, &p[0], &p[1], &p[2], &p[3], &p[4]); err != nil {
return u, err
}
copy(u[0:4], p[0])
copy(u[4:6], p[1])
copy(u[6:8], p[2])
copy(u[8:10], p[3])
copy(u[10:16], p[4])
return
}
|
[
"func",
"Parse",
"(",
"s",
"string",
")",
"(",
"u",
"UUID",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"s",
")",
"!=",
"36",
"{",
"return",
"UUID",
"{",
"}",
",",
"ErrUUIDInvalid",
"\n",
"}",
"\n\n",
"// create stack addresses for each section of the uuid.",
"p",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"5",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"fmt",
".",
"Sscanf",
"(",
"s",
",",
"format",
",",
"&",
"p",
"[",
"0",
"]",
",",
"&",
"p",
"[",
"1",
"]",
",",
"&",
"p",
"[",
"2",
"]",
",",
"&",
"p",
"[",
"3",
"]",
",",
"&",
"p",
"[",
"4",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"u",
",",
"err",
"\n",
"}",
"\n\n",
"copy",
"(",
"u",
"[",
"0",
":",
"4",
"]",
",",
"p",
"[",
"0",
"]",
")",
"\n",
"copy",
"(",
"u",
"[",
"4",
":",
"6",
"]",
",",
"p",
"[",
"1",
"]",
")",
"\n",
"copy",
"(",
"u",
"[",
"6",
":",
"8",
"]",
",",
"p",
"[",
"2",
"]",
")",
"\n",
"copy",
"(",
"u",
"[",
"8",
":",
"10",
"]",
",",
"p",
"[",
"3",
"]",
")",
"\n",
"copy",
"(",
"u",
"[",
"10",
":",
"16",
"]",
",",
"p",
"[",
"4",
"]",
")",
"\n\n",
"return",
"\n",
"}"
] |
// Parse attempts to extract a uuid from the string or returns an error.
|
[
"Parse",
"attempts",
"to",
"extract",
"a",
"uuid",
"from",
"the",
"string",
"or",
"returns",
"an",
"error",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/uuid/uuid.go#L87-L106
|
train
|
docker/distribution
|
registry/storage/driver/s3-aws/s3.go
|
New
|
func New(params DriverParameters) (*Driver, error) {
if !params.V4Auth &&
(params.RegionEndpoint == "" ||
strings.Contains(params.RegionEndpoint, "s3.amazonaws.com")) {
return nil, fmt.Errorf("on Amazon S3 this storage driver can only be used with v4 authentication")
}
awsConfig := aws.NewConfig()
sess, err := session.NewSession()
if err != nil {
return nil, fmt.Errorf("failed to create new session: %v", err)
}
creds := credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: params.AccessKey,
SecretAccessKey: params.SecretKey,
SessionToken: params.SessionToken,
},
},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess)},
})
if params.RegionEndpoint != "" {
awsConfig.WithS3ForcePathStyle(true)
awsConfig.WithEndpoint(params.RegionEndpoint)
}
awsConfig.WithCredentials(creds)
awsConfig.WithRegion(params.Region)
awsConfig.WithDisableSSL(!params.Secure)
if params.UserAgent != "" || params.SkipVerify {
httpTransport := http.DefaultTransport
if params.SkipVerify {
httpTransport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
if params.UserAgent != "" {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport, transport.NewHeaderRequestModifier(http.Header{http.CanonicalHeaderKey("User-Agent"): []string{params.UserAgent}})),
})
} else {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport),
})
}
}
sess, err = session.NewSession(awsConfig)
if err != nil {
return nil, fmt.Errorf("failed to create new session with aws config: %v", err)
}
s3obj := s3.New(sess)
// enable S3 compatible signature v2 signing instead
if !params.V4Auth {
setv2Handlers(s3obj)
}
// TODO Currently multipart uploads have no timestamps, so this would be unwise
// if you initiated a new s3driver while another one is running on the same bucket.
// multis, _, err := bucket.ListMulti("", "")
// if err != nil {
// return nil, err
// }
// for _, multi := range multis {
// err := multi.Abort()
// //TODO appropriate to do this error checking?
// if err != nil {
// return nil, err
// }
// }
d := &driver{
S3: s3obj,
Bucket: params.Bucket,
ChunkSize: params.ChunkSize,
Encrypt: params.Encrypt,
KeyID: params.KeyID,
MultipartCopyChunkSize: params.MultipartCopyChunkSize,
MultipartCopyMaxConcurrency: params.MultipartCopyMaxConcurrency,
MultipartCopyThresholdSize: params.MultipartCopyThresholdSize,
RootDirectory: params.RootDirectory,
StorageClass: params.StorageClass,
ObjectACL: params.ObjectACL,
}
return &Driver{
baseEmbed: baseEmbed{
Base: base.Base{
StorageDriver: d,
},
},
}, nil
}
|
go
|
func New(params DriverParameters) (*Driver, error) {
if !params.V4Auth &&
(params.RegionEndpoint == "" ||
strings.Contains(params.RegionEndpoint, "s3.amazonaws.com")) {
return nil, fmt.Errorf("on Amazon S3 this storage driver can only be used with v4 authentication")
}
awsConfig := aws.NewConfig()
sess, err := session.NewSession()
if err != nil {
return nil, fmt.Errorf("failed to create new session: %v", err)
}
creds := credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: params.AccessKey,
SecretAccessKey: params.SecretKey,
SessionToken: params.SessionToken,
},
},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess)},
})
if params.RegionEndpoint != "" {
awsConfig.WithS3ForcePathStyle(true)
awsConfig.WithEndpoint(params.RegionEndpoint)
}
awsConfig.WithCredentials(creds)
awsConfig.WithRegion(params.Region)
awsConfig.WithDisableSSL(!params.Secure)
if params.UserAgent != "" || params.SkipVerify {
httpTransport := http.DefaultTransport
if params.SkipVerify {
httpTransport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
if params.UserAgent != "" {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport, transport.NewHeaderRequestModifier(http.Header{http.CanonicalHeaderKey("User-Agent"): []string{params.UserAgent}})),
})
} else {
awsConfig.WithHTTPClient(&http.Client{
Transport: transport.NewTransport(httpTransport),
})
}
}
sess, err = session.NewSession(awsConfig)
if err != nil {
return nil, fmt.Errorf("failed to create new session with aws config: %v", err)
}
s3obj := s3.New(sess)
// enable S3 compatible signature v2 signing instead
if !params.V4Auth {
setv2Handlers(s3obj)
}
// TODO Currently multipart uploads have no timestamps, so this would be unwise
// if you initiated a new s3driver while another one is running on the same bucket.
// multis, _, err := bucket.ListMulti("", "")
// if err != nil {
// return nil, err
// }
// for _, multi := range multis {
// err := multi.Abort()
// //TODO appropriate to do this error checking?
// if err != nil {
// return nil, err
// }
// }
d := &driver{
S3: s3obj,
Bucket: params.Bucket,
ChunkSize: params.ChunkSize,
Encrypt: params.Encrypt,
KeyID: params.KeyID,
MultipartCopyChunkSize: params.MultipartCopyChunkSize,
MultipartCopyMaxConcurrency: params.MultipartCopyMaxConcurrency,
MultipartCopyThresholdSize: params.MultipartCopyThresholdSize,
RootDirectory: params.RootDirectory,
StorageClass: params.StorageClass,
ObjectACL: params.ObjectACL,
}
return &Driver{
baseEmbed: baseEmbed{
Base: base.Base{
StorageDriver: d,
},
},
}, nil
}
|
[
"func",
"New",
"(",
"params",
"DriverParameters",
")",
"(",
"*",
"Driver",
",",
"error",
")",
"{",
"if",
"!",
"params",
".",
"V4Auth",
"&&",
"(",
"params",
".",
"RegionEndpoint",
"==",
"\"",
"\"",
"||",
"strings",
".",
"Contains",
"(",
"params",
".",
"RegionEndpoint",
",",
"\"",
"\"",
")",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"awsConfig",
":=",
"aws",
".",
"NewConfig",
"(",
")",
"\n",
"sess",
",",
"err",
":=",
"session",
".",
"NewSession",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"creds",
":=",
"credentials",
".",
"NewChainCredentials",
"(",
"[",
"]",
"credentials",
".",
"Provider",
"{",
"&",
"credentials",
".",
"StaticProvider",
"{",
"Value",
":",
"credentials",
".",
"Value",
"{",
"AccessKeyID",
":",
"params",
".",
"AccessKey",
",",
"SecretAccessKey",
":",
"params",
".",
"SecretKey",
",",
"SessionToken",
":",
"params",
".",
"SessionToken",
",",
"}",
",",
"}",
",",
"&",
"credentials",
".",
"EnvProvider",
"{",
"}",
",",
"&",
"credentials",
".",
"SharedCredentialsProvider",
"{",
"}",
",",
"&",
"ec2rolecreds",
".",
"EC2RoleProvider",
"{",
"Client",
":",
"ec2metadata",
".",
"New",
"(",
"sess",
")",
"}",
",",
"}",
")",
"\n\n",
"if",
"params",
".",
"RegionEndpoint",
"!=",
"\"",
"\"",
"{",
"awsConfig",
".",
"WithS3ForcePathStyle",
"(",
"true",
")",
"\n",
"awsConfig",
".",
"WithEndpoint",
"(",
"params",
".",
"RegionEndpoint",
")",
"\n",
"}",
"\n\n",
"awsConfig",
".",
"WithCredentials",
"(",
"creds",
")",
"\n",
"awsConfig",
".",
"WithRegion",
"(",
"params",
".",
"Region",
")",
"\n",
"awsConfig",
".",
"WithDisableSSL",
"(",
"!",
"params",
".",
"Secure",
")",
"\n\n",
"if",
"params",
".",
"UserAgent",
"!=",
"\"",
"\"",
"||",
"params",
".",
"SkipVerify",
"{",
"httpTransport",
":=",
"http",
".",
"DefaultTransport",
"\n",
"if",
"params",
".",
"SkipVerify",
"{",
"httpTransport",
"=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"true",
"}",
",",
"}",
"\n",
"}",
"\n",
"if",
"params",
".",
"UserAgent",
"!=",
"\"",
"\"",
"{",
"awsConfig",
".",
"WithHTTPClient",
"(",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"transport",
".",
"NewTransport",
"(",
"httpTransport",
",",
"transport",
".",
"NewHeaderRequestModifier",
"(",
"http",
".",
"Header",
"{",
"http",
".",
"CanonicalHeaderKey",
"(",
"\"",
"\"",
")",
":",
"[",
"]",
"string",
"{",
"params",
".",
"UserAgent",
"}",
"}",
")",
")",
",",
"}",
")",
"\n",
"}",
"else",
"{",
"awsConfig",
".",
"WithHTTPClient",
"(",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"transport",
".",
"NewTransport",
"(",
"httpTransport",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"sess",
",",
"err",
"=",
"session",
".",
"NewSession",
"(",
"awsConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"s3obj",
":=",
"s3",
".",
"New",
"(",
"sess",
")",
"\n\n",
"// enable S3 compatible signature v2 signing instead",
"if",
"!",
"params",
".",
"V4Auth",
"{",
"setv2Handlers",
"(",
"s3obj",
")",
"\n",
"}",
"\n\n",
"// TODO Currently multipart uploads have no timestamps, so this would be unwise",
"// if you initiated a new s3driver while another one is running on the same bucket.",
"// multis, _, err := bucket.ListMulti(\"\", \"\")",
"// if err != nil {",
"// \treturn nil, err",
"// }",
"// for _, multi := range multis {",
"// \terr := multi.Abort()",
"// \t//TODO appropriate to do this error checking?",
"// \tif err != nil {",
"// \t\treturn nil, err",
"// \t}",
"// }",
"d",
":=",
"&",
"driver",
"{",
"S3",
":",
"s3obj",
",",
"Bucket",
":",
"params",
".",
"Bucket",
",",
"ChunkSize",
":",
"params",
".",
"ChunkSize",
",",
"Encrypt",
":",
"params",
".",
"Encrypt",
",",
"KeyID",
":",
"params",
".",
"KeyID",
",",
"MultipartCopyChunkSize",
":",
"params",
".",
"MultipartCopyChunkSize",
",",
"MultipartCopyMaxConcurrency",
":",
"params",
".",
"MultipartCopyMaxConcurrency",
",",
"MultipartCopyThresholdSize",
":",
"params",
".",
"MultipartCopyThresholdSize",
",",
"RootDirectory",
":",
"params",
".",
"RootDirectory",
",",
"StorageClass",
":",
"params",
".",
"StorageClass",
",",
"ObjectACL",
":",
"params",
".",
"ObjectACL",
",",
"}",
"\n\n",
"return",
"&",
"Driver",
"{",
"baseEmbed",
":",
"baseEmbed",
"{",
"Base",
":",
"base",
".",
"Base",
"{",
"StorageDriver",
":",
"d",
",",
"}",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// New constructs a new Driver with the given AWS credentials, region, encryption flag, and
// bucketName
|
[
"New",
"constructs",
"a",
"new",
"Driver",
"with",
"the",
"given",
"AWS",
"credentials",
"region",
"encryption",
"flag",
"and",
"bucketName"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/s3-aws/s3.go#L400-L499
|
train
|
docker/distribution
|
registry/storage/driver/s3-aws/s3.go
|
Delete
|
func (d *driver) Delete(ctx context.Context, path string) error {
s3Objects := make([]*s3.ObjectIdentifier, 0, listMax)
s3Path := d.s3Path(path)
listObjectsInput := &s3.ListObjectsInput{
Bucket: aws.String(d.Bucket),
Prefix: aws.String(s3Path),
}
ListLoop:
for {
// list all the objects
resp, err := d.S3.ListObjects(listObjectsInput)
// resp.Contents can only be empty on the first call
// if there were no more results to return after the first call, resp.IsTruncated would have been false
// and the loop would be exited without recalling ListObjects
if err != nil || len(resp.Contents) == 0 {
return storagedriver.PathNotFoundError{Path: path}
}
for _, key := range resp.Contents {
// Stop if we encounter a key that is not a subpath (so that deleting "/a" does not delete "/ab").
if len(*key.Key) > len(s3Path) && (*key.Key)[len(s3Path)] != '/' {
break ListLoop
}
s3Objects = append(s3Objects, &s3.ObjectIdentifier{
Key: key.Key,
})
}
// resp.Contents must have at least one element or we would have returned not found
listObjectsInput.Marker = resp.Contents[len(resp.Contents)-1].Key
// from the s3 api docs, IsTruncated "specifies whether (true) or not (false) all of the results were returned"
// if everything has been returned, break
if resp.IsTruncated == nil || !*resp.IsTruncated {
break
}
}
// need to chunk objects into groups of 1000 per s3 restrictions
total := len(s3Objects)
for i := 0; i < total; i += 1000 {
_, err := d.S3.DeleteObjects(&s3.DeleteObjectsInput{
Bucket: aws.String(d.Bucket),
Delete: &s3.Delete{
Objects: s3Objects[i:min(i+1000, total)],
Quiet: aws.Bool(false),
},
})
if err != nil {
return err
}
}
return nil
}
|
go
|
func (d *driver) Delete(ctx context.Context, path string) error {
s3Objects := make([]*s3.ObjectIdentifier, 0, listMax)
s3Path := d.s3Path(path)
listObjectsInput := &s3.ListObjectsInput{
Bucket: aws.String(d.Bucket),
Prefix: aws.String(s3Path),
}
ListLoop:
for {
// list all the objects
resp, err := d.S3.ListObjects(listObjectsInput)
// resp.Contents can only be empty on the first call
// if there were no more results to return after the first call, resp.IsTruncated would have been false
// and the loop would be exited without recalling ListObjects
if err != nil || len(resp.Contents) == 0 {
return storagedriver.PathNotFoundError{Path: path}
}
for _, key := range resp.Contents {
// Stop if we encounter a key that is not a subpath (so that deleting "/a" does not delete "/ab").
if len(*key.Key) > len(s3Path) && (*key.Key)[len(s3Path)] != '/' {
break ListLoop
}
s3Objects = append(s3Objects, &s3.ObjectIdentifier{
Key: key.Key,
})
}
// resp.Contents must have at least one element or we would have returned not found
listObjectsInput.Marker = resp.Contents[len(resp.Contents)-1].Key
// from the s3 api docs, IsTruncated "specifies whether (true) or not (false) all of the results were returned"
// if everything has been returned, break
if resp.IsTruncated == nil || !*resp.IsTruncated {
break
}
}
// need to chunk objects into groups of 1000 per s3 restrictions
total := len(s3Objects)
for i := 0; i < total; i += 1000 {
_, err := d.S3.DeleteObjects(&s3.DeleteObjectsInput{
Bucket: aws.String(d.Bucket),
Delete: &s3.Delete{
Objects: s3Objects[i:min(i+1000, total)],
Quiet: aws.Bool(false),
},
})
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"driver",
")",
"Delete",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"error",
"{",
"s3Objects",
":=",
"make",
"(",
"[",
"]",
"*",
"s3",
".",
"ObjectIdentifier",
",",
"0",
",",
"listMax",
")",
"\n",
"s3Path",
":=",
"d",
".",
"s3Path",
"(",
"path",
")",
"\n",
"listObjectsInput",
":=",
"&",
"s3",
".",
"ListObjectsInput",
"{",
"Bucket",
":",
"aws",
".",
"String",
"(",
"d",
".",
"Bucket",
")",
",",
"Prefix",
":",
"aws",
".",
"String",
"(",
"s3Path",
")",
",",
"}",
"\n",
"ListLoop",
":",
"for",
"{",
"// list all the objects",
"resp",
",",
"err",
":=",
"d",
".",
"S3",
".",
"ListObjects",
"(",
"listObjectsInput",
")",
"\n\n",
"// resp.Contents can only be empty on the first call",
"// if there were no more results to return after the first call, resp.IsTruncated would have been false",
"// and the loop would be exited without recalling ListObjects",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"resp",
".",
"Contents",
")",
"==",
"0",
"{",
"return",
"storagedriver",
".",
"PathNotFoundError",
"{",
"Path",
":",
"path",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"key",
":=",
"range",
"resp",
".",
"Contents",
"{",
"// Stop if we encounter a key that is not a subpath (so that deleting \"/a\" does not delete \"/ab\").",
"if",
"len",
"(",
"*",
"key",
".",
"Key",
")",
">",
"len",
"(",
"s3Path",
")",
"&&",
"(",
"*",
"key",
".",
"Key",
")",
"[",
"len",
"(",
"s3Path",
")",
"]",
"!=",
"'/'",
"{",
"break",
"ListLoop",
"\n",
"}",
"\n",
"s3Objects",
"=",
"append",
"(",
"s3Objects",
",",
"&",
"s3",
".",
"ObjectIdentifier",
"{",
"Key",
":",
"key",
".",
"Key",
",",
"}",
")",
"\n",
"}",
"\n\n",
"// resp.Contents must have at least one element or we would have returned not found",
"listObjectsInput",
".",
"Marker",
"=",
"resp",
".",
"Contents",
"[",
"len",
"(",
"resp",
".",
"Contents",
")",
"-",
"1",
"]",
".",
"Key",
"\n\n",
"// from the s3 api docs, IsTruncated \"specifies whether (true) or not (false) all of the results were returned\"",
"// if everything has been returned, break",
"if",
"resp",
".",
"IsTruncated",
"==",
"nil",
"||",
"!",
"*",
"resp",
".",
"IsTruncated",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// need to chunk objects into groups of 1000 per s3 restrictions",
"total",
":=",
"len",
"(",
"s3Objects",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"total",
";",
"i",
"+=",
"1000",
"{",
"_",
",",
"err",
":=",
"d",
".",
"S3",
".",
"DeleteObjects",
"(",
"&",
"s3",
".",
"DeleteObjectsInput",
"{",
"Bucket",
":",
"aws",
".",
"String",
"(",
"d",
".",
"Bucket",
")",
",",
"Delete",
":",
"&",
"s3",
".",
"Delete",
"{",
"Objects",
":",
"s3Objects",
"[",
"i",
":",
"min",
"(",
"i",
"+",
"1000",
",",
"total",
")",
"]",
",",
"Quiet",
":",
"aws",
".",
"Bool",
"(",
"false",
")",
",",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Delete recursively deletes all objects stored at "path" and its subpaths.
// We must be careful since S3 does not guarantee read after delete consistency
|
[
"Delete",
"recursively",
"deletes",
"all",
"objects",
"stored",
"at",
"path",
"and",
"its",
"subpaths",
".",
"We",
"must",
"be",
"careful",
"since",
"S3",
"does",
"not",
"guarantee",
"read",
"after",
"delete",
"consistency"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/s3-aws/s3.go#L808-L862
|
train
|
docker/distribution
|
registry/storage/driver/s3-aws/s3.go
|
S3BucketKey
|
func (d *Driver) S3BucketKey(path string) string {
return d.StorageDriver.(*driver).s3Path(path)
}
|
go
|
func (d *Driver) S3BucketKey(path string) string {
return d.StorageDriver.(*driver).s3Path(path)
}
|
[
"func",
"(",
"d",
"*",
"Driver",
")",
"S3BucketKey",
"(",
"path",
"string",
")",
"string",
"{",
"return",
"d",
".",
"StorageDriver",
".",
"(",
"*",
"driver",
")",
".",
"s3Path",
"(",
"path",
")",
"\n",
"}"
] |
// S3BucketKey returns the s3 bucket key for the given storage driver path.
|
[
"S3BucketKey",
"returns",
"the",
"s3",
"bucket",
"key",
"for",
"the",
"given",
"storage",
"driver",
"path",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/s3-aws/s3.go#L1040-L1042
|
train
|
docker/distribution
|
registry/storage/cache/cachedblobdescriptorstore.go
|
NewCachedBlobStatter
|
func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService {
return &cachedBlobStatter{
cache: cache,
backend: backend,
}
}
|
go
|
func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService {
return &cachedBlobStatter{
cache: cache,
backend: backend,
}
}
|
[
"func",
"NewCachedBlobStatter",
"(",
"cache",
"distribution",
".",
"BlobDescriptorService",
",",
"backend",
"distribution",
".",
"BlobDescriptorService",
")",
"distribution",
".",
"BlobDescriptorService",
"{",
"return",
"&",
"cachedBlobStatter",
"{",
"cache",
":",
"cache",
",",
"backend",
":",
"backend",
",",
"}",
"\n",
"}"
] |
// NewCachedBlobStatter creates a new statter which prefers a cache and
// falls back to a backend.
|
[
"NewCachedBlobStatter",
"creates",
"a",
"new",
"statter",
"which",
"prefers",
"a",
"cache",
"and",
"falls",
"back",
"to",
"a",
"backend",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/cachedblobdescriptorstore.go#L49-L54
|
train
|
docker/distribution
|
registry/storage/cache/cachedblobdescriptorstore.go
|
NewCachedBlobStatterWithMetrics
|
func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter {
return &cachedBlobStatter{
cache: cache,
backend: backend,
tracker: tracker,
}
}
|
go
|
func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter {
return &cachedBlobStatter{
cache: cache,
backend: backend,
tracker: tracker,
}
}
|
[
"func",
"NewCachedBlobStatterWithMetrics",
"(",
"cache",
"distribution",
".",
"BlobDescriptorService",
",",
"backend",
"distribution",
".",
"BlobDescriptorService",
",",
"tracker",
"MetricsTracker",
")",
"distribution",
".",
"BlobStatter",
"{",
"return",
"&",
"cachedBlobStatter",
"{",
"cache",
":",
"cache",
",",
"backend",
":",
"backend",
",",
"tracker",
":",
"tracker",
",",
"}",
"\n",
"}"
] |
// NewCachedBlobStatterWithMetrics creates a new statter which prefers a cache and
// falls back to a backend. Hits and misses will send to the tracker.
|
[
"NewCachedBlobStatterWithMetrics",
"creates",
"a",
"new",
"statter",
"which",
"prefers",
"a",
"cache",
"and",
"falls",
"back",
"to",
"a",
"backend",
".",
"Hits",
"and",
"misses",
"will",
"send",
"to",
"the",
"tracker",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/cachedblobdescriptorstore.go#L58-L64
|
train
|
docker/distribution
|
context/version.go
|
WithVersion
|
func WithVersion(ctx context.Context, version string) context.Context {
ctx = context.WithValue(ctx, versionKey{}, version)
// push a new logger onto the stack
return WithLogger(ctx, GetLogger(ctx, versionKey{}))
}
|
go
|
func WithVersion(ctx context.Context, version string) context.Context {
ctx = context.WithValue(ctx, versionKey{}, version)
// push a new logger onto the stack
return WithLogger(ctx, GetLogger(ctx, versionKey{}))
}
|
[
"func",
"WithVersion",
"(",
"ctx",
"context",
".",
"Context",
",",
"version",
"string",
")",
"context",
".",
"Context",
"{",
"ctx",
"=",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"versionKey",
"{",
"}",
",",
"version",
")",
"\n",
"// push a new logger onto the stack",
"return",
"WithLogger",
"(",
"ctx",
",",
"GetLogger",
"(",
"ctx",
",",
"versionKey",
"{",
"}",
")",
")",
"\n",
"}"
] |
// WithVersion stores the application version in the context. The new context
// gets a logger to ensure log messages are marked with the application
// version.
|
[
"WithVersion",
"stores",
"the",
"application",
"version",
"in",
"the",
"context",
".",
"The",
"new",
"context",
"gets",
"a",
"logger",
"to",
"ensure",
"log",
"messages",
"are",
"marked",
"with",
"the",
"application",
"version",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/version.go#L12-L16
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/s3filter.go
|
newAWSIPs
|
func newAWSIPs(host string, updateFrequency time.Duration, awsRegion []string) *awsIPs {
ips := &awsIPs{
host: host,
updateFrequency: updateFrequency,
awsRegion: awsRegion,
updaterStopChan: make(chan bool),
}
if err := ips.tryUpdate(); err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Warn("failed to update AWS IP")
}
go ips.updater()
return ips
}
|
go
|
func newAWSIPs(host string, updateFrequency time.Duration, awsRegion []string) *awsIPs {
ips := &awsIPs{
host: host,
updateFrequency: updateFrequency,
awsRegion: awsRegion,
updaterStopChan: make(chan bool),
}
if err := ips.tryUpdate(); err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Warn("failed to update AWS IP")
}
go ips.updater()
return ips
}
|
[
"func",
"newAWSIPs",
"(",
"host",
"string",
",",
"updateFrequency",
"time",
".",
"Duration",
",",
"awsRegion",
"[",
"]",
"string",
")",
"*",
"awsIPs",
"{",
"ips",
":=",
"&",
"awsIPs",
"{",
"host",
":",
"host",
",",
"updateFrequency",
":",
"updateFrequency",
",",
"awsRegion",
":",
"awsRegion",
",",
"updaterStopChan",
":",
"make",
"(",
"chan",
"bool",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"ips",
".",
"tryUpdate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLogger",
"(",
"context",
".",
"Background",
"(",
")",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"go",
"ips",
".",
"updater",
"(",
")",
"\n",
"return",
"ips",
"\n",
"}"
] |
// newAWSIPs returns a New awsIP object.
// If awsRegion is `nil`, it accepts any region. Otherwise, it only allow the regions specified
|
[
"newAWSIPs",
"returns",
"a",
"New",
"awsIP",
"object",
".",
"If",
"awsRegion",
"is",
"nil",
"it",
"accepts",
"any",
"region",
".",
"Otherwise",
"it",
"only",
"allow",
"the",
"regions",
"specified"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L26-L38
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/s3filter.go
|
tryUpdate
|
func (s *awsIPs) tryUpdate() error {
response, err := fetchAWSIPs(s.host)
if err != nil {
return err
}
var ipv4 []net.IPNet
var ipv6 []net.IPNet
processAddress := func(output *[]net.IPNet, prefix string, region string) {
regionAllowed := false
if len(s.awsRegion) > 0 {
for _, ar := range s.awsRegion {
if strings.ToLower(region) == ar {
regionAllowed = true
break
}
}
} else {
regionAllowed = true
}
_, network, err := net.ParseCIDR(prefix)
if err != nil {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"cidr": prefix,
}).Error("unparseable cidr")
return
}
if regionAllowed {
*output = append(*output, *network)
}
}
for _, prefix := range response.Prefixes {
processAddress(&ipv4, prefix.IPV4Prefix, prefix.Region)
}
for _, prefix := range response.V6Prefixes {
processAddress(&ipv6, prefix.IPV6Prefix, prefix.Region)
}
s.mutex.Lock()
defer s.mutex.Unlock()
// Update each attr of awsips atomically.
s.ipv4 = ipv4
s.ipv6 = ipv6
s.initialized = true
return nil
}
|
go
|
func (s *awsIPs) tryUpdate() error {
response, err := fetchAWSIPs(s.host)
if err != nil {
return err
}
var ipv4 []net.IPNet
var ipv6 []net.IPNet
processAddress := func(output *[]net.IPNet, prefix string, region string) {
regionAllowed := false
if len(s.awsRegion) > 0 {
for _, ar := range s.awsRegion {
if strings.ToLower(region) == ar {
regionAllowed = true
break
}
}
} else {
regionAllowed = true
}
_, network, err := net.ParseCIDR(prefix)
if err != nil {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"cidr": prefix,
}).Error("unparseable cidr")
return
}
if regionAllowed {
*output = append(*output, *network)
}
}
for _, prefix := range response.Prefixes {
processAddress(&ipv4, prefix.IPV4Prefix, prefix.Region)
}
for _, prefix := range response.V6Prefixes {
processAddress(&ipv6, prefix.IPV6Prefix, prefix.Region)
}
s.mutex.Lock()
defer s.mutex.Unlock()
// Update each attr of awsips atomically.
s.ipv4 = ipv4
s.ipv6 = ipv6
s.initialized = true
return nil
}
|
[
"func",
"(",
"s",
"*",
"awsIPs",
")",
"tryUpdate",
"(",
")",
"error",
"{",
"response",
",",
"err",
":=",
"fetchAWSIPs",
"(",
"s",
".",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"ipv4",
"[",
"]",
"net",
".",
"IPNet",
"\n",
"var",
"ipv6",
"[",
"]",
"net",
".",
"IPNet",
"\n\n",
"processAddress",
":=",
"func",
"(",
"output",
"*",
"[",
"]",
"net",
".",
"IPNet",
",",
"prefix",
"string",
",",
"region",
"string",
")",
"{",
"regionAllowed",
":=",
"false",
"\n",
"if",
"len",
"(",
"s",
".",
"awsRegion",
")",
">",
"0",
"{",
"for",
"_",
",",
"ar",
":=",
"range",
"s",
".",
"awsRegion",
"{",
"if",
"strings",
".",
"ToLower",
"(",
"region",
")",
"==",
"ar",
"{",
"regionAllowed",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"regionAllowed",
"=",
"true",
"\n",
"}",
"\n\n",
"_",
",",
"network",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"prefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLoggerWithFields",
"(",
"dcontext",
".",
"Background",
"(",
")",
",",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"prefix",
",",
"}",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"regionAllowed",
"{",
"*",
"output",
"=",
"append",
"(",
"*",
"output",
",",
"*",
"network",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"for",
"_",
",",
"prefix",
":=",
"range",
"response",
".",
"Prefixes",
"{",
"processAddress",
"(",
"&",
"ipv4",
",",
"prefix",
".",
"IPV4Prefix",
",",
"prefix",
".",
"Region",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"prefix",
":=",
"range",
"response",
".",
"V6Prefixes",
"{",
"processAddress",
"(",
"&",
"ipv6",
",",
"prefix",
".",
"IPV6Prefix",
",",
"prefix",
".",
"Region",
")",
"\n",
"}",
"\n",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"// Update each attr of awsips atomically.",
"s",
".",
"ipv4",
"=",
"ipv4",
"\n",
"s",
".",
"ipv6",
"=",
"ipv6",
"\n",
"s",
".",
"initialized",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] |
// tryUpdate attempts to download the new set of ip addresses.
// tryUpdate must be thread safe with contains
|
[
"tryUpdate",
"attempts",
"to",
"download",
"the",
"new",
"set",
"of",
"ip",
"addresses",
".",
"tryUpdate",
"must",
"be",
"thread",
"safe",
"with",
"contains"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L84-L132
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/s3filter.go
|
updater
|
func (s *awsIPs) updater() {
defer close(s.updaterStopChan)
for {
time.Sleep(s.updateFrequency)
select {
case <-s.updaterStopChan:
dcontext.GetLogger(context.Background()).Info("aws ip updater received stop signal")
return
default:
err := s.tryUpdate()
if err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Error("git AWS IP")
}
}
}
}
|
go
|
func (s *awsIPs) updater() {
defer close(s.updaterStopChan)
for {
time.Sleep(s.updateFrequency)
select {
case <-s.updaterStopChan:
dcontext.GetLogger(context.Background()).Info("aws ip updater received stop signal")
return
default:
err := s.tryUpdate()
if err != nil {
dcontext.GetLogger(context.Background()).WithError(err).Error("git AWS IP")
}
}
}
}
|
[
"func",
"(",
"s",
"*",
"awsIPs",
")",
"updater",
"(",
")",
"{",
"defer",
"close",
"(",
"s",
".",
"updaterStopChan",
")",
"\n",
"for",
"{",
"time",
".",
"Sleep",
"(",
"s",
".",
"updateFrequency",
")",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"updaterStopChan",
":",
"dcontext",
".",
"GetLogger",
"(",
"context",
".",
"Background",
"(",
")",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"default",
":",
"err",
":=",
"s",
".",
"tryUpdate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLogger",
"(",
"context",
".",
"Background",
"(",
")",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// This function is meant to be run in a background goroutine.
// It will periodically update the ips from aws.
|
[
"This",
"function",
"is",
"meant",
"to",
"be",
"run",
"in",
"a",
"background",
"goroutine",
".",
"It",
"will",
"periodically",
"update",
"the",
"ips",
"from",
"aws",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L136-L151
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/s3filter.go
|
getCandidateNetworks
|
func (s *awsIPs) getCandidateNetworks(ip net.IP) []net.IPNet {
s.mutex.RLock()
defer s.mutex.RUnlock()
if ip.To4() != nil {
return s.ipv4
} else if ip.To16() != nil {
return s.ipv6
} else {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"ip": ip,
}).Error("unknown ip address format")
// assume mismatch, pass through cloudfront
return nil
}
}
|
go
|
func (s *awsIPs) getCandidateNetworks(ip net.IP) []net.IPNet {
s.mutex.RLock()
defer s.mutex.RUnlock()
if ip.To4() != nil {
return s.ipv4
} else if ip.To16() != nil {
return s.ipv6
} else {
dcontext.GetLoggerWithFields(dcontext.Background(), map[interface{}]interface{}{
"ip": ip,
}).Error("unknown ip address format")
// assume mismatch, pass through cloudfront
return nil
}
}
|
[
"func",
"(",
"s",
"*",
"awsIPs",
")",
"getCandidateNetworks",
"(",
"ip",
"net",
".",
"IP",
")",
"[",
"]",
"net",
".",
"IPNet",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ip",
".",
"To4",
"(",
")",
"!=",
"nil",
"{",
"return",
"s",
".",
"ipv4",
"\n",
"}",
"else",
"if",
"ip",
".",
"To16",
"(",
")",
"!=",
"nil",
"{",
"return",
"s",
".",
"ipv6",
"\n",
"}",
"else",
"{",
"dcontext",
".",
"GetLoggerWithFields",
"(",
"dcontext",
".",
"Background",
"(",
")",
",",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"ip",
",",
"}",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"// assume mismatch, pass through cloudfront",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// getCandidateNetworks returns either the ipv4 or ipv6 networks
// that were last read from aws. The networks returned
// have the same type as the ip address provided.
|
[
"getCandidateNetworks",
"returns",
"either",
"the",
"ipv4",
"or",
"ipv6",
"networks",
"that",
"were",
"last",
"read",
"from",
"aws",
".",
"The",
"networks",
"returned",
"have",
"the",
"same",
"type",
"as",
"the",
"ip",
"address",
"provided",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L156-L170
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/s3filter.go
|
contains
|
func (s *awsIPs) contains(ip net.IP) bool {
networks := s.getCandidateNetworks(ip)
for _, network := range networks {
if network.Contains(ip) {
return true
}
}
return false
}
|
go
|
func (s *awsIPs) contains(ip net.IP) bool {
networks := s.getCandidateNetworks(ip)
for _, network := range networks {
if network.Contains(ip) {
return true
}
}
return false
}
|
[
"func",
"(",
"s",
"*",
"awsIPs",
")",
"contains",
"(",
"ip",
"net",
".",
"IP",
")",
"bool",
"{",
"networks",
":=",
"s",
".",
"getCandidateNetworks",
"(",
"ip",
")",
"\n",
"for",
"_",
",",
"network",
":=",
"range",
"networks",
"{",
"if",
"network",
".",
"Contains",
"(",
"ip",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Contains determines whether the host is within aws.
|
[
"Contains",
"determines",
"whether",
"the",
"host",
"is",
"within",
"aws",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L173-L181
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/s3filter.go
|
parseIPFromRequest
|
func parseIPFromRequest(ctx context.Context) (net.IP, error) {
request, err := dcontext.GetRequest(ctx)
if err != nil {
return nil, err
}
ipStr := dcontext.RemoteIP(request)
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("invalid ip address from requester: %s", ipStr)
}
return ip, nil
}
|
go
|
func parseIPFromRequest(ctx context.Context) (net.IP, error) {
request, err := dcontext.GetRequest(ctx)
if err != nil {
return nil, err
}
ipStr := dcontext.RemoteIP(request)
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("invalid ip address from requester: %s", ipStr)
}
return ip, nil
}
|
[
"func",
"parseIPFromRequest",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"net",
".",
"IP",
",",
"error",
")",
"{",
"request",
",",
"err",
":=",
"dcontext",
".",
"GetRequest",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ipStr",
":=",
"dcontext",
".",
"RemoteIP",
"(",
"request",
")",
"\n",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"ipStr",
")",
"\n",
"if",
"ip",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ipStr",
")",
"\n",
"}",
"\n\n",
"return",
"ip",
",",
"nil",
"\n",
"}"
] |
// parseIPFromRequest attempts to extract the ip address of the
// client that made the request
|
[
"parseIPFromRequest",
"attempts",
"to",
"extract",
"the",
"ip",
"address",
"of",
"the",
"client",
"that",
"made",
"the",
"request"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L185-L197
|
train
|
docker/distribution
|
registry/storage/driver/middleware/cloudfront/s3filter.go
|
eligibleForS3
|
func eligibleForS3(ctx context.Context, awsIPs *awsIPs) bool {
if awsIPs != nil && awsIPs.initialized {
if addr, err := parseIPFromRequest(ctx); err == nil {
request, err := dcontext.GetRequest(ctx)
if err != nil {
dcontext.GetLogger(ctx).Warnf("the CloudFront middleware cannot parse the request: %s", err)
} else {
loggerField := map[interface{}]interface{}{
"user-client": request.UserAgent(),
"ip": dcontext.RemoteIP(request),
}
if awsIPs.contains(addr) {
dcontext.GetLoggerWithFields(ctx, loggerField).Info("request from the allowed AWS region, skipping CloudFront")
return true
}
dcontext.GetLoggerWithFields(ctx, loggerField).Warn("request not from the allowed AWS region, fallback to CloudFront")
}
} else {
dcontext.GetLogger(ctx).WithError(err).Warn("failed to parse ip address from context, fallback to CloudFront")
}
}
return false
}
|
go
|
func eligibleForS3(ctx context.Context, awsIPs *awsIPs) bool {
if awsIPs != nil && awsIPs.initialized {
if addr, err := parseIPFromRequest(ctx); err == nil {
request, err := dcontext.GetRequest(ctx)
if err != nil {
dcontext.GetLogger(ctx).Warnf("the CloudFront middleware cannot parse the request: %s", err)
} else {
loggerField := map[interface{}]interface{}{
"user-client": request.UserAgent(),
"ip": dcontext.RemoteIP(request),
}
if awsIPs.contains(addr) {
dcontext.GetLoggerWithFields(ctx, loggerField).Info("request from the allowed AWS region, skipping CloudFront")
return true
}
dcontext.GetLoggerWithFields(ctx, loggerField).Warn("request not from the allowed AWS region, fallback to CloudFront")
}
} else {
dcontext.GetLogger(ctx).WithError(err).Warn("failed to parse ip address from context, fallback to CloudFront")
}
}
return false
}
|
[
"func",
"eligibleForS3",
"(",
"ctx",
"context",
".",
"Context",
",",
"awsIPs",
"*",
"awsIPs",
")",
"bool",
"{",
"if",
"awsIPs",
"!=",
"nil",
"&&",
"awsIPs",
".",
"initialized",
"{",
"if",
"addr",
",",
"err",
":=",
"parseIPFromRequest",
"(",
"ctx",
")",
";",
"err",
"==",
"nil",
"{",
"request",
",",
"err",
":=",
"dcontext",
".",
"GetRequest",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"loggerField",
":=",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"request",
".",
"UserAgent",
"(",
")",
",",
"\"",
"\"",
":",
"dcontext",
".",
"RemoteIP",
"(",
"request",
")",
",",
"}",
"\n",
"if",
"awsIPs",
".",
"contains",
"(",
"addr",
")",
"{",
"dcontext",
".",
"GetLoggerWithFields",
"(",
"ctx",
",",
"loggerField",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"dcontext",
".",
"GetLoggerWithFields",
"(",
"ctx",
",",
"loggerField",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// eligibleForS3 checks if a request is eligible for using S3 directly
// Return true only when the IP belongs to a specific aws region and user-agent is docker
|
[
"eligibleForS3",
"checks",
"if",
"a",
"request",
"is",
"eligible",
"for",
"using",
"S3",
"directly",
"Return",
"true",
"only",
"when",
"the",
"IP",
"belongs",
"to",
"a",
"specific",
"aws",
"region",
"and",
"user",
"-",
"agent",
"is",
"docker"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/cloudfront/s3filter.go#L201-L223
|
train
|
docker/distribution
|
registry/storage/cache/redis/redis.go
|
RepositoryScoped
|
func (rbds *redisBlobDescriptorService) RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) {
if _, err := reference.ParseNormalizedNamed(repo); err != nil {
return nil, err
}
return &repositoryScopedRedisBlobDescriptorService{
repo: repo,
upstream: rbds,
}, nil
}
|
go
|
func (rbds *redisBlobDescriptorService) RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) {
if _, err := reference.ParseNormalizedNamed(repo); err != nil {
return nil, err
}
return &repositoryScopedRedisBlobDescriptorService{
repo: repo,
upstream: rbds,
}, nil
}
|
[
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"RepositoryScoped",
"(",
"repo",
"string",
")",
"(",
"distribution",
".",
"BlobDescriptorService",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"reference",
".",
"ParseNormalizedNamed",
"(",
"repo",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"repositoryScopedRedisBlobDescriptorService",
"{",
"repo",
":",
"repo",
",",
"upstream",
":",
"rbds",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// RepositoryScoped returns the scoped cache.
|
[
"RepositoryScoped",
"returns",
"the",
"scoped",
"cache",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L43-L52
|
train
|
docker/distribution
|
registry/storage/cache/redis/redis.go
|
Stat
|
func (rbds *redisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.stat(ctx, conn, dgst)
}
|
go
|
func (rbds *redisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.stat(ctx, conn, dgst)
}
|
[
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"Stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"if",
"err",
":=",
"dgst",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"conn",
":=",
"rbds",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"return",
"rbds",
".",
"stat",
"(",
"ctx",
",",
"conn",
",",
"dgst",
")",
"\n",
"}"
] |
// Stat retrieves the descriptor data from the redis hash entry.
|
[
"Stat",
"retrieves",
"the",
"descriptor",
"data",
"from",
"the",
"redis",
"hash",
"entry",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L55-L64
|
train
|
docker/distribution
|
registry/storage/cache/redis/redis.go
|
stat
|
func (rbds *redisBlobDescriptorService) stat(ctx context.Context, conn redis.Conn, dgst digest.Digest) (distribution.Descriptor, error) {
reply, err := redis.Values(conn.Do("HMGET", rbds.blobDescriptorHashKey(dgst), "digest", "size", "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
// NOTE(stevvooe): The "size" field used to be "length". We treat a
// missing "size" field here as an unknown blob, which causes a cache
// miss, effectively migrating the field.
if len(reply) < 3 || reply[0] == nil || reply[1] == nil { // don't care if mediatype is nil
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
var desc distribution.Descriptor
if _, err := redis.Scan(reply, &desc.Digest, &desc.Size, &desc.MediaType); err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
|
go
|
func (rbds *redisBlobDescriptorService) stat(ctx context.Context, conn redis.Conn, dgst digest.Digest) (distribution.Descriptor, error) {
reply, err := redis.Values(conn.Do("HMGET", rbds.blobDescriptorHashKey(dgst), "digest", "size", "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
// NOTE(stevvooe): The "size" field used to be "length". We treat a
// missing "size" field here as an unknown blob, which causes a cache
// miss, effectively migrating the field.
if len(reply) < 3 || reply[0] == nil || reply[1] == nil { // don't care if mediatype is nil
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
var desc distribution.Descriptor
if _, err := redis.Scan(reply, &desc.Digest, &desc.Size, &desc.MediaType); err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
}
|
[
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"redis",
".",
"Conn",
",",
"dgst",
"digest",
".",
"Digest",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"reply",
",",
"err",
":=",
"redis",
".",
"Values",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"rbds",
".",
"blobDescriptorHashKey",
"(",
"dgst",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// NOTE(stevvooe): The \"size\" field used to be \"length\". We treat a",
"// missing \"size\" field here as an unknown blob, which causes a cache",
"// miss, effectively migrating the field.",
"if",
"len",
"(",
"reply",
")",
"<",
"3",
"||",
"reply",
"[",
"0",
"]",
"==",
"nil",
"||",
"reply",
"[",
"1",
"]",
"==",
"nil",
"{",
"// don't care if mediatype is nil",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"distribution",
".",
"ErrBlobUnknown",
"\n",
"}",
"\n\n",
"var",
"desc",
"distribution",
".",
"Descriptor",
"\n",
"if",
"_",
",",
"err",
":=",
"redis",
".",
"Scan",
"(",
"reply",
",",
"&",
"desc",
".",
"Digest",
",",
"&",
"desc",
".",
"Size",
",",
"&",
"desc",
".",
"MediaType",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"desc",
",",
"nil",
"\n",
"}"
] |
// stat provides an internal stat call that takes a connection parameter. This
// allows some internal management of the connection scope.
|
[
"stat",
"provides",
"an",
"internal",
"stat",
"call",
"that",
"takes",
"a",
"connection",
"parameter",
".",
"This",
"allows",
"some",
"internal",
"management",
"of",
"the",
"connection",
"scope",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L89-L108
|
train
|
docker/distribution
|
registry/storage/cache/redis/redis.go
|
SetDescriptor
|
func (rbds *redisBlobDescriptorService) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
if err := dgst.Validate(); err != nil {
return err
}
if err := cache.ValidateDescriptor(desc); err != nil {
return err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.setDescriptor(ctx, conn, dgst, desc)
}
|
go
|
func (rbds *redisBlobDescriptorService) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
if err := dgst.Validate(); err != nil {
return err
}
if err := cache.ValidateDescriptor(desc); err != nil {
return err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.setDescriptor(ctx, conn, dgst, desc)
}
|
[
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"SetDescriptor",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"error",
"{",
"if",
"err",
":=",
"dgst",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"cache",
".",
"ValidateDescriptor",
"(",
"desc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"conn",
":=",
"rbds",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"return",
"rbds",
".",
"setDescriptor",
"(",
"ctx",
",",
"conn",
",",
"dgst",
",",
"desc",
")",
"\n",
"}"
] |
// SetDescriptor sets the descriptor data for the given digest using a redis
// hash. A hash is used here since we may store unrelated fields about a layer
// in the future.
|
[
"SetDescriptor",
"sets",
"the",
"descriptor",
"data",
"for",
"the",
"given",
"digest",
"using",
"a",
"redis",
"hash",
".",
"A",
"hash",
"is",
"used",
"here",
"since",
"we",
"may",
"store",
"unrelated",
"fields",
"about",
"a",
"layer",
"in",
"the",
"future",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L113-L126
|
train
|
docker/distribution
|
registry/storage/cache/redis/redis.go
|
Stat
|
func (rsrbds *repositoryScopedRedisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return distribution.Descriptor{}, err
}
if !member {
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
upstream, err := rsrbds.upstream.stat(ctx, conn, dgst)
if err != nil {
return distribution.Descriptor{}, err
}
// We allow a per repository mediatype, let's look it up here.
mediatype, err := redis.String(conn.Do("HGET", rsrbds.blobDescriptorHashKey(dgst), "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
if mediatype != "" {
upstream.MediaType = mediatype
}
return upstream, nil
}
|
go
|
func (rsrbds *repositoryScopedRedisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return distribution.Descriptor{}, err
}
if !member {
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
upstream, err := rsrbds.upstream.stat(ctx, conn, dgst)
if err != nil {
return distribution.Descriptor{}, err
}
// We allow a per repository mediatype, let's look it up here.
mediatype, err := redis.String(conn.Do("HGET", rsrbds.blobDescriptorHashKey(dgst), "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
if mediatype != "" {
upstream.MediaType = mediatype
}
return upstream, nil
}
|
[
"func",
"(",
"rsrbds",
"*",
"repositoryScopedRedisBlobDescriptorService",
")",
"Stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"if",
"err",
":=",
"dgst",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"conn",
":=",
"rsrbds",
".",
"upstream",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"// Check membership to repository first",
"member",
",",
"err",
":=",
"redis",
".",
"Bool",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"rsrbds",
".",
"repositoryBlobSetKey",
"(",
"rsrbds",
".",
"repo",
")",
",",
"dgst",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"member",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"distribution",
".",
"ErrBlobUnknown",
"\n",
"}",
"\n\n",
"upstream",
",",
"err",
":=",
"rsrbds",
".",
"upstream",
".",
"stat",
"(",
"ctx",
",",
"conn",
",",
"dgst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// We allow a per repository mediatype, let's look it up here.",
"mediatype",
",",
"err",
":=",
"redis",
".",
"String",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"rsrbds",
".",
"blobDescriptorHashKey",
"(",
"dgst",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"mediatype",
"!=",
"\"",
"\"",
"{",
"upstream",
".",
"MediaType",
"=",
"mediatype",
"\n",
"}",
"\n\n",
"return",
"upstream",
",",
"nil",
"\n",
"}"
] |
// Stat ensures that the digest is a member of the specified repository and
// forwards the descriptor request to the global blob store. If the media type
// differs for the repository, we override it.
|
[
"Stat",
"ensures",
"that",
"the",
"digest",
"is",
"a",
"member",
"of",
"the",
"specified",
"repository",
"and",
"forwards",
"the",
"descriptor",
"request",
"to",
"the",
"global",
"blob",
"store",
".",
"If",
"the",
"media",
"type",
"differs",
"for",
"the",
"repository",
"we",
"override",
"it",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L158-L192
|
train
|
docker/distribution
|
registry/storage/cache/redis/redis.go
|
Clear
|
func (rsrbds *repositoryScopedRedisBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
if err := dgst.Validate(); err != nil {
return err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return err
}
if !member {
return distribution.ErrBlobUnknown
}
return rsrbds.upstream.Clear(ctx, dgst)
}
|
go
|
func (rsrbds *repositoryScopedRedisBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
if err := dgst.Validate(); err != nil {
return err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return err
}
if !member {
return distribution.ErrBlobUnknown
}
return rsrbds.upstream.Clear(ctx, dgst)
}
|
[
"func",
"(",
"rsrbds",
"*",
"repositoryScopedRedisBlobDescriptorService",
")",
"Clear",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"error",
"{",
"if",
"err",
":=",
"dgst",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"conn",
":=",
"rsrbds",
".",
"upstream",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"// Check membership to repository first",
"member",
",",
"err",
":=",
"redis",
".",
"Bool",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"rsrbds",
".",
"repositoryBlobSetKey",
"(",
"rsrbds",
".",
"repo",
")",
",",
"dgst",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"member",
"{",
"return",
"distribution",
".",
"ErrBlobUnknown",
"\n",
"}",
"\n\n",
"return",
"rsrbds",
".",
"upstream",
".",
"Clear",
"(",
"ctx",
",",
"dgst",
")",
"\n",
"}"
] |
// Clear removes the descriptor from the cache and forwards to the upstream descriptor store
|
[
"Clear",
"removes",
"the",
"descriptor",
"from",
"the",
"cache",
"and",
"forwards",
"to",
"the",
"upstream",
"descriptor",
"store"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L195-L214
|
train
|
docker/distribution
|
registry/handlers/catalog.go
|
createLinkEntry
|
func createLinkEntry(origURL string, maxEntries int, lastEntry string) (string, error) {
calledURL, err := url.Parse(origURL)
if err != nil {
return "", err
}
v := url.Values{}
v.Add("n", strconv.Itoa(maxEntries))
v.Add("last", lastEntry)
calledURL.RawQuery = v.Encode()
calledURL.Fragment = ""
urlStr := fmt.Sprintf("<%s>; rel=\"next\"", calledURL.String())
return urlStr, nil
}
|
go
|
func createLinkEntry(origURL string, maxEntries int, lastEntry string) (string, error) {
calledURL, err := url.Parse(origURL)
if err != nil {
return "", err
}
v := url.Values{}
v.Add("n", strconv.Itoa(maxEntries))
v.Add("last", lastEntry)
calledURL.RawQuery = v.Encode()
calledURL.Fragment = ""
urlStr := fmt.Sprintf("<%s>; rel=\"next\"", calledURL.String())
return urlStr, nil
}
|
[
"func",
"createLinkEntry",
"(",
"origURL",
"string",
",",
"maxEntries",
"int",
",",
"lastEntry",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"calledURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"origURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"v",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"v",
".",
"Add",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"maxEntries",
")",
")",
"\n",
"v",
".",
"Add",
"(",
"\"",
"\"",
",",
"lastEntry",
")",
"\n\n",
"calledURL",
".",
"RawQuery",
"=",
"v",
".",
"Encode",
"(",
")",
"\n\n",
"calledURL",
".",
"Fragment",
"=",
"\"",
"\"",
"\n",
"urlStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"calledURL",
".",
"String",
"(",
")",
")",
"\n\n",
"return",
"urlStr",
",",
"nil",
"\n",
"}"
] |
// Use the original URL from the request to create a new URL for
// the link header
|
[
"Use",
"the",
"original",
"URL",
"from",
"the",
"request",
"to",
"create",
"a",
"new",
"URL",
"for",
"the",
"link",
"header"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/catalog.go#L82-L98
|
train
|
docker/distribution
|
contrib/token-server/main.go
|
handlerWithContext
|
func handlerWithContext(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := dcontext.WithRequest(ctx, r)
logger := dcontext.GetRequestLogger(ctx)
ctx = dcontext.WithLogger(ctx, logger)
handler(ctx, w, r)
})
}
|
go
|
func handlerWithContext(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := dcontext.WithRequest(ctx, r)
logger := dcontext.GetRequestLogger(ctx)
ctx = dcontext.WithLogger(ctx, logger)
handler(ctx, w, r)
})
}
|
[
"func",
"handlerWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"handler",
"func",
"(",
"context",
".",
"Context",
",",
"http",
".",
"ResponseWriter",
",",
"*",
"http",
".",
"Request",
")",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"ctx",
":=",
"dcontext",
".",
"WithRequest",
"(",
"ctx",
",",
"r",
")",
"\n",
"logger",
":=",
"dcontext",
".",
"GetRequestLogger",
"(",
"ctx",
")",
"\n",
"ctx",
"=",
"dcontext",
".",
"WithLogger",
"(",
"ctx",
",",
"logger",
")",
"\n\n",
"handler",
"(",
"ctx",
",",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// handlerWithContext wraps the given context-aware handler by setting up the
// request context from a base context.
|
[
"handlerWithContext",
"wraps",
"the",
"given",
"context",
"-",
"aware",
"handler",
"by",
"setting",
"up",
"the",
"request",
"context",
"from",
"a",
"base",
"context",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/contrib/token-server/main.go#L117-L125
|
train
|
docker/distribution
|
registry/handlers/app.go
|
register
|
func (app *App) register(routeName string, dispatch dispatchFunc) {
handler := app.dispatcher(dispatch)
// Chain the handler with prometheus instrumented handler
if app.Config.HTTP.Debug.Prometheus.Enabled {
namespace := metrics.NewNamespace(prometheus.NamespacePrefix, "http", nil)
httpMetrics := namespace.NewDefaultHttpMetrics(strings.Replace(routeName, "-", "_", -1))
metrics.Register(namespace)
handler = metrics.InstrumentHandler(httpMetrics, handler)
}
// TODO(stevvooe): This odd dispatcher/route registration is by-product of
// some limitations in the gorilla/mux router. We are using it to keep
// routing consistent between the client and server, but we may want to
// replace it with manual routing and structure-based dispatch for better
// control over the request execution.
app.router.GetRoute(routeName).Handler(handler)
}
|
go
|
func (app *App) register(routeName string, dispatch dispatchFunc) {
handler := app.dispatcher(dispatch)
// Chain the handler with prometheus instrumented handler
if app.Config.HTTP.Debug.Prometheus.Enabled {
namespace := metrics.NewNamespace(prometheus.NamespacePrefix, "http", nil)
httpMetrics := namespace.NewDefaultHttpMetrics(strings.Replace(routeName, "-", "_", -1))
metrics.Register(namespace)
handler = metrics.InstrumentHandler(httpMetrics, handler)
}
// TODO(stevvooe): This odd dispatcher/route registration is by-product of
// some limitations in the gorilla/mux router. We are using it to keep
// routing consistent between the client and server, but we may want to
// replace it with manual routing and structure-based dispatch for better
// control over the request execution.
app.router.GetRoute(routeName).Handler(handler)
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"register",
"(",
"routeName",
"string",
",",
"dispatch",
"dispatchFunc",
")",
"{",
"handler",
":=",
"app",
".",
"dispatcher",
"(",
"dispatch",
")",
"\n\n",
"// Chain the handler with prometheus instrumented handler",
"if",
"app",
".",
"Config",
".",
"HTTP",
".",
"Debug",
".",
"Prometheus",
".",
"Enabled",
"{",
"namespace",
":=",
"metrics",
".",
"NewNamespace",
"(",
"prometheus",
".",
"NamespacePrefix",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"httpMetrics",
":=",
"namespace",
".",
"NewDefaultHttpMetrics",
"(",
"strings",
".",
"Replace",
"(",
"routeName",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
")",
"\n",
"metrics",
".",
"Register",
"(",
"namespace",
")",
"\n",
"handler",
"=",
"metrics",
".",
"InstrumentHandler",
"(",
"httpMetrics",
",",
"handler",
")",
"\n",
"}",
"\n\n",
"// TODO(stevvooe): This odd dispatcher/route registration is by-product of",
"// some limitations in the gorilla/mux router. We are using it to keep",
"// routing consistent between the client and server, but we may want to",
"// replace it with manual routing and structure-based dispatch for better",
"// control over the request execution.",
"app",
".",
"router",
".",
"GetRoute",
"(",
"routeName",
")",
".",
"Handler",
"(",
"handler",
")",
"\n",
"}"
] |
// register a handler with the application, by route name. The handler will be
// passed through the application filters and context will be constructed at
// request time.
|
[
"register",
"a",
"handler",
"with",
"the",
"application",
"by",
"route",
"name",
".",
"The",
"handler",
"will",
"be",
"passed",
"through",
"the",
"application",
"filters",
"and",
"context",
"will",
"be",
"constructed",
"at",
"request",
"time",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L426-L444
|
train
|
docker/distribution
|
registry/handlers/app.go
|
configureEvents
|
func (app *App) configureEvents(configuration *configuration.Configuration) {
// Configure all of the endpoint sinks.
var sinks []notifications.Sink
for _, endpoint := range configuration.Notifications.Endpoints {
if endpoint.Disabled {
dcontext.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name)
continue
}
dcontext.GetLogger(app).Infof("configuring endpoint %v (%v), timeout=%s, headers=%v", endpoint.Name, endpoint.URL, endpoint.Timeout, endpoint.Headers)
endpoint := notifications.NewEndpoint(endpoint.Name, endpoint.URL, notifications.EndpointConfig{
Timeout: endpoint.Timeout,
Threshold: endpoint.Threshold,
Backoff: endpoint.Backoff,
Headers: endpoint.Headers,
IgnoredMediaTypes: endpoint.IgnoredMediaTypes,
Ignore: endpoint.Ignore,
})
sinks = append(sinks, endpoint)
}
// NOTE(stevvooe): Moving to a new queuing implementation is as easy as
// replacing broadcaster with a rabbitmq implementation. It's recommended
// that the registry instances also act as the workers to keep deployment
// simple.
app.events.sink = notifications.NewBroadcaster(sinks...)
// Populate registry event source
hostname, err := os.Hostname()
if err != nil {
hostname = configuration.HTTP.Addr
} else {
// try to pick the port off the config
_, port, err := net.SplitHostPort(configuration.HTTP.Addr)
if err == nil {
hostname = net.JoinHostPort(hostname, port)
}
}
app.events.source = notifications.SourceRecord{
Addr: hostname,
InstanceID: dcontext.GetStringValue(app, "instance.id"),
}
}
|
go
|
func (app *App) configureEvents(configuration *configuration.Configuration) {
// Configure all of the endpoint sinks.
var sinks []notifications.Sink
for _, endpoint := range configuration.Notifications.Endpoints {
if endpoint.Disabled {
dcontext.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name)
continue
}
dcontext.GetLogger(app).Infof("configuring endpoint %v (%v), timeout=%s, headers=%v", endpoint.Name, endpoint.URL, endpoint.Timeout, endpoint.Headers)
endpoint := notifications.NewEndpoint(endpoint.Name, endpoint.URL, notifications.EndpointConfig{
Timeout: endpoint.Timeout,
Threshold: endpoint.Threshold,
Backoff: endpoint.Backoff,
Headers: endpoint.Headers,
IgnoredMediaTypes: endpoint.IgnoredMediaTypes,
Ignore: endpoint.Ignore,
})
sinks = append(sinks, endpoint)
}
// NOTE(stevvooe): Moving to a new queuing implementation is as easy as
// replacing broadcaster with a rabbitmq implementation. It's recommended
// that the registry instances also act as the workers to keep deployment
// simple.
app.events.sink = notifications.NewBroadcaster(sinks...)
// Populate registry event source
hostname, err := os.Hostname()
if err != nil {
hostname = configuration.HTTP.Addr
} else {
// try to pick the port off the config
_, port, err := net.SplitHostPort(configuration.HTTP.Addr)
if err == nil {
hostname = net.JoinHostPort(hostname, port)
}
}
app.events.source = notifications.SourceRecord{
Addr: hostname,
InstanceID: dcontext.GetStringValue(app, "instance.id"),
}
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"configureEvents",
"(",
"configuration",
"*",
"configuration",
".",
"Configuration",
")",
"{",
"// Configure all of the endpoint sinks.",
"var",
"sinks",
"[",
"]",
"notifications",
".",
"Sink",
"\n",
"for",
"_",
",",
"endpoint",
":=",
"range",
"configuration",
".",
"Notifications",
".",
"Endpoints",
"{",
"if",
"endpoint",
".",
"Disabled",
"{",
"dcontext",
".",
"GetLogger",
"(",
"app",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"endpoint",
".",
"Name",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"dcontext",
".",
"GetLogger",
"(",
"app",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"endpoint",
".",
"Name",
",",
"endpoint",
".",
"URL",
",",
"endpoint",
".",
"Timeout",
",",
"endpoint",
".",
"Headers",
")",
"\n",
"endpoint",
":=",
"notifications",
".",
"NewEndpoint",
"(",
"endpoint",
".",
"Name",
",",
"endpoint",
".",
"URL",
",",
"notifications",
".",
"EndpointConfig",
"{",
"Timeout",
":",
"endpoint",
".",
"Timeout",
",",
"Threshold",
":",
"endpoint",
".",
"Threshold",
",",
"Backoff",
":",
"endpoint",
".",
"Backoff",
",",
"Headers",
":",
"endpoint",
".",
"Headers",
",",
"IgnoredMediaTypes",
":",
"endpoint",
".",
"IgnoredMediaTypes",
",",
"Ignore",
":",
"endpoint",
".",
"Ignore",
",",
"}",
")",
"\n\n",
"sinks",
"=",
"append",
"(",
"sinks",
",",
"endpoint",
")",
"\n",
"}",
"\n\n",
"// NOTE(stevvooe): Moving to a new queuing implementation is as easy as",
"// replacing broadcaster with a rabbitmq implementation. It's recommended",
"// that the registry instances also act as the workers to keep deployment",
"// simple.",
"app",
".",
"events",
".",
"sink",
"=",
"notifications",
".",
"NewBroadcaster",
"(",
"sinks",
"...",
")",
"\n\n",
"// Populate registry event source",
"hostname",
",",
"err",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"hostname",
"=",
"configuration",
".",
"HTTP",
".",
"Addr",
"\n",
"}",
"else",
"{",
"// try to pick the port off the config",
"_",
",",
"port",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"configuration",
".",
"HTTP",
".",
"Addr",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"hostname",
"=",
"net",
".",
"JoinHostPort",
"(",
"hostname",
",",
"port",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"app",
".",
"events",
".",
"source",
"=",
"notifications",
".",
"SourceRecord",
"{",
"Addr",
":",
"hostname",
",",
"InstanceID",
":",
"dcontext",
".",
"GetStringValue",
"(",
"app",
",",
"\"",
"\"",
")",
",",
"}",
"\n",
"}"
] |
// configureEvents prepares the event sink for action.
|
[
"configureEvents",
"prepares",
"the",
"event",
"sink",
"for",
"action",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L447-L491
|
train
|
docker/distribution
|
registry/handlers/app.go
|
configureLogHook
|
func (app *App) configureLogHook(configuration *configuration.Configuration) {
entry, ok := dcontext.GetLogger(app).(*logrus.Entry)
if !ok {
// somehow, we are not using logrus
return
}
logger := entry.Logger
for _, configHook := range configuration.Log.Hooks {
if !configHook.Disabled {
switch configHook.Type {
case "mail":
hook := &logHook{}
hook.LevelsParam = configHook.Levels
hook.Mail = &mailer{
Addr: configHook.MailOptions.SMTP.Addr,
Username: configHook.MailOptions.SMTP.Username,
Password: configHook.MailOptions.SMTP.Password,
Insecure: configHook.MailOptions.SMTP.Insecure,
From: configHook.MailOptions.From,
To: configHook.MailOptions.To,
}
logger.Hooks.Add(hook)
default:
}
}
}
}
|
go
|
func (app *App) configureLogHook(configuration *configuration.Configuration) {
entry, ok := dcontext.GetLogger(app).(*logrus.Entry)
if !ok {
// somehow, we are not using logrus
return
}
logger := entry.Logger
for _, configHook := range configuration.Log.Hooks {
if !configHook.Disabled {
switch configHook.Type {
case "mail":
hook := &logHook{}
hook.LevelsParam = configHook.Levels
hook.Mail = &mailer{
Addr: configHook.MailOptions.SMTP.Addr,
Username: configHook.MailOptions.SMTP.Username,
Password: configHook.MailOptions.SMTP.Password,
Insecure: configHook.MailOptions.SMTP.Insecure,
From: configHook.MailOptions.From,
To: configHook.MailOptions.To,
}
logger.Hooks.Add(hook)
default:
}
}
}
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"configureLogHook",
"(",
"configuration",
"*",
"configuration",
".",
"Configuration",
")",
"{",
"entry",
",",
"ok",
":=",
"dcontext",
".",
"GetLogger",
"(",
"app",
")",
".",
"(",
"*",
"logrus",
".",
"Entry",
")",
"\n",
"if",
"!",
"ok",
"{",
"// somehow, we are not using logrus",
"return",
"\n",
"}",
"\n\n",
"logger",
":=",
"entry",
".",
"Logger",
"\n\n",
"for",
"_",
",",
"configHook",
":=",
"range",
"configuration",
".",
"Log",
".",
"Hooks",
"{",
"if",
"!",
"configHook",
".",
"Disabled",
"{",
"switch",
"configHook",
".",
"Type",
"{",
"case",
"\"",
"\"",
":",
"hook",
":=",
"&",
"logHook",
"{",
"}",
"\n",
"hook",
".",
"LevelsParam",
"=",
"configHook",
".",
"Levels",
"\n",
"hook",
".",
"Mail",
"=",
"&",
"mailer",
"{",
"Addr",
":",
"configHook",
".",
"MailOptions",
".",
"SMTP",
".",
"Addr",
",",
"Username",
":",
"configHook",
".",
"MailOptions",
".",
"SMTP",
".",
"Username",
",",
"Password",
":",
"configHook",
".",
"MailOptions",
".",
"SMTP",
".",
"Password",
",",
"Insecure",
":",
"configHook",
".",
"MailOptions",
".",
"SMTP",
".",
"Insecure",
",",
"From",
":",
"configHook",
".",
"MailOptions",
".",
"From",
",",
"To",
":",
"configHook",
".",
"MailOptions",
".",
"To",
",",
"}",
"\n",
"logger",
".",
"Hooks",
".",
"Add",
"(",
"hook",
")",
"\n",
"default",
":",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// configureLogHook prepares logging hook parameters.
|
[
"configureLogHook",
"prepares",
"logging",
"hook",
"parameters",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L578-L606
|
train
|
docker/distribution
|
registry/handlers/app.go
|
configureSecret
|
func (app *App) configureSecret(configuration *configuration.Configuration) {
if configuration.HTTP.Secret == "" {
var secretBytes [randomSecretSize]byte
if _, err := cryptorand.Read(secretBytes[:]); err != nil {
panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err))
}
configuration.HTTP.Secret = string(secretBytes[:])
dcontext.GetLogger(app).Warn("No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable.")
}
}
|
go
|
func (app *App) configureSecret(configuration *configuration.Configuration) {
if configuration.HTTP.Secret == "" {
var secretBytes [randomSecretSize]byte
if _, err := cryptorand.Read(secretBytes[:]); err != nil {
panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err))
}
configuration.HTTP.Secret = string(secretBytes[:])
dcontext.GetLogger(app).Warn("No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable.")
}
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"configureSecret",
"(",
"configuration",
"*",
"configuration",
".",
"Configuration",
")",
"{",
"if",
"configuration",
".",
"HTTP",
".",
"Secret",
"==",
"\"",
"\"",
"{",
"var",
"secretBytes",
"[",
"randomSecretSize",
"]",
"byte",
"\n",
"if",
"_",
",",
"err",
":=",
"cryptorand",
".",
"Read",
"(",
"secretBytes",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"configuration",
".",
"HTTP",
".",
"Secret",
"=",
"string",
"(",
"secretBytes",
"[",
":",
"]",
")",
"\n",
"dcontext",
".",
"GetLogger",
"(",
"app",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] |
// configureSecret creates a random secret if a secret wasn't included in the
// configuration.
|
[
"configureSecret",
"creates",
"a",
"random",
"secret",
"if",
"a",
"secret",
"wasn",
"t",
"included",
"in",
"the",
"configuration",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L610-L619
|
train
|
docker/distribution
|
registry/handlers/app.go
|
context
|
func (app *App) context(w http.ResponseWriter, r *http.Request) *Context {
ctx := r.Context()
ctx = dcontext.WithVars(ctx, r)
ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx,
"vars.name",
"vars.reference",
"vars.digest",
"vars.uuid"))
context := &Context{
App: app,
Context: ctx,
}
if app.httpHost.Scheme != "" && app.httpHost.Host != "" {
// A "host" item in the configuration takes precedence over
// X-Forwarded-Proto and X-Forwarded-Host headers, and the
// hostname in the request.
context.urlBuilder = v2.NewURLBuilder(&app.httpHost, false)
} else {
context.urlBuilder = v2.NewURLBuilderFromRequest(r, app.Config.HTTP.RelativeURLs)
}
return context
}
|
go
|
func (app *App) context(w http.ResponseWriter, r *http.Request) *Context {
ctx := r.Context()
ctx = dcontext.WithVars(ctx, r)
ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx,
"vars.name",
"vars.reference",
"vars.digest",
"vars.uuid"))
context := &Context{
App: app,
Context: ctx,
}
if app.httpHost.Scheme != "" && app.httpHost.Host != "" {
// A "host" item in the configuration takes precedence over
// X-Forwarded-Proto and X-Forwarded-Host headers, and the
// hostname in the request.
context.urlBuilder = v2.NewURLBuilder(&app.httpHost, false)
} else {
context.urlBuilder = v2.NewURLBuilderFromRequest(r, app.Config.HTTP.RelativeURLs)
}
return context
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"context",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"Context",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"ctx",
"=",
"dcontext",
".",
"WithVars",
"(",
"ctx",
",",
"r",
")",
"\n",
"ctx",
"=",
"dcontext",
".",
"WithLogger",
"(",
"ctx",
",",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
")",
"\n\n",
"context",
":=",
"&",
"Context",
"{",
"App",
":",
"app",
",",
"Context",
":",
"ctx",
",",
"}",
"\n\n",
"if",
"app",
".",
"httpHost",
".",
"Scheme",
"!=",
"\"",
"\"",
"&&",
"app",
".",
"httpHost",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"// A \"host\" item in the configuration takes precedence over",
"// X-Forwarded-Proto and X-Forwarded-Host headers, and the",
"// hostname in the request.",
"context",
".",
"urlBuilder",
"=",
"v2",
".",
"NewURLBuilder",
"(",
"&",
"app",
".",
"httpHost",
",",
"false",
")",
"\n",
"}",
"else",
"{",
"context",
".",
"urlBuilder",
"=",
"v2",
".",
"NewURLBuilderFromRequest",
"(",
"r",
",",
"app",
".",
"Config",
".",
"HTTP",
".",
"RelativeURLs",
")",
"\n",
"}",
"\n\n",
"return",
"context",
"\n",
"}"
] |
// context constructs the context object for the application. This only be
// called once per request.
|
[
"context",
"constructs",
"the",
"context",
"object",
"for",
"the",
"application",
".",
"This",
"only",
"be",
"called",
"once",
"per",
"request",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L780-L804
|
train
|
docker/distribution
|
registry/handlers/app.go
|
authorized
|
func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Context) error {
dcontext.GetLogger(context).Debug("authorizing request")
repo := getName(context)
if app.accessController == nil {
return nil // access controller is not enabled.
}
var accessRecords []auth.Access
if repo != "" {
accessRecords = appendAccessRecords(accessRecords, r.Method, repo)
if fromRepo := r.FormValue("from"); fromRepo != "" {
// mounting a blob from one repository to another requires pull (GET)
// access to the source repository.
accessRecords = appendAccessRecords(accessRecords, "GET", fromRepo)
}
} else {
// Only allow the name not to be set on the base route.
if app.nameRequired(r) {
// For this to be properly secured, repo must always be set for a
// resource that may make a modification. The only condition under
// which name is not set and we still allow access is when the
// base route is accessed. This section prevents us from making
// that mistake elsewhere in the code, allowing any operation to
// proceed.
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
return fmt.Errorf("forbidden: no repository name")
}
accessRecords = appendCatalogAccessRecord(accessRecords, r)
}
ctx, err := app.accessController.Authorized(context.Context, accessRecords...)
if err != nil {
switch err := err.(type) {
case auth.Challenge:
// Add the appropriate WWW-Auth header
err.SetHeaders(r, w)
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized.WithDetail(accessRecords)); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
default:
// This condition is a potential security problem either in
// the configuration or whatever is backing the access
// controller. Just return a bad request with no information
// to avoid exposure. The request should not proceed.
dcontext.GetLogger(context).Errorf("error checking authorization: %v", err)
w.WriteHeader(http.StatusBadRequest)
}
return err
}
dcontext.GetLogger(ctx, auth.UserNameKey).Info("authorized request")
// TODO(stevvooe): This pattern needs to be cleaned up a bit. One context
// should be replaced by another, rather than replacing the context on a
// mutable object.
context.Context = ctx
return nil
}
|
go
|
func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Context) error {
dcontext.GetLogger(context).Debug("authorizing request")
repo := getName(context)
if app.accessController == nil {
return nil // access controller is not enabled.
}
var accessRecords []auth.Access
if repo != "" {
accessRecords = appendAccessRecords(accessRecords, r.Method, repo)
if fromRepo := r.FormValue("from"); fromRepo != "" {
// mounting a blob from one repository to another requires pull (GET)
// access to the source repository.
accessRecords = appendAccessRecords(accessRecords, "GET", fromRepo)
}
} else {
// Only allow the name not to be set on the base route.
if app.nameRequired(r) {
// For this to be properly secured, repo must always be set for a
// resource that may make a modification. The only condition under
// which name is not set and we still allow access is when the
// base route is accessed. This section prevents us from making
// that mistake elsewhere in the code, allowing any operation to
// proceed.
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
return fmt.Errorf("forbidden: no repository name")
}
accessRecords = appendCatalogAccessRecord(accessRecords, r)
}
ctx, err := app.accessController.Authorized(context.Context, accessRecords...)
if err != nil {
switch err := err.(type) {
case auth.Challenge:
// Add the appropriate WWW-Auth header
err.SetHeaders(r, w)
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized.WithDetail(accessRecords)); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
default:
// This condition is a potential security problem either in
// the configuration or whatever is backing the access
// controller. Just return a bad request with no information
// to avoid exposure. The request should not proceed.
dcontext.GetLogger(context).Errorf("error checking authorization: %v", err)
w.WriteHeader(http.StatusBadRequest)
}
return err
}
dcontext.GetLogger(ctx, auth.UserNameKey).Info("authorized request")
// TODO(stevvooe): This pattern needs to be cleaned up a bit. One context
// should be replaced by another, rather than replacing the context on a
// mutable object.
context.Context = ctx
return nil
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"authorized",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"context",
"*",
"Context",
")",
"error",
"{",
"dcontext",
".",
"GetLogger",
"(",
"context",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"repo",
":=",
"getName",
"(",
"context",
")",
"\n\n",
"if",
"app",
".",
"accessController",
"==",
"nil",
"{",
"return",
"nil",
"// access controller is not enabled.",
"\n",
"}",
"\n\n",
"var",
"accessRecords",
"[",
"]",
"auth",
".",
"Access",
"\n\n",
"if",
"repo",
"!=",
"\"",
"\"",
"{",
"accessRecords",
"=",
"appendAccessRecords",
"(",
"accessRecords",
",",
"r",
".",
"Method",
",",
"repo",
")",
"\n",
"if",
"fromRepo",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
";",
"fromRepo",
"!=",
"\"",
"\"",
"{",
"// mounting a blob from one repository to another requires pull (GET)",
"// access to the source repository.",
"accessRecords",
"=",
"appendAccessRecords",
"(",
"accessRecords",
",",
"\"",
"\"",
",",
"fromRepo",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Only allow the name not to be set on the base route.",
"if",
"app",
".",
"nameRequired",
"(",
"r",
")",
"{",
"// For this to be properly secured, repo must always be set for a",
"// resource that may make a modification. The only condition under",
"// which name is not set and we still allow access is when the",
"// base route is accessed. This section prevents us from making",
"// that mistake elsewhere in the code, allowing any operation to",
"// proceed.",
"if",
"err",
":=",
"errcode",
".",
"ServeJSON",
"(",
"w",
",",
"errcode",
".",
"ErrorCodeUnauthorized",
")",
";",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLogger",
"(",
"context",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"context",
".",
"Errors",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"accessRecords",
"=",
"appendCatalogAccessRecord",
"(",
"accessRecords",
",",
"r",
")",
"\n",
"}",
"\n\n",
"ctx",
",",
"err",
":=",
"app",
".",
"accessController",
".",
"Authorized",
"(",
"context",
".",
"Context",
",",
"accessRecords",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"auth",
".",
"Challenge",
":",
"// Add the appropriate WWW-Auth header",
"err",
".",
"SetHeaders",
"(",
"r",
",",
"w",
")",
"\n\n",
"if",
"err",
":=",
"errcode",
".",
"ServeJSON",
"(",
"w",
",",
"errcode",
".",
"ErrorCodeUnauthorized",
".",
"WithDetail",
"(",
"accessRecords",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLogger",
"(",
"context",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"context",
".",
"Errors",
")",
"\n",
"}",
"\n",
"default",
":",
"// This condition is a potential security problem either in",
"// the configuration or whatever is backing the access",
"// controller. Just return a bad request with no information",
"// to avoid exposure. The request should not proceed.",
"dcontext",
".",
"GetLogger",
"(",
"context",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}",
"\n\n",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
",",
"auth",
".",
"UserNameKey",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"// TODO(stevvooe): This pattern needs to be cleaned up a bit. One context",
"// should be replaced by another, rather than replacing the context on a",
"// mutable object.",
"context",
".",
"Context",
"=",
"ctx",
"\n",
"return",
"nil",
"\n",
"}"
] |
// authorized checks if the request can proceed with access to the requested
// repository. If it succeeds, the context may access the requested
// repository. An error will be returned if access is not available.
|
[
"authorized",
"checks",
"if",
"the",
"request",
"can",
"proceed",
"with",
"access",
"to",
"the",
"requested",
"repository",
".",
"If",
"it",
"succeeds",
"the",
"context",
"may",
"access",
"the",
"requested",
"repository",
".",
"An",
"error",
"will",
"be",
"returned",
"if",
"access",
"is",
"not",
"available",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L809-L871
|
train
|
docker/distribution
|
registry/handlers/app.go
|
eventBridge
|
func (app *App) eventBridge(ctx *Context, r *http.Request) notifications.Listener {
actor := notifications.ActorRecord{
Name: getUserName(ctx, r),
}
request := notifications.NewRequestRecord(dcontext.GetRequestID(ctx), r)
return notifications.NewBridge(ctx.urlBuilder, app.events.source, actor, request, app.events.sink, app.Config.Notifications.EventConfig.IncludeReferences)
}
|
go
|
func (app *App) eventBridge(ctx *Context, r *http.Request) notifications.Listener {
actor := notifications.ActorRecord{
Name: getUserName(ctx, r),
}
request := notifications.NewRequestRecord(dcontext.GetRequestID(ctx), r)
return notifications.NewBridge(ctx.urlBuilder, app.events.source, actor, request, app.events.sink, app.Config.Notifications.EventConfig.IncludeReferences)
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"eventBridge",
"(",
"ctx",
"*",
"Context",
",",
"r",
"*",
"http",
".",
"Request",
")",
"notifications",
".",
"Listener",
"{",
"actor",
":=",
"notifications",
".",
"ActorRecord",
"{",
"Name",
":",
"getUserName",
"(",
"ctx",
",",
"r",
")",
",",
"}",
"\n",
"request",
":=",
"notifications",
".",
"NewRequestRecord",
"(",
"dcontext",
".",
"GetRequestID",
"(",
"ctx",
")",
",",
"r",
")",
"\n\n",
"return",
"notifications",
".",
"NewBridge",
"(",
"ctx",
".",
"urlBuilder",
",",
"app",
".",
"events",
".",
"source",
",",
"actor",
",",
"request",
",",
"app",
".",
"events",
".",
"sink",
",",
"app",
".",
"Config",
".",
"Notifications",
".",
"EventConfig",
".",
"IncludeReferences",
")",
"\n",
"}"
] |
// eventBridge returns a bridge for the current request, configured with the
// correct actor and source.
|
[
"eventBridge",
"returns",
"a",
"bridge",
"for",
"the",
"current",
"request",
"configured",
"with",
"the",
"correct",
"actor",
"and",
"source",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L875-L882
|
train
|
docker/distribution
|
registry/handlers/app.go
|
nameRequired
|
func (app *App) nameRequired(r *http.Request) bool {
route := mux.CurrentRoute(r)
if route == nil {
return true
}
routeName := route.GetName()
return routeName != v2.RouteNameBase && routeName != v2.RouteNameCatalog
}
|
go
|
func (app *App) nameRequired(r *http.Request) bool {
route := mux.CurrentRoute(r)
if route == nil {
return true
}
routeName := route.GetName()
return routeName != v2.RouteNameBase && routeName != v2.RouteNameCatalog
}
|
[
"func",
"(",
"app",
"*",
"App",
")",
"nameRequired",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"route",
":=",
"mux",
".",
"CurrentRoute",
"(",
"r",
")",
"\n",
"if",
"route",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"routeName",
":=",
"route",
".",
"GetName",
"(",
")",
"\n",
"return",
"routeName",
"!=",
"v2",
".",
"RouteNameBase",
"&&",
"routeName",
"!=",
"v2",
".",
"RouteNameCatalog",
"\n",
"}"
] |
// nameRequired returns true if the route requires a name.
|
[
"nameRequired",
"returns",
"true",
"if",
"the",
"route",
"requires",
"a",
"name",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L885-L892
|
train
|
docker/distribution
|
registry/handlers/app.go
|
apiBase
|
func apiBase(w http.ResponseWriter, r *http.Request) {
const emptyJSON = "{}"
// Provide a simple /v2/ 200 OK response with empty json response.
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprint(len(emptyJSON)))
fmt.Fprint(w, emptyJSON)
}
|
go
|
func apiBase(w http.ResponseWriter, r *http.Request) {
const emptyJSON = "{}"
// Provide a simple /v2/ 200 OK response with empty json response.
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprint(len(emptyJSON)))
fmt.Fprint(w, emptyJSON)
}
|
[
"func",
"apiBase",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"const",
"emptyJSON",
"=",
"\"",
"\"",
"\n",
"// Provide a simple /v2/ 200 OK response with empty json response.",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprint",
"(",
"len",
"(",
"emptyJSON",
")",
")",
")",
"\n\n",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"emptyJSON",
")",
"\n",
"}"
] |
// apiBase implements a simple yes-man for doing overall checks against the
// api. This can support auth roundtrips to support docker login.
|
[
"apiBase",
"implements",
"a",
"simple",
"yes",
"-",
"man",
"for",
"doing",
"overall",
"checks",
"against",
"the",
"api",
".",
"This",
"can",
"support",
"auth",
"roundtrips",
"to",
"support",
"docker",
"login",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L896-L903
|
train
|
docker/distribution
|
registry/handlers/app.go
|
appendAccessRecords
|
func appendAccessRecords(records []auth.Access, method string, repo string) []auth.Access {
resource := auth.Resource{
Type: "repository",
Name: repo,
}
switch method {
case "GET", "HEAD":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
})
case "POST", "PUT", "PATCH":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
},
auth.Access{
Resource: resource,
Action: "push",
})
case "DELETE":
records = append(records,
auth.Access{
Resource: resource,
Action: "delete",
})
}
return records
}
|
go
|
func appendAccessRecords(records []auth.Access, method string, repo string) []auth.Access {
resource := auth.Resource{
Type: "repository",
Name: repo,
}
switch method {
case "GET", "HEAD":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
})
case "POST", "PUT", "PATCH":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
},
auth.Access{
Resource: resource,
Action: "push",
})
case "DELETE":
records = append(records,
auth.Access{
Resource: resource,
Action: "delete",
})
}
return records
}
|
[
"func",
"appendAccessRecords",
"(",
"records",
"[",
"]",
"auth",
".",
"Access",
",",
"method",
"string",
",",
"repo",
"string",
")",
"[",
"]",
"auth",
".",
"Access",
"{",
"resource",
":=",
"auth",
".",
"Resource",
"{",
"Type",
":",
"\"",
"\"",
",",
"Name",
":",
"repo",
",",
"}",
"\n\n",
"switch",
"method",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"records",
"=",
"append",
"(",
"records",
",",
"auth",
".",
"Access",
"{",
"Resource",
":",
"resource",
",",
"Action",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"records",
"=",
"append",
"(",
"records",
",",
"auth",
".",
"Access",
"{",
"Resource",
":",
"resource",
",",
"Action",
":",
"\"",
"\"",
",",
"}",
",",
"auth",
".",
"Access",
"{",
"Resource",
":",
"resource",
",",
"Action",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"case",
"\"",
"\"",
":",
"records",
"=",
"append",
"(",
"records",
",",
"auth",
".",
"Access",
"{",
"Resource",
":",
"resource",
",",
"Action",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"records",
"\n",
"}"
] |
// appendAccessRecords checks the method and adds the appropriate Access records to the records list.
|
[
"appendAccessRecords",
"checks",
"the",
"method",
"and",
"adds",
"the",
"appropriate",
"Access",
"records",
"to",
"the",
"records",
"list",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L906-L937
|
train
|
docker/distribution
|
registry/handlers/app.go
|
appendCatalogAccessRecord
|
func appendCatalogAccessRecord(accessRecords []auth.Access, r *http.Request) []auth.Access {
route := mux.CurrentRoute(r)
routeName := route.GetName()
if routeName == v2.RouteNameCatalog {
resource := auth.Resource{
Type: "registry",
Name: "catalog",
}
accessRecords = append(accessRecords,
auth.Access{
Resource: resource,
Action: "*",
})
}
return accessRecords
}
|
go
|
func appendCatalogAccessRecord(accessRecords []auth.Access, r *http.Request) []auth.Access {
route := mux.CurrentRoute(r)
routeName := route.GetName()
if routeName == v2.RouteNameCatalog {
resource := auth.Resource{
Type: "registry",
Name: "catalog",
}
accessRecords = append(accessRecords,
auth.Access{
Resource: resource,
Action: "*",
})
}
return accessRecords
}
|
[
"func",
"appendCatalogAccessRecord",
"(",
"accessRecords",
"[",
"]",
"auth",
".",
"Access",
",",
"r",
"*",
"http",
".",
"Request",
")",
"[",
"]",
"auth",
".",
"Access",
"{",
"route",
":=",
"mux",
".",
"CurrentRoute",
"(",
"r",
")",
"\n",
"routeName",
":=",
"route",
".",
"GetName",
"(",
")",
"\n\n",
"if",
"routeName",
"==",
"v2",
".",
"RouteNameCatalog",
"{",
"resource",
":=",
"auth",
".",
"Resource",
"{",
"Type",
":",
"\"",
"\"",
",",
"Name",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"accessRecords",
"=",
"append",
"(",
"accessRecords",
",",
"auth",
".",
"Access",
"{",
"Resource",
":",
"resource",
",",
"Action",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"accessRecords",
"\n",
"}"
] |
// Add the access record for the catalog if it's our current route
|
[
"Add",
"the",
"access",
"record",
"for",
"the",
"catalog",
"if",
"it",
"s",
"our",
"current",
"route"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L940-L957
|
train
|
docker/distribution
|
registry/handlers/app.go
|
applyRegistryMiddleware
|
func applyRegistryMiddleware(ctx context.Context, registry distribution.Namespace, middlewares []configuration.Middleware) (distribution.Namespace, error) {
for _, mw := range middlewares {
rmw, err := registrymiddleware.Get(ctx, mw.Name, mw.Options, registry)
if err != nil {
return nil, fmt.Errorf("unable to configure registry middleware (%s): %s", mw.Name, err)
}
registry = rmw
}
return registry, nil
}
|
go
|
func applyRegistryMiddleware(ctx context.Context, registry distribution.Namespace, middlewares []configuration.Middleware) (distribution.Namespace, error) {
for _, mw := range middlewares {
rmw, err := registrymiddleware.Get(ctx, mw.Name, mw.Options, registry)
if err != nil {
return nil, fmt.Errorf("unable to configure registry middleware (%s): %s", mw.Name, err)
}
registry = rmw
}
return registry, nil
}
|
[
"func",
"applyRegistryMiddleware",
"(",
"ctx",
"context",
".",
"Context",
",",
"registry",
"distribution",
".",
"Namespace",
",",
"middlewares",
"[",
"]",
"configuration",
".",
"Middleware",
")",
"(",
"distribution",
".",
"Namespace",
",",
"error",
")",
"{",
"for",
"_",
",",
"mw",
":=",
"range",
"middlewares",
"{",
"rmw",
",",
"err",
":=",
"registrymiddleware",
".",
"Get",
"(",
"ctx",
",",
"mw",
".",
"Name",
",",
"mw",
".",
"Options",
",",
"registry",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"mw",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"registry",
"=",
"rmw",
"\n",
"}",
"\n",
"return",
"registry",
",",
"nil",
"\n\n",
"}"
] |
// applyRegistryMiddleware wraps a registry instance with the configured middlewares
|
[
"applyRegistryMiddleware",
"wraps",
"a",
"registry",
"instance",
"with",
"the",
"configured",
"middlewares"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L960-L970
|
train
|
docker/distribution
|
registry/handlers/app.go
|
applyRepoMiddleware
|
func applyRepoMiddleware(ctx context.Context, repository distribution.Repository, middlewares []configuration.Middleware) (distribution.Repository, error) {
for _, mw := range middlewares {
rmw, err := repositorymiddleware.Get(ctx, mw.Name, mw.Options, repository)
if err != nil {
return nil, err
}
repository = rmw
}
return repository, nil
}
|
go
|
func applyRepoMiddleware(ctx context.Context, repository distribution.Repository, middlewares []configuration.Middleware) (distribution.Repository, error) {
for _, mw := range middlewares {
rmw, err := repositorymiddleware.Get(ctx, mw.Name, mw.Options, repository)
if err != nil {
return nil, err
}
repository = rmw
}
return repository, nil
}
|
[
"func",
"applyRepoMiddleware",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
"distribution",
".",
"Repository",
",",
"middlewares",
"[",
"]",
"configuration",
".",
"Middleware",
")",
"(",
"distribution",
".",
"Repository",
",",
"error",
")",
"{",
"for",
"_",
",",
"mw",
":=",
"range",
"middlewares",
"{",
"rmw",
",",
"err",
":=",
"repositorymiddleware",
".",
"Get",
"(",
"ctx",
",",
"mw",
".",
"Name",
",",
"mw",
".",
"Options",
",",
"repository",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"repository",
"=",
"rmw",
"\n",
"}",
"\n",
"return",
"repository",
",",
"nil",
"\n",
"}"
] |
// applyRepoMiddleware wraps a repository with the configured middlewares
|
[
"applyRepoMiddleware",
"wraps",
"a",
"repository",
"with",
"the",
"configured",
"middlewares"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L973-L982
|
train
|
docker/distribution
|
registry/handlers/app.go
|
applyStorageMiddleware
|
func applyStorageMiddleware(driver storagedriver.StorageDriver, middlewares []configuration.Middleware) (storagedriver.StorageDriver, error) {
for _, mw := range middlewares {
smw, err := storagemiddleware.Get(mw.Name, mw.Options, driver)
if err != nil {
return nil, fmt.Errorf("unable to configure storage middleware (%s): %v", mw.Name, err)
}
driver = smw
}
return driver, nil
}
|
go
|
func applyStorageMiddleware(driver storagedriver.StorageDriver, middlewares []configuration.Middleware) (storagedriver.StorageDriver, error) {
for _, mw := range middlewares {
smw, err := storagemiddleware.Get(mw.Name, mw.Options, driver)
if err != nil {
return nil, fmt.Errorf("unable to configure storage middleware (%s): %v", mw.Name, err)
}
driver = smw
}
return driver, nil
}
|
[
"func",
"applyStorageMiddleware",
"(",
"driver",
"storagedriver",
".",
"StorageDriver",
",",
"middlewares",
"[",
"]",
"configuration",
".",
"Middleware",
")",
"(",
"storagedriver",
".",
"StorageDriver",
",",
"error",
")",
"{",
"for",
"_",
",",
"mw",
":=",
"range",
"middlewares",
"{",
"smw",
",",
"err",
":=",
"storagemiddleware",
".",
"Get",
"(",
"mw",
".",
"Name",
",",
"mw",
".",
"Options",
",",
"driver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"mw",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"driver",
"=",
"smw",
"\n",
"}",
"\n",
"return",
"driver",
",",
"nil",
"\n",
"}"
] |
// applyStorageMiddleware wraps a storage driver with the configured middlewares
|
[
"applyStorageMiddleware",
"wraps",
"a",
"storage",
"driver",
"with",
"the",
"configured",
"middlewares"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L985-L994
|
train
|
docker/distribution
|
registry/handlers/app.go
|
startUploadPurger
|
func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageDriver, log dcontext.Logger, config map[interface{}]interface{}) {
if config["enabled"] == false {
return
}
var purgeAgeDuration time.Duration
var err error
purgeAge, ok := config["age"]
if ok {
ageStr, ok := purgeAge.(string)
if !ok {
badPurgeUploadConfig("age is not a string")
}
purgeAgeDuration, err = time.ParseDuration(ageStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse duration: %s", err.Error()))
}
} else {
badPurgeUploadConfig("age missing")
}
var intervalDuration time.Duration
interval, ok := config["interval"]
if ok {
intervalStr, ok := interval.(string)
if !ok {
badPurgeUploadConfig("interval is not a string")
}
intervalDuration, err = time.ParseDuration(intervalStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse interval: %s", err.Error()))
}
} else {
badPurgeUploadConfig("interval missing")
}
var dryRunBool bool
dryRun, ok := config["dryrun"]
if ok {
dryRunBool, ok = dryRun.(bool)
if !ok {
badPurgeUploadConfig("cannot parse dryrun")
}
} else {
badPurgeUploadConfig("dryrun missing")
}
go func() {
rand.Seed(time.Now().Unix())
jitter := time.Duration(rand.Int()%60) * time.Minute
log.Infof("Starting upload purge in %s", jitter)
time.Sleep(jitter)
for {
storage.PurgeUploads(ctx, storageDriver, time.Now().Add(-purgeAgeDuration), !dryRunBool)
log.Infof("Starting upload purge in %s", intervalDuration)
time.Sleep(intervalDuration)
}
}()
}
|
go
|
func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageDriver, log dcontext.Logger, config map[interface{}]interface{}) {
if config["enabled"] == false {
return
}
var purgeAgeDuration time.Duration
var err error
purgeAge, ok := config["age"]
if ok {
ageStr, ok := purgeAge.(string)
if !ok {
badPurgeUploadConfig("age is not a string")
}
purgeAgeDuration, err = time.ParseDuration(ageStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse duration: %s", err.Error()))
}
} else {
badPurgeUploadConfig("age missing")
}
var intervalDuration time.Duration
interval, ok := config["interval"]
if ok {
intervalStr, ok := interval.(string)
if !ok {
badPurgeUploadConfig("interval is not a string")
}
intervalDuration, err = time.ParseDuration(intervalStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse interval: %s", err.Error()))
}
} else {
badPurgeUploadConfig("interval missing")
}
var dryRunBool bool
dryRun, ok := config["dryrun"]
if ok {
dryRunBool, ok = dryRun.(bool)
if !ok {
badPurgeUploadConfig("cannot parse dryrun")
}
} else {
badPurgeUploadConfig("dryrun missing")
}
go func() {
rand.Seed(time.Now().Unix())
jitter := time.Duration(rand.Int()%60) * time.Minute
log.Infof("Starting upload purge in %s", jitter)
time.Sleep(jitter)
for {
storage.PurgeUploads(ctx, storageDriver, time.Now().Add(-purgeAgeDuration), !dryRunBool)
log.Infof("Starting upload purge in %s", intervalDuration)
time.Sleep(intervalDuration)
}
}()
}
|
[
"func",
"startUploadPurger",
"(",
"ctx",
"context",
".",
"Context",
",",
"storageDriver",
"storagedriver",
".",
"StorageDriver",
",",
"log",
"dcontext",
".",
"Logger",
",",
"config",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
")",
"{",
"if",
"config",
"[",
"\"",
"\"",
"]",
"==",
"false",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"purgeAgeDuration",
"time",
".",
"Duration",
"\n",
"var",
"err",
"error",
"\n",
"purgeAge",
",",
"ok",
":=",
"config",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"ageStr",
",",
"ok",
":=",
"purgeAge",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"badPurgeUploadConfig",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"purgeAgeDuration",
",",
"err",
"=",
"time",
".",
"ParseDuration",
"(",
"ageStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"badPurgeUploadConfig",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"badPurgeUploadConfig",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"intervalDuration",
"time",
".",
"Duration",
"\n",
"interval",
",",
"ok",
":=",
"config",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"intervalStr",
",",
"ok",
":=",
"interval",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"badPurgeUploadConfig",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"intervalDuration",
",",
"err",
"=",
"time",
".",
"ParseDuration",
"(",
"intervalStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"badPurgeUploadConfig",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"badPurgeUploadConfig",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"dryRunBool",
"bool",
"\n",
"dryRun",
",",
"ok",
":=",
"config",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"dryRunBool",
",",
"ok",
"=",
"dryRun",
".",
"(",
"bool",
")",
"\n",
"if",
"!",
"ok",
"{",
"badPurgeUploadConfig",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"badPurgeUploadConfig",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"rand",
".",
"Seed",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
")",
"\n",
"jitter",
":=",
"time",
".",
"Duration",
"(",
"rand",
".",
"Int",
"(",
")",
"%",
"60",
")",
"*",
"time",
".",
"Minute",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"jitter",
")",
"\n",
"time",
".",
"Sleep",
"(",
"jitter",
")",
"\n\n",
"for",
"{",
"storage",
".",
"PurgeUploads",
"(",
"ctx",
",",
"storageDriver",
",",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"purgeAgeDuration",
")",
",",
"!",
"dryRunBool",
")",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"intervalDuration",
")",
"\n",
"time",
".",
"Sleep",
"(",
"intervalDuration",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] |
// startUploadPurger schedules a goroutine which will periodically
// check upload directories for old files and delete them
|
[
"startUploadPurger",
"schedules",
"a",
"goroutine",
"which",
"will",
"periodically",
"check",
"upload",
"directories",
"for",
"old",
"files",
"and",
"delete",
"them"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L1014-L1074
|
train
|
docker/distribution
|
manifest/schema1/sign.go
|
Sign
|
func Sign(m *Manifest, pk libtrust.PrivateKey) (*SignedManifest, error) {
p, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
js, err := libtrust.NewJSONSignature(p)
if err != nil {
return nil, err
}
if err := js.Sign(pk); err != nil {
return nil, err
}
pretty, err := js.PrettySignature("signatures")
if err != nil {
return nil, err
}
return &SignedManifest{
Manifest: *m,
all: pretty,
Canonical: p,
}, nil
}
|
go
|
func Sign(m *Manifest, pk libtrust.PrivateKey) (*SignedManifest, error) {
p, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
js, err := libtrust.NewJSONSignature(p)
if err != nil {
return nil, err
}
if err := js.Sign(pk); err != nil {
return nil, err
}
pretty, err := js.PrettySignature("signatures")
if err != nil {
return nil, err
}
return &SignedManifest{
Manifest: *m,
all: pretty,
Canonical: p,
}, nil
}
|
[
"func",
"Sign",
"(",
"m",
"*",
"Manifest",
",",
"pk",
"libtrust",
".",
"PrivateKey",
")",
"(",
"*",
"SignedManifest",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"m",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"js",
",",
"err",
":=",
"libtrust",
".",
"NewJSONSignature",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"js",
".",
"Sign",
"(",
"pk",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"pretty",
",",
"err",
":=",
"js",
".",
"PrettySignature",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"SignedManifest",
"{",
"Manifest",
":",
"*",
"m",
",",
"all",
":",
"pretty",
",",
"Canonical",
":",
"p",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// Sign signs the manifest with the provided private key, returning a
// SignedManifest. This typically won't be used within the registry, except
// for testing.
|
[
"Sign",
"signs",
"the",
"manifest",
"with",
"the",
"provided",
"private",
"key",
"returning",
"a",
"SignedManifest",
".",
"This",
"typically",
"won",
"t",
"be",
"used",
"within",
"the",
"registry",
"except",
"for",
"testing",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/sign.go#L13-L38
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.