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
|
manifest/schema1/sign.go
|
SignWithChain
|
func SignWithChain(m *Manifest, key libtrust.PrivateKey, chain []*x509.Certificate) (*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.SignWithChain(key, chain); 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 SignWithChain(m *Manifest, key libtrust.PrivateKey, chain []*x509.Certificate) (*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.SignWithChain(key, chain); 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",
"SignWithChain",
"(",
"m",
"*",
"Manifest",
",",
"key",
"libtrust",
".",
"PrivateKey",
",",
"chain",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"(",
"*",
"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",
".",
"SignWithChain",
"(",
"key",
",",
"chain",
")",
";",
"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",
"}"
] |
// SignWithChain signs the manifest with the given private key and x509 chain.
// The public key of the first element in the chain must be the public key
// corresponding with the sign key.
|
[
"SignWithChain",
"signs",
"the",
"manifest",
"with",
"the",
"given",
"private",
"key",
"and",
"x509",
"chain",
".",
"The",
"public",
"key",
"of",
"the",
"first",
"element",
"in",
"the",
"chain",
"must",
"be",
"the",
"public",
"key",
"corresponding",
"with",
"the",
"sign",
"key",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/sign.go#L43-L68
|
train
|
docker/distribution
|
digestset/set.go
|
checkShortMatch
|
func checkShortMatch(alg digest.Algorithm, hex, shortAlg, shortHex string) bool {
if len(hex) == len(shortHex) {
if hex != shortHex {
return false
}
if len(shortAlg) > 0 && string(alg) != shortAlg {
return false
}
} else if !strings.HasPrefix(hex, shortHex) {
return false
} else if len(shortAlg) > 0 && string(alg) != shortAlg {
return false
}
return true
}
|
go
|
func checkShortMatch(alg digest.Algorithm, hex, shortAlg, shortHex string) bool {
if len(hex) == len(shortHex) {
if hex != shortHex {
return false
}
if len(shortAlg) > 0 && string(alg) != shortAlg {
return false
}
} else if !strings.HasPrefix(hex, shortHex) {
return false
} else if len(shortAlg) > 0 && string(alg) != shortAlg {
return false
}
return true
}
|
[
"func",
"checkShortMatch",
"(",
"alg",
"digest",
".",
"Algorithm",
",",
"hex",
",",
"shortAlg",
",",
"shortHex",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"hex",
")",
"==",
"len",
"(",
"shortHex",
")",
"{",
"if",
"hex",
"!=",
"shortHex",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"shortAlg",
")",
">",
"0",
"&&",
"string",
"(",
"alg",
")",
"!=",
"shortAlg",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"else",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"hex",
",",
"shortHex",
")",
"{",
"return",
"false",
"\n",
"}",
"else",
"if",
"len",
"(",
"shortAlg",
")",
">",
"0",
"&&",
"string",
"(",
"alg",
")",
"!=",
"shortAlg",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// checkShortMatch checks whether two digests match as either whole
// values or short values. This function does not test equality,
// rather whether the second value could match against the first
// value.
|
[
"checkShortMatch",
"checks",
"whether",
"two",
"digests",
"match",
"as",
"either",
"whole",
"values",
"or",
"short",
"values",
".",
"This",
"function",
"does",
"not",
"test",
"equality",
"rather",
"whether",
"the",
"second",
"value",
"could",
"match",
"against",
"the",
"first",
"value",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/digestset/set.go#L49-L63
|
train
|
docker/distribution
|
digestset/set.go
|
Lookup
|
func (dst *Set) Lookup(d string) (digest.Digest, error) {
dst.mutex.RLock()
defer dst.mutex.RUnlock()
if len(dst.entries) == 0 {
return "", ErrDigestNotFound
}
var (
searchFunc func(int) bool
alg digest.Algorithm
hex string
)
dgst, err := digest.Parse(d)
if err == digest.ErrDigestInvalidFormat {
hex = d
searchFunc = func(i int) bool {
return dst.entries[i].val >= d
}
} else {
hex = dgst.Hex()
alg = dgst.Algorithm()
searchFunc = func(i int) bool {
if dst.entries[i].val == hex {
return dst.entries[i].alg >= alg
}
return dst.entries[i].val >= hex
}
}
idx := sort.Search(len(dst.entries), searchFunc)
if idx == len(dst.entries) || !checkShortMatch(dst.entries[idx].alg, dst.entries[idx].val, string(alg), hex) {
return "", ErrDigestNotFound
}
if dst.entries[idx].alg == alg && dst.entries[idx].val == hex {
return dst.entries[idx].digest, nil
}
if idx+1 < len(dst.entries) && checkShortMatch(dst.entries[idx+1].alg, dst.entries[idx+1].val, string(alg), hex) {
return "", ErrDigestAmbiguous
}
return dst.entries[idx].digest, nil
}
|
go
|
func (dst *Set) Lookup(d string) (digest.Digest, error) {
dst.mutex.RLock()
defer dst.mutex.RUnlock()
if len(dst.entries) == 0 {
return "", ErrDigestNotFound
}
var (
searchFunc func(int) bool
alg digest.Algorithm
hex string
)
dgst, err := digest.Parse(d)
if err == digest.ErrDigestInvalidFormat {
hex = d
searchFunc = func(i int) bool {
return dst.entries[i].val >= d
}
} else {
hex = dgst.Hex()
alg = dgst.Algorithm()
searchFunc = func(i int) bool {
if dst.entries[i].val == hex {
return dst.entries[i].alg >= alg
}
return dst.entries[i].val >= hex
}
}
idx := sort.Search(len(dst.entries), searchFunc)
if idx == len(dst.entries) || !checkShortMatch(dst.entries[idx].alg, dst.entries[idx].val, string(alg), hex) {
return "", ErrDigestNotFound
}
if dst.entries[idx].alg == alg && dst.entries[idx].val == hex {
return dst.entries[idx].digest, nil
}
if idx+1 < len(dst.entries) && checkShortMatch(dst.entries[idx+1].alg, dst.entries[idx+1].val, string(alg), hex) {
return "", ErrDigestAmbiguous
}
return dst.entries[idx].digest, nil
}
|
[
"func",
"(",
"dst",
"*",
"Set",
")",
"Lookup",
"(",
"d",
"string",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"dst",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"dst",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"len",
"(",
"dst",
".",
"entries",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"ErrDigestNotFound",
"\n",
"}",
"\n",
"var",
"(",
"searchFunc",
"func",
"(",
"int",
")",
"bool",
"\n",
"alg",
"digest",
".",
"Algorithm",
"\n",
"hex",
"string",
"\n",
")",
"\n",
"dgst",
",",
"err",
":=",
"digest",
".",
"Parse",
"(",
"d",
")",
"\n",
"if",
"err",
"==",
"digest",
".",
"ErrDigestInvalidFormat",
"{",
"hex",
"=",
"d",
"\n",
"searchFunc",
"=",
"func",
"(",
"i",
"int",
")",
"bool",
"{",
"return",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"val",
">=",
"d",
"\n",
"}",
"\n",
"}",
"else",
"{",
"hex",
"=",
"dgst",
".",
"Hex",
"(",
")",
"\n",
"alg",
"=",
"dgst",
".",
"Algorithm",
"(",
")",
"\n",
"searchFunc",
"=",
"func",
"(",
"i",
"int",
")",
"bool",
"{",
"if",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"val",
"==",
"hex",
"{",
"return",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"alg",
">=",
"alg",
"\n",
"}",
"\n",
"return",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"val",
">=",
"hex",
"\n",
"}",
"\n",
"}",
"\n",
"idx",
":=",
"sort",
".",
"Search",
"(",
"len",
"(",
"dst",
".",
"entries",
")",
",",
"searchFunc",
")",
"\n",
"if",
"idx",
"==",
"len",
"(",
"dst",
".",
"entries",
")",
"||",
"!",
"checkShortMatch",
"(",
"dst",
".",
"entries",
"[",
"idx",
"]",
".",
"alg",
",",
"dst",
".",
"entries",
"[",
"idx",
"]",
".",
"val",
",",
"string",
"(",
"alg",
")",
",",
"hex",
")",
"{",
"return",
"\"",
"\"",
",",
"ErrDigestNotFound",
"\n",
"}",
"\n",
"if",
"dst",
".",
"entries",
"[",
"idx",
"]",
".",
"alg",
"==",
"alg",
"&&",
"dst",
".",
"entries",
"[",
"idx",
"]",
".",
"val",
"==",
"hex",
"{",
"return",
"dst",
".",
"entries",
"[",
"idx",
"]",
".",
"digest",
",",
"nil",
"\n",
"}",
"\n",
"if",
"idx",
"+",
"1",
"<",
"len",
"(",
"dst",
".",
"entries",
")",
"&&",
"checkShortMatch",
"(",
"dst",
".",
"entries",
"[",
"idx",
"+",
"1",
"]",
".",
"alg",
",",
"dst",
".",
"entries",
"[",
"idx",
"+",
"1",
"]",
".",
"val",
",",
"string",
"(",
"alg",
")",
",",
"hex",
")",
"{",
"return",
"\"",
"\"",
",",
"ErrDigestAmbiguous",
"\n",
"}",
"\n\n",
"return",
"dst",
".",
"entries",
"[",
"idx",
"]",
".",
"digest",
",",
"nil",
"\n",
"}"
] |
// Lookup looks for a digest matching the given string representation.
// If no digests could be found ErrDigestNotFound will be returned
// with an empty digest value. If multiple matches are found
// ErrDigestAmbiguous will be returned with an empty digest value.
|
[
"Lookup",
"looks",
"for",
"a",
"digest",
"matching",
"the",
"given",
"string",
"representation",
".",
"If",
"no",
"digests",
"could",
"be",
"found",
"ErrDigestNotFound",
"will",
"be",
"returned",
"with",
"an",
"empty",
"digest",
"value",
".",
"If",
"multiple",
"matches",
"are",
"found",
"ErrDigestAmbiguous",
"will",
"be",
"returned",
"with",
"an",
"empty",
"digest",
"value",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/digestset/set.go#L69-L108
|
train
|
docker/distribution
|
digestset/set.go
|
Add
|
func (dst *Set) Add(d digest.Digest) error {
if err := d.Validate(); err != nil {
return err
}
dst.mutex.Lock()
defer dst.mutex.Unlock()
entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d}
searchFunc := func(i int) bool {
if dst.entries[i].val == entry.val {
return dst.entries[i].alg >= entry.alg
}
return dst.entries[i].val >= entry.val
}
idx := sort.Search(len(dst.entries), searchFunc)
if idx == len(dst.entries) {
dst.entries = append(dst.entries, entry)
return nil
} else if dst.entries[idx].digest == d {
return nil
}
entries := append(dst.entries, nil)
copy(entries[idx+1:], entries[idx:len(entries)-1])
entries[idx] = entry
dst.entries = entries
return nil
}
|
go
|
func (dst *Set) Add(d digest.Digest) error {
if err := d.Validate(); err != nil {
return err
}
dst.mutex.Lock()
defer dst.mutex.Unlock()
entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d}
searchFunc := func(i int) bool {
if dst.entries[i].val == entry.val {
return dst.entries[i].alg >= entry.alg
}
return dst.entries[i].val >= entry.val
}
idx := sort.Search(len(dst.entries), searchFunc)
if idx == len(dst.entries) {
dst.entries = append(dst.entries, entry)
return nil
} else if dst.entries[idx].digest == d {
return nil
}
entries := append(dst.entries, nil)
copy(entries[idx+1:], entries[idx:len(entries)-1])
entries[idx] = entry
dst.entries = entries
return nil
}
|
[
"func",
"(",
"dst",
"*",
"Set",
")",
"Add",
"(",
"d",
"digest",
".",
"Digest",
")",
"error",
"{",
"if",
"err",
":=",
"d",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"dst",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dst",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"entry",
":=",
"&",
"digestEntry",
"{",
"alg",
":",
"d",
".",
"Algorithm",
"(",
")",
",",
"val",
":",
"d",
".",
"Hex",
"(",
")",
",",
"digest",
":",
"d",
"}",
"\n",
"searchFunc",
":=",
"func",
"(",
"i",
"int",
")",
"bool",
"{",
"if",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"val",
"==",
"entry",
".",
"val",
"{",
"return",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"alg",
">=",
"entry",
".",
"alg",
"\n",
"}",
"\n",
"return",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"val",
">=",
"entry",
".",
"val",
"\n",
"}",
"\n",
"idx",
":=",
"sort",
".",
"Search",
"(",
"len",
"(",
"dst",
".",
"entries",
")",
",",
"searchFunc",
")",
"\n",
"if",
"idx",
"==",
"len",
"(",
"dst",
".",
"entries",
")",
"{",
"dst",
".",
"entries",
"=",
"append",
"(",
"dst",
".",
"entries",
",",
"entry",
")",
"\n",
"return",
"nil",
"\n",
"}",
"else",
"if",
"dst",
".",
"entries",
"[",
"idx",
"]",
".",
"digest",
"==",
"d",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"entries",
":=",
"append",
"(",
"dst",
".",
"entries",
",",
"nil",
")",
"\n",
"copy",
"(",
"entries",
"[",
"idx",
"+",
"1",
":",
"]",
",",
"entries",
"[",
"idx",
":",
"len",
"(",
"entries",
")",
"-",
"1",
"]",
")",
"\n",
"entries",
"[",
"idx",
"]",
"=",
"entry",
"\n",
"dst",
".",
"entries",
"=",
"entries",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Add adds the given digest to the set. An error will be returned
// if the given digest is invalid. If the digest already exists in the
// set, this operation will be a no-op.
|
[
"Add",
"adds",
"the",
"given",
"digest",
"to",
"the",
"set",
".",
"An",
"error",
"will",
"be",
"returned",
"if",
"the",
"given",
"digest",
"is",
"invalid",
".",
"If",
"the",
"digest",
"already",
"exists",
"in",
"the",
"set",
"this",
"operation",
"will",
"be",
"a",
"no",
"-",
"op",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/digestset/set.go#L113-L139
|
train
|
docker/distribution
|
digestset/set.go
|
All
|
func (dst *Set) All() []digest.Digest {
dst.mutex.RLock()
defer dst.mutex.RUnlock()
retValues := make([]digest.Digest, len(dst.entries))
for i := range dst.entries {
retValues[i] = dst.entries[i].digest
}
return retValues
}
|
go
|
func (dst *Set) All() []digest.Digest {
dst.mutex.RLock()
defer dst.mutex.RUnlock()
retValues := make([]digest.Digest, len(dst.entries))
for i := range dst.entries {
retValues[i] = dst.entries[i].digest
}
return retValues
}
|
[
"func",
"(",
"dst",
"*",
"Set",
")",
"All",
"(",
")",
"[",
"]",
"digest",
".",
"Digest",
"{",
"dst",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"dst",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"retValues",
":=",
"make",
"(",
"[",
"]",
"digest",
".",
"Digest",
",",
"len",
"(",
"dst",
".",
"entries",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"dst",
".",
"entries",
"{",
"retValues",
"[",
"i",
"]",
"=",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"digest",
"\n",
"}",
"\n\n",
"return",
"retValues",
"\n",
"}"
] |
// All returns all the digests in the set
|
[
"All",
"returns",
"all",
"the",
"digests",
"in",
"the",
"set"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/digestset/set.go#L172-L181
|
train
|
docker/distribution
|
digestset/set.go
|
ShortCodeTable
|
func ShortCodeTable(dst *Set, length int) map[digest.Digest]string {
dst.mutex.RLock()
defer dst.mutex.RUnlock()
m := make(map[digest.Digest]string, len(dst.entries))
l := length
resetIdx := 0
for i := 0; i < len(dst.entries); i++ {
var short string
extended := true
for extended {
extended = false
if len(dst.entries[i].val) <= l {
short = dst.entries[i].digest.String()
} else {
short = dst.entries[i].val[:l]
for j := i + 1; j < len(dst.entries); j++ {
if checkShortMatch(dst.entries[j].alg, dst.entries[j].val, "", short) {
if j > resetIdx {
resetIdx = j
}
extended = true
} else {
break
}
}
if extended {
l++
}
}
}
m[dst.entries[i].digest] = short
if i >= resetIdx {
l = length
}
}
return m
}
|
go
|
func ShortCodeTable(dst *Set, length int) map[digest.Digest]string {
dst.mutex.RLock()
defer dst.mutex.RUnlock()
m := make(map[digest.Digest]string, len(dst.entries))
l := length
resetIdx := 0
for i := 0; i < len(dst.entries); i++ {
var short string
extended := true
for extended {
extended = false
if len(dst.entries[i].val) <= l {
short = dst.entries[i].digest.String()
} else {
short = dst.entries[i].val[:l]
for j := i + 1; j < len(dst.entries); j++ {
if checkShortMatch(dst.entries[j].alg, dst.entries[j].val, "", short) {
if j > resetIdx {
resetIdx = j
}
extended = true
} else {
break
}
}
if extended {
l++
}
}
}
m[dst.entries[i].digest] = short
if i >= resetIdx {
l = length
}
}
return m
}
|
[
"func",
"ShortCodeTable",
"(",
"dst",
"*",
"Set",
",",
"length",
"int",
")",
"map",
"[",
"digest",
".",
"Digest",
"]",
"string",
"{",
"dst",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"dst",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"m",
":=",
"make",
"(",
"map",
"[",
"digest",
".",
"Digest",
"]",
"string",
",",
"len",
"(",
"dst",
".",
"entries",
")",
")",
"\n",
"l",
":=",
"length",
"\n",
"resetIdx",
":=",
"0",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"dst",
".",
"entries",
")",
";",
"i",
"++",
"{",
"var",
"short",
"string",
"\n",
"extended",
":=",
"true",
"\n",
"for",
"extended",
"{",
"extended",
"=",
"false",
"\n",
"if",
"len",
"(",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"val",
")",
"<=",
"l",
"{",
"short",
"=",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"digest",
".",
"String",
"(",
")",
"\n",
"}",
"else",
"{",
"short",
"=",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"val",
"[",
":",
"l",
"]",
"\n",
"for",
"j",
":=",
"i",
"+",
"1",
";",
"j",
"<",
"len",
"(",
"dst",
".",
"entries",
")",
";",
"j",
"++",
"{",
"if",
"checkShortMatch",
"(",
"dst",
".",
"entries",
"[",
"j",
"]",
".",
"alg",
",",
"dst",
".",
"entries",
"[",
"j",
"]",
".",
"val",
",",
"\"",
"\"",
",",
"short",
")",
"{",
"if",
"j",
">",
"resetIdx",
"{",
"resetIdx",
"=",
"j",
"\n",
"}",
"\n",
"extended",
"=",
"true",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"extended",
"{",
"l",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"m",
"[",
"dst",
".",
"entries",
"[",
"i",
"]",
".",
"digest",
"]",
"=",
"short",
"\n",
"if",
"i",
">=",
"resetIdx",
"{",
"l",
"=",
"length",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] |
// ShortCodeTable returns a map of Digest to unique short codes. The
// length represents the minimum value, the maximum length may be the
// entire value of digest if uniqueness cannot be achieved without the
// full value. This function will attempt to make short codes as short
// as possible to be unique.
|
[
"ShortCodeTable",
"returns",
"a",
"map",
"of",
"Digest",
"to",
"unique",
"short",
"codes",
".",
"The",
"length",
"represents",
"the",
"minimum",
"value",
"the",
"maximum",
"length",
"may",
"be",
"the",
"entire",
"value",
"of",
"digest",
"if",
"uniqueness",
"cannot",
"be",
"achieved",
"without",
"the",
"full",
"value",
".",
"This",
"function",
"will",
"attempt",
"to",
"make",
"short",
"codes",
"as",
"short",
"as",
"possible",
"to",
"be",
"unique",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/digestset/set.go#L188-L224
|
train
|
docker/distribution
|
registry/handlers/manifests.go
|
manifestDispatcher
|
func manifestDispatcher(ctx *Context, r *http.Request) http.Handler {
manifestHandler := &manifestHandler{
Context: ctx,
}
reference := getReference(ctx)
dgst, err := digest.Parse(reference)
if err != nil {
// We just have a tag
manifestHandler.Tag = reference
} else {
manifestHandler.Digest = dgst
}
mhandler := handlers.MethodHandler{
"GET": http.HandlerFunc(manifestHandler.GetManifest),
"HEAD": http.HandlerFunc(manifestHandler.GetManifest),
}
if !ctx.readOnly {
mhandler["PUT"] = http.HandlerFunc(manifestHandler.PutManifest)
mhandler["DELETE"] = http.HandlerFunc(manifestHandler.DeleteManifest)
}
return mhandler
}
|
go
|
func manifestDispatcher(ctx *Context, r *http.Request) http.Handler {
manifestHandler := &manifestHandler{
Context: ctx,
}
reference := getReference(ctx)
dgst, err := digest.Parse(reference)
if err != nil {
// We just have a tag
manifestHandler.Tag = reference
} else {
manifestHandler.Digest = dgst
}
mhandler := handlers.MethodHandler{
"GET": http.HandlerFunc(manifestHandler.GetManifest),
"HEAD": http.HandlerFunc(manifestHandler.GetManifest),
}
if !ctx.readOnly {
mhandler["PUT"] = http.HandlerFunc(manifestHandler.PutManifest)
mhandler["DELETE"] = http.HandlerFunc(manifestHandler.DeleteManifest)
}
return mhandler
}
|
[
"func",
"manifestDispatcher",
"(",
"ctx",
"*",
"Context",
",",
"r",
"*",
"http",
".",
"Request",
")",
"http",
".",
"Handler",
"{",
"manifestHandler",
":=",
"&",
"manifestHandler",
"{",
"Context",
":",
"ctx",
",",
"}",
"\n",
"reference",
":=",
"getReference",
"(",
"ctx",
")",
"\n",
"dgst",
",",
"err",
":=",
"digest",
".",
"Parse",
"(",
"reference",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// We just have a tag",
"manifestHandler",
".",
"Tag",
"=",
"reference",
"\n",
"}",
"else",
"{",
"manifestHandler",
".",
"Digest",
"=",
"dgst",
"\n",
"}",
"\n\n",
"mhandler",
":=",
"handlers",
".",
"MethodHandler",
"{",
"\"",
"\"",
":",
"http",
".",
"HandlerFunc",
"(",
"manifestHandler",
".",
"GetManifest",
")",
",",
"\"",
"\"",
":",
"http",
".",
"HandlerFunc",
"(",
"manifestHandler",
".",
"GetManifest",
")",
",",
"}",
"\n\n",
"if",
"!",
"ctx",
".",
"readOnly",
"{",
"mhandler",
"[",
"\"",
"\"",
"]",
"=",
"http",
".",
"HandlerFunc",
"(",
"manifestHandler",
".",
"PutManifest",
")",
"\n",
"mhandler",
"[",
"\"",
"\"",
"]",
"=",
"http",
".",
"HandlerFunc",
"(",
"manifestHandler",
".",
"DeleteManifest",
")",
"\n",
"}",
"\n\n",
"return",
"mhandler",
"\n",
"}"
] |
// manifestDispatcher takes the request context and builds the
// appropriate handler for handling manifest requests.
|
[
"manifestDispatcher",
"takes",
"the",
"request",
"context",
"and",
"builds",
"the",
"appropriate",
"handler",
"for",
"handling",
"manifest",
"requests",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/manifests.go#L46-L70
|
train
|
docker/distribution
|
registry/handlers/manifests.go
|
applyResourcePolicy
|
func (imh *manifestHandler) applyResourcePolicy(manifest distribution.Manifest) error {
allowedClasses := imh.App.Config.Policy.Repository.Classes
if len(allowedClasses) == 0 {
return nil
}
var class string
switch m := manifest.(type) {
case *schema1.SignedManifest:
class = imageClass
case *schema2.DeserializedManifest:
switch m.Config.MediaType {
case schema2.MediaTypeImageConfig:
class = imageClass
case schema2.MediaTypePluginConfig:
class = "plugin"
default:
return errcode.ErrorCodeDenied.WithMessage("unknown manifest class for " + m.Config.MediaType)
}
case *ocischema.DeserializedManifest:
switch m.Config.MediaType {
case v1.MediaTypeImageConfig:
class = imageClass
default:
return errcode.ErrorCodeDenied.WithMessage("unknown manifest class for " + m.Config.MediaType)
}
}
if class == "" {
return nil
}
// Check to see if class is allowed in registry
var allowedClass bool
for _, c := range allowedClasses {
if class == c {
allowedClass = true
break
}
}
if !allowedClass {
return errcode.ErrorCodeDenied.WithMessage(fmt.Sprintf("registry does not allow %s manifest", class))
}
resources := auth.AuthorizedResources(imh)
n := imh.Repository.Named().Name()
var foundResource bool
for _, r := range resources {
if r.Name == n {
if r.Class == "" {
r.Class = imageClass
}
if r.Class == class {
return nil
}
foundResource = true
}
}
// resource was found but no matching class was found
if foundResource {
return errcode.ErrorCodeDenied.WithMessage(fmt.Sprintf("repository not authorized for %s manifest", class))
}
return nil
}
|
go
|
func (imh *manifestHandler) applyResourcePolicy(manifest distribution.Manifest) error {
allowedClasses := imh.App.Config.Policy.Repository.Classes
if len(allowedClasses) == 0 {
return nil
}
var class string
switch m := manifest.(type) {
case *schema1.SignedManifest:
class = imageClass
case *schema2.DeserializedManifest:
switch m.Config.MediaType {
case schema2.MediaTypeImageConfig:
class = imageClass
case schema2.MediaTypePluginConfig:
class = "plugin"
default:
return errcode.ErrorCodeDenied.WithMessage("unknown manifest class for " + m.Config.MediaType)
}
case *ocischema.DeserializedManifest:
switch m.Config.MediaType {
case v1.MediaTypeImageConfig:
class = imageClass
default:
return errcode.ErrorCodeDenied.WithMessage("unknown manifest class for " + m.Config.MediaType)
}
}
if class == "" {
return nil
}
// Check to see if class is allowed in registry
var allowedClass bool
for _, c := range allowedClasses {
if class == c {
allowedClass = true
break
}
}
if !allowedClass {
return errcode.ErrorCodeDenied.WithMessage(fmt.Sprintf("registry does not allow %s manifest", class))
}
resources := auth.AuthorizedResources(imh)
n := imh.Repository.Named().Name()
var foundResource bool
for _, r := range resources {
if r.Name == n {
if r.Class == "" {
r.Class = imageClass
}
if r.Class == class {
return nil
}
foundResource = true
}
}
// resource was found but no matching class was found
if foundResource {
return errcode.ErrorCodeDenied.WithMessage(fmt.Sprintf("repository not authorized for %s manifest", class))
}
return nil
}
|
[
"func",
"(",
"imh",
"*",
"manifestHandler",
")",
"applyResourcePolicy",
"(",
"manifest",
"distribution",
".",
"Manifest",
")",
"error",
"{",
"allowedClasses",
":=",
"imh",
".",
"App",
".",
"Config",
".",
"Policy",
".",
"Repository",
".",
"Classes",
"\n",
"if",
"len",
"(",
"allowedClasses",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"class",
"string",
"\n",
"switch",
"m",
":=",
"manifest",
".",
"(",
"type",
")",
"{",
"case",
"*",
"schema1",
".",
"SignedManifest",
":",
"class",
"=",
"imageClass",
"\n",
"case",
"*",
"schema2",
".",
"DeserializedManifest",
":",
"switch",
"m",
".",
"Config",
".",
"MediaType",
"{",
"case",
"schema2",
".",
"MediaTypeImageConfig",
":",
"class",
"=",
"imageClass",
"\n",
"case",
"schema2",
".",
"MediaTypePluginConfig",
":",
"class",
"=",
"\"",
"\"",
"\n",
"default",
":",
"return",
"errcode",
".",
"ErrorCodeDenied",
".",
"WithMessage",
"(",
"\"",
"\"",
"+",
"m",
".",
"Config",
".",
"MediaType",
")",
"\n",
"}",
"\n",
"case",
"*",
"ocischema",
".",
"DeserializedManifest",
":",
"switch",
"m",
".",
"Config",
".",
"MediaType",
"{",
"case",
"v1",
".",
"MediaTypeImageConfig",
":",
"class",
"=",
"imageClass",
"\n",
"default",
":",
"return",
"errcode",
".",
"ErrorCodeDenied",
".",
"WithMessage",
"(",
"\"",
"\"",
"+",
"m",
".",
"Config",
".",
"MediaType",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"class",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Check to see if class is allowed in registry",
"var",
"allowedClass",
"bool",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"allowedClasses",
"{",
"if",
"class",
"==",
"c",
"{",
"allowedClass",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"allowedClass",
"{",
"return",
"errcode",
".",
"ErrorCodeDenied",
".",
"WithMessage",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"class",
")",
")",
"\n",
"}",
"\n\n",
"resources",
":=",
"auth",
".",
"AuthorizedResources",
"(",
"imh",
")",
"\n",
"n",
":=",
"imh",
".",
"Repository",
".",
"Named",
"(",
")",
".",
"Name",
"(",
")",
"\n\n",
"var",
"foundResource",
"bool",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"resources",
"{",
"if",
"r",
".",
"Name",
"==",
"n",
"{",
"if",
"r",
".",
"Class",
"==",
"\"",
"\"",
"{",
"r",
".",
"Class",
"=",
"imageClass",
"\n",
"}",
"\n",
"if",
"r",
".",
"Class",
"==",
"class",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"foundResource",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// resource was found but no matching class was found",
"if",
"foundResource",
"{",
"return",
"errcode",
".",
"ErrorCodeDenied",
".",
"WithMessage",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"class",
")",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n\n",
"}"
] |
// applyResourcePolicy checks whether the resource class matches what has
// been authorized and allowed by the policy configuration.
|
[
"applyResourcePolicy",
"checks",
"whether",
"the",
"resource",
"class",
"matches",
"what",
"has",
"been",
"authorized",
"and",
"allowed",
"by",
"the",
"policy",
"configuration",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/manifests.go#L418-L485
|
train
|
docker/distribution
|
registry/handlers/manifests.go
|
DeleteManifest
|
func (imh *manifestHandler) DeleteManifest(w http.ResponseWriter, r *http.Request) {
dcontext.GetLogger(imh).Debug("DeleteImageManifest")
manifests, err := imh.Repository.Manifests(imh)
if err != nil {
imh.Errors = append(imh.Errors, err)
return
}
err = manifests.Delete(imh, imh.Digest)
if err != nil {
switch err {
case digest.ErrDigestUnsupported:
case digest.ErrDigestInvalidFormat:
imh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid)
return
case distribution.ErrBlobUnknown:
imh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown)
return
case distribution.ErrUnsupported:
imh.Errors = append(imh.Errors, errcode.ErrorCodeUnsupported)
return
default:
imh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown)
return
}
}
tagService := imh.Repository.Tags(imh)
referencedTags, err := tagService.Lookup(imh, distribution.Descriptor{Digest: imh.Digest})
if err != nil {
imh.Errors = append(imh.Errors, err)
return
}
for _, tag := range referencedTags {
if err := tagService.Untag(imh, tag); err != nil {
imh.Errors = append(imh.Errors, err)
return
}
}
w.WriteHeader(http.StatusAccepted)
}
|
go
|
func (imh *manifestHandler) DeleteManifest(w http.ResponseWriter, r *http.Request) {
dcontext.GetLogger(imh).Debug("DeleteImageManifest")
manifests, err := imh.Repository.Manifests(imh)
if err != nil {
imh.Errors = append(imh.Errors, err)
return
}
err = manifests.Delete(imh, imh.Digest)
if err != nil {
switch err {
case digest.ErrDigestUnsupported:
case digest.ErrDigestInvalidFormat:
imh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid)
return
case distribution.ErrBlobUnknown:
imh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown)
return
case distribution.ErrUnsupported:
imh.Errors = append(imh.Errors, errcode.ErrorCodeUnsupported)
return
default:
imh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown)
return
}
}
tagService := imh.Repository.Tags(imh)
referencedTags, err := tagService.Lookup(imh, distribution.Descriptor{Digest: imh.Digest})
if err != nil {
imh.Errors = append(imh.Errors, err)
return
}
for _, tag := range referencedTags {
if err := tagService.Untag(imh, tag); err != nil {
imh.Errors = append(imh.Errors, err)
return
}
}
w.WriteHeader(http.StatusAccepted)
}
|
[
"func",
"(",
"imh",
"*",
"manifestHandler",
")",
"DeleteManifest",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"dcontext",
".",
"GetLogger",
"(",
"imh",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"manifests",
",",
"err",
":=",
"imh",
".",
"Repository",
".",
"Manifests",
"(",
"imh",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"imh",
".",
"Errors",
"=",
"append",
"(",
"imh",
".",
"Errors",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"err",
"=",
"manifests",
".",
"Delete",
"(",
"imh",
",",
"imh",
".",
"Digest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
"{",
"case",
"digest",
".",
"ErrDigestUnsupported",
":",
"case",
"digest",
".",
"ErrDigestInvalidFormat",
":",
"imh",
".",
"Errors",
"=",
"append",
"(",
"imh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeDigestInvalid",
")",
"\n",
"return",
"\n",
"case",
"distribution",
".",
"ErrBlobUnknown",
":",
"imh",
".",
"Errors",
"=",
"append",
"(",
"imh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeManifestUnknown",
")",
"\n",
"return",
"\n",
"case",
"distribution",
".",
"ErrUnsupported",
":",
"imh",
".",
"Errors",
"=",
"append",
"(",
"imh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnsupported",
")",
"\n",
"return",
"\n",
"default",
":",
"imh",
".",
"Errors",
"=",
"append",
"(",
"imh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"tagService",
":=",
"imh",
".",
"Repository",
".",
"Tags",
"(",
"imh",
")",
"\n",
"referencedTags",
",",
"err",
":=",
"tagService",
".",
"Lookup",
"(",
"imh",
",",
"distribution",
".",
"Descriptor",
"{",
"Digest",
":",
"imh",
".",
"Digest",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"imh",
".",
"Errors",
"=",
"append",
"(",
"imh",
".",
"Errors",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"tag",
":=",
"range",
"referencedTags",
"{",
"if",
"err",
":=",
"tagService",
".",
"Untag",
"(",
"imh",
",",
"tag",
")",
";",
"err",
"!=",
"nil",
"{",
"imh",
".",
"Errors",
"=",
"append",
"(",
"imh",
".",
"Errors",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusAccepted",
")",
"\n",
"}"
] |
// DeleteManifest removes the manifest with the given digest from the registry.
|
[
"DeleteManifest",
"removes",
"the",
"manifest",
"with",
"the",
"given",
"digest",
"from",
"the",
"registry",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/manifests.go#L488-L531
|
train
|
docker/distribution
|
configuration/parser.go
|
MajorMinorVersion
|
func MajorMinorVersion(major, minor uint) Version {
return Version(fmt.Sprintf("%d.%d", major, minor))
}
|
go
|
func MajorMinorVersion(major, minor uint) Version {
return Version(fmt.Sprintf("%d.%d", major, minor))
}
|
[
"func",
"MajorMinorVersion",
"(",
"major",
",",
"minor",
"uint",
")",
"Version",
"{",
"return",
"Version",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"major",
",",
"minor",
")",
")",
"\n",
"}"
] |
// MajorMinorVersion constructs a Version from its Major and Minor components
|
[
"MajorMinorVersion",
"constructs",
"a",
"Version",
"from",
"its",
"Major",
"and",
"Minor",
"components"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/configuration/parser.go#L21-L23
|
train
|
docker/distribution
|
reference/helpers.go
|
IsNameOnly
|
func IsNameOnly(ref Named) bool {
if _, ok := ref.(NamedTagged); ok {
return false
}
if _, ok := ref.(Canonical); ok {
return false
}
return true
}
|
go
|
func IsNameOnly(ref Named) bool {
if _, ok := ref.(NamedTagged); ok {
return false
}
if _, ok := ref.(Canonical); ok {
return false
}
return true
}
|
[
"func",
"IsNameOnly",
"(",
"ref",
"Named",
")",
"bool",
"{",
"if",
"_",
",",
"ok",
":=",
"ref",
".",
"(",
"NamedTagged",
")",
";",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"ref",
".",
"(",
"Canonical",
")",
";",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// IsNameOnly returns true if reference only contains a repo name.
|
[
"IsNameOnly",
"returns",
"true",
"if",
"reference",
"only",
"contains",
"a",
"repo",
"name",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/helpers.go#L6-L14
|
train
|
docker/distribution
|
reference/helpers.go
|
FamiliarName
|
func FamiliarName(ref Named) string {
if nn, ok := ref.(normalizedNamed); ok {
return nn.Familiar().Name()
}
return ref.Name()
}
|
go
|
func FamiliarName(ref Named) string {
if nn, ok := ref.(normalizedNamed); ok {
return nn.Familiar().Name()
}
return ref.Name()
}
|
[
"func",
"FamiliarName",
"(",
"ref",
"Named",
")",
"string",
"{",
"if",
"nn",
",",
"ok",
":=",
"ref",
".",
"(",
"normalizedNamed",
")",
";",
"ok",
"{",
"return",
"nn",
".",
"Familiar",
"(",
")",
".",
"Name",
"(",
")",
"\n",
"}",
"\n",
"return",
"ref",
".",
"Name",
"(",
")",
"\n",
"}"
] |
// FamiliarName returns the familiar name string
// for the given named, familiarizing if needed.
|
[
"FamiliarName",
"returns",
"the",
"familiar",
"name",
"string",
"for",
"the",
"given",
"named",
"familiarizing",
"if",
"needed",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/helpers.go#L18-L23
|
train
|
docker/distribution
|
reference/helpers.go
|
FamiliarString
|
func FamiliarString(ref Reference) string {
if nn, ok := ref.(normalizedNamed); ok {
return nn.Familiar().String()
}
return ref.String()
}
|
go
|
func FamiliarString(ref Reference) string {
if nn, ok := ref.(normalizedNamed); ok {
return nn.Familiar().String()
}
return ref.String()
}
|
[
"func",
"FamiliarString",
"(",
"ref",
"Reference",
")",
"string",
"{",
"if",
"nn",
",",
"ok",
":=",
"ref",
".",
"(",
"normalizedNamed",
")",
";",
"ok",
"{",
"return",
"nn",
".",
"Familiar",
"(",
")",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"return",
"ref",
".",
"String",
"(",
")",
"\n",
"}"
] |
// FamiliarString returns the familiar string representation
// for the given reference, familiarizing if needed.
|
[
"FamiliarString",
"returns",
"the",
"familiar",
"string",
"representation",
"for",
"the",
"given",
"reference",
"familiarizing",
"if",
"needed",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/helpers.go#L27-L32
|
train
|
docker/distribution
|
registry/storage/io.go
|
limitReader
|
func limitReader(r io.Reader, n int64) io.Reader {
return &limitedReader{r: r, n: n}
}
|
go
|
func limitReader(r io.Reader, n int64) io.Reader {
return &limitedReader{r: r, n: n}
}
|
[
"func",
"limitReader",
"(",
"r",
"io",
".",
"Reader",
",",
"n",
"int64",
")",
"io",
".",
"Reader",
"{",
"return",
"&",
"limitedReader",
"{",
"r",
":",
"r",
",",
"n",
":",
"n",
"}",
"\n",
"}"
] |
// limitReader returns a new reader limited to n bytes. Unlike io.LimitReader,
// this returns an error when the limit reached.
|
[
"limitReader",
"returns",
"a",
"new",
"reader",
"limited",
"to",
"n",
"bytes",
".",
"Unlike",
"io",
".",
"LimitReader",
"this",
"returns",
"an",
"error",
"when",
"the",
"limit",
"reached",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/io.go#L32-L34
|
train
|
docker/distribution
|
registry/storage/driver/base/base.go
|
setDriverName
|
func (base *Base) setDriverName(e error) error {
switch actual := e.(type) {
case nil:
return nil
case storagedriver.ErrUnsupportedMethod:
actual.DriverName = base.StorageDriver.Name()
return actual
case storagedriver.PathNotFoundError:
actual.DriverName = base.StorageDriver.Name()
return actual
case storagedriver.InvalidPathError:
actual.DriverName = base.StorageDriver.Name()
return actual
case storagedriver.InvalidOffsetError:
actual.DriverName = base.StorageDriver.Name()
return actual
default:
storageError := storagedriver.Error{
DriverName: base.StorageDriver.Name(),
Enclosed: e,
}
return storageError
}
}
|
go
|
func (base *Base) setDriverName(e error) error {
switch actual := e.(type) {
case nil:
return nil
case storagedriver.ErrUnsupportedMethod:
actual.DriverName = base.StorageDriver.Name()
return actual
case storagedriver.PathNotFoundError:
actual.DriverName = base.StorageDriver.Name()
return actual
case storagedriver.InvalidPathError:
actual.DriverName = base.StorageDriver.Name()
return actual
case storagedriver.InvalidOffsetError:
actual.DriverName = base.StorageDriver.Name()
return actual
default:
storageError := storagedriver.Error{
DriverName: base.StorageDriver.Name(),
Enclosed: e,
}
return storageError
}
}
|
[
"func",
"(",
"base",
"*",
"Base",
")",
"setDriverName",
"(",
"e",
"error",
")",
"error",
"{",
"switch",
"actual",
":=",
"e",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"nil",
"\n",
"case",
"storagedriver",
".",
"ErrUnsupportedMethod",
":",
"actual",
".",
"DriverName",
"=",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"\n",
"return",
"actual",
"\n",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"actual",
".",
"DriverName",
"=",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"\n",
"return",
"actual",
"\n",
"case",
"storagedriver",
".",
"InvalidPathError",
":",
"actual",
".",
"DriverName",
"=",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"\n",
"return",
"actual",
"\n",
"case",
"storagedriver",
".",
"InvalidOffsetError",
":",
"actual",
".",
"DriverName",
"=",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"\n",
"return",
"actual",
"\n",
"default",
":",
"storageError",
":=",
"storagedriver",
".",
"Error",
"{",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
",",
"Enclosed",
":",
"e",
",",
"}",
"\n\n",
"return",
"storageError",
"\n",
"}",
"\n",
"}"
] |
// Format errors received from the storage driver
|
[
"Format",
"errors",
"received",
"from",
"the",
"storage",
"driver"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/base.go#L67-L91
|
train
|
docker/distribution
|
registry/storage/driver/base/base.go
|
GetContent
|
func (base *Base) GetContent(ctx context.Context, path string) ([]byte, error) {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.GetContent(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(path) {
return nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
start := time.Now()
b, e := base.StorageDriver.GetContent(ctx, path)
storageAction.WithValues(base.Name(), "GetContent").UpdateSince(start)
return b, base.setDriverName(e)
}
|
go
|
func (base *Base) GetContent(ctx context.Context, path string) ([]byte, error) {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.GetContent(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(path) {
return nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
start := time.Now()
b, e := base.StorageDriver.GetContent(ctx, path)
storageAction.WithValues(base.Name(), "GetContent").UpdateSince(start)
return b, base.setDriverName(e)
}
|
[
"func",
"(",
"base",
"*",
"Base",
")",
"GetContent",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"ctx",
",",
"done",
":=",
"dcontext",
".",
"WithTrace",
"(",
"ctx",
")",
"\n",
"defer",
"done",
"(",
"\"",
"\"",
",",
"base",
".",
"Name",
"(",
")",
",",
"path",
")",
"\n\n",
"if",
"!",
"storagedriver",
".",
"PathRegexp",
".",
"MatchString",
"(",
"path",
")",
"{",
"return",
"nil",
",",
"storagedriver",
".",
"InvalidPathError",
"{",
"Path",
":",
"path",
",",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"b",
",",
"e",
":=",
"base",
".",
"StorageDriver",
".",
"GetContent",
"(",
"ctx",
",",
"path",
")",
"\n",
"storageAction",
".",
"WithValues",
"(",
"base",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
".",
"UpdateSince",
"(",
"start",
")",
"\n",
"return",
"b",
",",
"base",
".",
"setDriverName",
"(",
"e",
")",
"\n",
"}"
] |
// GetContent wraps GetContent of underlying storage driver.
|
[
"GetContent",
"wraps",
"GetContent",
"of",
"underlying",
"storage",
"driver",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/base.go#L94-L106
|
train
|
docker/distribution
|
registry/storage/driver/base/base.go
|
Reader
|
func (base *Base) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Reader(%q, %d)", base.Name(), path, offset)
if offset < 0 {
return nil, storagedriver.InvalidOffsetError{Path: path, Offset: offset, DriverName: base.StorageDriver.Name()}
}
if !storagedriver.PathRegexp.MatchString(path) {
return nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
rc, e := base.StorageDriver.Reader(ctx, path, offset)
return rc, base.setDriverName(e)
}
|
go
|
func (base *Base) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Reader(%q, %d)", base.Name(), path, offset)
if offset < 0 {
return nil, storagedriver.InvalidOffsetError{Path: path, Offset: offset, DriverName: base.StorageDriver.Name()}
}
if !storagedriver.PathRegexp.MatchString(path) {
return nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
rc, e := base.StorageDriver.Reader(ctx, path, offset)
return rc, base.setDriverName(e)
}
|
[
"func",
"(",
"base",
"*",
"Base",
")",
"Reader",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"offset",
"int64",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"ctx",
",",
"done",
":=",
"dcontext",
".",
"WithTrace",
"(",
"ctx",
")",
"\n",
"defer",
"done",
"(",
"\"",
"\"",
",",
"base",
".",
"Name",
"(",
")",
",",
"path",
",",
"offset",
")",
"\n\n",
"if",
"offset",
"<",
"0",
"{",
"return",
"nil",
",",
"storagedriver",
".",
"InvalidOffsetError",
"{",
"Path",
":",
"path",
",",
"Offset",
":",
"offset",
",",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"storagedriver",
".",
"PathRegexp",
".",
"MatchString",
"(",
"path",
")",
"{",
"return",
"nil",
",",
"storagedriver",
".",
"InvalidPathError",
"{",
"Path",
":",
"path",
",",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"rc",
",",
"e",
":=",
"base",
".",
"StorageDriver",
".",
"Reader",
"(",
"ctx",
",",
"path",
",",
"offset",
")",
"\n",
"return",
"rc",
",",
"base",
".",
"setDriverName",
"(",
"e",
")",
"\n",
"}"
] |
// Reader wraps Reader of underlying storage driver.
|
[
"Reader",
"wraps",
"Reader",
"of",
"underlying",
"storage",
"driver",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/base.go#L124-L138
|
train
|
docker/distribution
|
registry/storage/driver/base/base.go
|
Writer
|
func (base *Base) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Writer(%q, %v)", base.Name(), path, append)
if !storagedriver.PathRegexp.MatchString(path) {
return nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
writer, e := base.StorageDriver.Writer(ctx, path, append)
return writer, base.setDriverName(e)
}
|
go
|
func (base *Base) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Writer(%q, %v)", base.Name(), path, append)
if !storagedriver.PathRegexp.MatchString(path) {
return nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
writer, e := base.StorageDriver.Writer(ctx, path, append)
return writer, base.setDriverName(e)
}
|
[
"func",
"(",
"base",
"*",
"Base",
")",
"Writer",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"append",
"bool",
")",
"(",
"storagedriver",
".",
"FileWriter",
",",
"error",
")",
"{",
"ctx",
",",
"done",
":=",
"dcontext",
".",
"WithTrace",
"(",
"ctx",
")",
"\n",
"defer",
"done",
"(",
"\"",
"\"",
",",
"base",
".",
"Name",
"(",
")",
",",
"path",
",",
"append",
")",
"\n\n",
"if",
"!",
"storagedriver",
".",
"PathRegexp",
".",
"MatchString",
"(",
"path",
")",
"{",
"return",
"nil",
",",
"storagedriver",
".",
"InvalidPathError",
"{",
"Path",
":",
"path",
",",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"writer",
",",
"e",
":=",
"base",
".",
"StorageDriver",
".",
"Writer",
"(",
"ctx",
",",
"path",
",",
"append",
")",
"\n",
"return",
"writer",
",",
"base",
".",
"setDriverName",
"(",
"e",
")",
"\n",
"}"
] |
// Writer wraps Writer of underlying storage driver.
|
[
"Writer",
"wraps",
"Writer",
"of",
"underlying",
"storage",
"driver",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/base.go#L141-L151
|
train
|
docker/distribution
|
registry/storage/driver/base/base.go
|
Move
|
func (base *Base) Move(ctx context.Context, sourcePath string, destPath string) error {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Move(%q, %q", base.Name(), sourcePath, destPath)
if !storagedriver.PathRegexp.MatchString(sourcePath) {
return storagedriver.InvalidPathError{Path: sourcePath, DriverName: base.StorageDriver.Name()}
} else if !storagedriver.PathRegexp.MatchString(destPath) {
return storagedriver.InvalidPathError{Path: destPath, DriverName: base.StorageDriver.Name()}
}
start := time.Now()
err := base.setDriverName(base.StorageDriver.Move(ctx, sourcePath, destPath))
storageAction.WithValues(base.Name(), "Move").UpdateSince(start)
return err
}
|
go
|
func (base *Base) Move(ctx context.Context, sourcePath string, destPath string) error {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Move(%q, %q", base.Name(), sourcePath, destPath)
if !storagedriver.PathRegexp.MatchString(sourcePath) {
return storagedriver.InvalidPathError{Path: sourcePath, DriverName: base.StorageDriver.Name()}
} else if !storagedriver.PathRegexp.MatchString(destPath) {
return storagedriver.InvalidPathError{Path: destPath, DriverName: base.StorageDriver.Name()}
}
start := time.Now()
err := base.setDriverName(base.StorageDriver.Move(ctx, sourcePath, destPath))
storageAction.WithValues(base.Name(), "Move").UpdateSince(start)
return err
}
|
[
"func",
"(",
"base",
"*",
"Base",
")",
"Move",
"(",
"ctx",
"context",
".",
"Context",
",",
"sourcePath",
"string",
",",
"destPath",
"string",
")",
"error",
"{",
"ctx",
",",
"done",
":=",
"dcontext",
".",
"WithTrace",
"(",
"ctx",
")",
"\n",
"defer",
"done",
"(",
"\"",
"\"",
",",
"base",
".",
"Name",
"(",
")",
",",
"sourcePath",
",",
"destPath",
")",
"\n\n",
"if",
"!",
"storagedriver",
".",
"PathRegexp",
".",
"MatchString",
"(",
"sourcePath",
")",
"{",
"return",
"storagedriver",
".",
"InvalidPathError",
"{",
"Path",
":",
"sourcePath",
",",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"}",
"\n",
"}",
"else",
"if",
"!",
"storagedriver",
".",
"PathRegexp",
".",
"MatchString",
"(",
"destPath",
")",
"{",
"return",
"storagedriver",
".",
"InvalidPathError",
"{",
"Path",
":",
"destPath",
",",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"err",
":=",
"base",
".",
"setDriverName",
"(",
"base",
".",
"StorageDriver",
".",
"Move",
"(",
"ctx",
",",
"sourcePath",
",",
"destPath",
")",
")",
"\n",
"storageAction",
".",
"WithValues",
"(",
"base",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
".",
"UpdateSince",
"(",
"start",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Move wraps Move of underlying storage driver.
|
[
"Move",
"wraps",
"Move",
"of",
"underlying",
"storage",
"driver",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/base.go#L184-L198
|
train
|
docker/distribution
|
registry/storage/driver/base/base.go
|
Walk
|
func (base *Base) Walk(ctx context.Context, path string, f storagedriver.WalkFn) error {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Walk(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(path) && path != "/" {
return storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
return base.setDriverName(base.StorageDriver.Walk(ctx, path, f))
}
|
go
|
func (base *Base) Walk(ctx context.Context, path string, f storagedriver.WalkFn) error {
ctx, done := dcontext.WithTrace(ctx)
defer done("%s.Walk(%q)", base.Name(), path)
if !storagedriver.PathRegexp.MatchString(path) && path != "/" {
return storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}
}
return base.setDriverName(base.StorageDriver.Walk(ctx, path, f))
}
|
[
"func",
"(",
"base",
"*",
"Base",
")",
"Walk",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"f",
"storagedriver",
".",
"WalkFn",
")",
"error",
"{",
"ctx",
",",
"done",
":=",
"dcontext",
".",
"WithTrace",
"(",
"ctx",
")",
"\n",
"defer",
"done",
"(",
"\"",
"\"",
",",
"base",
".",
"Name",
"(",
")",
",",
"path",
")",
"\n\n",
"if",
"!",
"storagedriver",
".",
"PathRegexp",
".",
"MatchString",
"(",
"path",
")",
"&&",
"path",
"!=",
"\"",
"\"",
"{",
"return",
"storagedriver",
".",
"InvalidPathError",
"{",
"Path",
":",
"path",
",",
"DriverName",
":",
"base",
".",
"StorageDriver",
".",
"Name",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"return",
"base",
".",
"setDriverName",
"(",
"base",
".",
"StorageDriver",
".",
"Walk",
"(",
"ctx",
",",
"path",
",",
"f",
")",
")",
"\n",
"}"
] |
// Walk wraps Walk of underlying storage driver.
|
[
"Walk",
"wraps",
"Walk",
"of",
"underlying",
"storage",
"driver",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/base/base.go#L231-L240
|
train
|
docker/distribution
|
registry/middleware/repository/middleware.go
|
Get
|
func Get(ctx context.Context, name string, options map[string]interface{}, repository distribution.Repository) (distribution.Repository, error) {
if middlewares != nil {
if initFunc, exists := middlewares[name]; exists {
return initFunc(ctx, repository, options)
}
}
return nil, fmt.Errorf("no repository middleware registered with name: %s", name)
}
|
go
|
func Get(ctx context.Context, name string, options map[string]interface{}, repository distribution.Repository) (distribution.Repository, error) {
if middlewares != nil {
if initFunc, exists := middlewares[name]; exists {
return initFunc(ctx, repository, options)
}
}
return nil, fmt.Errorf("no repository middleware registered with name: %s", name)
}
|
[
"func",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"repository",
"distribution",
".",
"Repository",
")",
"(",
"distribution",
".",
"Repository",
",",
"error",
")",
"{",
"if",
"middlewares",
"!=",
"nil",
"{",
"if",
"initFunc",
",",
"exists",
":=",
"middlewares",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"initFunc",
"(",
"ctx",
",",
"repository",
",",
"options",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
] |
// Get constructs a RepositoryMiddleware with the given options using the named backend.
|
[
"Get",
"constructs",
"a",
"RepositoryMiddleware",
"with",
"the",
"given",
"options",
"using",
"the",
"named",
"backend",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/middleware/repository/middleware.go#L32-L40
|
train
|
docker/distribution
|
manifest/schema1/manifest.go
|
UnmarshalJSON
|
func (sm *SignedManifest) UnmarshalJSON(b []byte) error {
sm.all = make([]byte, len(b))
// store manifest and signatures in all
copy(sm.all, b)
jsig, err := libtrust.ParsePrettySignature(b, "signatures")
if err != nil {
return err
}
// Resolve the payload in the manifest.
bytes, err := jsig.Payload()
if err != nil {
return err
}
// sm.Canonical stores the canonical manifest JSON
sm.Canonical = make([]byte, len(bytes))
copy(sm.Canonical, bytes)
// Unmarshal canonical JSON into Manifest object
var manifest Manifest
if err := json.Unmarshal(sm.Canonical, &manifest); err != nil {
return err
}
sm.Manifest = manifest
return nil
}
|
go
|
func (sm *SignedManifest) UnmarshalJSON(b []byte) error {
sm.all = make([]byte, len(b))
// store manifest and signatures in all
copy(sm.all, b)
jsig, err := libtrust.ParsePrettySignature(b, "signatures")
if err != nil {
return err
}
// Resolve the payload in the manifest.
bytes, err := jsig.Payload()
if err != nil {
return err
}
// sm.Canonical stores the canonical manifest JSON
sm.Canonical = make([]byte, len(bytes))
copy(sm.Canonical, bytes)
// Unmarshal canonical JSON into Manifest object
var manifest Manifest
if err := json.Unmarshal(sm.Canonical, &manifest); err != nil {
return err
}
sm.Manifest = manifest
return nil
}
|
[
"func",
"(",
"sm",
"*",
"SignedManifest",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"sm",
".",
"all",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"b",
")",
")",
"\n",
"// store manifest and signatures in all",
"copy",
"(",
"sm",
".",
"all",
",",
"b",
")",
"\n\n",
"jsig",
",",
"err",
":=",
"libtrust",
".",
"ParsePrettySignature",
"(",
"b",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Resolve the payload in the manifest.",
"bytes",
",",
"err",
":=",
"jsig",
".",
"Payload",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// sm.Canonical stores the canonical manifest JSON",
"sm",
".",
"Canonical",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"bytes",
")",
")",
"\n",
"copy",
"(",
"sm",
".",
"Canonical",
",",
"bytes",
")",
"\n\n",
"// Unmarshal canonical JSON into Manifest object",
"var",
"manifest",
"Manifest",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"sm",
".",
"Canonical",
",",
"&",
"manifest",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"sm",
".",
"Manifest",
"=",
"manifest",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON populates a new SignedManifest struct from JSON data.
|
[
"UnmarshalJSON",
"populates",
"a",
"new",
"SignedManifest",
"struct",
"from",
"JSON",
"data",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/manifest.go#L110-L139
|
train
|
docker/distribution
|
manifest/schema1/manifest.go
|
References
|
func (sm SignedManifest) References() []distribution.Descriptor {
dependencies := make([]distribution.Descriptor, len(sm.FSLayers))
for i, fsLayer := range sm.FSLayers {
dependencies[i] = distribution.Descriptor{
MediaType: "application/vnd.docker.container.image.rootfs.diff+x-gtar",
Digest: fsLayer.BlobSum,
}
}
return dependencies
}
|
go
|
func (sm SignedManifest) References() []distribution.Descriptor {
dependencies := make([]distribution.Descriptor, len(sm.FSLayers))
for i, fsLayer := range sm.FSLayers {
dependencies[i] = distribution.Descriptor{
MediaType: "application/vnd.docker.container.image.rootfs.diff+x-gtar",
Digest: fsLayer.BlobSum,
}
}
return dependencies
}
|
[
"func",
"(",
"sm",
"SignedManifest",
")",
"References",
"(",
")",
"[",
"]",
"distribution",
".",
"Descriptor",
"{",
"dependencies",
":=",
"make",
"(",
"[",
"]",
"distribution",
".",
"Descriptor",
",",
"len",
"(",
"sm",
".",
"FSLayers",
")",
")",
"\n",
"for",
"i",
",",
"fsLayer",
":=",
"range",
"sm",
".",
"FSLayers",
"{",
"dependencies",
"[",
"i",
"]",
"=",
"distribution",
".",
"Descriptor",
"{",
"MediaType",
":",
"\"",
"\"",
",",
"Digest",
":",
"fsLayer",
".",
"BlobSum",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"dependencies",
"\n\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/schema1/manifest.go#L142-L153
|
train
|
docker/distribution
|
manifest/schema1/manifest.go
|
MarshalJSON
|
func (sm *SignedManifest) MarshalJSON() ([]byte, error) {
if len(sm.all) > 0 {
return sm.all, nil
}
// If the raw data is not available, just dump the inner content.
return json.Marshal(&sm.Manifest)
}
|
go
|
func (sm *SignedManifest) MarshalJSON() ([]byte, error) {
if len(sm.all) > 0 {
return sm.all, nil
}
// If the raw data is not available, just dump the inner content.
return json.Marshal(&sm.Manifest)
}
|
[
"func",
"(",
"sm",
"*",
"SignedManifest",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"sm",
".",
"all",
")",
">",
"0",
"{",
"return",
"sm",
".",
"all",
",",
"nil",
"\n",
"}",
"\n\n",
"// If the raw data is not available, just dump the inner content.",
"return",
"json",
".",
"Marshal",
"(",
"&",
"sm",
".",
"Manifest",
")",
"\n",
"}"
] |
// MarshalJSON returns the contents of raw. If Raw is nil, marshals the inner
// contents. Applications requiring a marshaled signed manifest should simply
// use Raw directly, since the the content produced by json.Marshal will be
// compacted and will fail signature checks.
|
[
"MarshalJSON",
"returns",
"the",
"contents",
"of",
"raw",
".",
"If",
"Raw",
"is",
"nil",
"marshals",
"the",
"inner",
"contents",
".",
"Applications",
"requiring",
"a",
"marshaled",
"signed",
"manifest",
"should",
"simply",
"use",
"Raw",
"directly",
"since",
"the",
"the",
"content",
"produced",
"by",
"json",
".",
"Marshal",
"will",
"be",
"compacted",
"and",
"will",
"fail",
"signature",
"checks",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/manifest.go#L159-L166
|
train
|
docker/distribution
|
manifest/schema1/manifest.go
|
Payload
|
func (sm SignedManifest) Payload() (string, []byte, error) {
return MediaTypeSignedManifest, sm.all, nil
}
|
go
|
func (sm SignedManifest) Payload() (string, []byte, error) {
return MediaTypeSignedManifest, sm.all, nil
}
|
[
"func",
"(",
"sm",
"SignedManifest",
")",
"Payload",
"(",
")",
"(",
"string",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"MediaTypeSignedManifest",
",",
"sm",
".",
"all",
",",
"nil",
"\n",
"}"
] |
// Payload returns the signed content of the signed manifest.
|
[
"Payload",
"returns",
"the",
"signed",
"content",
"of",
"the",
"signed",
"manifest",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/manifest.go#L169-L171
|
train
|
docker/distribution
|
context/logger.go
|
WithLogger
|
func WithLogger(ctx context.Context, logger Logger) context.Context {
return context.WithValue(ctx, loggerKey{}, logger)
}
|
go
|
func WithLogger(ctx context.Context, logger Logger) context.Context {
return context.WithValue(ctx, loggerKey{}, logger)
}
|
[
"func",
"WithLogger",
"(",
"ctx",
"context",
".",
"Context",
",",
"logger",
"Logger",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"loggerKey",
"{",
"}",
",",
"logger",
")",
"\n",
"}"
] |
// WithLogger creates a new context with provided logger.
|
[
"WithLogger",
"creates",
"a",
"new",
"context",
"with",
"provided",
"logger",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/logger.go#L49-L51
|
train
|
docker/distribution
|
context/logger.go
|
GetLoggerWithField
|
func GetLoggerWithField(ctx context.Context, key, value interface{}, keys ...interface{}) Logger {
return getLogrusLogger(ctx, keys...).WithField(fmt.Sprint(key), value)
}
|
go
|
func GetLoggerWithField(ctx context.Context, key, value interface{}, keys ...interface{}) Logger {
return getLogrusLogger(ctx, keys...).WithField(fmt.Sprint(key), value)
}
|
[
"func",
"GetLoggerWithField",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
",",
"value",
"interface",
"{",
"}",
",",
"keys",
"...",
"interface",
"{",
"}",
")",
"Logger",
"{",
"return",
"getLogrusLogger",
"(",
"ctx",
",",
"keys",
"...",
")",
".",
"WithField",
"(",
"fmt",
".",
"Sprint",
"(",
"key",
")",
",",
"value",
")",
"\n",
"}"
] |
// GetLoggerWithField returns a logger instance with the specified field key
// and value without affecting the context. Extra specified keys will be
// resolved from the context.
|
[
"GetLoggerWithField",
"returns",
"a",
"logger",
"instance",
"with",
"the",
"specified",
"field",
"key",
"and",
"value",
"without",
"affecting",
"the",
"context",
".",
"Extra",
"specified",
"keys",
"will",
"be",
"resolved",
"from",
"the",
"context",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/logger.go#L56-L58
|
train
|
docker/distribution
|
context/logger.go
|
GetLoggerWithFields
|
func GetLoggerWithFields(ctx context.Context, fields map[interface{}]interface{}, keys ...interface{}) Logger {
// must convert from interface{} -> interface{} to string -> interface{} for logrus.
lfields := make(logrus.Fields, len(fields))
for key, value := range fields {
lfields[fmt.Sprint(key)] = value
}
return getLogrusLogger(ctx, keys...).WithFields(lfields)
}
|
go
|
func GetLoggerWithFields(ctx context.Context, fields map[interface{}]interface{}, keys ...interface{}) Logger {
// must convert from interface{} -> interface{} to string -> interface{} for logrus.
lfields := make(logrus.Fields, len(fields))
for key, value := range fields {
lfields[fmt.Sprint(key)] = value
}
return getLogrusLogger(ctx, keys...).WithFields(lfields)
}
|
[
"func",
"GetLoggerWithFields",
"(",
"ctx",
"context",
".",
"Context",
",",
"fields",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
",",
"keys",
"...",
"interface",
"{",
"}",
")",
"Logger",
"{",
"// must convert from interface{} -> interface{} to string -> interface{} for logrus.",
"lfields",
":=",
"make",
"(",
"logrus",
".",
"Fields",
",",
"len",
"(",
"fields",
")",
")",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"fields",
"{",
"lfields",
"[",
"fmt",
".",
"Sprint",
"(",
"key",
")",
"]",
"=",
"value",
"\n",
"}",
"\n\n",
"return",
"getLogrusLogger",
"(",
"ctx",
",",
"keys",
"...",
")",
".",
"WithFields",
"(",
"lfields",
")",
"\n",
"}"
] |
// GetLoggerWithFields returns a logger instance with the specified fields
// without affecting the context. Extra specified keys will be resolved from
// the context.
|
[
"GetLoggerWithFields",
"returns",
"a",
"logger",
"instance",
"with",
"the",
"specified",
"fields",
"without",
"affecting",
"the",
"context",
".",
"Extra",
"specified",
"keys",
"will",
"be",
"resolved",
"from",
"the",
"context",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/logger.go#L63-L71
|
train
|
docker/distribution
|
context/logger.go
|
getLogrusLogger
|
func getLogrusLogger(ctx context.Context, keys ...interface{}) *logrus.Entry {
var logger *logrus.Entry
// Get a logger, if it is present.
loggerInterface := ctx.Value(loggerKey{})
if loggerInterface != nil {
if lgr, ok := loggerInterface.(*logrus.Entry); ok {
logger = lgr
}
}
if logger == nil {
fields := logrus.Fields{}
// Fill in the instance id, if we have it.
instanceID := ctx.Value("instance.id")
if instanceID != nil {
fields["instance.id"] = instanceID
}
fields["go.version"] = runtime.Version()
// If no logger is found, just return the standard logger.
logger = logrus.StandardLogger().WithFields(fields)
}
fields := logrus.Fields{}
for _, key := range keys {
v := ctx.Value(key)
if v != nil {
fields[fmt.Sprint(key)] = v
}
}
return logger.WithFields(fields)
}
|
go
|
func getLogrusLogger(ctx context.Context, keys ...interface{}) *logrus.Entry {
var logger *logrus.Entry
// Get a logger, if it is present.
loggerInterface := ctx.Value(loggerKey{})
if loggerInterface != nil {
if lgr, ok := loggerInterface.(*logrus.Entry); ok {
logger = lgr
}
}
if logger == nil {
fields := logrus.Fields{}
// Fill in the instance id, if we have it.
instanceID := ctx.Value("instance.id")
if instanceID != nil {
fields["instance.id"] = instanceID
}
fields["go.version"] = runtime.Version()
// If no logger is found, just return the standard logger.
logger = logrus.StandardLogger().WithFields(fields)
}
fields := logrus.Fields{}
for _, key := range keys {
v := ctx.Value(key)
if v != nil {
fields[fmt.Sprint(key)] = v
}
}
return logger.WithFields(fields)
}
|
[
"func",
"getLogrusLogger",
"(",
"ctx",
"context",
".",
"Context",
",",
"keys",
"...",
"interface",
"{",
"}",
")",
"*",
"logrus",
".",
"Entry",
"{",
"var",
"logger",
"*",
"logrus",
".",
"Entry",
"\n\n",
"// Get a logger, if it is present.",
"loggerInterface",
":=",
"ctx",
".",
"Value",
"(",
"loggerKey",
"{",
"}",
")",
"\n",
"if",
"loggerInterface",
"!=",
"nil",
"{",
"if",
"lgr",
",",
"ok",
":=",
"loggerInterface",
".",
"(",
"*",
"logrus",
".",
"Entry",
")",
";",
"ok",
"{",
"logger",
"=",
"lgr",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"logger",
"==",
"nil",
"{",
"fields",
":=",
"logrus",
".",
"Fields",
"{",
"}",
"\n\n",
"// Fill in the instance id, if we have it.",
"instanceID",
":=",
"ctx",
".",
"Value",
"(",
"\"",
"\"",
")",
"\n",
"if",
"instanceID",
"!=",
"nil",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"instanceID",
"\n",
"}",
"\n\n",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"runtime",
".",
"Version",
"(",
")",
"\n",
"// If no logger is found, just return the standard logger.",
"logger",
"=",
"logrus",
".",
"StandardLogger",
"(",
")",
".",
"WithFields",
"(",
"fields",
")",
"\n",
"}",
"\n\n",
"fields",
":=",
"logrus",
".",
"Fields",
"{",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"v",
":=",
"ctx",
".",
"Value",
"(",
"key",
")",
"\n",
"if",
"v",
"!=",
"nil",
"{",
"fields",
"[",
"fmt",
".",
"Sprint",
"(",
"key",
")",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"logger",
".",
"WithFields",
"(",
"fields",
")",
"\n",
"}"
] |
// GetLogrusLogger returns the logrus logger for the context. If one more keys
// are provided, they will be resolved on the context and included in the
// logger. Only use this function if specific logrus functionality is
// required.
|
[
"GetLogrusLogger",
"returns",
"the",
"logrus",
"logger",
"for",
"the",
"context",
".",
"If",
"one",
"more",
"keys",
"are",
"provided",
"they",
"will",
"be",
"resolved",
"on",
"the",
"context",
"and",
"included",
"in",
"the",
"logger",
".",
"Only",
"use",
"this",
"function",
"if",
"specific",
"logrus",
"functionality",
"is",
"required",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/logger.go#L87-L121
|
train
|
docker/distribution
|
registry/handlers/context.go
|
getUserName
|
func getUserName(ctx context.Context, r *http.Request) string {
username := dcontext.GetStringValue(ctx, auth.UserNameKey)
// Fallback to request user with basic auth
if username == "" {
var ok bool
uname, _, ok := basicAuth(r)
if ok {
username = uname
}
}
return username
}
|
go
|
func getUserName(ctx context.Context, r *http.Request) string {
username := dcontext.GetStringValue(ctx, auth.UserNameKey)
// Fallback to request user with basic auth
if username == "" {
var ok bool
uname, _, ok := basicAuth(r)
if ok {
username = uname
}
}
return username
}
|
[
"func",
"getUserName",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"username",
":=",
"dcontext",
".",
"GetStringValue",
"(",
"ctx",
",",
"auth",
".",
"UserNameKey",
")",
"\n\n",
"// Fallback to request user with basic auth",
"if",
"username",
"==",
"\"",
"\"",
"{",
"var",
"ok",
"bool",
"\n",
"uname",
",",
"_",
",",
"ok",
":=",
"basicAuth",
"(",
"r",
")",
"\n",
"if",
"ok",
"{",
"username",
"=",
"uname",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"username",
"\n",
"}"
] |
// getUserName attempts to resolve a username from the context and request. If
// a username cannot be resolved, the empty string is returned.
|
[
"getUserName",
"attempts",
"to",
"resolve",
"a",
"username",
"from",
"the",
"context",
"and",
"request",
".",
"If",
"a",
"username",
"cannot",
"be",
"resolved",
"the",
"empty",
"string",
"is",
"returned",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/context.go#L82-L95
|
train
|
docker/distribution
|
registry/registry.go
|
NewRegistry
|
func NewRegistry(ctx context.Context, config *configuration.Configuration) (*Registry, error) {
var err error
ctx, err = configureLogging(ctx, config)
if err != nil {
return nil, fmt.Errorf("error configuring logger: %v", err)
}
configureBugsnag(config)
// inject a logger into the uuid library. warns us if there is a problem
// with uuid generation under low entropy.
uuid.Loggerf = dcontext.GetLogger(ctx).Warnf
app := handlers.NewApp(ctx, config)
// TODO(aaronl): The global scope of the health checks means NewRegistry
// can only be called once per process.
app.RegisterHealthChecks()
handler := configureReporting(app)
handler = alive("/", handler)
handler = health.Handler(handler)
handler = panicHandler(handler)
if !config.Log.AccessLog.Disabled {
handler = gorhandlers.CombinedLoggingHandler(os.Stdout, handler)
}
server := &http.Server{
Handler: handler,
}
return &Registry{
app: app,
config: config,
server: server,
}, nil
}
|
go
|
func NewRegistry(ctx context.Context, config *configuration.Configuration) (*Registry, error) {
var err error
ctx, err = configureLogging(ctx, config)
if err != nil {
return nil, fmt.Errorf("error configuring logger: %v", err)
}
configureBugsnag(config)
// inject a logger into the uuid library. warns us if there is a problem
// with uuid generation under low entropy.
uuid.Loggerf = dcontext.GetLogger(ctx).Warnf
app := handlers.NewApp(ctx, config)
// TODO(aaronl): The global scope of the health checks means NewRegistry
// can only be called once per process.
app.RegisterHealthChecks()
handler := configureReporting(app)
handler = alive("/", handler)
handler = health.Handler(handler)
handler = panicHandler(handler)
if !config.Log.AccessLog.Disabled {
handler = gorhandlers.CombinedLoggingHandler(os.Stdout, handler)
}
server := &http.Server{
Handler: handler,
}
return &Registry{
app: app,
config: config,
server: server,
}, nil
}
|
[
"func",
"NewRegistry",
"(",
"ctx",
"context",
".",
"Context",
",",
"config",
"*",
"configuration",
".",
"Configuration",
")",
"(",
"*",
"Registry",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"ctx",
",",
"err",
"=",
"configureLogging",
"(",
"ctx",
",",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"configureBugsnag",
"(",
"config",
")",
"\n\n",
"// inject a logger into the uuid library. warns us if there is a problem",
"// with uuid generation under low entropy.",
"uuid",
".",
"Loggerf",
"=",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Warnf",
"\n\n",
"app",
":=",
"handlers",
".",
"NewApp",
"(",
"ctx",
",",
"config",
")",
"\n",
"// TODO(aaronl): The global scope of the health checks means NewRegistry",
"// can only be called once per process.",
"app",
".",
"RegisterHealthChecks",
"(",
")",
"\n",
"handler",
":=",
"configureReporting",
"(",
"app",
")",
"\n",
"handler",
"=",
"alive",
"(",
"\"",
"\"",
",",
"handler",
")",
"\n",
"handler",
"=",
"health",
".",
"Handler",
"(",
"handler",
")",
"\n",
"handler",
"=",
"panicHandler",
"(",
"handler",
")",
"\n",
"if",
"!",
"config",
".",
"Log",
".",
"AccessLog",
".",
"Disabled",
"{",
"handler",
"=",
"gorhandlers",
".",
"CombinedLoggingHandler",
"(",
"os",
".",
"Stdout",
",",
"handler",
")",
"\n",
"}",
"\n\n",
"server",
":=",
"&",
"http",
".",
"Server",
"{",
"Handler",
":",
"handler",
",",
"}",
"\n\n",
"return",
"&",
"Registry",
"{",
"app",
":",
"app",
",",
"config",
":",
"config",
",",
"server",
":",
"server",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewRegistry creates a new registry from a context and configuration struct.
|
[
"NewRegistry",
"creates",
"a",
"new",
"registry",
"from",
"a",
"context",
"and",
"configuration",
"struct",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/registry.go#L92-L126
|
train
|
docker/distribution
|
registry/registry.go
|
configureLogging
|
func configureLogging(ctx context.Context, config *configuration.Configuration) (context.Context, error) {
log.SetLevel(logLevel(config.Log.Level))
formatter := config.Log.Formatter
if formatter == "" {
formatter = "text" // default formatter
}
switch formatter {
case "json":
log.SetFormatter(&log.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
})
case "text":
log.SetFormatter(&log.TextFormatter{
TimestampFormat: time.RFC3339Nano,
})
case "logstash":
log.SetFormatter(&logstash.LogstashFormatter{
TimestampFormat: time.RFC3339Nano,
})
default:
// just let the library use default on empty string.
if config.Log.Formatter != "" {
return ctx, fmt.Errorf("unsupported logging formatter: %q", config.Log.Formatter)
}
}
if config.Log.Formatter != "" {
log.Debugf("using %q logging formatter", config.Log.Formatter)
}
if len(config.Log.Fields) > 0 {
// build up the static fields, if present.
var fields []interface{}
for k := range config.Log.Fields {
fields = append(fields, k)
}
ctx = dcontext.WithValues(ctx, config.Log.Fields)
ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, fields...))
}
return ctx, nil
}
|
go
|
func configureLogging(ctx context.Context, config *configuration.Configuration) (context.Context, error) {
log.SetLevel(logLevel(config.Log.Level))
formatter := config.Log.Formatter
if formatter == "" {
formatter = "text" // default formatter
}
switch formatter {
case "json":
log.SetFormatter(&log.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
})
case "text":
log.SetFormatter(&log.TextFormatter{
TimestampFormat: time.RFC3339Nano,
})
case "logstash":
log.SetFormatter(&logstash.LogstashFormatter{
TimestampFormat: time.RFC3339Nano,
})
default:
// just let the library use default on empty string.
if config.Log.Formatter != "" {
return ctx, fmt.Errorf("unsupported logging formatter: %q", config.Log.Formatter)
}
}
if config.Log.Formatter != "" {
log.Debugf("using %q logging formatter", config.Log.Formatter)
}
if len(config.Log.Fields) > 0 {
// build up the static fields, if present.
var fields []interface{}
for k := range config.Log.Fields {
fields = append(fields, k)
}
ctx = dcontext.WithValues(ctx, config.Log.Fields)
ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, fields...))
}
return ctx, nil
}
|
[
"func",
"configureLogging",
"(",
"ctx",
"context",
".",
"Context",
",",
"config",
"*",
"configuration",
".",
"Configuration",
")",
"(",
"context",
".",
"Context",
",",
"error",
")",
"{",
"log",
".",
"SetLevel",
"(",
"logLevel",
"(",
"config",
".",
"Log",
".",
"Level",
")",
")",
"\n\n",
"formatter",
":=",
"config",
".",
"Log",
".",
"Formatter",
"\n",
"if",
"formatter",
"==",
"\"",
"\"",
"{",
"formatter",
"=",
"\"",
"\"",
"// default formatter",
"\n",
"}",
"\n\n",
"switch",
"formatter",
"{",
"case",
"\"",
"\"",
":",
"log",
".",
"SetFormatter",
"(",
"&",
"log",
".",
"JSONFormatter",
"{",
"TimestampFormat",
":",
"time",
".",
"RFC3339Nano",
",",
"}",
")",
"\n",
"case",
"\"",
"\"",
":",
"log",
".",
"SetFormatter",
"(",
"&",
"log",
".",
"TextFormatter",
"{",
"TimestampFormat",
":",
"time",
".",
"RFC3339Nano",
",",
"}",
")",
"\n",
"case",
"\"",
"\"",
":",
"log",
".",
"SetFormatter",
"(",
"&",
"logstash",
".",
"LogstashFormatter",
"{",
"TimestampFormat",
":",
"time",
".",
"RFC3339Nano",
",",
"}",
")",
"\n",
"default",
":",
"// just let the library use default on empty string.",
"if",
"config",
".",
"Log",
".",
"Formatter",
"!=",
"\"",
"\"",
"{",
"return",
"ctx",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"config",
".",
"Log",
".",
"Formatter",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"config",
".",
"Log",
".",
"Formatter",
"!=",
"\"",
"\"",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"config",
".",
"Log",
".",
"Formatter",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"config",
".",
"Log",
".",
"Fields",
")",
">",
"0",
"{",
"// build up the static fields, if present.",
"var",
"fields",
"[",
"]",
"interface",
"{",
"}",
"\n",
"for",
"k",
":=",
"range",
"config",
".",
"Log",
".",
"Fields",
"{",
"fields",
"=",
"append",
"(",
"fields",
",",
"k",
")",
"\n",
"}",
"\n\n",
"ctx",
"=",
"dcontext",
".",
"WithValues",
"(",
"ctx",
",",
"config",
".",
"Log",
".",
"Fields",
")",
"\n",
"ctx",
"=",
"dcontext",
".",
"WithLogger",
"(",
"ctx",
",",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
",",
"fields",
"...",
")",
")",
"\n",
"}",
"\n\n",
"return",
"ctx",
",",
"nil",
"\n",
"}"
] |
// configureLogging prepares the context with a logger using the
// configuration.
|
[
"configureLogging",
"prepares",
"the",
"context",
"with",
"a",
"logger",
"using",
"the",
"configuration",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/registry.go#L272-L316
|
train
|
docker/distribution
|
registry/registry.go
|
configureBugsnag
|
func configureBugsnag(config *configuration.Configuration) {
if config.Reporting.Bugsnag.APIKey == "" {
return
}
bugsnagConfig := bugsnag.Configuration{
APIKey: config.Reporting.Bugsnag.APIKey,
}
if config.Reporting.Bugsnag.ReleaseStage != "" {
bugsnagConfig.ReleaseStage = config.Reporting.Bugsnag.ReleaseStage
}
if config.Reporting.Bugsnag.Endpoint != "" {
bugsnagConfig.Endpoint = config.Reporting.Bugsnag.Endpoint
}
bugsnag.Configure(bugsnagConfig)
// configure logrus bugsnag hook
hook, err := logrus_bugsnag.NewBugsnagHook()
if err != nil {
log.Fatalln(err)
}
log.AddHook(hook)
}
|
go
|
func configureBugsnag(config *configuration.Configuration) {
if config.Reporting.Bugsnag.APIKey == "" {
return
}
bugsnagConfig := bugsnag.Configuration{
APIKey: config.Reporting.Bugsnag.APIKey,
}
if config.Reporting.Bugsnag.ReleaseStage != "" {
bugsnagConfig.ReleaseStage = config.Reporting.Bugsnag.ReleaseStage
}
if config.Reporting.Bugsnag.Endpoint != "" {
bugsnagConfig.Endpoint = config.Reporting.Bugsnag.Endpoint
}
bugsnag.Configure(bugsnagConfig)
// configure logrus bugsnag hook
hook, err := logrus_bugsnag.NewBugsnagHook()
if err != nil {
log.Fatalln(err)
}
log.AddHook(hook)
}
|
[
"func",
"configureBugsnag",
"(",
"config",
"*",
"configuration",
".",
"Configuration",
")",
"{",
"if",
"config",
".",
"Reporting",
".",
"Bugsnag",
".",
"APIKey",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"bugsnagConfig",
":=",
"bugsnag",
".",
"Configuration",
"{",
"APIKey",
":",
"config",
".",
"Reporting",
".",
"Bugsnag",
".",
"APIKey",
",",
"}",
"\n",
"if",
"config",
".",
"Reporting",
".",
"Bugsnag",
".",
"ReleaseStage",
"!=",
"\"",
"\"",
"{",
"bugsnagConfig",
".",
"ReleaseStage",
"=",
"config",
".",
"Reporting",
".",
"Bugsnag",
".",
"ReleaseStage",
"\n",
"}",
"\n",
"if",
"config",
".",
"Reporting",
".",
"Bugsnag",
".",
"Endpoint",
"!=",
"\"",
"\"",
"{",
"bugsnagConfig",
".",
"Endpoint",
"=",
"config",
".",
"Reporting",
".",
"Bugsnag",
".",
"Endpoint",
"\n",
"}",
"\n",
"bugsnag",
".",
"Configure",
"(",
"bugsnagConfig",
")",
"\n\n",
"// configure logrus bugsnag hook",
"hook",
",",
"err",
":=",
"logrus_bugsnag",
".",
"NewBugsnagHook",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalln",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"log",
".",
"AddHook",
"(",
"hook",
")",
"\n",
"}"
] |
// configureBugsnag configures bugsnag reporting, if enabled
|
[
"configureBugsnag",
"configures",
"bugsnag",
"reporting",
"if",
"enabled"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/registry.go#L329-L352
|
train
|
docker/distribution
|
registry/registry.go
|
panicHandler
|
func panicHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Panic(fmt.Sprintf("%v", err))
}
}()
handler.ServeHTTP(w, r)
})
}
|
go
|
func panicHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Panic(fmt.Sprintf("%v", err))
}
}()
handler.ServeHTTP(w, r)
})
}
|
[
"func",
"panicHandler",
"(",
"handler",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"handler",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// panicHandler add an HTTP handler to web app. The handler recover the happening
// panic. logrus.Panic transmits panic message to pre-config log hooks, which is
// defined in config.yml.
|
[
"panicHandler",
"add",
"an",
"HTTP",
"handler",
"to",
"web",
"app",
".",
"The",
"handler",
"recover",
"the",
"happening",
"panic",
".",
"logrus",
".",
"Panic",
"transmits",
"panic",
"message",
"to",
"pre",
"-",
"config",
"log",
"hooks",
"which",
"is",
"defined",
"in",
"config",
".",
"yml",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/registry.go#L357-L366
|
train
|
docker/distribution
|
registry/storage/cache/memory/memory.go
|
NewInMemoryBlobDescriptorCacheProvider
|
func NewInMemoryBlobDescriptorCacheProvider() cache.BlobDescriptorCacheProvider {
return &inMemoryBlobDescriptorCacheProvider{
global: newMapBlobDescriptorCache(),
repositories: make(map[string]*mapBlobDescriptorCache),
}
}
|
go
|
func NewInMemoryBlobDescriptorCacheProvider() cache.BlobDescriptorCacheProvider {
return &inMemoryBlobDescriptorCacheProvider{
global: newMapBlobDescriptorCache(),
repositories: make(map[string]*mapBlobDescriptorCache),
}
}
|
[
"func",
"NewInMemoryBlobDescriptorCacheProvider",
"(",
")",
"cache",
".",
"BlobDescriptorCacheProvider",
"{",
"return",
"&",
"inMemoryBlobDescriptorCacheProvider",
"{",
"global",
":",
"newMapBlobDescriptorCache",
"(",
")",
",",
"repositories",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"mapBlobDescriptorCache",
")",
",",
"}",
"\n",
"}"
] |
// NewInMemoryBlobDescriptorCacheProvider returns a new mapped-based cache for
// storing blob descriptor data.
|
[
"NewInMemoryBlobDescriptorCacheProvider",
"returns",
"a",
"new",
"mapped",
"-",
"based",
"cache",
"for",
"storing",
"blob",
"descriptor",
"data",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/memory/memory.go#L21-L26
|
train
|
docker/distribution
|
registry/storage/registry.go
|
ManifestURLsAllowRegexp
|
func ManifestURLsAllowRegexp(r *regexp.Regexp) RegistryOption {
return func(registry *registry) error {
registry.manifestURLs.allow = r
return nil
}
}
|
go
|
func ManifestURLsAllowRegexp(r *regexp.Regexp) RegistryOption {
return func(registry *registry) error {
registry.manifestURLs.allow = r
return nil
}
}
|
[
"func",
"ManifestURLsAllowRegexp",
"(",
"r",
"*",
"regexp",
".",
"Regexp",
")",
"RegistryOption",
"{",
"return",
"func",
"(",
"registry",
"*",
"registry",
")",
"error",
"{",
"registry",
".",
"manifestURLs",
".",
"allow",
"=",
"r",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// ManifestURLsAllowRegexp is a functional option for NewRegistry.
|
[
"ManifestURLsAllowRegexp",
"is",
"a",
"functional",
"option",
"for",
"NewRegistry",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L68-L73
|
train
|
docker/distribution
|
registry/storage/registry.go
|
ManifestURLsDenyRegexp
|
func ManifestURLsDenyRegexp(r *regexp.Regexp) RegistryOption {
return func(registry *registry) error {
registry.manifestURLs.deny = r
return nil
}
}
|
go
|
func ManifestURLsDenyRegexp(r *regexp.Regexp) RegistryOption {
return func(registry *registry) error {
registry.manifestURLs.deny = r
return nil
}
}
|
[
"func",
"ManifestURLsDenyRegexp",
"(",
"r",
"*",
"regexp",
".",
"Regexp",
")",
"RegistryOption",
"{",
"return",
"func",
"(",
"registry",
"*",
"registry",
")",
"error",
"{",
"registry",
".",
"manifestURLs",
".",
"deny",
"=",
"r",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// ManifestURLsDenyRegexp is a functional option for NewRegistry.
|
[
"ManifestURLsDenyRegexp",
"is",
"a",
"functional",
"option",
"for",
"NewRegistry",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L76-L81
|
train
|
docker/distribution
|
registry/storage/registry.go
|
Schema1SigningKey
|
func Schema1SigningKey(key libtrust.PrivateKey) RegistryOption {
return func(registry *registry) error {
registry.schema1SigningKey = key
return nil
}
}
|
go
|
func Schema1SigningKey(key libtrust.PrivateKey) RegistryOption {
return func(registry *registry) error {
registry.schema1SigningKey = key
return nil
}
}
|
[
"func",
"Schema1SigningKey",
"(",
"key",
"libtrust",
".",
"PrivateKey",
")",
"RegistryOption",
"{",
"return",
"func",
"(",
"registry",
"*",
"registry",
")",
"error",
"{",
"registry",
".",
"schema1SigningKey",
"=",
"key",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// Schema1SigningKey returns a functional option for NewRegistry. It sets the
// key for signing all schema1 manifests.
|
[
"Schema1SigningKey",
"returns",
"a",
"functional",
"option",
"for",
"NewRegistry",
".",
"It",
"sets",
"the",
"key",
"for",
"signing",
"all",
"schema1",
"manifests",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L85-L90
|
train
|
docker/distribution
|
registry/storage/registry.go
|
BlobDescriptorServiceFactory
|
func BlobDescriptorServiceFactory(factory distribution.BlobDescriptorServiceFactory) RegistryOption {
return func(registry *registry) error {
registry.blobDescriptorServiceFactory = factory
return nil
}
}
|
go
|
func BlobDescriptorServiceFactory(factory distribution.BlobDescriptorServiceFactory) RegistryOption {
return func(registry *registry) error {
registry.blobDescriptorServiceFactory = factory
return nil
}
}
|
[
"func",
"BlobDescriptorServiceFactory",
"(",
"factory",
"distribution",
".",
"BlobDescriptorServiceFactory",
")",
"RegistryOption",
"{",
"return",
"func",
"(",
"registry",
"*",
"registry",
")",
"error",
"{",
"registry",
".",
"blobDescriptorServiceFactory",
"=",
"factory",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// BlobDescriptorServiceFactory returns a functional option for NewRegistry. It sets the
// factory to create BlobDescriptorServiceFactory middleware.
|
[
"BlobDescriptorServiceFactory",
"returns",
"a",
"functional",
"option",
"for",
"NewRegistry",
".",
"It",
"sets",
"the",
"factory",
"to",
"create",
"BlobDescriptorServiceFactory",
"middleware",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L94-L99
|
train
|
docker/distribution
|
registry/storage/registry.go
|
BlobDescriptorCacheProvider
|
func BlobDescriptorCacheProvider(blobDescriptorCacheProvider cache.BlobDescriptorCacheProvider) RegistryOption {
// TODO(aaronl): The duplication of statter across several objects is
// ugly, and prevents us from using interface types in the registry
// struct. Ideally, blobStore and blobServer should be lazily
// initialized, and use the current value of
// blobDescriptorCacheProvider.
return func(registry *registry) error {
if blobDescriptorCacheProvider != nil {
statter := cache.NewCachedBlobStatter(blobDescriptorCacheProvider, registry.statter)
registry.blobStore.statter = statter
registry.blobServer.statter = statter
registry.blobDescriptorCacheProvider = blobDescriptorCacheProvider
}
return nil
}
}
|
go
|
func BlobDescriptorCacheProvider(blobDescriptorCacheProvider cache.BlobDescriptorCacheProvider) RegistryOption {
// TODO(aaronl): The duplication of statter across several objects is
// ugly, and prevents us from using interface types in the registry
// struct. Ideally, blobStore and blobServer should be lazily
// initialized, and use the current value of
// blobDescriptorCacheProvider.
return func(registry *registry) error {
if blobDescriptorCacheProvider != nil {
statter := cache.NewCachedBlobStatter(blobDescriptorCacheProvider, registry.statter)
registry.blobStore.statter = statter
registry.blobServer.statter = statter
registry.blobDescriptorCacheProvider = blobDescriptorCacheProvider
}
return nil
}
}
|
[
"func",
"BlobDescriptorCacheProvider",
"(",
"blobDescriptorCacheProvider",
"cache",
".",
"BlobDescriptorCacheProvider",
")",
"RegistryOption",
"{",
"// TODO(aaronl): The duplication of statter across several objects is",
"// ugly, and prevents us from using interface types in the registry",
"// struct. Ideally, blobStore and blobServer should be lazily",
"// initialized, and use the current value of",
"// blobDescriptorCacheProvider.",
"return",
"func",
"(",
"registry",
"*",
"registry",
")",
"error",
"{",
"if",
"blobDescriptorCacheProvider",
"!=",
"nil",
"{",
"statter",
":=",
"cache",
".",
"NewCachedBlobStatter",
"(",
"blobDescriptorCacheProvider",
",",
"registry",
".",
"statter",
")",
"\n",
"registry",
".",
"blobStore",
".",
"statter",
"=",
"statter",
"\n",
"registry",
".",
"blobServer",
".",
"statter",
"=",
"statter",
"\n",
"registry",
".",
"blobDescriptorCacheProvider",
"=",
"blobDescriptorCacheProvider",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// BlobDescriptorCacheProvider returns a functional option for
// NewRegistry. It creates a cached blob statter for use by the
// registry.
|
[
"BlobDescriptorCacheProvider",
"returns",
"a",
"functional",
"option",
"for",
"NewRegistry",
".",
"It",
"creates",
"a",
"cached",
"blob",
"statter",
"for",
"use",
"by",
"the",
"registry",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L104-L119
|
train
|
docker/distribution
|
registry/storage/registry.go
|
Repository
|
func (reg *registry) Repository(ctx context.Context, canonicalName reference.Named) (distribution.Repository, error) {
var descriptorCache distribution.BlobDescriptorService
if reg.blobDescriptorCacheProvider != nil {
var err error
descriptorCache, err = reg.blobDescriptorCacheProvider.RepositoryScoped(canonicalName.Name())
if err != nil {
return nil, err
}
}
return &repository{
ctx: ctx,
registry: reg,
name: canonicalName,
descriptorCache: descriptorCache,
}, nil
}
|
go
|
func (reg *registry) Repository(ctx context.Context, canonicalName reference.Named) (distribution.Repository, error) {
var descriptorCache distribution.BlobDescriptorService
if reg.blobDescriptorCacheProvider != nil {
var err error
descriptorCache, err = reg.blobDescriptorCacheProvider.RepositoryScoped(canonicalName.Name())
if err != nil {
return nil, err
}
}
return &repository{
ctx: ctx,
registry: reg,
name: canonicalName,
descriptorCache: descriptorCache,
}, nil
}
|
[
"func",
"(",
"reg",
"*",
"registry",
")",
"Repository",
"(",
"ctx",
"context",
".",
"Context",
",",
"canonicalName",
"reference",
".",
"Named",
")",
"(",
"distribution",
".",
"Repository",
",",
"error",
")",
"{",
"var",
"descriptorCache",
"distribution",
".",
"BlobDescriptorService",
"\n",
"if",
"reg",
".",
"blobDescriptorCacheProvider",
"!=",
"nil",
"{",
"var",
"err",
"error",
"\n",
"descriptorCache",
",",
"err",
"=",
"reg",
".",
"blobDescriptorCacheProvider",
".",
"RepositoryScoped",
"(",
"canonicalName",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"repository",
"{",
"ctx",
":",
"ctx",
",",
"registry",
":",
"reg",
",",
"name",
":",
"canonicalName",
",",
"descriptorCache",
":",
"descriptorCache",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// Repository returns an instance of the repository tied to the registry.
// Instances should not be shared between goroutines but are cheap to
// allocate. In general, they should be request scoped.
|
[
"Repository",
"returns",
"an",
"instance",
"of",
"the",
"repository",
"tied",
"to",
"the",
"registry",
".",
"Instances",
"should",
"not",
"be",
"shared",
"between",
"goroutines",
"but",
"are",
"cheap",
"to",
"allocate",
".",
"In",
"general",
"they",
"should",
"be",
"request",
"scoped",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L166-L182
|
train
|
docker/distribution
|
registry/storage/registry.go
|
Manifests
|
func (repo *repository) Manifests(ctx context.Context, options ...distribution.ManifestServiceOption) (distribution.ManifestService, error) {
manifestLinkPathFns := []linkPathFunc{
// NOTE(stevvooe): Need to search through multiple locations since
// 2.1.0 unintentionally linked into _layers.
manifestRevisionLinkPath,
blobLinkPath,
}
manifestDirectoryPathSpec := manifestRevisionsPathSpec{name: repo.name.Name()}
var statter distribution.BlobDescriptorService = &linkedBlobStatter{
blobStore: repo.blobStore,
repository: repo,
linkPathFns: manifestLinkPathFns,
}
if repo.registry.blobDescriptorServiceFactory != nil {
statter = repo.registry.blobDescriptorServiceFactory.BlobAccessController(statter)
}
blobStore := &linkedBlobStore{
ctx: ctx,
blobStore: repo.blobStore,
repository: repo,
deleteEnabled: repo.registry.deleteEnabled,
blobAccessController: statter,
// TODO(stevvooe): linkPath limits this blob store to only
// manifests. This instance cannot be used for blob checks.
linkPathFns: manifestLinkPathFns,
linkDirectoryPathSpec: manifestDirectoryPathSpec,
}
var v1Handler ManifestHandler
if repo.schema1Enabled {
v1Handler = &signedManifestHandler{
ctx: ctx,
schema1SigningKey: repo.schema1SigningKey,
repository: repo,
blobStore: blobStore,
}
} else {
v1Handler = &v1UnsupportedHandler{
innerHandler: &signedManifestHandler{
ctx: ctx,
schema1SigningKey: repo.schema1SigningKey,
repository: repo,
blobStore: blobStore,
},
}
}
ms := &manifestStore{
ctx: ctx,
repository: repo,
blobStore: blobStore,
schema1Handler: v1Handler,
schema2Handler: &schema2ManifestHandler{
ctx: ctx,
repository: repo,
blobStore: blobStore,
manifestURLs: repo.registry.manifestURLs,
},
manifestListHandler: &manifestListHandler{
ctx: ctx,
repository: repo,
blobStore: blobStore,
},
ocischemaHandler: &ocischemaManifestHandler{
ctx: ctx,
repository: repo,
blobStore: blobStore,
manifestURLs: repo.registry.manifestURLs,
},
}
// Apply options
for _, option := range options {
err := option.Apply(ms)
if err != nil {
return nil, err
}
}
return ms, nil
}
|
go
|
func (repo *repository) Manifests(ctx context.Context, options ...distribution.ManifestServiceOption) (distribution.ManifestService, error) {
manifestLinkPathFns := []linkPathFunc{
// NOTE(stevvooe): Need to search through multiple locations since
// 2.1.0 unintentionally linked into _layers.
manifestRevisionLinkPath,
blobLinkPath,
}
manifestDirectoryPathSpec := manifestRevisionsPathSpec{name: repo.name.Name()}
var statter distribution.BlobDescriptorService = &linkedBlobStatter{
blobStore: repo.blobStore,
repository: repo,
linkPathFns: manifestLinkPathFns,
}
if repo.registry.blobDescriptorServiceFactory != nil {
statter = repo.registry.blobDescriptorServiceFactory.BlobAccessController(statter)
}
blobStore := &linkedBlobStore{
ctx: ctx,
blobStore: repo.blobStore,
repository: repo,
deleteEnabled: repo.registry.deleteEnabled,
blobAccessController: statter,
// TODO(stevvooe): linkPath limits this blob store to only
// manifests. This instance cannot be used for blob checks.
linkPathFns: manifestLinkPathFns,
linkDirectoryPathSpec: manifestDirectoryPathSpec,
}
var v1Handler ManifestHandler
if repo.schema1Enabled {
v1Handler = &signedManifestHandler{
ctx: ctx,
schema1SigningKey: repo.schema1SigningKey,
repository: repo,
blobStore: blobStore,
}
} else {
v1Handler = &v1UnsupportedHandler{
innerHandler: &signedManifestHandler{
ctx: ctx,
schema1SigningKey: repo.schema1SigningKey,
repository: repo,
blobStore: blobStore,
},
}
}
ms := &manifestStore{
ctx: ctx,
repository: repo,
blobStore: blobStore,
schema1Handler: v1Handler,
schema2Handler: &schema2ManifestHandler{
ctx: ctx,
repository: repo,
blobStore: blobStore,
manifestURLs: repo.registry.manifestURLs,
},
manifestListHandler: &manifestListHandler{
ctx: ctx,
repository: repo,
blobStore: blobStore,
},
ocischemaHandler: &ocischemaManifestHandler{
ctx: ctx,
repository: repo,
blobStore: blobStore,
manifestURLs: repo.registry.manifestURLs,
},
}
// Apply options
for _, option := range options {
err := option.Apply(ms)
if err != nil {
return nil, err
}
}
return ms, nil
}
|
[
"func",
"(",
"repo",
"*",
"repository",
")",
"Manifests",
"(",
"ctx",
"context",
".",
"Context",
",",
"options",
"...",
"distribution",
".",
"ManifestServiceOption",
")",
"(",
"distribution",
".",
"ManifestService",
",",
"error",
")",
"{",
"manifestLinkPathFns",
":=",
"[",
"]",
"linkPathFunc",
"{",
"// NOTE(stevvooe): Need to search through multiple locations since",
"// 2.1.0 unintentionally linked into _layers.",
"manifestRevisionLinkPath",
",",
"blobLinkPath",
",",
"}",
"\n\n",
"manifestDirectoryPathSpec",
":=",
"manifestRevisionsPathSpec",
"{",
"name",
":",
"repo",
".",
"name",
".",
"Name",
"(",
")",
"}",
"\n\n",
"var",
"statter",
"distribution",
".",
"BlobDescriptorService",
"=",
"&",
"linkedBlobStatter",
"{",
"blobStore",
":",
"repo",
".",
"blobStore",
",",
"repository",
":",
"repo",
",",
"linkPathFns",
":",
"manifestLinkPathFns",
",",
"}",
"\n\n",
"if",
"repo",
".",
"registry",
".",
"blobDescriptorServiceFactory",
"!=",
"nil",
"{",
"statter",
"=",
"repo",
".",
"registry",
".",
"blobDescriptorServiceFactory",
".",
"BlobAccessController",
"(",
"statter",
")",
"\n",
"}",
"\n\n",
"blobStore",
":=",
"&",
"linkedBlobStore",
"{",
"ctx",
":",
"ctx",
",",
"blobStore",
":",
"repo",
".",
"blobStore",
",",
"repository",
":",
"repo",
",",
"deleteEnabled",
":",
"repo",
".",
"registry",
".",
"deleteEnabled",
",",
"blobAccessController",
":",
"statter",
",",
"// TODO(stevvooe): linkPath limits this blob store to only",
"// manifests. This instance cannot be used for blob checks.",
"linkPathFns",
":",
"manifestLinkPathFns",
",",
"linkDirectoryPathSpec",
":",
"manifestDirectoryPathSpec",
",",
"}",
"\n\n",
"var",
"v1Handler",
"ManifestHandler",
"\n",
"if",
"repo",
".",
"schema1Enabled",
"{",
"v1Handler",
"=",
"&",
"signedManifestHandler",
"{",
"ctx",
":",
"ctx",
",",
"schema1SigningKey",
":",
"repo",
".",
"schema1SigningKey",
",",
"repository",
":",
"repo",
",",
"blobStore",
":",
"blobStore",
",",
"}",
"\n",
"}",
"else",
"{",
"v1Handler",
"=",
"&",
"v1UnsupportedHandler",
"{",
"innerHandler",
":",
"&",
"signedManifestHandler",
"{",
"ctx",
":",
"ctx",
",",
"schema1SigningKey",
":",
"repo",
".",
"schema1SigningKey",
",",
"repository",
":",
"repo",
",",
"blobStore",
":",
"blobStore",
",",
"}",
",",
"}",
"\n",
"}",
"\n\n",
"ms",
":=",
"&",
"manifestStore",
"{",
"ctx",
":",
"ctx",
",",
"repository",
":",
"repo",
",",
"blobStore",
":",
"blobStore",
",",
"schema1Handler",
":",
"v1Handler",
",",
"schema2Handler",
":",
"&",
"schema2ManifestHandler",
"{",
"ctx",
":",
"ctx",
",",
"repository",
":",
"repo",
",",
"blobStore",
":",
"blobStore",
",",
"manifestURLs",
":",
"repo",
".",
"registry",
".",
"manifestURLs",
",",
"}",
",",
"manifestListHandler",
":",
"&",
"manifestListHandler",
"{",
"ctx",
":",
"ctx",
",",
"repository",
":",
"repo",
",",
"blobStore",
":",
"blobStore",
",",
"}",
",",
"ocischemaHandler",
":",
"&",
"ocischemaManifestHandler",
"{",
"ctx",
":",
"ctx",
",",
"repository",
":",
"repo",
",",
"blobStore",
":",
"blobStore",
",",
"manifestURLs",
":",
"repo",
".",
"registry",
".",
"manifestURLs",
",",
"}",
",",
"}",
"\n\n",
"// Apply options",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"err",
":=",
"option",
".",
"Apply",
"(",
"ms",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"ms",
",",
"nil",
"\n",
"}"
] |
// Manifests returns an instance of ManifestService. Instantiation is cheap and
// may be context sensitive in the future. The instance should be used similar
// to a request local.
|
[
"Manifests",
"returns",
"an",
"instance",
"of",
"ManifestService",
".",
"Instantiation",
"is",
"cheap",
"and",
"may",
"be",
"context",
"sensitive",
"in",
"the",
"future",
".",
"The",
"instance",
"should",
"be",
"used",
"similar",
"to",
"a",
"request",
"local",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L217-L302
|
train
|
docker/distribution
|
registry/storage/registry.go
|
Blobs
|
func (repo *repository) Blobs(ctx context.Context) distribution.BlobStore {
var statter distribution.BlobDescriptorService = &linkedBlobStatter{
blobStore: repo.blobStore,
repository: repo,
linkPathFns: []linkPathFunc{blobLinkPath},
}
if repo.descriptorCache != nil {
statter = cache.NewCachedBlobStatter(repo.descriptorCache, statter)
}
if repo.registry.blobDescriptorServiceFactory != nil {
statter = repo.registry.blobDescriptorServiceFactory.BlobAccessController(statter)
}
return &linkedBlobStore{
registry: repo.registry,
blobStore: repo.blobStore,
blobServer: repo.blobServer,
blobAccessController: statter,
repository: repo,
ctx: ctx,
// TODO(stevvooe): linkPath limits this blob store to only layers.
// This instance cannot be used for manifest checks.
linkPathFns: []linkPathFunc{blobLinkPath},
deleteEnabled: repo.registry.deleteEnabled,
resumableDigestEnabled: repo.resumableDigestEnabled,
}
}
|
go
|
func (repo *repository) Blobs(ctx context.Context) distribution.BlobStore {
var statter distribution.BlobDescriptorService = &linkedBlobStatter{
blobStore: repo.blobStore,
repository: repo,
linkPathFns: []linkPathFunc{blobLinkPath},
}
if repo.descriptorCache != nil {
statter = cache.NewCachedBlobStatter(repo.descriptorCache, statter)
}
if repo.registry.blobDescriptorServiceFactory != nil {
statter = repo.registry.blobDescriptorServiceFactory.BlobAccessController(statter)
}
return &linkedBlobStore{
registry: repo.registry,
blobStore: repo.blobStore,
blobServer: repo.blobServer,
blobAccessController: statter,
repository: repo,
ctx: ctx,
// TODO(stevvooe): linkPath limits this blob store to only layers.
// This instance cannot be used for manifest checks.
linkPathFns: []linkPathFunc{blobLinkPath},
deleteEnabled: repo.registry.deleteEnabled,
resumableDigestEnabled: repo.resumableDigestEnabled,
}
}
|
[
"func",
"(",
"repo",
"*",
"repository",
")",
"Blobs",
"(",
"ctx",
"context",
".",
"Context",
")",
"distribution",
".",
"BlobStore",
"{",
"var",
"statter",
"distribution",
".",
"BlobDescriptorService",
"=",
"&",
"linkedBlobStatter",
"{",
"blobStore",
":",
"repo",
".",
"blobStore",
",",
"repository",
":",
"repo",
",",
"linkPathFns",
":",
"[",
"]",
"linkPathFunc",
"{",
"blobLinkPath",
"}",
",",
"}",
"\n\n",
"if",
"repo",
".",
"descriptorCache",
"!=",
"nil",
"{",
"statter",
"=",
"cache",
".",
"NewCachedBlobStatter",
"(",
"repo",
".",
"descriptorCache",
",",
"statter",
")",
"\n",
"}",
"\n\n",
"if",
"repo",
".",
"registry",
".",
"blobDescriptorServiceFactory",
"!=",
"nil",
"{",
"statter",
"=",
"repo",
".",
"registry",
".",
"blobDescriptorServiceFactory",
".",
"BlobAccessController",
"(",
"statter",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"linkedBlobStore",
"{",
"registry",
":",
"repo",
".",
"registry",
",",
"blobStore",
":",
"repo",
".",
"blobStore",
",",
"blobServer",
":",
"repo",
".",
"blobServer",
",",
"blobAccessController",
":",
"statter",
",",
"repository",
":",
"repo",
",",
"ctx",
":",
"ctx",
",",
"// TODO(stevvooe): linkPath limits this blob store to only layers.",
"// This instance cannot be used for manifest checks.",
"linkPathFns",
":",
"[",
"]",
"linkPathFunc",
"{",
"blobLinkPath",
"}",
",",
"deleteEnabled",
":",
"repo",
".",
"registry",
".",
"deleteEnabled",
",",
"resumableDigestEnabled",
":",
"repo",
".",
"resumableDigestEnabled",
",",
"}",
"\n",
"}"
] |
// Blobs returns an instance of the BlobStore. Instantiation is cheap and
// may be context sensitive in the future. The instance should be used similar
// to a request local.
|
[
"Blobs",
"returns",
"an",
"instance",
"of",
"the",
"BlobStore",
".",
"Instantiation",
"is",
"cheap",
"and",
"may",
"be",
"context",
"sensitive",
"in",
"the",
"future",
".",
"The",
"instance",
"should",
"be",
"used",
"similar",
"to",
"a",
"request",
"local",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/registry.go#L307-L336
|
train
|
docker/distribution
|
notifications/endpoint.go
|
defaults
|
func (ec *EndpointConfig) defaults() {
if ec.Timeout <= 0 {
ec.Timeout = time.Second
}
if ec.Threshold <= 0 {
ec.Threshold = 10
}
if ec.Backoff <= 0 {
ec.Backoff = time.Second
}
if ec.Transport == nil {
ec.Transport = http.DefaultTransport.(*http.Transport)
}
}
|
go
|
func (ec *EndpointConfig) defaults() {
if ec.Timeout <= 0 {
ec.Timeout = time.Second
}
if ec.Threshold <= 0 {
ec.Threshold = 10
}
if ec.Backoff <= 0 {
ec.Backoff = time.Second
}
if ec.Transport == nil {
ec.Transport = http.DefaultTransport.(*http.Transport)
}
}
|
[
"func",
"(",
"ec",
"*",
"EndpointConfig",
")",
"defaults",
"(",
")",
"{",
"if",
"ec",
".",
"Timeout",
"<=",
"0",
"{",
"ec",
".",
"Timeout",
"=",
"time",
".",
"Second",
"\n",
"}",
"\n\n",
"if",
"ec",
".",
"Threshold",
"<=",
"0",
"{",
"ec",
".",
"Threshold",
"=",
"10",
"\n",
"}",
"\n\n",
"if",
"ec",
".",
"Backoff",
"<=",
"0",
"{",
"ec",
".",
"Backoff",
"=",
"time",
".",
"Second",
"\n",
"}",
"\n\n",
"if",
"ec",
".",
"Transport",
"==",
"nil",
"{",
"ec",
".",
"Transport",
"=",
"http",
".",
"DefaultTransport",
".",
"(",
"*",
"http",
".",
"Transport",
")",
"\n",
"}",
"\n",
"}"
] |
// defaults set any zero-valued fields to a reasonable default.
|
[
"defaults",
"set",
"any",
"zero",
"-",
"valued",
"fields",
"to",
"a",
"reasonable",
"default",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/endpoint.go#L23-L39
|
train
|
docker/distribution
|
notifications/endpoint.go
|
NewEndpoint
|
func NewEndpoint(name, url string, config EndpointConfig) *Endpoint {
var endpoint Endpoint
endpoint.name = name
endpoint.url = url
endpoint.EndpointConfig = config
endpoint.defaults()
endpoint.metrics = newSafeMetrics()
// Configures the inmemory queue, retry, http pipeline.
endpoint.Sink = newHTTPSink(
endpoint.url, endpoint.Timeout, endpoint.Headers,
endpoint.Transport, endpoint.metrics.httpStatusListener())
endpoint.Sink = newRetryingSink(endpoint.Sink, endpoint.Threshold, endpoint.Backoff)
endpoint.Sink = newEventQueue(endpoint.Sink, endpoint.metrics.eventQueueListener())
mediaTypes := append(config.Ignore.MediaTypes, config.IgnoredMediaTypes...)
endpoint.Sink = newIgnoredSink(endpoint.Sink, mediaTypes, config.Ignore.Actions)
register(&endpoint)
return &endpoint
}
|
go
|
func NewEndpoint(name, url string, config EndpointConfig) *Endpoint {
var endpoint Endpoint
endpoint.name = name
endpoint.url = url
endpoint.EndpointConfig = config
endpoint.defaults()
endpoint.metrics = newSafeMetrics()
// Configures the inmemory queue, retry, http pipeline.
endpoint.Sink = newHTTPSink(
endpoint.url, endpoint.Timeout, endpoint.Headers,
endpoint.Transport, endpoint.metrics.httpStatusListener())
endpoint.Sink = newRetryingSink(endpoint.Sink, endpoint.Threshold, endpoint.Backoff)
endpoint.Sink = newEventQueue(endpoint.Sink, endpoint.metrics.eventQueueListener())
mediaTypes := append(config.Ignore.MediaTypes, config.IgnoredMediaTypes...)
endpoint.Sink = newIgnoredSink(endpoint.Sink, mediaTypes, config.Ignore.Actions)
register(&endpoint)
return &endpoint
}
|
[
"func",
"NewEndpoint",
"(",
"name",
",",
"url",
"string",
",",
"config",
"EndpointConfig",
")",
"*",
"Endpoint",
"{",
"var",
"endpoint",
"Endpoint",
"\n",
"endpoint",
".",
"name",
"=",
"name",
"\n",
"endpoint",
".",
"url",
"=",
"url",
"\n",
"endpoint",
".",
"EndpointConfig",
"=",
"config",
"\n",
"endpoint",
".",
"defaults",
"(",
")",
"\n",
"endpoint",
".",
"metrics",
"=",
"newSafeMetrics",
"(",
")",
"\n\n",
"// Configures the inmemory queue, retry, http pipeline.",
"endpoint",
".",
"Sink",
"=",
"newHTTPSink",
"(",
"endpoint",
".",
"url",
",",
"endpoint",
".",
"Timeout",
",",
"endpoint",
".",
"Headers",
",",
"endpoint",
".",
"Transport",
",",
"endpoint",
".",
"metrics",
".",
"httpStatusListener",
"(",
")",
")",
"\n",
"endpoint",
".",
"Sink",
"=",
"newRetryingSink",
"(",
"endpoint",
".",
"Sink",
",",
"endpoint",
".",
"Threshold",
",",
"endpoint",
".",
"Backoff",
")",
"\n",
"endpoint",
".",
"Sink",
"=",
"newEventQueue",
"(",
"endpoint",
".",
"Sink",
",",
"endpoint",
".",
"metrics",
".",
"eventQueueListener",
"(",
")",
")",
"\n",
"mediaTypes",
":=",
"append",
"(",
"config",
".",
"Ignore",
".",
"MediaTypes",
",",
"config",
".",
"IgnoredMediaTypes",
"...",
")",
"\n",
"endpoint",
".",
"Sink",
"=",
"newIgnoredSink",
"(",
"endpoint",
".",
"Sink",
",",
"mediaTypes",
",",
"config",
".",
"Ignore",
".",
"Actions",
")",
"\n\n",
"register",
"(",
"&",
"endpoint",
")",
"\n",
"return",
"&",
"endpoint",
"\n",
"}"
] |
// NewEndpoint returns a running endpoint, ready to receive events.
|
[
"NewEndpoint",
"returns",
"a",
"running",
"endpoint",
"ready",
"to",
"receive",
"events",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/endpoint.go#L55-L74
|
train
|
docker/distribution
|
notifications/endpoint.go
|
ReadMetrics
|
func (e *Endpoint) ReadMetrics(em *EndpointMetrics) {
e.metrics.Lock()
defer e.metrics.Unlock()
*em = e.metrics.EndpointMetrics
// Map still need to copied in a threadsafe manner.
em.Statuses = make(map[string]int)
for k, v := range e.metrics.Statuses {
em.Statuses[k] = v
}
}
|
go
|
func (e *Endpoint) ReadMetrics(em *EndpointMetrics) {
e.metrics.Lock()
defer e.metrics.Unlock()
*em = e.metrics.EndpointMetrics
// Map still need to copied in a threadsafe manner.
em.Statuses = make(map[string]int)
for k, v := range e.metrics.Statuses {
em.Statuses[k] = v
}
}
|
[
"func",
"(",
"e",
"*",
"Endpoint",
")",
"ReadMetrics",
"(",
"em",
"*",
"EndpointMetrics",
")",
"{",
"e",
".",
"metrics",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"metrics",
".",
"Unlock",
"(",
")",
"\n\n",
"*",
"em",
"=",
"e",
".",
"metrics",
".",
"EndpointMetrics",
"\n",
"// Map still need to copied in a threadsafe manner.",
"em",
".",
"Statuses",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"e",
".",
"metrics",
".",
"Statuses",
"{",
"em",
".",
"Statuses",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}"
] |
// ReadMetrics populates em with metrics from the endpoint.
|
[
"ReadMetrics",
"populates",
"em",
"with",
"metrics",
"from",
"the",
"endpoint",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/endpoint.go#L87-L97
|
train
|
docker/distribution
|
manifest/schema1/config_builder.go
|
NewConfigManifestBuilder
|
func NewConfigManifestBuilder(bs distribution.BlobService, pk libtrust.PrivateKey, ref reference.Named, configJSON []byte) distribution.ManifestBuilder {
return &configManifestBuilder{
bs: bs,
pk: pk,
configJSON: configJSON,
ref: ref,
}
}
|
go
|
func NewConfigManifestBuilder(bs distribution.BlobService, pk libtrust.PrivateKey, ref reference.Named, configJSON []byte) distribution.ManifestBuilder {
return &configManifestBuilder{
bs: bs,
pk: pk,
configJSON: configJSON,
ref: ref,
}
}
|
[
"func",
"NewConfigManifestBuilder",
"(",
"bs",
"distribution",
".",
"BlobService",
",",
"pk",
"libtrust",
".",
"PrivateKey",
",",
"ref",
"reference",
".",
"Named",
",",
"configJSON",
"[",
"]",
"byte",
")",
"distribution",
".",
"ManifestBuilder",
"{",
"return",
"&",
"configManifestBuilder",
"{",
"bs",
":",
"bs",
",",
"pk",
":",
"pk",
",",
"configJSON",
":",
"configJSON",
",",
"ref",
":",
"ref",
",",
"}",
"\n",
"}"
] |
// NewConfigManifestBuilder is used to build new manifests for the current
// schema version from an image configuration and a set of descriptors.
// It takes a BlobService so that it can add an empty tar to the blob store
// if the resulting manifest needs empty layers.
|
[
"NewConfigManifestBuilder",
"is",
"used",
"to",
"build",
"new",
"manifests",
"for",
"the",
"current",
"schema",
"version",
"from",
"an",
"image",
"configuration",
"and",
"a",
"set",
"of",
"descriptors",
".",
"It",
"takes",
"a",
"BlobService",
"so",
"that",
"it",
"can",
"add",
"an",
"empty",
"tar",
"to",
"the",
"blob",
"store",
"if",
"the",
"resulting",
"manifest",
"needs",
"empty",
"layers",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/config_builder.go#L55-L62
|
train
|
docker/distribution
|
manifest/schema1/config_builder.go
|
emptyTar
|
func (mb *configManifestBuilder) emptyTar(ctx context.Context) (digest.Digest, error) {
if mb.emptyTarDigest != "" {
// Already put an empty tar
return mb.emptyTarDigest, nil
}
descriptor, err := mb.bs.Stat(ctx, digestSHA256GzippedEmptyTar)
switch err {
case nil:
mb.emptyTarDigest = descriptor.Digest
return descriptor.Digest, nil
case distribution.ErrBlobUnknown:
// nop
default:
return "", err
}
// Add gzipped empty tar to the blob store
descriptor, err = mb.bs.Put(ctx, "", gzippedEmptyTar)
if err != nil {
return "", err
}
mb.emptyTarDigest = descriptor.Digest
return descriptor.Digest, nil
}
|
go
|
func (mb *configManifestBuilder) emptyTar(ctx context.Context) (digest.Digest, error) {
if mb.emptyTarDigest != "" {
// Already put an empty tar
return mb.emptyTarDigest, nil
}
descriptor, err := mb.bs.Stat(ctx, digestSHA256GzippedEmptyTar)
switch err {
case nil:
mb.emptyTarDigest = descriptor.Digest
return descriptor.Digest, nil
case distribution.ErrBlobUnknown:
// nop
default:
return "", err
}
// Add gzipped empty tar to the blob store
descriptor, err = mb.bs.Put(ctx, "", gzippedEmptyTar)
if err != nil {
return "", err
}
mb.emptyTarDigest = descriptor.Digest
return descriptor.Digest, nil
}
|
[
"func",
"(",
"mb",
"*",
"configManifestBuilder",
")",
"emptyTar",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"if",
"mb",
".",
"emptyTarDigest",
"!=",
"\"",
"\"",
"{",
"// Already put an empty tar",
"return",
"mb",
".",
"emptyTarDigest",
",",
"nil",
"\n",
"}",
"\n\n",
"descriptor",
",",
"err",
":=",
"mb",
".",
"bs",
".",
"Stat",
"(",
"ctx",
",",
"digestSHA256GzippedEmptyTar",
")",
"\n",
"switch",
"err",
"{",
"case",
"nil",
":",
"mb",
".",
"emptyTarDigest",
"=",
"descriptor",
".",
"Digest",
"\n",
"return",
"descriptor",
".",
"Digest",
",",
"nil",
"\n",
"case",
"distribution",
".",
"ErrBlobUnknown",
":",
"// nop",
"default",
":",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"// Add gzipped empty tar to the blob store",
"descriptor",
",",
"err",
"=",
"mb",
".",
"bs",
".",
"Put",
"(",
"ctx",
",",
"\"",
"\"",
",",
"gzippedEmptyTar",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"mb",
".",
"emptyTarDigest",
"=",
"descriptor",
".",
"Digest",
"\n\n",
"return",
"descriptor",
".",
"Digest",
",",
"nil",
"\n",
"}"
] |
// emptyTar pushes a compressed empty tar to the blob store if one doesn't
// already exist, and returns its blobsum.
|
[
"emptyTar",
"pushes",
"a",
"compressed",
"empty",
"tar",
"to",
"the",
"blob",
"store",
"if",
"one",
"doesn",
"t",
"already",
"exist",
"and",
"returns",
"its",
"blobsum",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/config_builder.go#L213-L239
|
train
|
docker/distribution
|
manifest/schema1/config_builder.go
|
MakeV1ConfigFromConfig
|
func MakeV1ConfigFromConfig(configJSON []byte, v1ID, parentV1ID string, throwaway bool) ([]byte, error) {
// Top-level v1compatibility string should be a modified version of the
// image config.
var configAsMap map[string]*json.RawMessage
if err := json.Unmarshal(configJSON, &configAsMap); err != nil {
return nil, err
}
// Delete fields that didn't exist in old manifest
delete(configAsMap, "rootfs")
delete(configAsMap, "history")
configAsMap["id"] = rawJSON(v1ID)
if parentV1ID != "" {
configAsMap["parent"] = rawJSON(parentV1ID)
}
if throwaway {
configAsMap["throwaway"] = rawJSON(true)
}
return json.Marshal(configAsMap)
}
|
go
|
func MakeV1ConfigFromConfig(configJSON []byte, v1ID, parentV1ID string, throwaway bool) ([]byte, error) {
// Top-level v1compatibility string should be a modified version of the
// image config.
var configAsMap map[string]*json.RawMessage
if err := json.Unmarshal(configJSON, &configAsMap); err != nil {
return nil, err
}
// Delete fields that didn't exist in old manifest
delete(configAsMap, "rootfs")
delete(configAsMap, "history")
configAsMap["id"] = rawJSON(v1ID)
if parentV1ID != "" {
configAsMap["parent"] = rawJSON(parentV1ID)
}
if throwaway {
configAsMap["throwaway"] = rawJSON(true)
}
return json.Marshal(configAsMap)
}
|
[
"func",
"MakeV1ConfigFromConfig",
"(",
"configJSON",
"[",
"]",
"byte",
",",
"v1ID",
",",
"parentV1ID",
"string",
",",
"throwaway",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Top-level v1compatibility string should be a modified version of the",
"// image config.",
"var",
"configAsMap",
"map",
"[",
"string",
"]",
"*",
"json",
".",
"RawMessage",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"configJSON",
",",
"&",
"configAsMap",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Delete fields that didn't exist in old manifest",
"delete",
"(",
"configAsMap",
",",
"\"",
"\"",
")",
"\n",
"delete",
"(",
"configAsMap",
",",
"\"",
"\"",
")",
"\n",
"configAsMap",
"[",
"\"",
"\"",
"]",
"=",
"rawJSON",
"(",
"v1ID",
")",
"\n",
"if",
"parentV1ID",
"!=",
"\"",
"\"",
"{",
"configAsMap",
"[",
"\"",
"\"",
"]",
"=",
"rawJSON",
"(",
"parentV1ID",
")",
"\n",
"}",
"\n",
"if",
"throwaway",
"{",
"configAsMap",
"[",
"\"",
"\"",
"]",
"=",
"rawJSON",
"(",
"true",
")",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"configAsMap",
")",
"\n",
"}"
] |
// MakeV1ConfigFromConfig creates an legacy V1 image config from image config JSON
|
[
"MakeV1ConfigFromConfig",
"creates",
"an",
"legacy",
"V1",
"image",
"config",
"from",
"image",
"config",
"JSON"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/config_builder.go#L259-L279
|
train
|
docker/distribution
|
registry/storage/driver/azure/azure.go
|
FromParameters
|
func FromParameters(parameters map[string]interface{}) (*Driver, error) {
accountName, ok := parameters[paramAccountName]
if !ok || fmt.Sprint(accountName) == "" {
return nil, fmt.Errorf("no %s parameter provided", paramAccountName)
}
accountKey, ok := parameters[paramAccountKey]
if !ok || fmt.Sprint(accountKey) == "" {
return nil, fmt.Errorf("no %s parameter provided", paramAccountKey)
}
container, ok := parameters[paramContainer]
if !ok || fmt.Sprint(container) == "" {
return nil, fmt.Errorf("no %s parameter provided", paramContainer)
}
realm, ok := parameters[paramRealm]
if !ok || fmt.Sprint(realm) == "" {
realm = azure.DefaultBaseURL
}
return New(fmt.Sprint(accountName), fmt.Sprint(accountKey), fmt.Sprint(container), fmt.Sprint(realm))
}
|
go
|
func FromParameters(parameters map[string]interface{}) (*Driver, error) {
accountName, ok := parameters[paramAccountName]
if !ok || fmt.Sprint(accountName) == "" {
return nil, fmt.Errorf("no %s parameter provided", paramAccountName)
}
accountKey, ok := parameters[paramAccountKey]
if !ok || fmt.Sprint(accountKey) == "" {
return nil, fmt.Errorf("no %s parameter provided", paramAccountKey)
}
container, ok := parameters[paramContainer]
if !ok || fmt.Sprint(container) == "" {
return nil, fmt.Errorf("no %s parameter provided", paramContainer)
}
realm, ok := parameters[paramRealm]
if !ok || fmt.Sprint(realm) == "" {
realm = azure.DefaultBaseURL
}
return New(fmt.Sprint(accountName), fmt.Sprint(accountKey), fmt.Sprint(container), fmt.Sprint(realm))
}
|
[
"func",
"FromParameters",
"(",
"parameters",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"*",
"Driver",
",",
"error",
")",
"{",
"accountName",
",",
"ok",
":=",
"parameters",
"[",
"paramAccountName",
"]",
"\n",
"if",
"!",
"ok",
"||",
"fmt",
".",
"Sprint",
"(",
"accountName",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"paramAccountName",
")",
"\n",
"}",
"\n\n",
"accountKey",
",",
"ok",
":=",
"parameters",
"[",
"paramAccountKey",
"]",
"\n",
"if",
"!",
"ok",
"||",
"fmt",
".",
"Sprint",
"(",
"accountKey",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"paramAccountKey",
")",
"\n",
"}",
"\n\n",
"container",
",",
"ok",
":=",
"parameters",
"[",
"paramContainer",
"]",
"\n",
"if",
"!",
"ok",
"||",
"fmt",
".",
"Sprint",
"(",
"container",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"paramContainer",
")",
"\n",
"}",
"\n\n",
"realm",
",",
"ok",
":=",
"parameters",
"[",
"paramRealm",
"]",
"\n",
"if",
"!",
"ok",
"||",
"fmt",
".",
"Sprint",
"(",
"realm",
")",
"==",
"\"",
"\"",
"{",
"realm",
"=",
"azure",
".",
"DefaultBaseURL",
"\n",
"}",
"\n\n",
"return",
"New",
"(",
"fmt",
".",
"Sprint",
"(",
"accountName",
")",
",",
"fmt",
".",
"Sprint",
"(",
"accountKey",
")",
",",
"fmt",
".",
"Sprint",
"(",
"container",
")",
",",
"fmt",
".",
"Sprint",
"(",
"realm",
")",
")",
"\n",
"}"
] |
// FromParameters constructs a new Driver with a given parameters map.
|
[
"FromParameters",
"constructs",
"a",
"new",
"Driver",
"with",
"a",
"given",
"parameters",
"map",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/azure/azure.go#L55-L77
|
train
|
docker/distribution
|
registry/storage/driver/azure/azure.go
|
New
|
func New(accountName, accountKey, container, realm string) (*Driver, error) {
api, err := azure.NewClient(accountName, accountKey, realm, azure.DefaultAPIVersion, true)
if err != nil {
return nil, err
}
blobClient := api.GetBlobService()
// Create registry container
containerRef := blobClient.GetContainerReference(container)
if _, err = containerRef.CreateIfNotExists(nil); err != nil {
return nil, err
}
d := &driver{
client: blobClient,
container: container}
return &Driver{baseEmbed: baseEmbed{Base: base.Base{StorageDriver: d}}}, nil
}
|
go
|
func New(accountName, accountKey, container, realm string) (*Driver, error) {
api, err := azure.NewClient(accountName, accountKey, realm, azure.DefaultAPIVersion, true)
if err != nil {
return nil, err
}
blobClient := api.GetBlobService()
// Create registry container
containerRef := blobClient.GetContainerReference(container)
if _, err = containerRef.CreateIfNotExists(nil); err != nil {
return nil, err
}
d := &driver{
client: blobClient,
container: container}
return &Driver{baseEmbed: baseEmbed{Base: base.Base{StorageDriver: d}}}, nil
}
|
[
"func",
"New",
"(",
"accountName",
",",
"accountKey",
",",
"container",
",",
"realm",
"string",
")",
"(",
"*",
"Driver",
",",
"error",
")",
"{",
"api",
",",
"err",
":=",
"azure",
".",
"NewClient",
"(",
"accountName",
",",
"accountKey",
",",
"realm",
",",
"azure",
".",
"DefaultAPIVersion",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"blobClient",
":=",
"api",
".",
"GetBlobService",
"(",
")",
"\n\n",
"// Create registry container",
"containerRef",
":=",
"blobClient",
".",
"GetContainerReference",
"(",
"container",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"containerRef",
".",
"CreateIfNotExists",
"(",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"d",
":=",
"&",
"driver",
"{",
"client",
":",
"blobClient",
",",
"container",
":",
"container",
"}",
"\n",
"return",
"&",
"Driver",
"{",
"baseEmbed",
":",
"baseEmbed",
"{",
"Base",
":",
"base",
".",
"Base",
"{",
"StorageDriver",
":",
"d",
"}",
"}",
"}",
",",
"nil",
"\n",
"}"
] |
// New constructs a new Driver with the given Azure Storage Account credentials
|
[
"New",
"constructs",
"a",
"new",
"Driver",
"with",
"the",
"given",
"Azure",
"Storage",
"Account",
"credentials"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/azure/azure.go#L80-L98
|
train
|
docker/distribution
|
notifications/sinks.go
|
NewBroadcaster
|
func NewBroadcaster(sinks ...Sink) *Broadcaster {
b := Broadcaster{
sinks: sinks,
events: make(chan []Event),
closed: make(chan chan struct{}),
}
// Start the broadcaster
go b.run()
return &b
}
|
go
|
func NewBroadcaster(sinks ...Sink) *Broadcaster {
b := Broadcaster{
sinks: sinks,
events: make(chan []Event),
closed: make(chan chan struct{}),
}
// Start the broadcaster
go b.run()
return &b
}
|
[
"func",
"NewBroadcaster",
"(",
"sinks",
"...",
"Sink",
")",
"*",
"Broadcaster",
"{",
"b",
":=",
"Broadcaster",
"{",
"sinks",
":",
"sinks",
",",
"events",
":",
"make",
"(",
"chan",
"[",
"]",
"Event",
")",
",",
"closed",
":",
"make",
"(",
"chan",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n\n",
"// Start the broadcaster",
"go",
"b",
".",
"run",
"(",
")",
"\n\n",
"return",
"&",
"b",
"\n",
"}"
] |
// NewBroadcaster ...
// Add appends one or more sinks to the list of sinks. The broadcaster
// behavior will be affected by the properties of the sink. Generally, the
// sink should accept all messages and deal with reliability on its own. Use
// of EventQueue and RetryingSink should be used here.
|
[
"NewBroadcaster",
"...",
"Add",
"appends",
"one",
"or",
"more",
"sinks",
"to",
"the",
"list",
"of",
"sinks",
".",
"The",
"broadcaster",
"behavior",
"will",
"be",
"affected",
"by",
"the",
"properties",
"of",
"the",
"sink",
".",
"Generally",
"the",
"sink",
"should",
"accept",
"all",
"messages",
"and",
"deal",
"with",
"reliability",
"on",
"its",
"own",
".",
"Use",
"of",
"EventQueue",
"and",
"RetryingSink",
"should",
"be",
"used",
"here",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L31-L42
|
train
|
docker/distribution
|
notifications/sinks.go
|
newEventQueue
|
func newEventQueue(sink Sink, listeners ...eventQueueListener) *eventQueue {
eq := eventQueue{
sink: sink,
events: list.New(),
listeners: listeners,
}
eq.cond = sync.NewCond(&eq.mu)
go eq.run()
return &eq
}
|
go
|
func newEventQueue(sink Sink, listeners ...eventQueueListener) *eventQueue {
eq := eventQueue{
sink: sink,
events: list.New(),
listeners: listeners,
}
eq.cond = sync.NewCond(&eq.mu)
go eq.run()
return &eq
}
|
[
"func",
"newEventQueue",
"(",
"sink",
"Sink",
",",
"listeners",
"...",
"eventQueueListener",
")",
"*",
"eventQueue",
"{",
"eq",
":=",
"eventQueue",
"{",
"sink",
":",
"sink",
",",
"events",
":",
"list",
".",
"New",
"(",
")",
",",
"listeners",
":",
"listeners",
",",
"}",
"\n\n",
"eq",
".",
"cond",
"=",
"sync",
".",
"NewCond",
"(",
"&",
"eq",
".",
"mu",
")",
"\n",
"go",
"eq",
".",
"run",
"(",
")",
"\n",
"return",
"&",
"eq",
"\n",
"}"
] |
// newEventQueue returns a queue to the provided sink. If the updater is non-
// nil, it will be called to update pending metrics on ingress and egress.
|
[
"newEventQueue",
"returns",
"a",
"queue",
"to",
"the",
"provided",
"sink",
".",
"If",
"the",
"updater",
"is",
"non",
"-",
"nil",
"it",
"will",
"be",
"called",
"to",
"update",
"pending",
"metrics",
"on",
"ingress",
"and",
"egress",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L123-L133
|
train
|
docker/distribution
|
notifications/sinks.go
|
Write
|
func (eq *eventQueue) Write(events ...Event) error {
eq.mu.Lock()
defer eq.mu.Unlock()
if eq.closed {
return ErrSinkClosed
}
for _, listener := range eq.listeners {
listener.ingress(events...)
}
eq.events.PushBack(events)
eq.cond.Signal() // signal waiters
return nil
}
|
go
|
func (eq *eventQueue) Write(events ...Event) error {
eq.mu.Lock()
defer eq.mu.Unlock()
if eq.closed {
return ErrSinkClosed
}
for _, listener := range eq.listeners {
listener.ingress(events...)
}
eq.events.PushBack(events)
eq.cond.Signal() // signal waiters
return nil
}
|
[
"func",
"(",
"eq",
"*",
"eventQueue",
")",
"Write",
"(",
"events",
"...",
"Event",
")",
"error",
"{",
"eq",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"eq",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"eq",
".",
"closed",
"{",
"return",
"ErrSinkClosed",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"listener",
":=",
"range",
"eq",
".",
"listeners",
"{",
"listener",
".",
"ingress",
"(",
"events",
"...",
")",
"\n",
"}",
"\n",
"eq",
".",
"events",
".",
"PushBack",
"(",
"events",
")",
"\n",
"eq",
".",
"cond",
".",
"Signal",
"(",
")",
"// signal waiters",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Write accepts the events into the queue, only failing if the queue has
// beend closed.
|
[
"Write",
"accepts",
"the",
"events",
"into",
"the",
"queue",
"only",
"failing",
"if",
"the",
"queue",
"has",
"beend",
"closed",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L137-L152
|
train
|
docker/distribution
|
notifications/sinks.go
|
Close
|
func (eq *eventQueue) Close() error {
eq.mu.Lock()
defer eq.mu.Unlock()
if eq.closed {
return fmt.Errorf("eventqueue: already closed")
}
// set closed flag
eq.closed = true
eq.cond.Signal() // signal flushes queue
eq.cond.Wait() // wait for signal from last flush
return eq.sink.Close()
}
|
go
|
func (eq *eventQueue) Close() error {
eq.mu.Lock()
defer eq.mu.Unlock()
if eq.closed {
return fmt.Errorf("eventqueue: already closed")
}
// set closed flag
eq.closed = true
eq.cond.Signal() // signal flushes queue
eq.cond.Wait() // wait for signal from last flush
return eq.sink.Close()
}
|
[
"func",
"(",
"eq",
"*",
"eventQueue",
")",
"Close",
"(",
")",
"error",
"{",
"eq",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"eq",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"eq",
".",
"closed",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// set closed flag",
"eq",
".",
"closed",
"=",
"true",
"\n",
"eq",
".",
"cond",
".",
"Signal",
"(",
")",
"// signal flushes queue",
"\n",
"eq",
".",
"cond",
".",
"Wait",
"(",
")",
"// wait for signal from last flush",
"\n\n",
"return",
"eq",
".",
"sink",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Close shuts down the event queue, flushing
|
[
"Close",
"shuts",
"down",
"the",
"event",
"queue",
"flushing"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L155-L169
|
train
|
docker/distribution
|
notifications/sinks.go
|
next
|
func (eq *eventQueue) next() []Event {
eq.mu.Lock()
defer eq.mu.Unlock()
for eq.events.Len() < 1 {
if eq.closed {
eq.cond.Broadcast()
return nil
}
eq.cond.Wait()
}
front := eq.events.Front()
block := front.Value.([]Event)
eq.events.Remove(front)
return block
}
|
go
|
func (eq *eventQueue) next() []Event {
eq.mu.Lock()
defer eq.mu.Unlock()
for eq.events.Len() < 1 {
if eq.closed {
eq.cond.Broadcast()
return nil
}
eq.cond.Wait()
}
front := eq.events.Front()
block := front.Value.([]Event)
eq.events.Remove(front)
return block
}
|
[
"func",
"(",
"eq",
"*",
"eventQueue",
")",
"next",
"(",
")",
"[",
"]",
"Event",
"{",
"eq",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"eq",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"eq",
".",
"events",
".",
"Len",
"(",
")",
"<",
"1",
"{",
"if",
"eq",
".",
"closed",
"{",
"eq",
".",
"cond",
".",
"Broadcast",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"eq",
".",
"cond",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n\n",
"front",
":=",
"eq",
".",
"events",
".",
"Front",
"(",
")",
"\n",
"block",
":=",
"front",
".",
"Value",
".",
"(",
"[",
"]",
"Event",
")",
"\n",
"eq",
".",
"events",
".",
"Remove",
"(",
"front",
")",
"\n\n",
"return",
"block",
"\n",
"}"
] |
// next encompasses the critical section of the run loop. When the queue is
// empty, it will block on the condition. If new data arrives, it will wake
// and return a block. When closed, a nil slice will be returned.
|
[
"next",
"encompasses",
"the",
"critical",
"section",
"of",
"the",
"run",
"loop",
".",
"When",
"the",
"queue",
"is",
"empty",
"it",
"will",
"block",
"on",
"the",
"condition",
".",
"If",
"new",
"data",
"arrives",
"it",
"will",
"wake",
"and",
"return",
"a",
"block",
".",
"When",
"closed",
"a",
"nil",
"slice",
"will",
"be",
"returned",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L193-L211
|
train
|
docker/distribution
|
notifications/sinks.go
|
Write
|
func (imts *ignoredSink) Write(events ...Event) error {
var kept []Event
for _, e := range events {
if !imts.ignoreMediaTypes[e.Target.MediaType] {
kept = append(kept, e)
}
}
if len(kept) == 0 {
return nil
}
var results []Event
for _, e := range kept {
if !imts.ignoreActions[e.Action] {
results = append(results, e)
}
}
if len(results) == 0 {
return nil
}
return imts.Sink.Write(results...)
}
|
go
|
func (imts *ignoredSink) Write(events ...Event) error {
var kept []Event
for _, e := range events {
if !imts.ignoreMediaTypes[e.Target.MediaType] {
kept = append(kept, e)
}
}
if len(kept) == 0 {
return nil
}
var results []Event
for _, e := range kept {
if !imts.ignoreActions[e.Action] {
results = append(results, e)
}
}
if len(results) == 0 {
return nil
}
return imts.Sink.Write(results...)
}
|
[
"func",
"(",
"imts",
"*",
"ignoredSink",
")",
"Write",
"(",
"events",
"...",
"Event",
")",
"error",
"{",
"var",
"kept",
"[",
"]",
"Event",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"events",
"{",
"if",
"!",
"imts",
".",
"ignoreMediaTypes",
"[",
"e",
".",
"Target",
".",
"MediaType",
"]",
"{",
"kept",
"=",
"append",
"(",
"kept",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"kept",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"results",
"[",
"]",
"Event",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"kept",
"{",
"if",
"!",
"imts",
".",
"ignoreActions",
"[",
"e",
".",
"Action",
"]",
"{",
"results",
"=",
"append",
"(",
"results",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"imts",
".",
"Sink",
".",
"Write",
"(",
"results",
"...",
")",
"\n",
"}"
] |
// Write discards events with ignored target media types and passes the rest
// along.
|
[
"Write",
"discards",
"events",
"with",
"ignored",
"target",
"media",
"types",
"and",
"passes",
"the",
"rest",
"along",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L245-L266
|
train
|
docker/distribution
|
notifications/sinks.go
|
write
|
func (rs *retryingSink) write(events ...Event) error {
if err := rs.sink.Write(events...); err != nil {
rs.failure()
return err
}
rs.reset()
return nil
}
|
go
|
func (rs *retryingSink) write(events ...Event) error {
if err := rs.sink.Write(events...); err != nil {
rs.failure()
return err
}
rs.reset()
return nil
}
|
[
"func",
"(",
"rs",
"*",
"retryingSink",
")",
"write",
"(",
"events",
"...",
"Event",
")",
"error",
"{",
"if",
"err",
":=",
"rs",
".",
"sink",
".",
"Write",
"(",
"events",
"...",
")",
";",
"err",
"!=",
"nil",
"{",
"rs",
".",
"failure",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"rs",
".",
"reset",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// write provides a helper that dispatches failure and success properly. Used
// by write as the single-flight write call.
|
[
"write",
"provides",
"a",
"helper",
"that",
"dispatches",
"failure",
"and",
"success",
"properly",
".",
"Used",
"by",
"write",
"as",
"the",
"single",
"-",
"flight",
"write",
"call",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L350-L358
|
train
|
docker/distribution
|
notifications/sinks.go
|
wait
|
func (rs *retryingSink) wait(backoff time.Duration) {
rs.mu.Unlock()
defer rs.mu.Lock()
// backoff here
time.Sleep(backoff)
}
|
go
|
func (rs *retryingSink) wait(backoff time.Duration) {
rs.mu.Unlock()
defer rs.mu.Lock()
// backoff here
time.Sleep(backoff)
}
|
[
"func",
"(",
"rs",
"*",
"retryingSink",
")",
"wait",
"(",
"backoff",
"time",
".",
"Duration",
")",
"{",
"rs",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"defer",
"rs",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"// backoff here",
"time",
".",
"Sleep",
"(",
"backoff",
")",
"\n",
"}"
] |
// wait backoff time against the sink, unlocking so others can proceed. Should
// only be called by methods that currently have the mutex.
|
[
"wait",
"backoff",
"time",
"against",
"the",
"sink",
"unlocking",
"so",
"others",
"can",
"proceed",
".",
"Should",
"only",
"be",
"called",
"by",
"methods",
"that",
"currently",
"have",
"the",
"mutex",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L362-L368
|
train
|
docker/distribution
|
notifications/sinks.go
|
reset
|
func (rs *retryingSink) reset() {
rs.failures.recent = 0
rs.failures.last = time.Time{}
}
|
go
|
func (rs *retryingSink) reset() {
rs.failures.recent = 0
rs.failures.last = time.Time{}
}
|
[
"func",
"(",
"rs",
"*",
"retryingSink",
")",
"reset",
"(",
")",
"{",
"rs",
".",
"failures",
".",
"recent",
"=",
"0",
"\n",
"rs",
".",
"failures",
".",
"last",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"}"
] |
// reset marks a successful call.
|
[
"reset",
"marks",
"a",
"successful",
"call",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L371-L374
|
train
|
docker/distribution
|
notifications/sinks.go
|
failure
|
func (rs *retryingSink) failure() {
rs.failures.recent++
rs.failures.last = time.Now().UTC()
}
|
go
|
func (rs *retryingSink) failure() {
rs.failures.recent++
rs.failures.last = time.Now().UTC()
}
|
[
"func",
"(",
"rs",
"*",
"retryingSink",
")",
"failure",
"(",
")",
"{",
"rs",
".",
"failures",
".",
"recent",
"++",
"\n",
"rs",
".",
"failures",
".",
"last",
"=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"}"
] |
// failure records a failure.
|
[
"failure",
"records",
"a",
"failure",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L377-L380
|
train
|
docker/distribution
|
notifications/sinks.go
|
proceed
|
func (rs *retryingSink) proceed() bool {
return rs.failures.recent < rs.failures.threshold ||
time.Now().UTC().After(rs.failures.last.Add(rs.failures.backoff))
}
|
go
|
func (rs *retryingSink) proceed() bool {
return rs.failures.recent < rs.failures.threshold ||
time.Now().UTC().After(rs.failures.last.Add(rs.failures.backoff))
}
|
[
"func",
"(",
"rs",
"*",
"retryingSink",
")",
"proceed",
"(",
")",
"bool",
"{",
"return",
"rs",
".",
"failures",
".",
"recent",
"<",
"rs",
".",
"failures",
".",
"threshold",
"||",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"After",
"(",
"rs",
".",
"failures",
".",
"last",
".",
"Add",
"(",
"rs",
".",
"failures",
".",
"backoff",
")",
")",
"\n",
"}"
] |
// proceed returns true if the call should proceed based on circuit breaker
// heuristics.
|
[
"proceed",
"returns",
"true",
"if",
"the",
"call",
"should",
"proceed",
"based",
"on",
"circuit",
"breaker",
"heuristics",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/sinks.go#L384-L387
|
train
|
docker/distribution
|
registry/auth/token/stringset.go
|
newStringSet
|
func newStringSet(keys ...string) stringSet {
ss := make(stringSet, len(keys))
ss.add(keys...)
return ss
}
|
go
|
func newStringSet(keys ...string) stringSet {
ss := make(stringSet, len(keys))
ss.add(keys...)
return ss
}
|
[
"func",
"newStringSet",
"(",
"keys",
"...",
"string",
")",
"stringSet",
"{",
"ss",
":=",
"make",
"(",
"stringSet",
",",
"len",
"(",
"keys",
")",
")",
"\n",
"ss",
".",
"add",
"(",
"keys",
"...",
")",
"\n",
"return",
"ss",
"\n",
"}"
] |
// NewStringSet creates a new StringSet with the given strings.
|
[
"NewStringSet",
"creates",
"a",
"new",
"StringSet",
"with",
"the",
"given",
"strings",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/stringset.go#L7-L11
|
train
|
docker/distribution
|
registry/auth/token/stringset.go
|
add
|
func (ss stringSet) add(keys ...string) {
for _, key := range keys {
ss[key] = struct{}{}
}
}
|
go
|
func (ss stringSet) add(keys ...string) {
for _, key := range keys {
ss[key] = struct{}{}
}
}
|
[
"func",
"(",
"ss",
"stringSet",
")",
"add",
"(",
"keys",
"...",
"string",
")",
"{",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"ss",
"[",
"key",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}"
] |
// Add inserts the given keys into this StringSet.
|
[
"Add",
"inserts",
"the",
"given",
"keys",
"into",
"this",
"StringSet",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/stringset.go#L14-L18
|
train
|
docker/distribution
|
registry/auth/token/stringset.go
|
contains
|
func (ss stringSet) contains(key string) bool {
_, ok := ss[key]
return ok
}
|
go
|
func (ss stringSet) contains(key string) bool {
_, ok := ss[key]
return ok
}
|
[
"func",
"(",
"ss",
"stringSet",
")",
"contains",
"(",
"key",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"ss",
"[",
"key",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] |
// Contains returns whether the given key is in this StringSet.
|
[
"Contains",
"returns",
"whether",
"the",
"given",
"key",
"is",
"in",
"this",
"StringSet",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/stringset.go#L21-L24
|
train
|
docker/distribution
|
registry/auth/token/stringset.go
|
keys
|
func (ss stringSet) keys() []string {
keys := make([]string, 0, len(ss))
for key := range ss {
keys = append(keys, key)
}
return keys
}
|
go
|
func (ss stringSet) keys() []string {
keys := make([]string, 0, len(ss))
for key := range ss {
keys = append(keys, key)
}
return keys
}
|
[
"func",
"(",
"ss",
"stringSet",
")",
"keys",
"(",
")",
"[",
"]",
"string",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"ss",
")",
")",
"\n\n",
"for",
"key",
":=",
"range",
"ss",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"key",
")",
"\n",
"}",
"\n\n",
"return",
"keys",
"\n",
"}"
] |
// Keys returns a slice of all keys in this StringSet.
|
[
"Keys",
"returns",
"a",
"slice",
"of",
"all",
"keys",
"in",
"this",
"StringSet",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/stringset.go#L27-L35
|
train
|
docker/distribution
|
registry/storage/driver/gcs/gcs.go
|
New
|
func New(params driverParameters) (storagedriver.StorageDriver, error) {
rootDirectory := strings.Trim(params.rootDirectory, "/")
if rootDirectory != "" {
rootDirectory += "/"
}
if params.chunkSize <= 0 || params.chunkSize%minChunkSize != 0 {
return nil, fmt.Errorf("Invalid chunksize: %d is not a positive multiple of %d", params.chunkSize, minChunkSize)
}
d := &driver{
bucket: params.bucket,
rootDirectory: rootDirectory,
email: params.email,
privateKey: params.privateKey,
client: params.client,
chunkSize: params.chunkSize,
}
return &Wrapper{
baseEmbed: baseEmbed{
Base: base.Base{
StorageDriver: base.NewRegulator(d, params.maxConcurrency),
},
},
}, nil
}
|
go
|
func New(params driverParameters) (storagedriver.StorageDriver, error) {
rootDirectory := strings.Trim(params.rootDirectory, "/")
if rootDirectory != "" {
rootDirectory += "/"
}
if params.chunkSize <= 0 || params.chunkSize%minChunkSize != 0 {
return nil, fmt.Errorf("Invalid chunksize: %d is not a positive multiple of %d", params.chunkSize, minChunkSize)
}
d := &driver{
bucket: params.bucket,
rootDirectory: rootDirectory,
email: params.email,
privateKey: params.privateKey,
client: params.client,
chunkSize: params.chunkSize,
}
return &Wrapper{
baseEmbed: baseEmbed{
Base: base.Base{
StorageDriver: base.NewRegulator(d, params.maxConcurrency),
},
},
}, nil
}
|
[
"func",
"New",
"(",
"params",
"driverParameters",
")",
"(",
"storagedriver",
".",
"StorageDriver",
",",
"error",
")",
"{",
"rootDirectory",
":=",
"strings",
".",
"Trim",
"(",
"params",
".",
"rootDirectory",
",",
"\"",
"\"",
")",
"\n",
"if",
"rootDirectory",
"!=",
"\"",
"\"",
"{",
"rootDirectory",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"params",
".",
"chunkSize",
"<=",
"0",
"||",
"params",
".",
"chunkSize",
"%",
"minChunkSize",
"!=",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"params",
".",
"chunkSize",
",",
"minChunkSize",
")",
"\n",
"}",
"\n",
"d",
":=",
"&",
"driver",
"{",
"bucket",
":",
"params",
".",
"bucket",
",",
"rootDirectory",
":",
"rootDirectory",
",",
"email",
":",
"params",
".",
"email",
",",
"privateKey",
":",
"params",
".",
"privateKey",
",",
"client",
":",
"params",
".",
"client",
",",
"chunkSize",
":",
"params",
".",
"chunkSize",
",",
"}",
"\n\n",
"return",
"&",
"Wrapper",
"{",
"baseEmbed",
":",
"baseEmbed",
"{",
"Base",
":",
"base",
".",
"Base",
"{",
"StorageDriver",
":",
"base",
".",
"NewRegulator",
"(",
"d",
",",
"params",
".",
"maxConcurrency",
")",
",",
"}",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// New constructs a new driver
|
[
"New",
"constructs",
"a",
"new",
"driver"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/gcs/gcs.go#L214-L238
|
train
|
docker/distribution
|
registry/storage/driver/gcs/gcs.go
|
Cancel
|
func (w *writer) Cancel() error {
w.closed = true
err := storageDeleteObject(cloud.NewContext(dummyProjectID, w.client), w.bucket, w.name)
if err != nil {
if status, ok := err.(*googleapi.Error); ok {
if status.Code == http.StatusNotFound {
err = nil
}
}
}
return err
}
|
go
|
func (w *writer) Cancel() error {
w.closed = true
err := storageDeleteObject(cloud.NewContext(dummyProjectID, w.client), w.bucket, w.name)
if err != nil {
if status, ok := err.(*googleapi.Error); ok {
if status.Code == http.StatusNotFound {
err = nil
}
}
}
return err
}
|
[
"func",
"(",
"w",
"*",
"writer",
")",
"Cancel",
"(",
")",
"error",
"{",
"w",
".",
"closed",
"=",
"true",
"\n",
"err",
":=",
"storageDeleteObject",
"(",
"cloud",
".",
"NewContext",
"(",
"dummyProjectID",
",",
"w",
".",
"client",
")",
",",
"w",
".",
"bucket",
",",
"w",
".",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"status",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"googleapi",
".",
"Error",
")",
";",
"ok",
"{",
"if",
"status",
".",
"Code",
"==",
"http",
".",
"StatusNotFound",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// Cancel removes any written content from this FileWriter.
|
[
"Cancel",
"removes",
"any",
"written",
"content",
"from",
"this",
"FileWriter",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/gcs/gcs.go#L374-L385
|
train
|
docker/distribution
|
registry/storage/driver/gcs/gcs.go
|
Commit
|
func (w *writer) Commit() error {
if err := w.checkClosed(); err != nil {
return err
}
w.closed = true
// no session started yet just perform a simple upload
if w.sessionURI == "" {
err := retry(func() error {
wc := storage.NewWriter(cloud.NewContext(dummyProjectID, w.client), w.bucket, w.name)
wc.ContentType = "application/octet-stream"
return putContentsClose(wc, w.buffer[0:w.buffSize])
})
if err != nil {
return err
}
w.size = w.offset + int64(w.buffSize)
w.buffSize = 0
return nil
}
size := w.offset + int64(w.buffSize)
var nn int
// loop must be performed at least once to ensure the file is committed even when
// the buffer is empty
for {
n, err := putChunk(w.client, w.sessionURI, w.buffer[nn:w.buffSize], w.offset, size)
nn += int(n)
w.offset += n
w.size = w.offset
if err != nil {
w.buffSize = copy(w.buffer, w.buffer[nn:w.buffSize])
return err
}
if nn == w.buffSize {
break
}
}
w.buffSize = 0
return nil
}
|
go
|
func (w *writer) Commit() error {
if err := w.checkClosed(); err != nil {
return err
}
w.closed = true
// no session started yet just perform a simple upload
if w.sessionURI == "" {
err := retry(func() error {
wc := storage.NewWriter(cloud.NewContext(dummyProjectID, w.client), w.bucket, w.name)
wc.ContentType = "application/octet-stream"
return putContentsClose(wc, w.buffer[0:w.buffSize])
})
if err != nil {
return err
}
w.size = w.offset + int64(w.buffSize)
w.buffSize = 0
return nil
}
size := w.offset + int64(w.buffSize)
var nn int
// loop must be performed at least once to ensure the file is committed even when
// the buffer is empty
for {
n, err := putChunk(w.client, w.sessionURI, w.buffer[nn:w.buffSize], w.offset, size)
nn += int(n)
w.offset += n
w.size = w.offset
if err != nil {
w.buffSize = copy(w.buffer, w.buffer[nn:w.buffSize])
return err
}
if nn == w.buffSize {
break
}
}
w.buffSize = 0
return nil
}
|
[
"func",
"(",
"w",
"*",
"writer",
")",
"Commit",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"w",
".",
"checkClosed",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"w",
".",
"closed",
"=",
"true",
"\n\n",
"// no session started yet just perform a simple upload",
"if",
"w",
".",
"sessionURI",
"==",
"\"",
"\"",
"{",
"err",
":=",
"retry",
"(",
"func",
"(",
")",
"error",
"{",
"wc",
":=",
"storage",
".",
"NewWriter",
"(",
"cloud",
".",
"NewContext",
"(",
"dummyProjectID",
",",
"w",
".",
"client",
")",
",",
"w",
".",
"bucket",
",",
"w",
".",
"name",
")",
"\n",
"wc",
".",
"ContentType",
"=",
"\"",
"\"",
"\n",
"return",
"putContentsClose",
"(",
"wc",
",",
"w",
".",
"buffer",
"[",
"0",
":",
"w",
".",
"buffSize",
"]",
")",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"w",
".",
"size",
"=",
"w",
".",
"offset",
"+",
"int64",
"(",
"w",
".",
"buffSize",
")",
"\n",
"w",
".",
"buffSize",
"=",
"0",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"size",
":=",
"w",
".",
"offset",
"+",
"int64",
"(",
"w",
".",
"buffSize",
")",
"\n",
"var",
"nn",
"int",
"\n",
"// loop must be performed at least once to ensure the file is committed even when",
"// the buffer is empty",
"for",
"{",
"n",
",",
"err",
":=",
"putChunk",
"(",
"w",
".",
"client",
",",
"w",
".",
"sessionURI",
",",
"w",
".",
"buffer",
"[",
"nn",
":",
"w",
".",
"buffSize",
"]",
",",
"w",
".",
"offset",
",",
"size",
")",
"\n",
"nn",
"+=",
"int",
"(",
"n",
")",
"\n",
"w",
".",
"offset",
"+=",
"n",
"\n",
"w",
".",
"size",
"=",
"w",
".",
"offset",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"buffSize",
"=",
"copy",
"(",
"w",
".",
"buffer",
",",
"w",
".",
"buffer",
"[",
"nn",
":",
"w",
".",
"buffSize",
"]",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"nn",
"==",
"w",
".",
"buffSize",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"w",
".",
"buffSize",
"=",
"0",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Commit flushes all content written to this FileWriter and makes it
// available for future calls to StorageDriver.GetContent and
// StorageDriver.Reader.
|
[
"Commit",
"flushes",
"all",
"content",
"written",
"to",
"this",
"FileWriter",
"and",
"makes",
"it",
"available",
"for",
"future",
"calls",
"to",
"StorageDriver",
".",
"GetContent",
"and",
"StorageDriver",
".",
"Reader",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/gcs/gcs.go#L445-L485
|
train
|
docker/distribution
|
registry/storage/driver/gcs/gcs.go
|
listAll
|
func (d *driver) listAll(context context.Context, prefix string) ([]string, error) {
list := make([]string, 0, 64)
query := &storage.Query{}
query.Prefix = prefix
query.Versions = false
for {
objects, err := storageListObjects(d.context(context), d.bucket, query)
if err != nil {
return nil, err
}
for _, obj := range objects.Results {
// GCS does not guarantee strong consistency between
// DELETE and LIST operations. Check that the object is not deleted,
// and filter out any objects with a non-zero time-deleted
if obj.Deleted.IsZero() {
list = append(list, obj.Name)
}
}
query = objects.Next
if query == nil {
break
}
}
return list, nil
}
|
go
|
func (d *driver) listAll(context context.Context, prefix string) ([]string, error) {
list := make([]string, 0, 64)
query := &storage.Query{}
query.Prefix = prefix
query.Versions = false
for {
objects, err := storageListObjects(d.context(context), d.bucket, query)
if err != nil {
return nil, err
}
for _, obj := range objects.Results {
// GCS does not guarantee strong consistency between
// DELETE and LIST operations. Check that the object is not deleted,
// and filter out any objects with a non-zero time-deleted
if obj.Deleted.IsZero() {
list = append(list, obj.Name)
}
}
query = objects.Next
if query == nil {
break
}
}
return list, nil
}
|
[
"func",
"(",
"d",
"*",
"driver",
")",
"listAll",
"(",
"context",
"context",
".",
"Context",
",",
"prefix",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"list",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"64",
")",
"\n",
"query",
":=",
"&",
"storage",
".",
"Query",
"{",
"}",
"\n",
"query",
".",
"Prefix",
"=",
"prefix",
"\n",
"query",
".",
"Versions",
"=",
"false",
"\n",
"for",
"{",
"objects",
",",
"err",
":=",
"storageListObjects",
"(",
"d",
".",
"context",
"(",
"context",
")",
",",
"d",
".",
"bucket",
",",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"objects",
".",
"Results",
"{",
"// GCS does not guarantee strong consistency between",
"// DELETE and LIST operations. Check that the object is not deleted,",
"// and filter out any objects with a non-zero time-deleted",
"if",
"obj",
".",
"Deleted",
".",
"IsZero",
"(",
")",
"{",
"list",
"=",
"append",
"(",
"list",
",",
"obj",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"query",
"=",
"objects",
".",
"Next",
"\n",
"if",
"query",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"list",
",",
"nil",
"\n",
"}"
] |
// listAll recursively lists all names of objects stored at "prefix" and its subpaths.
|
[
"listAll",
"recursively",
"lists",
"all",
"names",
"of",
"objects",
"stored",
"at",
"prefix",
"and",
"its",
"subpaths",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/gcs/gcs.go#L701-L725
|
train
|
docker/distribution
|
registry/storage/driver/gcs/gcs.go
|
URLFor
|
func (d *driver) URLFor(context context.Context, path string, options map[string]interface{}) (string, error) {
if d.privateKey == nil {
return "", storagedriver.ErrUnsupportedMethod{}
}
name := d.pathToKey(path)
methodString := "GET"
method, ok := options["method"]
if ok {
methodString, ok = method.(string)
if !ok || (methodString != "GET" && methodString != "HEAD") {
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
}
}
opts := &storage.SignedURLOptions{
GoogleAccessID: d.email,
PrivateKey: d.privateKey,
Method: methodString,
Expires: expiresTime,
}
return storage.SignedURL(d.bucket, name, opts)
}
|
go
|
func (d *driver) URLFor(context context.Context, path string, options map[string]interface{}) (string, error) {
if d.privateKey == nil {
return "", storagedriver.ErrUnsupportedMethod{}
}
name := d.pathToKey(path)
methodString := "GET"
method, ok := options["method"]
if ok {
methodString, ok = method.(string)
if !ok || (methodString != "GET" && methodString != "HEAD") {
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
}
}
opts := &storage.SignedURLOptions{
GoogleAccessID: d.email,
PrivateKey: d.privateKey,
Method: methodString,
Expires: expiresTime,
}
return storage.SignedURL(d.bucket, name, opts)
}
|
[
"func",
"(",
"d",
"*",
"driver",
")",
"URLFor",
"(",
"context",
"context",
".",
"Context",
",",
"path",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"d",
".",
"privateKey",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"storagedriver",
".",
"ErrUnsupportedMethod",
"{",
"}",
"\n",
"}",
"\n\n",
"name",
":=",
"d",
".",
"pathToKey",
"(",
"path",
")",
"\n",
"methodString",
":=",
"\"",
"\"",
"\n",
"method",
",",
"ok",
":=",
"options",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"methodString",
",",
"ok",
"=",
"method",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"(",
"methodString",
"!=",
"\"",
"\"",
"&&",
"methodString",
"!=",
"\"",
"\"",
")",
"{",
"return",
"\"",
"\"",
",",
"storagedriver",
".",
"ErrUnsupportedMethod",
"{",
"}",
"\n",
"}",
"\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",
"opts",
":=",
"&",
"storage",
".",
"SignedURLOptions",
"{",
"GoogleAccessID",
":",
"d",
".",
"email",
",",
"PrivateKey",
":",
"d",
".",
"privateKey",
",",
"Method",
":",
"methodString",
",",
"Expires",
":",
"expiresTime",
",",
"}",
"\n",
"return",
"storage",
".",
"SignedURL",
"(",
"d",
".",
"bucket",
",",
"name",
",",
"opts",
")",
"\n",
"}"
] |
// URLFor returns a URL which may be used to retrieve the content stored at
// the given path, possibly using the given options.
// Returns ErrUnsupportedMethod if this driver has no privateKey
|
[
"URLFor",
"returns",
"a",
"URL",
"which",
"may",
"be",
"used",
"to",
"retrieve",
"the",
"content",
"stored",
"at",
"the",
"given",
"path",
"possibly",
"using",
"the",
"given",
"options",
".",
"Returns",
"ErrUnsupportedMethod",
"if",
"this",
"driver",
"has",
"no",
"privateKey"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/gcs/gcs.go#L803-L834
|
train
|
docker/distribution
|
notifications/bridge.go
|
NewRequestRecord
|
func NewRequestRecord(id string, r *http.Request) RequestRecord {
return RequestRecord{
ID: id,
Addr: context.RemoteAddr(r),
Host: r.Host,
Method: r.Method,
UserAgent: r.UserAgent(),
}
}
|
go
|
func NewRequestRecord(id string, r *http.Request) RequestRecord {
return RequestRecord{
ID: id,
Addr: context.RemoteAddr(r),
Host: r.Host,
Method: r.Method,
UserAgent: r.UserAgent(),
}
}
|
[
"func",
"NewRequestRecord",
"(",
"id",
"string",
",",
"r",
"*",
"http",
".",
"Request",
")",
"RequestRecord",
"{",
"return",
"RequestRecord",
"{",
"ID",
":",
"id",
",",
"Addr",
":",
"context",
".",
"RemoteAddr",
"(",
"r",
")",
",",
"Host",
":",
"r",
".",
"Host",
",",
"Method",
":",
"r",
".",
"Method",
",",
"UserAgent",
":",
"r",
".",
"UserAgent",
"(",
")",
",",
"}",
"\n",
"}"
] |
// NewRequestRecord builds a RequestRecord for use in NewBridge from an
// http.Request, associating it with a request id.
|
[
"NewRequestRecord",
"builds",
"a",
"RequestRecord",
"for",
"use",
"in",
"NewBridge",
"from",
"an",
"http",
".",
"Request",
"associating",
"it",
"with",
"a",
"request",
"id",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/bridge.go#L48-L56
|
train
|
docker/distribution
|
notifications/bridge.go
|
createEvent
|
func (b *bridge) createEvent(action string) *Event {
event := createEvent(action)
event.Source = b.source
event.Actor = b.actor
event.Request = b.request
return event
}
|
go
|
func (b *bridge) createEvent(action string) *Event {
event := createEvent(action)
event.Source = b.source
event.Actor = b.actor
event.Request = b.request
return event
}
|
[
"func",
"(",
"b",
"*",
"bridge",
")",
"createEvent",
"(",
"action",
"string",
")",
"*",
"Event",
"{",
"event",
":=",
"createEvent",
"(",
"action",
")",
"\n",
"event",
".",
"Source",
"=",
"b",
".",
"source",
"\n",
"event",
".",
"Actor",
"=",
"b",
".",
"actor",
"\n",
"event",
".",
"Request",
"=",
"b",
".",
"request",
"\n\n",
"return",
"event",
"\n",
"}"
] |
// createEvent creates an event with actor and source populated.
|
[
"createEvent",
"creates",
"an",
"event",
"with",
"actor",
"and",
"source",
"populated",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/bridge.go#L209-L216
|
train
|
docker/distribution
|
notifications/bridge.go
|
createEvent
|
func createEvent(action string) *Event {
return &Event{
ID: uuid.Generate().String(),
Timestamp: time.Now(),
Action: action,
}
}
|
go
|
func createEvent(action string) *Event {
return &Event{
ID: uuid.Generate().String(),
Timestamp: time.Now(),
Action: action,
}
}
|
[
"func",
"createEvent",
"(",
"action",
"string",
")",
"*",
"Event",
"{",
"return",
"&",
"Event",
"{",
"ID",
":",
"uuid",
".",
"Generate",
"(",
")",
".",
"String",
"(",
")",
",",
"Timestamp",
":",
"time",
".",
"Now",
"(",
")",
",",
"Action",
":",
"action",
",",
"}",
"\n",
"}"
] |
// createEvent returns a new event, timestamped, with the specified action.
|
[
"createEvent",
"returns",
"a",
"new",
"event",
"timestamped",
"with",
"the",
"specified",
"action",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/bridge.go#L219-L225
|
train
|
docker/distribution
|
registry/storage/tagstore.go
|
Tag
|
func (ts *tagStore) Tag(ctx context.Context, tag string, desc distribution.Descriptor) error {
currentPath, err := pathFor(manifestTagCurrentPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
})
if err != nil {
return err
}
lbs := ts.linkedBlobStore(ctx, tag)
// Link into the index
if err := lbs.linkBlob(ctx, desc); err != nil {
return err
}
// Overwrite the current link
return ts.blobStore.link(ctx, currentPath, desc.Digest)
}
|
go
|
func (ts *tagStore) Tag(ctx context.Context, tag string, desc distribution.Descriptor) error {
currentPath, err := pathFor(manifestTagCurrentPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
})
if err != nil {
return err
}
lbs := ts.linkedBlobStore(ctx, tag)
// Link into the index
if err := lbs.linkBlob(ctx, desc); err != nil {
return err
}
// Overwrite the current link
return ts.blobStore.link(ctx, currentPath, desc.Digest)
}
|
[
"func",
"(",
"ts",
"*",
"tagStore",
")",
"Tag",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"error",
"{",
"currentPath",
",",
"err",
":=",
"pathFor",
"(",
"manifestTagCurrentPathSpec",
"{",
"name",
":",
"ts",
".",
"repository",
".",
"Named",
"(",
")",
".",
"Name",
"(",
")",
",",
"tag",
":",
"tag",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"lbs",
":=",
"ts",
".",
"linkedBlobStore",
"(",
"ctx",
",",
"tag",
")",
"\n\n",
"// Link into the index",
"if",
"err",
":=",
"lbs",
".",
"linkBlob",
"(",
"ctx",
",",
"desc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Overwrite the current link",
"return",
"ts",
".",
"blobStore",
".",
"link",
"(",
"ctx",
",",
"currentPath",
",",
"desc",
".",
"Digest",
")",
"\n",
"}"
] |
// Tag tags the digest with the given tag, updating the the store to point at
// the current tag. The digest must point to a manifest.
|
[
"Tag",
"tags",
"the",
"digest",
"with",
"the",
"given",
"tag",
"updating",
"the",
"the",
"store",
"to",
"point",
"at",
"the",
"current",
"tag",
".",
"The",
"digest",
"must",
"point",
"to",
"a",
"manifest",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/tagstore.go#L55-L74
|
train
|
docker/distribution
|
registry/storage/tagstore.go
|
Get
|
func (ts *tagStore) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
currentPath, err := pathFor(manifestTagCurrentPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
})
if err != nil {
return distribution.Descriptor{}, err
}
revision, err := ts.blobStore.readlink(ctx, currentPath)
if err != nil {
switch err.(type) {
case storagedriver.PathNotFoundError:
return distribution.Descriptor{}, distribution.ErrTagUnknown{Tag: tag}
}
return distribution.Descriptor{}, err
}
return distribution.Descriptor{Digest: revision}, nil
}
|
go
|
func (ts *tagStore) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
currentPath, err := pathFor(manifestTagCurrentPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
})
if err != nil {
return distribution.Descriptor{}, err
}
revision, err := ts.blobStore.readlink(ctx, currentPath)
if err != nil {
switch err.(type) {
case storagedriver.PathNotFoundError:
return distribution.Descriptor{}, distribution.ErrTagUnknown{Tag: tag}
}
return distribution.Descriptor{}, err
}
return distribution.Descriptor{Digest: revision}, nil
}
|
[
"func",
"(",
"ts",
"*",
"tagStore",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"currentPath",
",",
"err",
":=",
"pathFor",
"(",
"manifestTagCurrentPathSpec",
"{",
"name",
":",
"ts",
".",
"repository",
".",
"Named",
"(",
")",
".",
"Name",
"(",
")",
",",
"tag",
":",
"tag",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"revision",
",",
"err",
":=",
"ts",
".",
"blobStore",
".",
"readlink",
"(",
"ctx",
",",
"currentPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"distribution",
".",
"ErrTagUnknown",
"{",
"Tag",
":",
"tag",
"}",
"\n",
"}",
"\n\n",
"return",
"distribution",
".",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"distribution",
".",
"Descriptor",
"{",
"Digest",
":",
"revision",
"}",
",",
"nil",
"\n",
"}"
] |
// resolve the current revision for name and tag.
|
[
"resolve",
"the",
"current",
"revision",
"for",
"name",
"and",
"tag",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/tagstore.go#L77-L98
|
train
|
docker/distribution
|
registry/storage/tagstore.go
|
Untag
|
func (ts *tagStore) Untag(ctx context.Context, tag string) error {
tagPath, err := pathFor(manifestTagPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
})
if err != nil {
return err
}
if err := ts.blobStore.driver.Delete(ctx, tagPath); err != nil {
switch err.(type) {
case storagedriver.PathNotFoundError:
return nil // Untag is idempotent, we don't care if it didn't exist
default:
return err
}
}
return nil
}
|
go
|
func (ts *tagStore) Untag(ctx context.Context, tag string) error {
tagPath, err := pathFor(manifestTagPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
})
if err != nil {
return err
}
if err := ts.blobStore.driver.Delete(ctx, tagPath); err != nil {
switch err.(type) {
case storagedriver.PathNotFoundError:
return nil // Untag is idempotent, we don't care if it didn't exist
default:
return err
}
}
return nil
}
|
[
"func",
"(",
"ts",
"*",
"tagStore",
")",
"Untag",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"error",
"{",
"tagPath",
",",
"err",
":=",
"pathFor",
"(",
"manifestTagPathSpec",
"{",
"name",
":",
"ts",
".",
"repository",
".",
"Named",
"(",
")",
".",
"Name",
"(",
")",
",",
"tag",
":",
"tag",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"ts",
".",
"blobStore",
".",
"driver",
".",
"Delete",
"(",
"ctx",
",",
"tagPath",
")",
";",
"err",
"!=",
"nil",
"{",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"return",
"nil",
"// Untag is idempotent, we don't care if it didn't exist",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Untag removes the tag association
|
[
"Untag",
"removes",
"the",
"tag",
"association"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/tagstore.go#L101-L120
|
train
|
docker/distribution
|
registry/storage/tagstore.go
|
linkedBlobStore
|
func (ts *tagStore) linkedBlobStore(ctx context.Context, tag string) *linkedBlobStore {
return &linkedBlobStore{
blobStore: ts.blobStore,
repository: ts.repository,
ctx: ctx,
linkPathFns: []linkPathFunc{func(name string, dgst digest.Digest) (string, error) {
return pathFor(manifestTagIndexEntryLinkPathSpec{
name: name,
tag: tag,
revision: dgst,
})
}},
}
}
|
go
|
func (ts *tagStore) linkedBlobStore(ctx context.Context, tag string) *linkedBlobStore {
return &linkedBlobStore{
blobStore: ts.blobStore,
repository: ts.repository,
ctx: ctx,
linkPathFns: []linkPathFunc{func(name string, dgst digest.Digest) (string, error) {
return pathFor(manifestTagIndexEntryLinkPathSpec{
name: name,
tag: tag,
revision: dgst,
})
}},
}
}
|
[
"func",
"(",
"ts",
"*",
"tagStore",
")",
"linkedBlobStore",
"(",
"ctx",
"context",
".",
"Context",
",",
"tag",
"string",
")",
"*",
"linkedBlobStore",
"{",
"return",
"&",
"linkedBlobStore",
"{",
"blobStore",
":",
"ts",
".",
"blobStore",
",",
"repository",
":",
"ts",
".",
"repository",
",",
"ctx",
":",
"ctx",
",",
"linkPathFns",
":",
"[",
"]",
"linkPathFunc",
"{",
"func",
"(",
"name",
"string",
",",
"dgst",
"digest",
".",
"Digest",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"pathFor",
"(",
"manifestTagIndexEntryLinkPathSpec",
"{",
"name",
":",
"name",
",",
"tag",
":",
"tag",
",",
"revision",
":",
"dgst",
",",
"}",
")",
"\n\n",
"}",
"}",
",",
"}",
"\n",
"}"
] |
// linkedBlobStore returns the linkedBlobStore for the named tag, allowing one
// to index manifest blobs by tag name. While the tag store doesn't map
// precisely to the linked blob store, using this ensures the links are
// managed via the same code path.
|
[
"linkedBlobStore",
"returns",
"the",
"linkedBlobStore",
"for",
"the",
"named",
"tag",
"allowing",
"one",
"to",
"index",
"manifest",
"blobs",
"by",
"tag",
"name",
".",
"While",
"the",
"tag",
"store",
"doesn",
"t",
"map",
"precisely",
"to",
"the",
"linked",
"blob",
"store",
"using",
"this",
"ensures",
"the",
"links",
"are",
"managed",
"via",
"the",
"same",
"code",
"path",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/tagstore.go#L126-L140
|
train
|
docker/distribution
|
registry/storage/tagstore.go
|
Lookup
|
func (ts *tagStore) Lookup(ctx context.Context, desc distribution.Descriptor) ([]string, error) {
allTags, err := ts.All(ctx)
switch err.(type) {
case distribution.ErrRepositoryUnknown:
// This tag store has been initialized but not yet populated
break
case nil:
break
default:
return nil, err
}
var tags []string
for _, tag := range allTags {
tagLinkPathSpec := manifestTagCurrentPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
}
tagLinkPath, _ := pathFor(tagLinkPathSpec)
tagDigest, err := ts.blobStore.readlink(ctx, tagLinkPath)
if err != nil {
switch err.(type) {
case storagedriver.PathNotFoundError:
continue
}
return nil, err
}
if tagDigest == desc.Digest {
tags = append(tags, tag)
}
}
return tags, nil
}
|
go
|
func (ts *tagStore) Lookup(ctx context.Context, desc distribution.Descriptor) ([]string, error) {
allTags, err := ts.All(ctx)
switch err.(type) {
case distribution.ErrRepositoryUnknown:
// This tag store has been initialized but not yet populated
break
case nil:
break
default:
return nil, err
}
var tags []string
for _, tag := range allTags {
tagLinkPathSpec := manifestTagCurrentPathSpec{
name: ts.repository.Named().Name(),
tag: tag,
}
tagLinkPath, _ := pathFor(tagLinkPathSpec)
tagDigest, err := ts.blobStore.readlink(ctx, tagLinkPath)
if err != nil {
switch err.(type) {
case storagedriver.PathNotFoundError:
continue
}
return nil, err
}
if tagDigest == desc.Digest {
tags = append(tags, tag)
}
}
return tags, nil
}
|
[
"func",
"(",
"ts",
"*",
"tagStore",
")",
"Lookup",
"(",
"ctx",
"context",
".",
"Context",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"allTags",
",",
"err",
":=",
"ts",
".",
"All",
"(",
"ctx",
")",
"\n",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"distribution",
".",
"ErrRepositoryUnknown",
":",
"// This tag store has been initialized but not yet populated",
"break",
"\n",
"case",
"nil",
":",
"break",
"\n",
"default",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"tags",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"tag",
":=",
"range",
"allTags",
"{",
"tagLinkPathSpec",
":=",
"manifestTagCurrentPathSpec",
"{",
"name",
":",
"ts",
".",
"repository",
".",
"Named",
"(",
")",
".",
"Name",
"(",
")",
",",
"tag",
":",
"tag",
",",
"}",
"\n\n",
"tagLinkPath",
",",
"_",
":=",
"pathFor",
"(",
"tagLinkPathSpec",
")",
"\n",
"tagDigest",
",",
"err",
":=",
"ts",
".",
"blobStore",
".",
"readlink",
"(",
"ctx",
",",
"tagLinkPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"continue",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"tagDigest",
"==",
"desc",
".",
"Digest",
"{",
"tags",
"=",
"append",
"(",
"tags",
",",
"tag",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"tags",
",",
"nil",
"\n",
"}"
] |
// Lookup recovers a list of tags which refer to this digest. When a manifest is deleted by
// digest, tag entries which point to it need to be recovered to avoid dangling tags.
|
[
"Lookup",
"recovers",
"a",
"list",
"of",
"tags",
"which",
"refer",
"to",
"this",
"digest",
".",
"When",
"a",
"manifest",
"is",
"deleted",
"by",
"digest",
"tag",
"entries",
"which",
"point",
"to",
"it",
"need",
"to",
"be",
"recovered",
"to",
"avoid",
"dangling",
"tags",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/tagstore.go#L144-L179
|
train
|
docker/distribution
|
registry/storage/driver/middleware/storagemiddleware.go
|
Get
|
func Get(name string, options map[string]interface{}, storageDriver storagedriver.StorageDriver) (storagedriver.StorageDriver, error) {
if storageMiddlewares != nil {
if initFunc, exists := storageMiddlewares[name]; exists {
return initFunc(storageDriver, options)
}
}
return nil, fmt.Errorf("no storage middleware registered with name: %s", name)
}
|
go
|
func Get(name string, options map[string]interface{}, storageDriver storagedriver.StorageDriver) (storagedriver.StorageDriver, error) {
if storageMiddlewares != nil {
if initFunc, exists := storageMiddlewares[name]; exists {
return initFunc(storageDriver, options)
}
}
return nil, fmt.Errorf("no storage middleware registered with name: %s", name)
}
|
[
"func",
"Get",
"(",
"name",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"storageDriver",
"storagedriver",
".",
"StorageDriver",
")",
"(",
"storagedriver",
".",
"StorageDriver",
",",
"error",
")",
"{",
"if",
"storageMiddlewares",
"!=",
"nil",
"{",
"if",
"initFunc",
",",
"exists",
":=",
"storageMiddlewares",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"initFunc",
"(",
"storageDriver",
",",
"options",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
] |
// Get constructs a StorageMiddleware with the given options using the named backend.
|
[
"Get",
"constructs",
"a",
"StorageMiddleware",
"with",
"the",
"given",
"options",
"using",
"the",
"named",
"backend",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/middleware/storagemiddleware.go#L31-L39
|
train
|
docker/distribution
|
context/http.go
|
RemoteAddr
|
func RemoteAddr(r *http.Request) string {
if prior := r.Header.Get("X-Forwarded-For"); prior != "" {
proxies := strings.Split(prior, ",")
if len(proxies) > 0 {
remoteAddr := strings.Trim(proxies[0], " ")
if parseIP(remoteAddr) != nil {
return remoteAddr
}
}
}
// X-Real-Ip is less supported, but worth checking in the
// absence of X-Forwarded-For
if realIP := r.Header.Get("X-Real-Ip"); realIP != "" {
if parseIP(realIP) != nil {
return realIP
}
}
return r.RemoteAddr
}
|
go
|
func RemoteAddr(r *http.Request) string {
if prior := r.Header.Get("X-Forwarded-For"); prior != "" {
proxies := strings.Split(prior, ",")
if len(proxies) > 0 {
remoteAddr := strings.Trim(proxies[0], " ")
if parseIP(remoteAddr) != nil {
return remoteAddr
}
}
}
// X-Real-Ip is less supported, but worth checking in the
// absence of X-Forwarded-For
if realIP := r.Header.Get("X-Real-Ip"); realIP != "" {
if parseIP(realIP) != nil {
return realIP
}
}
return r.RemoteAddr
}
|
[
"func",
"RemoteAddr",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"if",
"prior",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"prior",
"!=",
"\"",
"\"",
"{",
"proxies",
":=",
"strings",
".",
"Split",
"(",
"prior",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"proxies",
")",
">",
"0",
"{",
"remoteAddr",
":=",
"strings",
".",
"Trim",
"(",
"proxies",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"\n",
"if",
"parseIP",
"(",
"remoteAddr",
")",
"!=",
"nil",
"{",
"return",
"remoteAddr",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// X-Real-Ip is less supported, but worth checking in the",
"// absence of X-Forwarded-For",
"if",
"realIP",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"realIP",
"!=",
"\"",
"\"",
"{",
"if",
"parseIP",
"(",
"realIP",
")",
"!=",
"nil",
"{",
"return",
"realIP",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"RemoteAddr",
"\n",
"}"
] |
// RemoteAddr extracts the remote address of the request, taking into
// account proxy headers.
|
[
"RemoteAddr",
"extracts",
"the",
"remote",
"address",
"of",
"the",
"request",
"taking",
"into",
"account",
"proxy",
"headers",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L33-L52
|
train
|
docker/distribution
|
context/http.go
|
RemoteIP
|
func RemoteIP(r *http.Request) string {
addr := RemoteAddr(r)
// Try parsing it as "IP:port"
if ip, _, err := net.SplitHostPort(addr); err == nil {
return ip
}
return addr
}
|
go
|
func RemoteIP(r *http.Request) string {
addr := RemoteAddr(r)
// Try parsing it as "IP:port"
if ip, _, err := net.SplitHostPort(addr); err == nil {
return ip
}
return addr
}
|
[
"func",
"RemoteIP",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"addr",
":=",
"RemoteAddr",
"(",
"r",
")",
"\n\n",
"// Try parsing it as \"IP:port\"",
"if",
"ip",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"ip",
"\n",
"}",
"\n\n",
"return",
"addr",
"\n",
"}"
] |
// RemoteIP extracts the remote IP of the request, taking into
// account proxy headers.
|
[
"RemoteIP",
"extracts",
"the",
"remote",
"IP",
"of",
"the",
"request",
"taking",
"into",
"account",
"proxy",
"headers",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L56-L65
|
train
|
docker/distribution
|
context/http.go
|
WithRequest
|
func WithRequest(ctx context.Context, r *http.Request) context.Context {
if ctx.Value("http.request") != nil {
// NOTE(stevvooe): This needs to be considered a programming error. It
// is unlikely that we'd want to have more than one request in
// context.
panic("only one request per context")
}
return &httpRequestContext{
Context: ctx,
startedAt: time.Now(),
id: uuid.Generate().String(),
r: r,
}
}
|
go
|
func WithRequest(ctx context.Context, r *http.Request) context.Context {
if ctx.Value("http.request") != nil {
// NOTE(stevvooe): This needs to be considered a programming error. It
// is unlikely that we'd want to have more than one request in
// context.
panic("only one request per context")
}
return &httpRequestContext{
Context: ctx,
startedAt: time.Now(),
id: uuid.Generate().String(),
r: r,
}
}
|
[
"func",
"WithRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"*",
"http",
".",
"Request",
")",
"context",
".",
"Context",
"{",
"if",
"ctx",
".",
"Value",
"(",
"\"",
"\"",
")",
"!=",
"nil",
"{",
"// NOTE(stevvooe): This needs to be considered a programming error. It",
"// is unlikely that we'd want to have more than one request in",
"// context.",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"httpRequestContext",
"{",
"Context",
":",
"ctx",
",",
"startedAt",
":",
"time",
".",
"Now",
"(",
")",
",",
"id",
":",
"uuid",
".",
"Generate",
"(",
")",
".",
"String",
"(",
")",
",",
"r",
":",
"r",
",",
"}",
"\n",
"}"
] |
// WithRequest places the request on the context. The context of the request
// is assigned a unique id, available at "http.request.id". The request itself
// is available at "http.request". Other common attributes are available under
// the prefix "http.request.". If a request is already present on the context,
// this method will panic.
|
[
"WithRequest",
"places",
"the",
"request",
"on",
"the",
"context",
".",
"The",
"context",
"of",
"the",
"request",
"is",
"assigned",
"a",
"unique",
"id",
"available",
"at",
"http",
".",
"request",
".",
"id",
".",
"The",
"request",
"itself",
"is",
"available",
"at",
"http",
".",
"request",
".",
"Other",
"common",
"attributes",
"are",
"available",
"under",
"the",
"prefix",
"http",
".",
"request",
".",
".",
"If",
"a",
"request",
"is",
"already",
"present",
"on",
"the",
"context",
"this",
"method",
"will",
"panic",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L72-L86
|
train
|
docker/distribution
|
context/http.go
|
GetRequest
|
func GetRequest(ctx context.Context) (*http.Request, error) {
if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok {
return r, nil
}
return nil, ErrNoRequestContext
}
|
go
|
func GetRequest(ctx context.Context) (*http.Request, error) {
if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok {
return r, nil
}
return nil, ErrNoRequestContext
}
|
[
"func",
"GetRequest",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"if",
"r",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"http",
".",
"Request",
")",
";",
"r",
"!=",
"nil",
"&&",
"ok",
"{",
"return",
"r",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrNoRequestContext",
"\n",
"}"
] |
// GetRequest returns the http request in the given context. Returns
// ErrNoRequestContext if the context does not have an http request associated
// with it.
|
[
"GetRequest",
"returns",
"the",
"http",
"request",
"in",
"the",
"given",
"context",
".",
"Returns",
"ErrNoRequestContext",
"if",
"the",
"context",
"does",
"not",
"have",
"an",
"http",
"request",
"associated",
"with",
"it",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L91-L96
|
train
|
docker/distribution
|
context/http.go
|
WithResponseWriter
|
func WithResponseWriter(ctx context.Context, w http.ResponseWriter) (context.Context, http.ResponseWriter) {
irw := instrumentedResponseWriter{
ResponseWriter: w,
Context: ctx,
}
return &irw, &irw
}
|
go
|
func WithResponseWriter(ctx context.Context, w http.ResponseWriter) (context.Context, http.ResponseWriter) {
irw := instrumentedResponseWriter{
ResponseWriter: w,
Context: ctx,
}
return &irw, &irw
}
|
[
"func",
"WithResponseWriter",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"(",
"context",
".",
"Context",
",",
"http",
".",
"ResponseWriter",
")",
"{",
"irw",
":=",
"instrumentedResponseWriter",
"{",
"ResponseWriter",
":",
"w",
",",
"Context",
":",
"ctx",
",",
"}",
"\n",
"return",
"&",
"irw",
",",
"&",
"irw",
"\n",
"}"
] |
// WithResponseWriter returns a new context and response writer that makes
// interesting response statistics available within the context.
|
[
"WithResponseWriter",
"returns",
"a",
"new",
"context",
"and",
"response",
"writer",
"that",
"makes",
"interesting",
"response",
"statistics",
"available",
"within",
"the",
"context",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L106-L112
|
train
|
docker/distribution
|
context/http.go
|
GetResponseWriter
|
func GetResponseWriter(ctx context.Context) (http.ResponseWriter, error) {
v := ctx.Value("http.response")
rw, ok := v.(http.ResponseWriter)
if !ok || rw == nil {
return nil, ErrNoResponseWriterContext
}
return rw, nil
}
|
go
|
func GetResponseWriter(ctx context.Context) (http.ResponseWriter, error) {
v := ctx.Value("http.response")
rw, ok := v.(http.ResponseWriter)
if !ok || rw == nil {
return nil, ErrNoResponseWriterContext
}
return rw, nil
}
|
[
"func",
"GetResponseWriter",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"http",
".",
"ResponseWriter",
",",
"error",
")",
"{",
"v",
":=",
"ctx",
".",
"Value",
"(",
"\"",
"\"",
")",
"\n\n",
"rw",
",",
"ok",
":=",
"v",
".",
"(",
"http",
".",
"ResponseWriter",
")",
"\n",
"if",
"!",
"ok",
"||",
"rw",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrNoResponseWriterContext",
"\n",
"}",
"\n\n",
"return",
"rw",
",",
"nil",
"\n",
"}"
] |
// GetResponseWriter returns the http.ResponseWriter from the provided
// context. If not present, ErrNoResponseWriterContext is returned. The
// returned instance provides instrumentation in the context.
|
[
"GetResponseWriter",
"returns",
"the",
"http",
".",
"ResponseWriter",
"from",
"the",
"provided",
"context",
".",
"If",
"not",
"present",
"ErrNoResponseWriterContext",
"is",
"returned",
".",
"The",
"returned",
"instance",
"provides",
"instrumentation",
"in",
"the",
"context",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L117-L126
|
train
|
docker/distribution
|
context/http.go
|
GetResponseLogger
|
func GetResponseLogger(ctx context.Context) Logger {
l := getLogrusLogger(ctx,
"http.response.written",
"http.response.status",
"http.response.contenttype")
duration := Since(ctx, "http.request.startedat")
if duration > 0 {
l = l.WithField("http.response.duration", duration.String())
}
return l
}
|
go
|
func GetResponseLogger(ctx context.Context) Logger {
l := getLogrusLogger(ctx,
"http.response.written",
"http.response.status",
"http.response.contenttype")
duration := Since(ctx, "http.request.startedat")
if duration > 0 {
l = l.WithField("http.response.duration", duration.String())
}
return l
}
|
[
"func",
"GetResponseLogger",
"(",
"ctx",
"context",
".",
"Context",
")",
"Logger",
"{",
"l",
":=",
"getLogrusLogger",
"(",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"duration",
":=",
"Since",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"duration",
">",
"0",
"{",
"l",
"=",
"l",
".",
"WithField",
"(",
"\"",
"\"",
",",
"duration",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"l",
"\n",
"}"
] |
// GetResponseLogger reads the current response stats and builds a logger.
// Because the values are read at call time, pushing a logger returned from
// this function on the context will lead to missing or invalid data. Only
// call this at the end of a request, after the response has been written.
|
[
"GetResponseLogger",
"reads",
"the",
"current",
"response",
"stats",
"and",
"builds",
"a",
"logger",
".",
"Because",
"the",
"values",
"are",
"read",
"at",
"call",
"time",
"pushing",
"a",
"logger",
"returned",
"from",
"this",
"function",
"on",
"the",
"context",
"will",
"lead",
"to",
"missing",
"or",
"invalid",
"data",
".",
"Only",
"call",
"this",
"at",
"the",
"end",
"of",
"a",
"request",
"after",
"the",
"response",
"has",
"been",
"written",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/context/http.go#L163-L176
|
train
|
docker/distribution
|
registry/client/auth/challenge/authchallenge.go
|
ResponseChallenges
|
func ResponseChallenges(resp *http.Response) []Challenge {
if resp.StatusCode == http.StatusUnauthorized {
// Parse the WWW-Authenticate Header and store the challenges
// on this endpoint object.
return parseAuthHeader(resp.Header)
}
return nil
}
|
go
|
func ResponseChallenges(resp *http.Response) []Challenge {
if resp.StatusCode == http.StatusUnauthorized {
// Parse the WWW-Authenticate Header and store the challenges
// on this endpoint object.
return parseAuthHeader(resp.Header)
}
return nil
}
|
[
"func",
"ResponseChallenges",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"[",
"]",
"Challenge",
"{",
"if",
"resp",
".",
"StatusCode",
"==",
"http",
".",
"StatusUnauthorized",
"{",
"// Parse the WWW-Authenticate Header and store the challenges",
"// on this endpoint object.",
"return",
"parseAuthHeader",
"(",
"resp",
".",
"Header",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// ResponseChallenges returns a list of authorization challenges
// for the given http Response. Challenges are only checked if
// the response status code was a 401.
|
[
"ResponseChallenges",
"returns",
"a",
"list",
"of",
"authorization",
"challenges",
"for",
"the",
"given",
"http",
"Response",
".",
"Challenges",
"are",
"only",
"checked",
"if",
"the",
"response",
"status",
"code",
"was",
"a",
"401",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/challenge/authchallenge.go#L134-L142
|
train
|
docker/distribution
|
registry/storage/purgeuploads.go
|
PurgeUploads
|
func PurgeUploads(ctx context.Context, driver storageDriver.StorageDriver, olderThan time.Time, actuallyDelete bool) ([]string, []error) {
logrus.Infof("PurgeUploads starting: olderThan=%s, actuallyDelete=%t", olderThan, actuallyDelete)
uploadData, errors := getOutstandingUploads(ctx, driver)
var deleted []string
for _, uploadData := range uploadData {
if uploadData.startedAt.Before(olderThan) {
var err error
logrus.Infof("Upload files in %s have older date (%s) than purge date (%s). Removing upload directory.",
uploadData.containingDir, uploadData.startedAt, olderThan)
if actuallyDelete {
err = driver.Delete(ctx, uploadData.containingDir)
}
if err == nil {
deleted = append(deleted, uploadData.containingDir)
} else {
errors = append(errors, err)
}
}
}
logrus.Infof("Purge uploads finished. Num deleted=%d, num errors=%d", len(deleted), len(errors))
return deleted, errors
}
|
go
|
func PurgeUploads(ctx context.Context, driver storageDriver.StorageDriver, olderThan time.Time, actuallyDelete bool) ([]string, []error) {
logrus.Infof("PurgeUploads starting: olderThan=%s, actuallyDelete=%t", olderThan, actuallyDelete)
uploadData, errors := getOutstandingUploads(ctx, driver)
var deleted []string
for _, uploadData := range uploadData {
if uploadData.startedAt.Before(olderThan) {
var err error
logrus.Infof("Upload files in %s have older date (%s) than purge date (%s). Removing upload directory.",
uploadData.containingDir, uploadData.startedAt, olderThan)
if actuallyDelete {
err = driver.Delete(ctx, uploadData.containingDir)
}
if err == nil {
deleted = append(deleted, uploadData.containingDir)
} else {
errors = append(errors, err)
}
}
}
logrus.Infof("Purge uploads finished. Num deleted=%d, num errors=%d", len(deleted), len(errors))
return deleted, errors
}
|
[
"func",
"PurgeUploads",
"(",
"ctx",
"context",
".",
"Context",
",",
"driver",
"storageDriver",
".",
"StorageDriver",
",",
"olderThan",
"time",
".",
"Time",
",",
"actuallyDelete",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"[",
"]",
"error",
")",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"olderThan",
",",
"actuallyDelete",
")",
"\n",
"uploadData",
",",
"errors",
":=",
"getOutstandingUploads",
"(",
"ctx",
",",
"driver",
")",
"\n",
"var",
"deleted",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"uploadData",
":=",
"range",
"uploadData",
"{",
"if",
"uploadData",
".",
"startedAt",
".",
"Before",
"(",
"olderThan",
")",
"{",
"var",
"err",
"error",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"uploadData",
".",
"containingDir",
",",
"uploadData",
".",
"startedAt",
",",
"olderThan",
")",
"\n",
"if",
"actuallyDelete",
"{",
"err",
"=",
"driver",
".",
"Delete",
"(",
"ctx",
",",
"uploadData",
".",
"containingDir",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"deleted",
"=",
"append",
"(",
"deleted",
",",
"uploadData",
".",
"containingDir",
")",
"\n",
"}",
"else",
"{",
"errors",
"=",
"append",
"(",
"errors",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"len",
"(",
"deleted",
")",
",",
"len",
"(",
"errors",
")",
")",
"\n",
"return",
"deleted",
",",
"errors",
"\n",
"}"
] |
// PurgeUploads deletes files from the upload directory
// created before olderThan. The list of files deleted and errors
// encountered are returned
|
[
"PurgeUploads",
"deletes",
"files",
"from",
"the",
"upload",
"directory",
"created",
"before",
"olderThan",
".",
"The",
"list",
"of",
"files",
"deleted",
"and",
"errors",
"encountered",
"are",
"returned"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L32-L54
|
train
|
docker/distribution
|
registry/storage/purgeuploads.go
|
getOutstandingUploads
|
func getOutstandingUploads(ctx context.Context, driver storageDriver.StorageDriver) (map[string]uploadData, []error) {
var errors []error
uploads := make(map[string]uploadData)
inUploadDir := false
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return uploads, append(errors, err)
}
err = driver.Walk(ctx, root, func(fileInfo storageDriver.FileInfo) error {
filePath := fileInfo.Path()
_, file := path.Split(filePath)
if file[0] == '_' {
// Reserved directory
inUploadDir = (file == "_uploads")
if fileInfo.IsDir() && !inUploadDir {
return storageDriver.ErrSkipDir
}
}
uuid, isContainingDir := uuidFromPath(filePath)
if uuid == "" {
// Cannot reliably delete
return nil
}
ud, ok := uploads[uuid]
if !ok {
ud = newUploadData()
}
if isContainingDir {
ud.containingDir = filePath
}
if file == "startedat" {
if t, err := readStartedAtFile(driver, filePath); err == nil {
ud.startedAt = t
} else {
errors = pushError(errors, filePath, err)
}
}
uploads[uuid] = ud
return nil
})
if err != nil {
errors = pushError(errors, root, err)
}
return uploads, errors
}
|
go
|
func getOutstandingUploads(ctx context.Context, driver storageDriver.StorageDriver) (map[string]uploadData, []error) {
var errors []error
uploads := make(map[string]uploadData)
inUploadDir := false
root, err := pathFor(repositoriesRootPathSpec{})
if err != nil {
return uploads, append(errors, err)
}
err = driver.Walk(ctx, root, func(fileInfo storageDriver.FileInfo) error {
filePath := fileInfo.Path()
_, file := path.Split(filePath)
if file[0] == '_' {
// Reserved directory
inUploadDir = (file == "_uploads")
if fileInfo.IsDir() && !inUploadDir {
return storageDriver.ErrSkipDir
}
}
uuid, isContainingDir := uuidFromPath(filePath)
if uuid == "" {
// Cannot reliably delete
return nil
}
ud, ok := uploads[uuid]
if !ok {
ud = newUploadData()
}
if isContainingDir {
ud.containingDir = filePath
}
if file == "startedat" {
if t, err := readStartedAtFile(driver, filePath); err == nil {
ud.startedAt = t
} else {
errors = pushError(errors, filePath, err)
}
}
uploads[uuid] = ud
return nil
})
if err != nil {
errors = pushError(errors, root, err)
}
return uploads, errors
}
|
[
"func",
"getOutstandingUploads",
"(",
"ctx",
"context",
".",
"Context",
",",
"driver",
"storageDriver",
".",
"StorageDriver",
")",
"(",
"map",
"[",
"string",
"]",
"uploadData",
",",
"[",
"]",
"error",
")",
"{",
"var",
"errors",
"[",
"]",
"error",
"\n",
"uploads",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"uploadData",
")",
"\n\n",
"inUploadDir",
":=",
"false",
"\n",
"root",
",",
"err",
":=",
"pathFor",
"(",
"repositoriesRootPathSpec",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"uploads",
",",
"append",
"(",
"errors",
",",
"err",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"driver",
".",
"Walk",
"(",
"ctx",
",",
"root",
",",
"func",
"(",
"fileInfo",
"storageDriver",
".",
"FileInfo",
")",
"error",
"{",
"filePath",
":=",
"fileInfo",
".",
"Path",
"(",
")",
"\n",
"_",
",",
"file",
":=",
"path",
".",
"Split",
"(",
"filePath",
")",
"\n",
"if",
"file",
"[",
"0",
"]",
"==",
"'_'",
"{",
"// Reserved directory",
"inUploadDir",
"=",
"(",
"file",
"==",
"\"",
"\"",
")",
"\n\n",
"if",
"fileInfo",
".",
"IsDir",
"(",
")",
"&&",
"!",
"inUploadDir",
"{",
"return",
"storageDriver",
".",
"ErrSkipDir",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"uuid",
",",
"isContainingDir",
":=",
"uuidFromPath",
"(",
"filePath",
")",
"\n",
"if",
"uuid",
"==",
"\"",
"\"",
"{",
"// Cannot reliably delete",
"return",
"nil",
"\n",
"}",
"\n",
"ud",
",",
"ok",
":=",
"uploads",
"[",
"uuid",
"]",
"\n",
"if",
"!",
"ok",
"{",
"ud",
"=",
"newUploadData",
"(",
")",
"\n",
"}",
"\n",
"if",
"isContainingDir",
"{",
"ud",
".",
"containingDir",
"=",
"filePath",
"\n",
"}",
"\n",
"if",
"file",
"==",
"\"",
"\"",
"{",
"if",
"t",
",",
"err",
":=",
"readStartedAtFile",
"(",
"driver",
",",
"filePath",
")",
";",
"err",
"==",
"nil",
"{",
"ud",
".",
"startedAt",
"=",
"t",
"\n",
"}",
"else",
"{",
"errors",
"=",
"pushError",
"(",
"errors",
",",
"filePath",
",",
"err",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"uploads",
"[",
"uuid",
"]",
"=",
"ud",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
"=",
"pushError",
"(",
"errors",
",",
"root",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"uploads",
",",
"errors",
"\n",
"}"
] |
// getOutstandingUploads walks the upload directory, collecting files
// which could be eligible for deletion. The only reliable way to
// classify the age of a file is with the date stored in the startedAt
// file, so gather files by UUID with a date from startedAt.
|
[
"getOutstandingUploads",
"walks",
"the",
"upload",
"directory",
"collecting",
"files",
"which",
"could",
"be",
"eligible",
"for",
"deletion",
".",
"The",
"only",
"reliable",
"way",
"to",
"classify",
"the",
"age",
"of",
"a",
"file",
"is",
"with",
"the",
"date",
"stored",
"in",
"the",
"startedAt",
"file",
"so",
"gather",
"files",
"by",
"UUID",
"with",
"a",
"date",
"from",
"startedAt",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L60-L112
|
train
|
docker/distribution
|
registry/storage/purgeuploads.go
|
uuidFromPath
|
func uuidFromPath(path string) (string, bool) {
components := strings.Split(path, "/")
for i := len(components) - 1; i >= 0; i-- {
if u, err := uuid.Parse(components[i]); err == nil {
return u.String(), i == len(components)-1
}
}
return "", false
}
|
go
|
func uuidFromPath(path string) (string, bool) {
components := strings.Split(path, "/")
for i := len(components) - 1; i >= 0; i-- {
if u, err := uuid.Parse(components[i]); err == nil {
return u.String(), i == len(components)-1
}
}
return "", false
}
|
[
"func",
"uuidFromPath",
"(",
"path",
"string",
")",
"(",
"string",
",",
"bool",
")",
"{",
"components",
":=",
"strings",
".",
"Split",
"(",
"path",
",",
"\"",
"\"",
")",
"\n",
"for",
"i",
":=",
"len",
"(",
"components",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"if",
"u",
",",
"err",
":=",
"uuid",
".",
"Parse",
"(",
"components",
"[",
"i",
"]",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"u",
".",
"String",
"(",
")",
",",
"i",
"==",
"len",
"(",
"components",
")",
"-",
"1",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}"
] |
// uuidFromPath extracts the upload UUID from a given path
// If the UUID is the last path component, this is the containing
// directory for all upload files
|
[
"uuidFromPath",
"extracts",
"the",
"upload",
"UUID",
"from",
"a",
"given",
"path",
"If",
"the",
"UUID",
"is",
"the",
"last",
"path",
"component",
"this",
"is",
"the",
"containing",
"directory",
"for",
"all",
"upload",
"files"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L117-L125
|
train
|
docker/distribution
|
registry/storage/purgeuploads.go
|
readStartedAtFile
|
func readStartedAtFile(driver storageDriver.StorageDriver, path string) (time.Time, error) {
// todo:(richardscothern) - pass in a context
startedAtBytes, err := driver.GetContent(context.Background(), path)
if err != nil {
return time.Now(), err
}
startedAt, err := time.Parse(time.RFC3339, string(startedAtBytes))
if err != nil {
return time.Now(), err
}
return startedAt, nil
}
|
go
|
func readStartedAtFile(driver storageDriver.StorageDriver, path string) (time.Time, error) {
// todo:(richardscothern) - pass in a context
startedAtBytes, err := driver.GetContent(context.Background(), path)
if err != nil {
return time.Now(), err
}
startedAt, err := time.Parse(time.RFC3339, string(startedAtBytes))
if err != nil {
return time.Now(), err
}
return startedAt, nil
}
|
[
"func",
"readStartedAtFile",
"(",
"driver",
"storageDriver",
".",
"StorageDriver",
",",
"path",
"string",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"// todo:(richardscothern) - pass in a context",
"startedAtBytes",
",",
"err",
":=",
"driver",
".",
"GetContent",
"(",
"context",
".",
"Background",
"(",
")",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Now",
"(",
")",
",",
"err",
"\n",
"}",
"\n",
"startedAt",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"string",
"(",
"startedAtBytes",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Now",
"(",
")",
",",
"err",
"\n",
"}",
"\n",
"return",
"startedAt",
",",
"nil",
"\n",
"}"
] |
// readStartedAtFile reads the date from an upload's startedAtFile
|
[
"readStartedAtFile",
"reads",
"the",
"date",
"from",
"an",
"upload",
"s",
"startedAtFile"
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/purgeuploads.go#L128-L139
|
train
|
docker/distribution
|
registry/storage/filereader.go
|
newFileReader
|
func newFileReader(ctx context.Context, driver storagedriver.StorageDriver, path string, size int64) (*fileReader, error) {
return &fileReader{
ctx: ctx,
driver: driver,
path: path,
size: size,
}, nil
}
|
go
|
func newFileReader(ctx context.Context, driver storagedriver.StorageDriver, path string, size int64) (*fileReader, error) {
return &fileReader{
ctx: ctx,
driver: driver,
path: path,
size: size,
}, nil
}
|
[
"func",
"newFileReader",
"(",
"ctx",
"context",
".",
"Context",
",",
"driver",
"storagedriver",
".",
"StorageDriver",
",",
"path",
"string",
",",
"size",
"int64",
")",
"(",
"*",
"fileReader",
",",
"error",
")",
"{",
"return",
"&",
"fileReader",
"{",
"ctx",
":",
"ctx",
",",
"driver",
":",
"driver",
",",
"path",
":",
"path",
",",
"size",
":",
"size",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// newFileReader initializes a file reader for the remote file. The reader
// takes on the size and path that must be determined externally with a stat
// call. The reader operates optimistically, assuming that the file is already
// there.
|
[
"newFileReader",
"initializes",
"a",
"file",
"reader",
"for",
"the",
"remote",
"file",
".",
"The",
"reader",
"takes",
"on",
"the",
"size",
"and",
"path",
"that",
"must",
"be",
"determined",
"externally",
"with",
"a",
"stat",
"call",
".",
"The",
"reader",
"operates",
"optimistically",
"assuming",
"that",
"the",
"file",
"is",
"already",
"there",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/filereader.go#L44-L51
|
train
|
docker/distribution
|
registry/storage/filereader.go
|
reader
|
func (fr *fileReader) reader() (io.Reader, error) {
if fr.err != nil {
return nil, fr.err
}
if fr.rc != nil {
return fr.brd, nil
}
// If we don't have a reader, open one up.
rc, err := fr.driver.Reader(fr.ctx, fr.path, fr.offset)
if err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
// NOTE(stevvooe): If the path is not found, we simply return a
// reader that returns io.EOF. However, we do not set fr.rc,
// allowing future attempts at getting a reader to possibly
// succeed if the file turns up later.
return ioutil.NopCloser(bytes.NewReader([]byte{})), nil
default:
return nil, err
}
}
fr.rc = rc
if fr.brd == nil {
fr.brd = bufio.NewReaderSize(fr.rc, fileReaderBufferSize)
} else {
fr.brd.Reset(fr.rc)
}
return fr.brd, nil
}
|
go
|
func (fr *fileReader) reader() (io.Reader, error) {
if fr.err != nil {
return nil, fr.err
}
if fr.rc != nil {
return fr.brd, nil
}
// If we don't have a reader, open one up.
rc, err := fr.driver.Reader(fr.ctx, fr.path, fr.offset)
if err != nil {
switch err := err.(type) {
case storagedriver.PathNotFoundError:
// NOTE(stevvooe): If the path is not found, we simply return a
// reader that returns io.EOF. However, we do not set fr.rc,
// allowing future attempts at getting a reader to possibly
// succeed if the file turns up later.
return ioutil.NopCloser(bytes.NewReader([]byte{})), nil
default:
return nil, err
}
}
fr.rc = rc
if fr.brd == nil {
fr.brd = bufio.NewReaderSize(fr.rc, fileReaderBufferSize)
} else {
fr.brd.Reset(fr.rc)
}
return fr.brd, nil
}
|
[
"func",
"(",
"fr",
"*",
"fileReader",
")",
"reader",
"(",
")",
"(",
"io",
".",
"Reader",
",",
"error",
")",
"{",
"if",
"fr",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fr",
".",
"err",
"\n",
"}",
"\n\n",
"if",
"fr",
".",
"rc",
"!=",
"nil",
"{",
"return",
"fr",
".",
"brd",
",",
"nil",
"\n",
"}",
"\n\n",
"// If we don't have a reader, open one up.",
"rc",
",",
"err",
":=",
"fr",
".",
"driver",
".",
"Reader",
"(",
"fr",
".",
"ctx",
",",
"fr",
".",
"path",
",",
"fr",
".",
"offset",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"storagedriver",
".",
"PathNotFoundError",
":",
"// NOTE(stevvooe): If the path is not found, we simply return a",
"// reader that returns io.EOF. However, we do not set fr.rc,",
"// allowing future attempts at getting a reader to possibly",
"// succeed if the file turns up later.",
"return",
"ioutil",
".",
"NopCloser",
"(",
"bytes",
".",
"NewReader",
"(",
"[",
"]",
"byte",
"{",
"}",
")",
")",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"fr",
".",
"rc",
"=",
"rc",
"\n\n",
"if",
"fr",
".",
"brd",
"==",
"nil",
"{",
"fr",
".",
"brd",
"=",
"bufio",
".",
"NewReaderSize",
"(",
"fr",
".",
"rc",
",",
"fileReaderBufferSize",
")",
"\n",
"}",
"else",
"{",
"fr",
".",
"brd",
".",
"Reset",
"(",
"fr",
".",
"rc",
")",
"\n",
"}",
"\n\n",
"return",
"fr",
".",
"brd",
",",
"nil",
"\n",
"}"
] |
// reader prepares the current reader at the lrs offset, ensuring its buffered
// and ready to go.
|
[
"reader",
"prepares",
"the",
"current",
"reader",
"at",
"the",
"lrs",
"offset",
"ensuring",
"its",
"buffered",
"and",
"ready",
"to",
"go",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/filereader.go#L111-L144
|
train
|
docker/distribution
|
registry/storage/filereader.go
|
reset
|
func (fr *fileReader) reset() {
if fr.err != nil {
return
}
if fr.rc != nil {
fr.rc.Close()
fr.rc = nil
}
}
|
go
|
func (fr *fileReader) reset() {
if fr.err != nil {
return
}
if fr.rc != nil {
fr.rc.Close()
fr.rc = nil
}
}
|
[
"func",
"(",
"fr",
"*",
"fileReader",
")",
"reset",
"(",
")",
"{",
"if",
"fr",
".",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"fr",
".",
"rc",
"!=",
"nil",
"{",
"fr",
".",
"rc",
".",
"Close",
"(",
")",
"\n",
"fr",
".",
"rc",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] |
// resetReader resets the reader, forcing the read method to open up a new
// connection and rebuild the buffered reader. This should be called when the
// offset and the reader will become out of sync, such as during a seek
// operation.
|
[
"resetReader",
"resets",
"the",
"reader",
"forcing",
"the",
"read",
"method",
"to",
"open",
"up",
"a",
"new",
"connection",
"and",
"rebuild",
"the",
"buffered",
"reader",
".",
"This",
"should",
"be",
"called",
"when",
"the",
"offset",
"and",
"the",
"reader",
"will",
"become",
"out",
"of",
"sync",
"such",
"as",
"during",
"a",
"seek",
"operation",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/filereader.go#L150-L158
|
train
|
docker/distribution
|
registry/handlers/blobupload.go
|
StartBlobUpload
|
func (buh *blobUploadHandler) StartBlobUpload(w http.ResponseWriter, r *http.Request) {
var options []distribution.BlobCreateOption
fromRepo := r.FormValue("from")
mountDigest := r.FormValue("mount")
if mountDigest != "" && fromRepo != "" {
opt, err := buh.createBlobMountOption(fromRepo, mountDigest)
if opt != nil && err == nil {
options = append(options, opt)
}
}
blobs := buh.Repository.Blobs(buh)
upload, err := blobs.Create(buh, options...)
if err != nil {
if ebm, ok := err.(distribution.ErrBlobMounted); ok {
if err := buh.writeBlobCreatedHeaders(w, ebm.Descriptor); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
} else if err == distribution.ErrUnsupported {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported)
} else {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
return
}
buh.Upload = upload
if err := buh.blobUploadResponse(w, r, true); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
w.Header().Set("Docker-Upload-UUID", buh.Upload.ID())
w.WriteHeader(http.StatusAccepted)
}
|
go
|
func (buh *blobUploadHandler) StartBlobUpload(w http.ResponseWriter, r *http.Request) {
var options []distribution.BlobCreateOption
fromRepo := r.FormValue("from")
mountDigest := r.FormValue("mount")
if mountDigest != "" && fromRepo != "" {
opt, err := buh.createBlobMountOption(fromRepo, mountDigest)
if opt != nil && err == nil {
options = append(options, opt)
}
}
blobs := buh.Repository.Blobs(buh)
upload, err := blobs.Create(buh, options...)
if err != nil {
if ebm, ok := err.(distribution.ErrBlobMounted); ok {
if err := buh.writeBlobCreatedHeaders(w, ebm.Descriptor); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
} else if err == distribution.ErrUnsupported {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported)
} else {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
return
}
buh.Upload = upload
if err := buh.blobUploadResponse(w, r, true); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
w.Header().Set("Docker-Upload-UUID", buh.Upload.ID())
w.WriteHeader(http.StatusAccepted)
}
|
[
"func",
"(",
"buh",
"*",
"blobUploadHandler",
")",
"StartBlobUpload",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"options",
"[",
"]",
"distribution",
".",
"BlobCreateOption",
"\n\n",
"fromRepo",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"mountDigest",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"mountDigest",
"!=",
"\"",
"\"",
"&&",
"fromRepo",
"!=",
"\"",
"\"",
"{",
"opt",
",",
"err",
":=",
"buh",
".",
"createBlobMountOption",
"(",
"fromRepo",
",",
"mountDigest",
")",
"\n",
"if",
"opt",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"options",
"=",
"append",
"(",
"options",
",",
"opt",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"blobs",
":=",
"buh",
".",
"Repository",
".",
"Blobs",
"(",
"buh",
")",
"\n",
"upload",
",",
"err",
":=",
"blobs",
".",
"Create",
"(",
"buh",
",",
"options",
"...",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"ebm",
",",
"ok",
":=",
"err",
".",
"(",
"distribution",
".",
"ErrBlobMounted",
")",
";",
"ok",
"{",
"if",
"err",
":=",
"buh",
".",
"writeBlobCreatedHeaders",
"(",
"w",
",",
"ebm",
".",
"Descriptor",
")",
";",
"err",
"!=",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"err",
"==",
"distribution",
".",
"ErrUnsupported",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnsupported",
")",
"\n",
"}",
"else",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"buh",
".",
"Upload",
"=",
"upload",
"\n\n",
"if",
"err",
":=",
"buh",
".",
"blobUploadResponse",
"(",
"w",
",",
"r",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"buh",
".",
"Upload",
".",
"ID",
"(",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusAccepted",
")",
"\n",
"}"
] |
// StartBlobUpload begins the blob upload process and allocates a server-side
// blob writer session, optionally mounting the blob from a separate repository.
|
[
"StartBlobUpload",
"begins",
"the",
"blob",
"upload",
"process",
"and",
"allocates",
"a",
"server",
"-",
"side",
"blob",
"writer",
"session",
"optionally",
"mounting",
"the",
"blob",
"from",
"a",
"separate",
"repository",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L107-L145
|
train
|
docker/distribution
|
registry/handlers/blobupload.go
|
GetUploadStatus
|
func (buh *blobUploadHandler) GetUploadStatus(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
// TODO(dmcgowan): Set last argument to false in blobUploadResponse when
// resumable upload is supported. This will enable returning a non-zero
// range for clients to begin uploading at an offset.
if err := buh.blobUploadResponse(w, r, true); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
w.Header().Set("Docker-Upload-UUID", buh.UUID)
w.WriteHeader(http.StatusNoContent)
}
|
go
|
func (buh *blobUploadHandler) GetUploadStatus(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
// TODO(dmcgowan): Set last argument to false in blobUploadResponse when
// resumable upload is supported. This will enable returning a non-zero
// range for clients to begin uploading at an offset.
if err := buh.blobUploadResponse(w, r, true); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
w.Header().Set("Docker-Upload-UUID", buh.UUID)
w.WriteHeader(http.StatusNoContent)
}
|
[
"func",
"(",
"buh",
"*",
"blobUploadHandler",
")",
"GetUploadStatus",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"buh",
".",
"Upload",
"==",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeBlobUploadUnknown",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// TODO(dmcgowan): Set last argument to false in blobUploadResponse when",
"// resumable upload is supported. This will enable returning a non-zero",
"// range for clients to begin uploading at an offset.",
"if",
"err",
":=",
"buh",
".",
"blobUploadResponse",
"(",
"w",
",",
"r",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"buh",
".",
"UUID",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNoContent",
")",
"\n",
"}"
] |
// GetUploadStatus returns the status of a given upload, identified by id.
|
[
"GetUploadStatus",
"returns",
"the",
"status",
"of",
"a",
"given",
"upload",
"identified",
"by",
"id",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L148-L164
|
train
|
docker/distribution
|
registry/handlers/blobupload.go
|
PatchBlobData
|
func (buh *blobUploadHandler) PatchBlobData(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
ct := r.Header.Get("Content-Type")
if ct != "" && ct != "application/octet-stream" {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(fmt.Errorf("bad Content-Type")))
// TODO(dmcgowan): encode error
return
}
// TODO(dmcgowan): support Content-Range header to seek and write range
if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PATCH"); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error()))
return
}
if err := buh.blobUploadResponse(w, r, false); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
w.WriteHeader(http.StatusAccepted)
}
|
go
|
func (buh *blobUploadHandler) PatchBlobData(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
ct := r.Header.Get("Content-Type")
if ct != "" && ct != "application/octet-stream" {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(fmt.Errorf("bad Content-Type")))
// TODO(dmcgowan): encode error
return
}
// TODO(dmcgowan): support Content-Range header to seek and write range
if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PATCH"); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error()))
return
}
if err := buh.blobUploadResponse(w, r, false); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
w.WriteHeader(http.StatusAccepted)
}
|
[
"func",
"(",
"buh",
"*",
"blobUploadHandler",
")",
"PatchBlobData",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"buh",
".",
"Upload",
"==",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeBlobUploadUnknown",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"ct",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"ct",
"!=",
"\"",
"\"",
"&&",
"ct",
"!=",
"\"",
"\"",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
")",
")",
"\n",
"// TODO(dmcgowan): encode error",
"return",
"\n",
"}",
"\n\n",
"// TODO(dmcgowan): support Content-Range header to seek and write range",
"if",
"err",
":=",
"copyFullPayload",
"(",
"buh",
",",
"w",
",",
"r",
",",
"buh",
".",
"Upload",
",",
"-",
"1",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"buh",
".",
"blobUploadResponse",
"(",
"w",
",",
"r",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusAccepted",
")",
"\n",
"}"
] |
// PatchBlobData writes data to an upload.
|
[
"PatchBlobData",
"writes",
"data",
"to",
"an",
"upload",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L167-L193
|
train
|
docker/distribution
|
registry/handlers/blobupload.go
|
PutBlobUploadComplete
|
func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
dgstStr := r.FormValue("digest") // TODO(stevvooe): Support multiple digest parameters!
if dgstStr == "" {
// no digest? return error, but allow retry.
buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest missing"))
return
}
dgst, err := digest.Parse(dgstStr)
if err != nil {
// no digest? return error, but allow retry.
buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest parsing failed"))
return
}
if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PUT"); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error()))
return
}
desc, err := buh.Upload.Commit(buh, distribution.Descriptor{
Digest: dgst,
// TODO(stevvooe): This isn't wildly important yet, but we should
// really set the mediatype. For now, we can let the backend take care
// of this.
})
if err != nil {
switch err := err.(type) {
case distribution.ErrBlobInvalidDigest:
buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err))
case errcode.Error:
buh.Errors = append(buh.Errors, err)
default:
switch err {
case distribution.ErrAccessDenied:
buh.Errors = append(buh.Errors, errcode.ErrorCodeDenied)
case distribution.ErrUnsupported:
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported)
case distribution.ErrBlobInvalidLength, distribution.ErrBlobDigestUnsupported:
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err))
default:
dcontext.GetLogger(buh).Errorf("unknown error completing upload: %v", err)
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
}
// Clean up the backend blob data if there was an error.
if err := buh.Upload.Cancel(buh); err != nil {
// If the cleanup fails, all we can do is observe and report.
dcontext.GetLogger(buh).Errorf("error canceling upload after error: %v", err)
}
return
}
if err := buh.writeBlobCreatedHeaders(w, desc); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
}
|
go
|
func (buh *blobUploadHandler) PutBlobUploadComplete(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
dgstStr := r.FormValue("digest") // TODO(stevvooe): Support multiple digest parameters!
if dgstStr == "" {
// no digest? return error, but allow retry.
buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest missing"))
return
}
dgst, err := digest.Parse(dgstStr)
if err != nil {
// no digest? return error, but allow retry.
buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail("digest parsing failed"))
return
}
if err := copyFullPayload(buh, w, r, buh.Upload, -1, "blob PUT"); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err.Error()))
return
}
desc, err := buh.Upload.Commit(buh, distribution.Descriptor{
Digest: dgst,
// TODO(stevvooe): This isn't wildly important yet, but we should
// really set the mediatype. For now, we can let the backend take care
// of this.
})
if err != nil {
switch err := err.(type) {
case distribution.ErrBlobInvalidDigest:
buh.Errors = append(buh.Errors, v2.ErrorCodeDigestInvalid.WithDetail(err))
case errcode.Error:
buh.Errors = append(buh.Errors, err)
default:
switch err {
case distribution.ErrAccessDenied:
buh.Errors = append(buh.Errors, errcode.ErrorCodeDenied)
case distribution.ErrUnsupported:
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnsupported)
case distribution.ErrBlobInvalidLength, distribution.ErrBlobDigestUnsupported:
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadInvalid.WithDetail(err))
default:
dcontext.GetLogger(buh).Errorf("unknown error completing upload: %v", err)
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
}
// Clean up the backend blob data if there was an error.
if err := buh.Upload.Cancel(buh); err != nil {
// If the cleanup fails, all we can do is observe and report.
dcontext.GetLogger(buh).Errorf("error canceling upload after error: %v", err)
}
return
}
if err := buh.writeBlobCreatedHeaders(w, desc); err != nil {
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
return
}
}
|
[
"func",
"(",
"buh",
"*",
"blobUploadHandler",
")",
"PutBlobUploadComplete",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"buh",
".",
"Upload",
"==",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeBlobUploadUnknown",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"dgstStr",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"// TODO(stevvooe): Support multiple digest parameters!",
"\n\n",
"if",
"dgstStr",
"==",
"\"",
"\"",
"{",
"// no digest? return error, but allow retry.",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeDigestInvalid",
".",
"WithDetail",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"dgst",
",",
"err",
":=",
"digest",
".",
"Parse",
"(",
"dgstStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// no digest? return error, but allow retry.",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeDigestInvalid",
".",
"WithDetail",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"copyFullPayload",
"(",
"buh",
",",
"w",
",",
"r",
",",
"buh",
".",
"Upload",
",",
"-",
"1",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"desc",
",",
"err",
":=",
"buh",
".",
"Upload",
".",
"Commit",
"(",
"buh",
",",
"distribution",
".",
"Descriptor",
"{",
"Digest",
":",
"dgst",
",",
"// TODO(stevvooe): This isn't wildly important yet, but we should",
"// really set the mediatype. For now, we can let the backend take care",
"// of this.",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"distribution",
".",
"ErrBlobInvalidDigest",
":",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeDigestInvalid",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"case",
"errcode",
".",
"Error",
":",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"err",
")",
"\n",
"default",
":",
"switch",
"err",
"{",
"case",
"distribution",
".",
"ErrAccessDenied",
":",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeDenied",
")",
"\n",
"case",
"distribution",
".",
"ErrUnsupported",
":",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnsupported",
")",
"\n",
"case",
"distribution",
".",
"ErrBlobInvalidLength",
",",
"distribution",
".",
"ErrBlobDigestUnsupported",
":",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeBlobUploadInvalid",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"default",
":",
"dcontext",
".",
"GetLogger",
"(",
"buh",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"// Clean up the backend blob data if there was an error.",
"if",
"err",
":=",
"buh",
".",
"Upload",
".",
"Cancel",
"(",
"buh",
")",
";",
"err",
"!=",
"nil",
"{",
"// If the cleanup fails, all we can do is observe and report.",
"dcontext",
".",
"GetLogger",
"(",
"buh",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"buh",
".",
"writeBlobCreatedHeaders",
"(",
"w",
",",
"desc",
")",
";",
"err",
"!=",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] |
// PutBlobUploadComplete takes the final request of a blob upload. The
// request may include all the blob data or no blob data. Any data
// provided is received and verified. If successful, the blob is linked
// into the blob store and 201 Created is returned with the canonical
// url of the blob.
|
[
"PutBlobUploadComplete",
"takes",
"the",
"final",
"request",
"of",
"a",
"blob",
"upload",
".",
"The",
"request",
"may",
"include",
"all",
"the",
"blob",
"data",
"or",
"no",
"blob",
"data",
".",
"Any",
"data",
"provided",
"is",
"received",
"and",
"verified",
".",
"If",
"successful",
"the",
"blob",
"is",
"linked",
"into",
"the",
"blob",
"store",
"and",
"201",
"Created",
"is",
"returned",
"with",
"the",
"canonical",
"url",
"of",
"the",
"blob",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L200-L267
|
train
|
docker/distribution
|
registry/handlers/blobupload.go
|
CancelBlobUpload
|
func (buh *blobUploadHandler) CancelBlobUpload(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
w.Header().Set("Docker-Upload-UUID", buh.UUID)
if err := buh.Upload.Cancel(buh); err != nil {
dcontext.GetLogger(buh).Errorf("error encountered canceling upload: %v", err)
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
w.WriteHeader(http.StatusNoContent)
}
|
go
|
func (buh *blobUploadHandler) CancelBlobUpload(w http.ResponseWriter, r *http.Request) {
if buh.Upload == nil {
buh.Errors = append(buh.Errors, v2.ErrorCodeBlobUploadUnknown)
return
}
w.Header().Set("Docker-Upload-UUID", buh.UUID)
if err := buh.Upload.Cancel(buh); err != nil {
dcontext.GetLogger(buh).Errorf("error encountered canceling upload: %v", err)
buh.Errors = append(buh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))
}
w.WriteHeader(http.StatusNoContent)
}
|
[
"func",
"(",
"buh",
"*",
"blobUploadHandler",
")",
"CancelBlobUpload",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"buh",
".",
"Upload",
"==",
"nil",
"{",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"v2",
".",
"ErrorCodeBlobUploadUnknown",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"buh",
".",
"UUID",
")",
"\n",
"if",
"err",
":=",
"buh",
".",
"Upload",
".",
"Cancel",
"(",
"buh",
")",
";",
"err",
"!=",
"nil",
"{",
"dcontext",
".",
"GetLogger",
"(",
"buh",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"buh",
".",
"Errors",
"=",
"append",
"(",
"buh",
".",
"Errors",
",",
"errcode",
".",
"ErrorCodeUnknown",
".",
"WithDetail",
"(",
"err",
")",
")",
"\n",
"}",
"\n\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNoContent",
")",
"\n",
"}"
] |
// CancelBlobUpload cancels an in-progress upload of a blob.
|
[
"CancelBlobUpload",
"cancels",
"an",
"in",
"-",
"progress",
"upload",
"of",
"a",
"blob",
"."
] |
3226863cbcba6dbc2f6c83a37b28126c934af3f8
|
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/blobupload.go#L270-L283
|
train
|
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.