repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
docker/distribution | registry/storage/cache/redis/redis.go | stat | func (rbds *redisBlobDescriptorService) stat(ctx context.Context, conn redis.Conn, dgst digest.Digest) (distribution.Descriptor, error) {
reply, err := redis.Values(conn.Do("HMGET", rbds.blobDescriptorHashKey(dgst), "digest", "size", "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
// NOTE(stevvooe): The "size" field used to be "length". We treat a
// missing "size" field here as an unknown blob, which causes a cache
// miss, effectively migrating the field.
if len(reply) < 3 || reply[0] == nil || reply[1] == nil { // don't care if mediatype is nil
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
var desc distribution.Descriptor
if _, err := redis.Scan(reply, &desc.Digest, &desc.Size, &desc.MediaType); err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
} | go | func (rbds *redisBlobDescriptorService) stat(ctx context.Context, conn redis.Conn, dgst digest.Digest) (distribution.Descriptor, error) {
reply, err := redis.Values(conn.Do("HMGET", rbds.blobDescriptorHashKey(dgst), "digest", "size", "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
// NOTE(stevvooe): The "size" field used to be "length". We treat a
// missing "size" field here as an unknown blob, which causes a cache
// miss, effectively migrating the field.
if len(reply) < 3 || reply[0] == nil || reply[1] == nil { // don't care if mediatype is nil
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
var desc distribution.Descriptor
if _, err := redis.Scan(reply, &desc.Digest, &desc.Size, &desc.MediaType); err != nil {
return distribution.Descriptor{}, err
}
return desc, nil
} | [
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"redis",
".",
"Conn",
",",
"dgst",
"digest",
".",
"Digest",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"rep... | // stat provides an internal stat call that takes a connection parameter. This
// allows some internal management of the connection scope. | [
"stat",
"provides",
"an",
"internal",
"stat",
"call",
"that",
"takes",
"a",
"connection",
"parameter",
".",
"This",
"allows",
"some",
"internal",
"management",
"of",
"the",
"connection",
"scope",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L89-L108 | train |
docker/distribution | registry/storage/cache/redis/redis.go | SetDescriptor | func (rbds *redisBlobDescriptorService) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
if err := dgst.Validate(); err != nil {
return err
}
if err := cache.ValidateDescriptor(desc); err != nil {
return err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.setDescriptor(ctx, conn, dgst, desc)
} | go | func (rbds *redisBlobDescriptorService) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
if err := dgst.Validate(); err != nil {
return err
}
if err := cache.ValidateDescriptor(desc); err != nil {
return err
}
conn := rbds.pool.Get()
defer conn.Close()
return rbds.setDescriptor(ctx, conn, dgst, desc)
} | [
"func",
"(",
"rbds",
"*",
"redisBlobDescriptorService",
")",
"SetDescriptor",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
",",
"desc",
"distribution",
".",
"Descriptor",
")",
"error",
"{",
"if",
"err",
":=",
"dgst",
".",
"V... | // SetDescriptor sets the descriptor data for the given digest using a redis
// hash. A hash is used here since we may store unrelated fields about a layer
// in the future. | [
"SetDescriptor",
"sets",
"the",
"descriptor",
"data",
"for",
"the",
"given",
"digest",
"using",
"a",
"redis",
"hash",
".",
"A",
"hash",
"is",
"used",
"here",
"since",
"we",
"may",
"store",
"unrelated",
"fields",
"about",
"a",
"layer",
"in",
"the",
"future"... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L113-L126 | train |
docker/distribution | registry/storage/cache/redis/redis.go | Stat | func (rsrbds *repositoryScopedRedisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return distribution.Descriptor{}, err
}
if !member {
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
upstream, err := rsrbds.upstream.stat(ctx, conn, dgst)
if err != nil {
return distribution.Descriptor{}, err
}
// We allow a per repository mediatype, let's look it up here.
mediatype, err := redis.String(conn.Do("HGET", rsrbds.blobDescriptorHashKey(dgst), "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
if mediatype != "" {
upstream.MediaType = mediatype
}
return upstream, nil
} | go | func (rsrbds *repositoryScopedRedisBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
if err := dgst.Validate(); err != nil {
return distribution.Descriptor{}, err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return distribution.Descriptor{}, err
}
if !member {
return distribution.Descriptor{}, distribution.ErrBlobUnknown
}
upstream, err := rsrbds.upstream.stat(ctx, conn, dgst)
if err != nil {
return distribution.Descriptor{}, err
}
// We allow a per repository mediatype, let's look it up here.
mediatype, err := redis.String(conn.Do("HGET", rsrbds.blobDescriptorHashKey(dgst), "mediatype"))
if err != nil {
return distribution.Descriptor{}, err
}
if mediatype != "" {
upstream.MediaType = mediatype
}
return upstream, nil
} | [
"func",
"(",
"rsrbds",
"*",
"repositoryScopedRedisBlobDescriptorService",
")",
"Stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"(",
"distribution",
".",
"Descriptor",
",",
"error",
")",
"{",
"if",
"err",
":=",
"dgst"... | // Stat ensures that the digest is a member of the specified repository and
// forwards the descriptor request to the global blob store. If the media type
// differs for the repository, we override it. | [
"Stat",
"ensures",
"that",
"the",
"digest",
"is",
"a",
"member",
"of",
"the",
"specified",
"repository",
"and",
"forwards",
"the",
"descriptor",
"request",
"to",
"the",
"global",
"blob",
"store",
".",
"If",
"the",
"media",
"type",
"differs",
"for",
"the",
... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L158-L192 | train |
docker/distribution | registry/storage/cache/redis/redis.go | Clear | func (rsrbds *repositoryScopedRedisBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
if err := dgst.Validate(); err != nil {
return err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return err
}
if !member {
return distribution.ErrBlobUnknown
}
return rsrbds.upstream.Clear(ctx, dgst)
} | go | func (rsrbds *repositoryScopedRedisBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
if err := dgst.Validate(); err != nil {
return err
}
conn := rsrbds.upstream.pool.Get()
defer conn.Close()
// Check membership to repository first
member, err := redis.Bool(conn.Do("SISMEMBER", rsrbds.repositoryBlobSetKey(rsrbds.repo), dgst))
if err != nil {
return err
}
if !member {
return distribution.ErrBlobUnknown
}
return rsrbds.upstream.Clear(ctx, dgst)
} | [
"func",
"(",
"rsrbds",
"*",
"repositoryScopedRedisBlobDescriptorService",
")",
"Clear",
"(",
"ctx",
"context",
".",
"Context",
",",
"dgst",
"digest",
".",
"Digest",
")",
"error",
"{",
"if",
"err",
":=",
"dgst",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
... | // Clear removes the descriptor from the cache and forwards to the upstream descriptor store | [
"Clear",
"removes",
"the",
"descriptor",
"from",
"the",
"cache",
"and",
"forwards",
"to",
"the",
"upstream",
"descriptor",
"store"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/cache/redis/redis.go#L195-L214 | train |
docker/distribution | registry/handlers/catalog.go | createLinkEntry | func createLinkEntry(origURL string, maxEntries int, lastEntry string) (string, error) {
calledURL, err := url.Parse(origURL)
if err != nil {
return "", err
}
v := url.Values{}
v.Add("n", strconv.Itoa(maxEntries))
v.Add("last", lastEntry)
calledURL.RawQuery = v.Encode()
calledURL.Fragment = ""
urlStr := fmt.Sprintf("<%s>; rel=\"next\"", calledURL.String())
return urlStr, nil
} | go | func createLinkEntry(origURL string, maxEntries int, lastEntry string) (string, error) {
calledURL, err := url.Parse(origURL)
if err != nil {
return "", err
}
v := url.Values{}
v.Add("n", strconv.Itoa(maxEntries))
v.Add("last", lastEntry)
calledURL.RawQuery = v.Encode()
calledURL.Fragment = ""
urlStr := fmt.Sprintf("<%s>; rel=\"next\"", calledURL.String())
return urlStr, nil
} | [
"func",
"createLinkEntry",
"(",
"origURL",
"string",
",",
"maxEntries",
"int",
",",
"lastEntry",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"calledURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"origURL",
")",
"\n",
"if",
"err",
"!=",
"ni... | // Use the original URL from the request to create a new URL for
// the link header | [
"Use",
"the",
"original",
"URL",
"from",
"the",
"request",
"to",
"create",
"a",
"new",
"URL",
"for",
"the",
"link",
"header"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/catalog.go#L82-L98 | train |
docker/distribution | contrib/token-server/main.go | handlerWithContext | func handlerWithContext(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := dcontext.WithRequest(ctx, r)
logger := dcontext.GetRequestLogger(ctx)
ctx = dcontext.WithLogger(ctx, logger)
handler(ctx, w, r)
})
} | go | func handlerWithContext(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := dcontext.WithRequest(ctx, r)
logger := dcontext.GetRequestLogger(ctx)
ctx = dcontext.WithLogger(ctx, logger)
handler(ctx, w, r)
})
} | [
"func",
"handlerWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"handler",
"func",
"(",
"context",
".",
"Context",
",",
"http",
".",
"ResponseWriter",
",",
"*",
"http",
".",
"Request",
")",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".... | // handlerWithContext wraps the given context-aware handler by setting up the
// request context from a base context. | [
"handlerWithContext",
"wraps",
"the",
"given",
"context",
"-",
"aware",
"handler",
"by",
"setting",
"up",
"the",
"request",
"context",
"from",
"a",
"base",
"context",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/contrib/token-server/main.go#L117-L125 | train |
docker/distribution | registry/handlers/app.go | register | func (app *App) register(routeName string, dispatch dispatchFunc) {
handler := app.dispatcher(dispatch)
// Chain the handler with prometheus instrumented handler
if app.Config.HTTP.Debug.Prometheus.Enabled {
namespace := metrics.NewNamespace(prometheus.NamespacePrefix, "http", nil)
httpMetrics := namespace.NewDefaultHttpMetrics(strings.Replace(routeName, "-", "_", -1))
metrics.Register(namespace)
handler = metrics.InstrumentHandler(httpMetrics, handler)
}
// TODO(stevvooe): This odd dispatcher/route registration is by-product of
// some limitations in the gorilla/mux router. We are using it to keep
// routing consistent between the client and server, but we may want to
// replace it with manual routing and structure-based dispatch for better
// control over the request execution.
app.router.GetRoute(routeName).Handler(handler)
} | go | func (app *App) register(routeName string, dispatch dispatchFunc) {
handler := app.dispatcher(dispatch)
// Chain the handler with prometheus instrumented handler
if app.Config.HTTP.Debug.Prometheus.Enabled {
namespace := metrics.NewNamespace(prometheus.NamespacePrefix, "http", nil)
httpMetrics := namespace.NewDefaultHttpMetrics(strings.Replace(routeName, "-", "_", -1))
metrics.Register(namespace)
handler = metrics.InstrumentHandler(httpMetrics, handler)
}
// TODO(stevvooe): This odd dispatcher/route registration is by-product of
// some limitations in the gorilla/mux router. We are using it to keep
// routing consistent between the client and server, but we may want to
// replace it with manual routing and structure-based dispatch for better
// control over the request execution.
app.router.GetRoute(routeName).Handler(handler)
} | [
"func",
"(",
"app",
"*",
"App",
")",
"register",
"(",
"routeName",
"string",
",",
"dispatch",
"dispatchFunc",
")",
"{",
"handler",
":=",
"app",
".",
"dispatcher",
"(",
"dispatch",
")",
"\n",
"if",
"app",
".",
"Config",
".",
"HTTP",
".",
"Debug",
".",
... | // register a handler with the application, by route name. The handler will be
// passed through the application filters and context will be constructed at
// request time. | [
"register",
"a",
"handler",
"with",
"the",
"application",
"by",
"route",
"name",
".",
"The",
"handler",
"will",
"be",
"passed",
"through",
"the",
"application",
"filters",
"and",
"context",
"will",
"be",
"constructed",
"at",
"request",
"time",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L426-L444 | train |
docker/distribution | registry/handlers/app.go | configureEvents | func (app *App) configureEvents(configuration *configuration.Configuration) {
// Configure all of the endpoint sinks.
var sinks []notifications.Sink
for _, endpoint := range configuration.Notifications.Endpoints {
if endpoint.Disabled {
dcontext.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name)
continue
}
dcontext.GetLogger(app).Infof("configuring endpoint %v (%v), timeout=%s, headers=%v", endpoint.Name, endpoint.URL, endpoint.Timeout, endpoint.Headers)
endpoint := notifications.NewEndpoint(endpoint.Name, endpoint.URL, notifications.EndpointConfig{
Timeout: endpoint.Timeout,
Threshold: endpoint.Threshold,
Backoff: endpoint.Backoff,
Headers: endpoint.Headers,
IgnoredMediaTypes: endpoint.IgnoredMediaTypes,
Ignore: endpoint.Ignore,
})
sinks = append(sinks, endpoint)
}
// NOTE(stevvooe): Moving to a new queuing implementation is as easy as
// replacing broadcaster with a rabbitmq implementation. It's recommended
// that the registry instances also act as the workers to keep deployment
// simple.
app.events.sink = notifications.NewBroadcaster(sinks...)
// Populate registry event source
hostname, err := os.Hostname()
if err != nil {
hostname = configuration.HTTP.Addr
} else {
// try to pick the port off the config
_, port, err := net.SplitHostPort(configuration.HTTP.Addr)
if err == nil {
hostname = net.JoinHostPort(hostname, port)
}
}
app.events.source = notifications.SourceRecord{
Addr: hostname,
InstanceID: dcontext.GetStringValue(app, "instance.id"),
}
} | go | func (app *App) configureEvents(configuration *configuration.Configuration) {
// Configure all of the endpoint sinks.
var sinks []notifications.Sink
for _, endpoint := range configuration.Notifications.Endpoints {
if endpoint.Disabled {
dcontext.GetLogger(app).Infof("endpoint %s disabled, skipping", endpoint.Name)
continue
}
dcontext.GetLogger(app).Infof("configuring endpoint %v (%v), timeout=%s, headers=%v", endpoint.Name, endpoint.URL, endpoint.Timeout, endpoint.Headers)
endpoint := notifications.NewEndpoint(endpoint.Name, endpoint.URL, notifications.EndpointConfig{
Timeout: endpoint.Timeout,
Threshold: endpoint.Threshold,
Backoff: endpoint.Backoff,
Headers: endpoint.Headers,
IgnoredMediaTypes: endpoint.IgnoredMediaTypes,
Ignore: endpoint.Ignore,
})
sinks = append(sinks, endpoint)
}
// NOTE(stevvooe): Moving to a new queuing implementation is as easy as
// replacing broadcaster with a rabbitmq implementation. It's recommended
// that the registry instances also act as the workers to keep deployment
// simple.
app.events.sink = notifications.NewBroadcaster(sinks...)
// Populate registry event source
hostname, err := os.Hostname()
if err != nil {
hostname = configuration.HTTP.Addr
} else {
// try to pick the port off the config
_, port, err := net.SplitHostPort(configuration.HTTP.Addr)
if err == nil {
hostname = net.JoinHostPort(hostname, port)
}
}
app.events.source = notifications.SourceRecord{
Addr: hostname,
InstanceID: dcontext.GetStringValue(app, "instance.id"),
}
} | [
"func",
"(",
"app",
"*",
"App",
")",
"configureEvents",
"(",
"configuration",
"*",
"configuration",
".",
"Configuration",
")",
"{",
"var",
"sinks",
"[",
"]",
"notifications",
".",
"Sink",
"\n",
"for",
"_",
",",
"endpoint",
":=",
"range",
"configuration",
"... | // configureEvents prepares the event sink for action. | [
"configureEvents",
"prepares",
"the",
"event",
"sink",
"for",
"action",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L447-L491 | train |
docker/distribution | registry/handlers/app.go | configureLogHook | func (app *App) configureLogHook(configuration *configuration.Configuration) {
entry, ok := dcontext.GetLogger(app).(*logrus.Entry)
if !ok {
// somehow, we are not using logrus
return
}
logger := entry.Logger
for _, configHook := range configuration.Log.Hooks {
if !configHook.Disabled {
switch configHook.Type {
case "mail":
hook := &logHook{}
hook.LevelsParam = configHook.Levels
hook.Mail = &mailer{
Addr: configHook.MailOptions.SMTP.Addr,
Username: configHook.MailOptions.SMTP.Username,
Password: configHook.MailOptions.SMTP.Password,
Insecure: configHook.MailOptions.SMTP.Insecure,
From: configHook.MailOptions.From,
To: configHook.MailOptions.To,
}
logger.Hooks.Add(hook)
default:
}
}
}
} | go | func (app *App) configureLogHook(configuration *configuration.Configuration) {
entry, ok := dcontext.GetLogger(app).(*logrus.Entry)
if !ok {
// somehow, we are not using logrus
return
}
logger := entry.Logger
for _, configHook := range configuration.Log.Hooks {
if !configHook.Disabled {
switch configHook.Type {
case "mail":
hook := &logHook{}
hook.LevelsParam = configHook.Levels
hook.Mail = &mailer{
Addr: configHook.MailOptions.SMTP.Addr,
Username: configHook.MailOptions.SMTP.Username,
Password: configHook.MailOptions.SMTP.Password,
Insecure: configHook.MailOptions.SMTP.Insecure,
From: configHook.MailOptions.From,
To: configHook.MailOptions.To,
}
logger.Hooks.Add(hook)
default:
}
}
}
} | [
"func",
"(",
"app",
"*",
"App",
")",
"configureLogHook",
"(",
"configuration",
"*",
"configuration",
".",
"Configuration",
")",
"{",
"entry",
",",
"ok",
":=",
"dcontext",
".",
"GetLogger",
"(",
"app",
")",
".",
"(",
"*",
"logrus",
".",
"Entry",
")",
"\... | // configureLogHook prepares logging hook parameters. | [
"configureLogHook",
"prepares",
"logging",
"hook",
"parameters",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L578-L606 | train |
docker/distribution | registry/handlers/app.go | configureSecret | func (app *App) configureSecret(configuration *configuration.Configuration) {
if configuration.HTTP.Secret == "" {
var secretBytes [randomSecretSize]byte
if _, err := cryptorand.Read(secretBytes[:]); err != nil {
panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err))
}
configuration.HTTP.Secret = string(secretBytes[:])
dcontext.GetLogger(app).Warn("No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable.")
}
} | go | func (app *App) configureSecret(configuration *configuration.Configuration) {
if configuration.HTTP.Secret == "" {
var secretBytes [randomSecretSize]byte
if _, err := cryptorand.Read(secretBytes[:]); err != nil {
panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err))
}
configuration.HTTP.Secret = string(secretBytes[:])
dcontext.GetLogger(app).Warn("No HTTP secret provided - generated random secret. This may cause problems with uploads if multiple registries are behind a load-balancer. To provide a shared secret, fill in http.secret in the configuration file or set the REGISTRY_HTTP_SECRET environment variable.")
}
} | [
"func",
"(",
"app",
"*",
"App",
")",
"configureSecret",
"(",
"configuration",
"*",
"configuration",
".",
"Configuration",
")",
"{",
"if",
"configuration",
".",
"HTTP",
".",
"Secret",
"==",
"\"\"",
"{",
"var",
"secretBytes",
"[",
"randomSecretSize",
"]",
"byt... | // configureSecret creates a random secret if a secret wasn't included in the
// configuration. | [
"configureSecret",
"creates",
"a",
"random",
"secret",
"if",
"a",
"secret",
"wasn",
"t",
"included",
"in",
"the",
"configuration",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L610-L619 | train |
docker/distribution | registry/handlers/app.go | context | func (app *App) context(w http.ResponseWriter, r *http.Request) *Context {
ctx := r.Context()
ctx = dcontext.WithVars(ctx, r)
ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx,
"vars.name",
"vars.reference",
"vars.digest",
"vars.uuid"))
context := &Context{
App: app,
Context: ctx,
}
if app.httpHost.Scheme != "" && app.httpHost.Host != "" {
// A "host" item in the configuration takes precedence over
// X-Forwarded-Proto and X-Forwarded-Host headers, and the
// hostname in the request.
context.urlBuilder = v2.NewURLBuilder(&app.httpHost, false)
} else {
context.urlBuilder = v2.NewURLBuilderFromRequest(r, app.Config.HTTP.RelativeURLs)
}
return context
} | go | func (app *App) context(w http.ResponseWriter, r *http.Request) *Context {
ctx := r.Context()
ctx = dcontext.WithVars(ctx, r)
ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx,
"vars.name",
"vars.reference",
"vars.digest",
"vars.uuid"))
context := &Context{
App: app,
Context: ctx,
}
if app.httpHost.Scheme != "" && app.httpHost.Host != "" {
// A "host" item in the configuration takes precedence over
// X-Forwarded-Proto and X-Forwarded-Host headers, and the
// hostname in the request.
context.urlBuilder = v2.NewURLBuilder(&app.httpHost, false)
} else {
context.urlBuilder = v2.NewURLBuilderFromRequest(r, app.Config.HTTP.RelativeURLs)
}
return context
} | [
"func",
"(",
"app",
"*",
"App",
")",
"context",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"Context",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"ctx",
"=",
"dcontext",
".",
"WithVars",
"... | // context constructs the context object for the application. This only be
// called once per request. | [
"context",
"constructs",
"the",
"context",
"object",
"for",
"the",
"application",
".",
"This",
"only",
"be",
"called",
"once",
"per",
"request",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L780-L804 | train |
docker/distribution | registry/handlers/app.go | authorized | func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Context) error {
dcontext.GetLogger(context).Debug("authorizing request")
repo := getName(context)
if app.accessController == nil {
return nil // access controller is not enabled.
}
var accessRecords []auth.Access
if repo != "" {
accessRecords = appendAccessRecords(accessRecords, r.Method, repo)
if fromRepo := r.FormValue("from"); fromRepo != "" {
// mounting a blob from one repository to another requires pull (GET)
// access to the source repository.
accessRecords = appendAccessRecords(accessRecords, "GET", fromRepo)
}
} else {
// Only allow the name not to be set on the base route.
if app.nameRequired(r) {
// For this to be properly secured, repo must always be set for a
// resource that may make a modification. The only condition under
// which name is not set and we still allow access is when the
// base route is accessed. This section prevents us from making
// that mistake elsewhere in the code, allowing any operation to
// proceed.
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
return fmt.Errorf("forbidden: no repository name")
}
accessRecords = appendCatalogAccessRecord(accessRecords, r)
}
ctx, err := app.accessController.Authorized(context.Context, accessRecords...)
if err != nil {
switch err := err.(type) {
case auth.Challenge:
// Add the appropriate WWW-Auth header
err.SetHeaders(r, w)
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized.WithDetail(accessRecords)); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
default:
// This condition is a potential security problem either in
// the configuration or whatever is backing the access
// controller. Just return a bad request with no information
// to avoid exposure. The request should not proceed.
dcontext.GetLogger(context).Errorf("error checking authorization: %v", err)
w.WriteHeader(http.StatusBadRequest)
}
return err
}
dcontext.GetLogger(ctx, auth.UserNameKey).Info("authorized request")
// TODO(stevvooe): This pattern needs to be cleaned up a bit. One context
// should be replaced by another, rather than replacing the context on a
// mutable object.
context.Context = ctx
return nil
} | go | func (app *App) authorized(w http.ResponseWriter, r *http.Request, context *Context) error {
dcontext.GetLogger(context).Debug("authorizing request")
repo := getName(context)
if app.accessController == nil {
return nil // access controller is not enabled.
}
var accessRecords []auth.Access
if repo != "" {
accessRecords = appendAccessRecords(accessRecords, r.Method, repo)
if fromRepo := r.FormValue("from"); fromRepo != "" {
// mounting a blob from one repository to another requires pull (GET)
// access to the source repository.
accessRecords = appendAccessRecords(accessRecords, "GET", fromRepo)
}
} else {
// Only allow the name not to be set on the base route.
if app.nameRequired(r) {
// For this to be properly secured, repo must always be set for a
// resource that may make a modification. The only condition under
// which name is not set and we still allow access is when the
// base route is accessed. This section prevents us from making
// that mistake elsewhere in the code, allowing any operation to
// proceed.
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
return fmt.Errorf("forbidden: no repository name")
}
accessRecords = appendCatalogAccessRecord(accessRecords, r)
}
ctx, err := app.accessController.Authorized(context.Context, accessRecords...)
if err != nil {
switch err := err.(type) {
case auth.Challenge:
// Add the appropriate WWW-Auth header
err.SetHeaders(r, w)
if err := errcode.ServeJSON(w, errcode.ErrorCodeUnauthorized.WithDetail(accessRecords)); err != nil {
dcontext.GetLogger(context).Errorf("error serving error json: %v (from %v)", err, context.Errors)
}
default:
// This condition is a potential security problem either in
// the configuration or whatever is backing the access
// controller. Just return a bad request with no information
// to avoid exposure. The request should not proceed.
dcontext.GetLogger(context).Errorf("error checking authorization: %v", err)
w.WriteHeader(http.StatusBadRequest)
}
return err
}
dcontext.GetLogger(ctx, auth.UserNameKey).Info("authorized request")
// TODO(stevvooe): This pattern needs to be cleaned up a bit. One context
// should be replaced by another, rather than replacing the context on a
// mutable object.
context.Context = ctx
return nil
} | [
"func",
"(",
"app",
"*",
"App",
")",
"authorized",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"context",
"*",
"Context",
")",
"error",
"{",
"dcontext",
".",
"GetLogger",
"(",
"context",
")",
".",
"Debug",
"("... | // authorized checks if the request can proceed with access to the requested
// repository. If it succeeds, the context may access the requested
// repository. An error will be returned if access is not available. | [
"authorized",
"checks",
"if",
"the",
"request",
"can",
"proceed",
"with",
"access",
"to",
"the",
"requested",
"repository",
".",
"If",
"it",
"succeeds",
"the",
"context",
"may",
"access",
"the",
"requested",
"repository",
".",
"An",
"error",
"will",
"be",
"r... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L809-L871 | train |
docker/distribution | registry/handlers/app.go | eventBridge | func (app *App) eventBridge(ctx *Context, r *http.Request) notifications.Listener {
actor := notifications.ActorRecord{
Name: getUserName(ctx, r),
}
request := notifications.NewRequestRecord(dcontext.GetRequestID(ctx), r)
return notifications.NewBridge(ctx.urlBuilder, app.events.source, actor, request, app.events.sink, app.Config.Notifications.EventConfig.IncludeReferences)
} | go | func (app *App) eventBridge(ctx *Context, r *http.Request) notifications.Listener {
actor := notifications.ActorRecord{
Name: getUserName(ctx, r),
}
request := notifications.NewRequestRecord(dcontext.GetRequestID(ctx), r)
return notifications.NewBridge(ctx.urlBuilder, app.events.source, actor, request, app.events.sink, app.Config.Notifications.EventConfig.IncludeReferences)
} | [
"func",
"(",
"app",
"*",
"App",
")",
"eventBridge",
"(",
"ctx",
"*",
"Context",
",",
"r",
"*",
"http",
".",
"Request",
")",
"notifications",
".",
"Listener",
"{",
"actor",
":=",
"notifications",
".",
"ActorRecord",
"{",
"Name",
":",
"getUserName",
"(",
... | // eventBridge returns a bridge for the current request, configured with the
// correct actor and source. | [
"eventBridge",
"returns",
"a",
"bridge",
"for",
"the",
"current",
"request",
"configured",
"with",
"the",
"correct",
"actor",
"and",
"source",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L875-L882 | train |
docker/distribution | registry/handlers/app.go | nameRequired | func (app *App) nameRequired(r *http.Request) bool {
route := mux.CurrentRoute(r)
if route == nil {
return true
}
routeName := route.GetName()
return routeName != v2.RouteNameBase && routeName != v2.RouteNameCatalog
} | go | func (app *App) nameRequired(r *http.Request) bool {
route := mux.CurrentRoute(r)
if route == nil {
return true
}
routeName := route.GetName()
return routeName != v2.RouteNameBase && routeName != v2.RouteNameCatalog
} | [
"func",
"(",
"app",
"*",
"App",
")",
"nameRequired",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"route",
":=",
"mux",
".",
"CurrentRoute",
"(",
"r",
")",
"\n",
"if",
"route",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"rou... | // nameRequired returns true if the route requires a name. | [
"nameRequired",
"returns",
"true",
"if",
"the",
"route",
"requires",
"a",
"name",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L885-L892 | train |
docker/distribution | registry/handlers/app.go | apiBase | func apiBase(w http.ResponseWriter, r *http.Request) {
const emptyJSON = "{}"
// Provide a simple /v2/ 200 OK response with empty json response.
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprint(len(emptyJSON)))
fmt.Fprint(w, emptyJSON)
} | go | func apiBase(w http.ResponseWriter, r *http.Request) {
const emptyJSON = "{}"
// Provide a simple /v2/ 200 OK response with empty json response.
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprint(len(emptyJSON)))
fmt.Fprint(w, emptyJSON)
} | [
"func",
"apiBase",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"const",
"emptyJSON",
"=",
"\"{}\"",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
... | // apiBase implements a simple yes-man for doing overall checks against the
// api. This can support auth roundtrips to support docker login. | [
"apiBase",
"implements",
"a",
"simple",
"yes",
"-",
"man",
"for",
"doing",
"overall",
"checks",
"against",
"the",
"api",
".",
"This",
"can",
"support",
"auth",
"roundtrips",
"to",
"support",
"docker",
"login",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L896-L903 | train |
docker/distribution | registry/handlers/app.go | appendAccessRecords | func appendAccessRecords(records []auth.Access, method string, repo string) []auth.Access {
resource := auth.Resource{
Type: "repository",
Name: repo,
}
switch method {
case "GET", "HEAD":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
})
case "POST", "PUT", "PATCH":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
},
auth.Access{
Resource: resource,
Action: "push",
})
case "DELETE":
records = append(records,
auth.Access{
Resource: resource,
Action: "delete",
})
}
return records
} | go | func appendAccessRecords(records []auth.Access, method string, repo string) []auth.Access {
resource := auth.Resource{
Type: "repository",
Name: repo,
}
switch method {
case "GET", "HEAD":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
})
case "POST", "PUT", "PATCH":
records = append(records,
auth.Access{
Resource: resource,
Action: "pull",
},
auth.Access{
Resource: resource,
Action: "push",
})
case "DELETE":
records = append(records,
auth.Access{
Resource: resource,
Action: "delete",
})
}
return records
} | [
"func",
"appendAccessRecords",
"(",
"records",
"[",
"]",
"auth",
".",
"Access",
",",
"method",
"string",
",",
"repo",
"string",
")",
"[",
"]",
"auth",
".",
"Access",
"{",
"resource",
":=",
"auth",
".",
"Resource",
"{",
"Type",
":",
"\"repository\"",
",",... | // appendAccessRecords checks the method and adds the appropriate Access records to the records list. | [
"appendAccessRecords",
"checks",
"the",
"method",
"and",
"adds",
"the",
"appropriate",
"Access",
"records",
"to",
"the",
"records",
"list",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L906-L937 | train |
docker/distribution | registry/handlers/app.go | appendCatalogAccessRecord | func appendCatalogAccessRecord(accessRecords []auth.Access, r *http.Request) []auth.Access {
route := mux.CurrentRoute(r)
routeName := route.GetName()
if routeName == v2.RouteNameCatalog {
resource := auth.Resource{
Type: "registry",
Name: "catalog",
}
accessRecords = append(accessRecords,
auth.Access{
Resource: resource,
Action: "*",
})
}
return accessRecords
} | go | func appendCatalogAccessRecord(accessRecords []auth.Access, r *http.Request) []auth.Access {
route := mux.CurrentRoute(r)
routeName := route.GetName()
if routeName == v2.RouteNameCatalog {
resource := auth.Resource{
Type: "registry",
Name: "catalog",
}
accessRecords = append(accessRecords,
auth.Access{
Resource: resource,
Action: "*",
})
}
return accessRecords
} | [
"func",
"appendCatalogAccessRecord",
"(",
"accessRecords",
"[",
"]",
"auth",
".",
"Access",
",",
"r",
"*",
"http",
".",
"Request",
")",
"[",
"]",
"auth",
".",
"Access",
"{",
"route",
":=",
"mux",
".",
"CurrentRoute",
"(",
"r",
")",
"\n",
"routeName",
"... | // Add the access record for the catalog if it's our current route | [
"Add",
"the",
"access",
"record",
"for",
"the",
"catalog",
"if",
"it",
"s",
"our",
"current",
"route"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L940-L957 | train |
docker/distribution | registry/handlers/app.go | applyRegistryMiddleware | func applyRegistryMiddleware(ctx context.Context, registry distribution.Namespace, middlewares []configuration.Middleware) (distribution.Namespace, error) {
for _, mw := range middlewares {
rmw, err := registrymiddleware.Get(ctx, mw.Name, mw.Options, registry)
if err != nil {
return nil, fmt.Errorf("unable to configure registry middleware (%s): %s", mw.Name, err)
}
registry = rmw
}
return registry, nil
} | go | func applyRegistryMiddleware(ctx context.Context, registry distribution.Namespace, middlewares []configuration.Middleware) (distribution.Namespace, error) {
for _, mw := range middlewares {
rmw, err := registrymiddleware.Get(ctx, mw.Name, mw.Options, registry)
if err != nil {
return nil, fmt.Errorf("unable to configure registry middleware (%s): %s", mw.Name, err)
}
registry = rmw
}
return registry, nil
} | [
"func",
"applyRegistryMiddleware",
"(",
"ctx",
"context",
".",
"Context",
",",
"registry",
"distribution",
".",
"Namespace",
",",
"middlewares",
"[",
"]",
"configuration",
".",
"Middleware",
")",
"(",
"distribution",
".",
"Namespace",
",",
"error",
")",
"{",
"... | // applyRegistryMiddleware wraps a registry instance with the configured middlewares | [
"applyRegistryMiddleware",
"wraps",
"a",
"registry",
"instance",
"with",
"the",
"configured",
"middlewares"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L960-L970 | train |
docker/distribution | registry/handlers/app.go | applyRepoMiddleware | func applyRepoMiddleware(ctx context.Context, repository distribution.Repository, middlewares []configuration.Middleware) (distribution.Repository, error) {
for _, mw := range middlewares {
rmw, err := repositorymiddleware.Get(ctx, mw.Name, mw.Options, repository)
if err != nil {
return nil, err
}
repository = rmw
}
return repository, nil
} | go | func applyRepoMiddleware(ctx context.Context, repository distribution.Repository, middlewares []configuration.Middleware) (distribution.Repository, error) {
for _, mw := range middlewares {
rmw, err := repositorymiddleware.Get(ctx, mw.Name, mw.Options, repository)
if err != nil {
return nil, err
}
repository = rmw
}
return repository, nil
} | [
"func",
"applyRepoMiddleware",
"(",
"ctx",
"context",
".",
"Context",
",",
"repository",
"distribution",
".",
"Repository",
",",
"middlewares",
"[",
"]",
"configuration",
".",
"Middleware",
")",
"(",
"distribution",
".",
"Repository",
",",
"error",
")",
"{",
"... | // applyRepoMiddleware wraps a repository with the configured middlewares | [
"applyRepoMiddleware",
"wraps",
"a",
"repository",
"with",
"the",
"configured",
"middlewares"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L973-L982 | train |
docker/distribution | registry/handlers/app.go | applyStorageMiddleware | func applyStorageMiddleware(driver storagedriver.StorageDriver, middlewares []configuration.Middleware) (storagedriver.StorageDriver, error) {
for _, mw := range middlewares {
smw, err := storagemiddleware.Get(mw.Name, mw.Options, driver)
if err != nil {
return nil, fmt.Errorf("unable to configure storage middleware (%s): %v", mw.Name, err)
}
driver = smw
}
return driver, nil
} | go | func applyStorageMiddleware(driver storagedriver.StorageDriver, middlewares []configuration.Middleware) (storagedriver.StorageDriver, error) {
for _, mw := range middlewares {
smw, err := storagemiddleware.Get(mw.Name, mw.Options, driver)
if err != nil {
return nil, fmt.Errorf("unable to configure storage middleware (%s): %v", mw.Name, err)
}
driver = smw
}
return driver, nil
} | [
"func",
"applyStorageMiddleware",
"(",
"driver",
"storagedriver",
".",
"StorageDriver",
",",
"middlewares",
"[",
"]",
"configuration",
".",
"Middleware",
")",
"(",
"storagedriver",
".",
"StorageDriver",
",",
"error",
")",
"{",
"for",
"_",
",",
"mw",
":=",
"ran... | // applyStorageMiddleware wraps a storage driver with the configured middlewares | [
"applyStorageMiddleware",
"wraps",
"a",
"storage",
"driver",
"with",
"the",
"configured",
"middlewares"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L985-L994 | train |
docker/distribution | registry/handlers/app.go | startUploadPurger | func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageDriver, log dcontext.Logger, config map[interface{}]interface{}) {
if config["enabled"] == false {
return
}
var purgeAgeDuration time.Duration
var err error
purgeAge, ok := config["age"]
if ok {
ageStr, ok := purgeAge.(string)
if !ok {
badPurgeUploadConfig("age is not a string")
}
purgeAgeDuration, err = time.ParseDuration(ageStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse duration: %s", err.Error()))
}
} else {
badPurgeUploadConfig("age missing")
}
var intervalDuration time.Duration
interval, ok := config["interval"]
if ok {
intervalStr, ok := interval.(string)
if !ok {
badPurgeUploadConfig("interval is not a string")
}
intervalDuration, err = time.ParseDuration(intervalStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse interval: %s", err.Error()))
}
} else {
badPurgeUploadConfig("interval missing")
}
var dryRunBool bool
dryRun, ok := config["dryrun"]
if ok {
dryRunBool, ok = dryRun.(bool)
if !ok {
badPurgeUploadConfig("cannot parse dryrun")
}
} else {
badPurgeUploadConfig("dryrun missing")
}
go func() {
rand.Seed(time.Now().Unix())
jitter := time.Duration(rand.Int()%60) * time.Minute
log.Infof("Starting upload purge in %s", jitter)
time.Sleep(jitter)
for {
storage.PurgeUploads(ctx, storageDriver, time.Now().Add(-purgeAgeDuration), !dryRunBool)
log.Infof("Starting upload purge in %s", intervalDuration)
time.Sleep(intervalDuration)
}
}()
} | go | func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageDriver, log dcontext.Logger, config map[interface{}]interface{}) {
if config["enabled"] == false {
return
}
var purgeAgeDuration time.Duration
var err error
purgeAge, ok := config["age"]
if ok {
ageStr, ok := purgeAge.(string)
if !ok {
badPurgeUploadConfig("age is not a string")
}
purgeAgeDuration, err = time.ParseDuration(ageStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse duration: %s", err.Error()))
}
} else {
badPurgeUploadConfig("age missing")
}
var intervalDuration time.Duration
interval, ok := config["interval"]
if ok {
intervalStr, ok := interval.(string)
if !ok {
badPurgeUploadConfig("interval is not a string")
}
intervalDuration, err = time.ParseDuration(intervalStr)
if err != nil {
badPurgeUploadConfig(fmt.Sprintf("Cannot parse interval: %s", err.Error()))
}
} else {
badPurgeUploadConfig("interval missing")
}
var dryRunBool bool
dryRun, ok := config["dryrun"]
if ok {
dryRunBool, ok = dryRun.(bool)
if !ok {
badPurgeUploadConfig("cannot parse dryrun")
}
} else {
badPurgeUploadConfig("dryrun missing")
}
go func() {
rand.Seed(time.Now().Unix())
jitter := time.Duration(rand.Int()%60) * time.Minute
log.Infof("Starting upload purge in %s", jitter)
time.Sleep(jitter)
for {
storage.PurgeUploads(ctx, storageDriver, time.Now().Add(-purgeAgeDuration), !dryRunBool)
log.Infof("Starting upload purge in %s", intervalDuration)
time.Sleep(intervalDuration)
}
}()
} | [
"func",
"startUploadPurger",
"(",
"ctx",
"context",
".",
"Context",
",",
"storageDriver",
"storagedriver",
".",
"StorageDriver",
",",
"log",
"dcontext",
".",
"Logger",
",",
"config",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
")",
"{",
... | // startUploadPurger schedules a goroutine which will periodically
// check upload directories for old files and delete them | [
"startUploadPurger",
"schedules",
"a",
"goroutine",
"which",
"will",
"periodically",
"check",
"upload",
"directories",
"for",
"old",
"files",
"and",
"delete",
"them"
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/app.go#L1014-L1074 | train |
docker/distribution | manifest/schema1/sign.go | Sign | func Sign(m *Manifest, pk libtrust.PrivateKey) (*SignedManifest, error) {
p, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
js, err := libtrust.NewJSONSignature(p)
if err != nil {
return nil, err
}
if err := js.Sign(pk); err != nil {
return nil, err
}
pretty, err := js.PrettySignature("signatures")
if err != nil {
return nil, err
}
return &SignedManifest{
Manifest: *m,
all: pretty,
Canonical: p,
}, nil
} | go | func Sign(m *Manifest, pk libtrust.PrivateKey) (*SignedManifest, error) {
p, err := json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
js, err := libtrust.NewJSONSignature(p)
if err != nil {
return nil, err
}
if err := js.Sign(pk); err != nil {
return nil, err
}
pretty, err := js.PrettySignature("signatures")
if err != nil {
return nil, err
}
return &SignedManifest{
Manifest: *m,
all: pretty,
Canonical: p,
}, nil
} | [
"func",
"Sign",
"(",
"m",
"*",
"Manifest",
",",
"pk",
"libtrust",
".",
"PrivateKey",
")",
"(",
"*",
"SignedManifest",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"m",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"if... | // Sign signs the manifest with the provided private key, returning a
// SignedManifest. This typically won't be used within the registry, except
// for testing. | [
"Sign",
"signs",
"the",
"manifest",
"with",
"the",
"provided",
"private",
"key",
"returning",
"a",
"SignedManifest",
".",
"This",
"typically",
"won",
"t",
"be",
"used",
"within",
"the",
"registry",
"except",
"for",
"testing",
"."
] | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/schema1/sign.go#L13-L38 | train |
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",
".",
"Mars... | // 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",
... | 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",
"{",
"re... | // 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",... | 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",... | // 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",... | 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",
".",
"Lo... | // 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",
... | 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",
"(",
"[",
... | // 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",
... | // 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",
"... | 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... | // 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... | // 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",
"(",
"\"DeleteImageManifest\"",
")",
... | // 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",
"(",
"\"%d.%d\"",
",",
"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",
")",
";"... | // 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",
"r... | // 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",
"retur... | // 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",
":... | // 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",
... | // 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",
... | // 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",
".",
"Wi... | // 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",
"... | // 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",
... | // 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",
... | // 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",
"copy",
"(",
"sm",
".",
"all",
",",
"b"... | // 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",
... | // 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",
"return",
... | // 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",
"t... | 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",
"...",
")",
".",
... | // 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",
"{",
"lfields",
":=",
"make",
"(",
"logrus",
"... | // 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",
"loggerInterface",
":=",
"ctx",
".",
"Value",
"(",
"... | // 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",
"... | 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",
"if",
"username",
"==",
... | // 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... | // 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",
... | // 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",
"bugsnagConfig",
":=",
"bugsnag",
".",
"Configurat... | // 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",
"fun... | // 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",
"def... | 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",
"... | // 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",
"\... | // 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"... | // 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... | // 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",
"{",
"return",
"func",
"(",
"registry",
"*",
"registry",
")",
"error",
"{",
"if",
"blobDescriptorCacheProvider",
"!=",
"nil",
"... | // 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",
"."... | // 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",
... | 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",... | // 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... | // 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",
"if",
"ec",
".",
"Threshold",
"<=",
"0",
"{",
"ec",
".",
"T... | // 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",
"... | // 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",
"*",
"em",
"=",
"e",
".",
"metrics"... | // 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",
... | // 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... | 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",
"!=",
"\"\"",
"{",
"return",
"mb",
".",
"emptyTarDigest... | // 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",
")",
"{",
"var",
"configAsMap",
"map",
"[",
"string",
"]",
"*",
"json",
... | // 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",
"||",
"fm... | // 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",
",... | // 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... | // 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",
"... | 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",
":",
"listen... | // 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",
"if",
"eq",
".",
"closed",
"{",
"return... | // 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",
"if",
"eq",
".",
"closed",
"{",
"return",
"fmt",
".",
"Errorf",
... | // 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",
"for",
"eq",
".",
"events",
".",
"Len",
"(",
")",
"<... | // 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",... | 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... | // 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",
"(",
")",
... | // 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",
"time",
".",
"Sleep",
"(",
"backoff",
... | // 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",
"... | // 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",
"for",
"key",
":=",
"range",
"ss",
"{",
"keys",
"=",
"append",
"("... | // 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",
"!=... | // 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",
".",
... | // 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",
"if",
"w",
".... | // 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",
")",
... | // 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",
".",
"private... | // 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",
... | 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",
... | // 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",
".... | // 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",
":",
"... | // 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",
"... | // 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",... | // 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... | // 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",
"... | // 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",
"b... | 3226863cbcba6dbc2f6c83a37b28126c934af3f8 | https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/tagstore.go#L126-L140 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.