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/api/v2/urls.go
BuildTagsURL
func (ub *URLBuilder) BuildTagsURL(name reference.Named) (string, error) { route := ub.cloneRoute(RouteNameTags) tagsURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return tagsURL.String(), nil }
go
func (ub *URLBuilder) BuildTagsURL(name reference.Named) (string, error) { route := ub.cloneRoute(RouteNameTags) tagsURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return tagsURL.String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildTagsURL", "(", "name", "reference", ".", "Named", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameTags", ")", "\n", "tagsURL", ",", "err", ":=", "route"...
// BuildTagsURL constructs a url to list the tags in the named repository.
[ "BuildTagsURL", "constructs", "a", "url", "to", "list", "the", "tags", "in", "the", "named", "repository", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L131-L140
train
docker/distribution
registry/api/v2/urls.go
BuildManifestURL
func (ub *URLBuilder) BuildManifestURL(ref reference.Named) (string, error) { route := ub.cloneRoute(RouteNameManifest) tagOrDigest := "" switch v := ref.(type) { case reference.Tagged: tagOrDigest = v.Tag() case reference.Digested: tagOrDigest = v.Digest().String() default: return "", fmt.Errorf("reference must have a tag or digest") } manifestURL, err := route.URL("name", ref.Name(), "reference", tagOrDigest) if err != nil { return "", err } return manifestURL.String(), nil }
go
func (ub *URLBuilder) BuildManifestURL(ref reference.Named) (string, error) { route := ub.cloneRoute(RouteNameManifest) tagOrDigest := "" switch v := ref.(type) { case reference.Tagged: tagOrDigest = v.Tag() case reference.Digested: tagOrDigest = v.Digest().String() default: return "", fmt.Errorf("reference must have a tag or digest") } manifestURL, err := route.URL("name", ref.Name(), "reference", tagOrDigest) if err != nil { return "", err } return manifestURL.String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildManifestURL", "(", "ref", "reference", ".", "Named", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameManifest", ")", "\n", "tagOrDigest", ":=", "\"\"", "\...
// BuildManifestURL constructs a url for the manifest identified by name and // reference. The argument reference may be either a tag or digest.
[ "BuildManifestURL", "constructs", "a", "url", "for", "the", "manifest", "identified", "by", "name", "and", "reference", ".", "The", "argument", "reference", "may", "be", "either", "a", "tag", "or", "digest", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L144-L163
train
docker/distribution
registry/api/v2/urls.go
BuildBlobURL
func (ub *URLBuilder) BuildBlobURL(ref reference.Canonical) (string, error) { route := ub.cloneRoute(RouteNameBlob) layerURL, err := route.URL("name", ref.Name(), "digest", ref.Digest().String()) if err != nil { return "", err } return layerURL.String(), nil }
go
func (ub *URLBuilder) BuildBlobURL(ref reference.Canonical) (string, error) { route := ub.cloneRoute(RouteNameBlob) layerURL, err := route.URL("name", ref.Name(), "digest", ref.Digest().String()) if err != nil { return "", err } return layerURL.String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildBlobURL", "(", "ref", "reference", ".", "Canonical", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameBlob", ")", "\n", "layerURL", ",", "err", ":=", "ro...
// BuildBlobURL constructs the url for the blob identified by name and dgst.
[ "BuildBlobURL", "constructs", "the", "url", "for", "the", "blob", "identified", "by", "name", "and", "dgst", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L166-L175
train
docker/distribution
registry/api/v2/urls.go
BuildBlobUploadURL
func (ub *URLBuilder) BuildBlobUploadURL(name reference.Named, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUpload) uploadURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
go
func (ub *URLBuilder) BuildBlobUploadURL(name reference.Named, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUpload) uploadURL, err := route.URL("name", name.Name()) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildBlobUploadURL", "(", "name", "reference", ".", "Named", ",", "values", "...", "url", ".", "Values", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "cloneRoute", "(", "RouteNameBlobUp...
// BuildBlobUploadURL constructs a url to begin a blob upload in the // repository identified by name.
[ "BuildBlobUploadURL", "constructs", "a", "url", "to", "begin", "a", "blob", "upload", "in", "the", "repository", "identified", "by", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L179-L188
train
docker/distribution
registry/api/v2/urls.go
BuildBlobUploadChunkURL
func (ub *URLBuilder) BuildBlobUploadChunkURL(name reference.Named, uuid string, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUploadChunk) uploadURL, err := route.URL("name", name.Name(), "uuid", uuid) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
go
func (ub *URLBuilder) BuildBlobUploadChunkURL(name reference.Named, uuid string, values ...url.Values) (string, error) { route := ub.cloneRoute(RouteNameBlobUploadChunk) uploadURL, err := route.URL("name", name.Name(), "uuid", uuid) if err != nil { return "", err } return appendValuesURL(uploadURL, values...).String(), nil }
[ "func", "(", "ub", "*", "URLBuilder", ")", "BuildBlobUploadChunkURL", "(", "name", "reference", ".", "Named", ",", "uuid", "string", ",", "values", "...", "url", ".", "Values", ")", "(", "string", ",", "error", ")", "{", "route", ":=", "ub", ".", "clon...
// BuildBlobUploadChunkURL constructs a url for the upload identified by uuid, // including any url values. This should generally not be used by clients, as // this url is provided by server implementations during the blob upload // process.
[ "BuildBlobUploadChunkURL", "constructs", "a", "url", "for", "the", "upload", "identified", "by", "uuid", "including", "any", "url", "values", ".", "This", "should", "generally", "not", "be", "used", "by", "clients", "as", "this", "url", "is", "provided", "by",...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L194-L203
train
docker/distribution
registry/api/v2/urls.go
cloneRoute
func (ub *URLBuilder) cloneRoute(name string) clonedRoute { route := new(mux.Route) root := new(url.URL) *route = *ub.router.GetRoute(name) // clone the route *root = *ub.root return clonedRoute{Route: route, root: root, relative: ub.relative} }
go
func (ub *URLBuilder) cloneRoute(name string) clonedRoute { route := new(mux.Route) root := new(url.URL) *route = *ub.router.GetRoute(name) // clone the route *root = *ub.root return clonedRoute{Route: route, root: root, relative: ub.relative} }
[ "func", "(", "ub", "*", "URLBuilder", ")", "cloneRoute", "(", "name", "string", ")", "clonedRoute", "{", "route", ":=", "new", "(", "mux", ".", "Route", ")", "\n", "root", ":=", "new", "(", "url", ".", "URL", ")", "\n", "*", "route", "=", "*", "u...
// clondedRoute returns a clone of the named route from the router. Routes // must be cloned to avoid modifying them during url generation.
[ "clondedRoute", "returns", "a", "clone", "of", "the", "named", "route", "from", "the", "router", ".", "Routes", "must", "be", "cloned", "to", "avoid", "modifying", "them", "during", "url", "generation", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L207-L215
train
docker/distribution
registry/api/v2/urls.go
appendValuesURL
func appendValuesURL(u *url.URL, values ...url.Values) *url.URL { merged := u.Query() for _, v := range values { for k, vv := range v { merged[k] = append(merged[k], vv...) } } u.RawQuery = merged.Encode() return u }
go
func appendValuesURL(u *url.URL, values ...url.Values) *url.URL { merged := u.Query() for _, v := range values { for k, vv := range v { merged[k] = append(merged[k], vv...) } } u.RawQuery = merged.Encode() return u }
[ "func", "appendValuesURL", "(", "u", "*", "url", ".", "URL", ",", "values", "...", "url", ".", "Values", ")", "*", "url", ".", "URL", "{", "merged", ":=", "u", ".", "Query", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "values", "{", "f...
// appendValuesURL appends the parameters to the url.
[ "appendValuesURL", "appends", "the", "parameters", "to", "the", "url", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/v2/urls.go#L243-L254
train
docker/distribution
notifications/http.go
newHTTPSink
func newHTTPSink(u string, timeout time.Duration, headers http.Header, transport *http.Transport, listeners ...httpStatusListener) *httpSink { if transport == nil { transport = http.DefaultTransport.(*http.Transport) } return &httpSink{ url: u, listeners: listeners, client: &http.Client{ Transport: &headerRoundTripper{ Transport: transport, headers: headers, }, Timeout: timeout, }, } }
go
func newHTTPSink(u string, timeout time.Duration, headers http.Header, transport *http.Transport, listeners ...httpStatusListener) *httpSink { if transport == nil { transport = http.DefaultTransport.(*http.Transport) } return &httpSink{ url: u, listeners: listeners, client: &http.Client{ Transport: &headerRoundTripper{ Transport: transport, headers: headers, }, Timeout: timeout, }, } }
[ "func", "newHTTPSink", "(", "u", "string", ",", "timeout", "time", ".", "Duration", ",", "headers", "http", ".", "Header", ",", "transport", "*", "http", ".", "Transport", ",", "listeners", "...", "httpStatusListener", ")", "*", "httpSink", "{", "if", "tra...
// newHTTPSink returns an unreliable, single-flight http sink. Wrap in other // sinks for increased reliability.
[ "newHTTPSink", "returns", "an", "unreliable", "single", "-", "flight", "http", "sink", ".", "Wrap", "in", "other", "sinks", "for", "increased", "reliability", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/http.go#L29-L44
train
docker/distribution
notifications/http.go
Write
func (hs *httpSink) Write(events ...Event) error { hs.mu.Lock() defer hs.mu.Unlock() defer hs.client.Transport.(*headerRoundTripper).CloseIdleConnections() if hs.closed { return ErrSinkClosed } envelope := Envelope{ Events: events, } // TODO(stevvooe): It is not ideal to keep re-encoding the request body on // retry but we are going to do it to keep the code simple. It is likely // we could change the event struct to manage its own buffer. p, err := json.MarshalIndent(envelope, "", " ") if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error marshaling event envelope: %v", hs, err) } body := bytes.NewReader(p) resp, err := hs.client.Post(hs.url, EventsMediaType, body) if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error posting: %v", hs, err) } defer resp.Body.Close() // The notifier will treat any 2xx or 3xx response as accepted by the // endpoint. switch { case resp.StatusCode >= 200 && resp.StatusCode < 400: for _, listener := range hs.listeners { listener.success(resp.StatusCode, events...) } // TODO(stevvooe): This is a little accepting: we may want to support // unsupported media type responses with retries using the correct // media type. There may also be cases that will never work. return nil default: for _, listener := range hs.listeners { listener.failure(resp.StatusCode, events...) } return fmt.Errorf("%v: response status %v unaccepted", hs, resp.Status) } }
go
func (hs *httpSink) Write(events ...Event) error { hs.mu.Lock() defer hs.mu.Unlock() defer hs.client.Transport.(*headerRoundTripper).CloseIdleConnections() if hs.closed { return ErrSinkClosed } envelope := Envelope{ Events: events, } // TODO(stevvooe): It is not ideal to keep re-encoding the request body on // retry but we are going to do it to keep the code simple. It is likely // we could change the event struct to manage its own buffer. p, err := json.MarshalIndent(envelope, "", " ") if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error marshaling event envelope: %v", hs, err) } body := bytes.NewReader(p) resp, err := hs.client.Post(hs.url, EventsMediaType, body) if err != nil { for _, listener := range hs.listeners { listener.err(err, events...) } return fmt.Errorf("%v: error posting: %v", hs, err) } defer resp.Body.Close() // The notifier will treat any 2xx or 3xx response as accepted by the // endpoint. switch { case resp.StatusCode >= 200 && resp.StatusCode < 400: for _, listener := range hs.listeners { listener.success(resp.StatusCode, events...) } // TODO(stevvooe): This is a little accepting: we may want to support // unsupported media type responses with retries using the correct // media type. There may also be cases that will never work. return nil default: for _, listener := range hs.listeners { listener.failure(resp.StatusCode, events...) } return fmt.Errorf("%v: response status %v unaccepted", hs, resp.Status) } }
[ "func", "(", "hs", "*", "httpSink", ")", "Write", "(", "events", "...", "Event", ")", "error", "{", "hs", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "hs", ".", "mu", ".", "Unlock", "(", ")", "\n", "defer", "hs", ".", "client", ".", "Trans...
// Accept makes an attempt to notify the endpoint, returning an error if it // fails. It is the caller's responsibility to retry on error. The events are // accepted or rejected as a group.
[ "Accept", "makes", "an", "attempt", "to", "notify", "the", "endpoint", "returning", "an", "error", "if", "it", "fails", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "retry", "on", "error", ".", "The", "events", "are", "accepted", "or", ...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/http.go#L56-L111
train
docker/distribution
notifications/http.go
Close
func (hs *httpSink) Close() error { hs.mu.Lock() defer hs.mu.Unlock() if hs.closed { return fmt.Errorf("httpsink: already closed") } hs.closed = true return nil }
go
func (hs *httpSink) Close() error { hs.mu.Lock() defer hs.mu.Unlock() if hs.closed { return fmt.Errorf("httpsink: already closed") } hs.closed = true return nil }
[ "func", "(", "hs", "*", "httpSink", ")", "Close", "(", ")", "error", "{", "hs", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "hs", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "hs", ".", "closed", "{", "return", "fmt", ".", "Errorf", "...
// Close the endpoint
[ "Close", "the", "endpoint" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/http.go#L114-L124
train
docker/distribution
registry/auth/auth.go
WithUser
func WithUser(ctx context.Context, user UserInfo) context.Context { return userInfoContext{ Context: ctx, user: user, } }
go
func WithUser(ctx context.Context, user UserInfo) context.Context { return userInfoContext{ Context: ctx, user: user, } }
[ "func", "WithUser", "(", "ctx", "context", ".", "Context", ",", "user", "UserInfo", ")", "context", ".", "Context", "{", "return", "userInfoContext", "{", "Context", ":", "ctx", ",", "user", ":", "user", ",", "}", "\n", "}" ]
// WithUser returns a context with the authorized user info.
[ "WithUser", "returns", "a", "context", "with", "the", "authorized", "user", "info", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L115-L120
train
docker/distribution
registry/auth/auth.go
WithResources
func WithResources(ctx context.Context, resources []Resource) context.Context { return resourceContext{ Context: ctx, resources: resources, } }
go
func WithResources(ctx context.Context, resources []Resource) context.Context { return resourceContext{ Context: ctx, resources: resources, } }
[ "func", "WithResources", "(", "ctx", "context", ".", "Context", ",", "resources", "[", "]", "Resource", ")", "context", ".", "Context", "{", "return", "resourceContext", "{", "Context", ":", "ctx", ",", "resources", ":", "resources", ",", "}", "\n", "}" ]
// WithResources returns a context with the authorized resources.
[ "WithResources", "returns", "a", "context", "with", "the", "authorized", "resources", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L139-L144
train
docker/distribution
registry/auth/auth.go
AuthorizedResources
func AuthorizedResources(ctx context.Context) []Resource { if resources, ok := ctx.Value(resourceKey{}).([]Resource); ok { return resources } return nil }
go
func AuthorizedResources(ctx context.Context) []Resource { if resources, ok := ctx.Value(resourceKey{}).([]Resource); ok { return resources } return nil }
[ "func", "AuthorizedResources", "(", "ctx", "context", ".", "Context", ")", "[", "]", "Resource", "{", "if", "resources", ",", "ok", ":=", "ctx", ".", "Value", "(", "resourceKey", "{", "}", ")", ".", "(", "[", "]", "Resource", ")", ";", "ok", "{", "...
// AuthorizedResources returns the list of resources which have // been authorized for this request.
[ "AuthorizedResources", "returns", "the", "list", "of", "resources", "which", "have", "been", "authorized", "for", "this", "request", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L163-L169
train
docker/distribution
registry/auth/auth.go
GetAccessController
func GetAccessController(name string, options map[string]interface{}) (AccessController, error) { if initFunc, exists := accessControllers[name]; exists { return initFunc(options) } return nil, fmt.Errorf("no access controller registered with name: %s", name) }
go
func GetAccessController(name string, options map[string]interface{}) (AccessController, error) { if initFunc, exists := accessControllers[name]; exists { return initFunc(options) } return nil, fmt.Errorf("no access controller registered with name: %s", name) }
[ "func", "GetAccessController", "(", "name", "string", ",", "options", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "AccessController", ",", "error", ")", "{", "if", "initFunc", ",", "exists", ":=", "accessControllers", "[", "name", "]", ";",...
// GetAccessController constructs an AccessController // with the given options using the named backend.
[ "GetAccessController", "constructs", "an", "AccessController", "with", "the", "given", "options", "using", "the", "named", "backend", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/auth.go#L195-L201
train
docker/distribution
reference/normalize.go
ParseNormalizedNamed
func ParseNormalizedNamed(s string) (Named, error) { if ok := anchoredIdentifierRegexp.MatchString(s); ok { return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) } domain, remainder := splitDockerDomain(s) var remoteName string if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { remoteName = remainder[:tagSep] } else { remoteName = remainder } if strings.ToLower(remoteName) != remoteName { return nil, errors.New("invalid reference format: repository name must be lowercase") } ref, err := Parse(domain + "/" + remainder) if err != nil { return nil, err } named, isNamed := ref.(Named) if !isNamed { return nil, fmt.Errorf("reference %s has no name", ref.String()) } return named, nil }
go
func ParseNormalizedNamed(s string) (Named, error) { if ok := anchoredIdentifierRegexp.MatchString(s); ok { return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) } domain, remainder := splitDockerDomain(s) var remoteName string if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { remoteName = remainder[:tagSep] } else { remoteName = remainder } if strings.ToLower(remoteName) != remoteName { return nil, errors.New("invalid reference format: repository name must be lowercase") } ref, err := Parse(domain + "/" + remainder) if err != nil { return nil, err } named, isNamed := ref.(Named) if !isNamed { return nil, fmt.Errorf("reference %s has no name", ref.String()) } return named, nil }
[ "func", "ParseNormalizedNamed", "(", "s", "string", ")", "(", "Named", ",", "error", ")", "{", "if", "ok", ":=", "anchoredIdentifierRegexp", ".", "MatchString", "(", "s", ")", ";", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid re...
// ParseNormalizedNamed parses a string into a named reference // transforming a familiar name from Docker UI to a fully // qualified reference. If the value may be an identifier // use ParseAnyReference.
[ "ParseNormalizedNamed", "parses", "a", "string", "into", "a", "named", "reference", "transforming", "a", "familiar", "name", "from", "Docker", "UI", "to", "a", "fully", "qualified", "reference", ".", "If", "the", "value", "may", "be", "an", "identifier", "use"...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L33-L57
train
docker/distribution
reference/normalize.go
splitDockerDomain
func splitDockerDomain(name string) (domain, remainder string) { i := strings.IndexRune(name, '/') if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") { domain, remainder = defaultDomain, name } else { domain, remainder = name[:i], name[i+1:] } if domain == legacyDefaultDomain { domain = defaultDomain } if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { remainder = officialRepoName + "/" + remainder } return }
go
func splitDockerDomain(name string) (domain, remainder string) { i := strings.IndexRune(name, '/') if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") { domain, remainder = defaultDomain, name } else { domain, remainder = name[:i], name[i+1:] } if domain == legacyDefaultDomain { domain = defaultDomain } if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { remainder = officialRepoName + "/" + remainder } return }
[ "func", "splitDockerDomain", "(", "name", "string", ")", "(", "domain", ",", "remainder", "string", ")", "{", "i", ":=", "strings", ".", "IndexRune", "(", "name", ",", "'/'", ")", "\n", "if", "i", "==", "-", "1", "||", "(", "!", "strings", ".", "Co...
// splitDockerDomain splits a repository name to domain and remotename string. // If no valid domain is found, the default domain is used. Repository name // needs to be already validated before.
[ "splitDockerDomain", "splits", "a", "repository", "name", "to", "domain", "and", "remotename", "string", ".", "If", "no", "valid", "domain", "is", "found", "the", "default", "domain", "is", "used", ".", "Repository", "name", "needs", "to", "be", "already", "...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L91-L105
train
docker/distribution
reference/normalize.go
TagNameOnly
func TagNameOnly(ref Named) Named { if IsNameOnly(ref) { namedTagged, err := WithTag(ref, defaultTag) if err != nil { // Default tag must be valid, to create a NamedTagged // type with non-validated input the WithTag function // should be used instead panic(err) } return namedTagged } return ref }
go
func TagNameOnly(ref Named) Named { if IsNameOnly(ref) { namedTagged, err := WithTag(ref, defaultTag) if err != nil { // Default tag must be valid, to create a NamedTagged // type with non-validated input the WithTag function // should be used instead panic(err) } return namedTagged } return ref }
[ "func", "TagNameOnly", "(", "ref", "Named", ")", "Named", "{", "if", "IsNameOnly", "(", "ref", ")", "{", "namedTagged", ",", "err", ":=", "WithTag", "(", "ref", ",", "defaultTag", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", ...
// TagNameOnly adds the default tag "latest" to a reference if it only has // a repo name.
[ "TagNameOnly", "adds", "the", "default", "tag", "latest", "to", "a", "reference", "if", "it", "only", "has", "a", "repo", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L157-L169
train
docker/distribution
reference/normalize.go
ParseAnyReference
func ParseAnyReference(ref string) (Reference, error) { if ok := anchoredIdentifierRegexp.MatchString(ref); ok { return digestReference("sha256:" + ref), nil } if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } return ParseNormalizedNamed(ref) }
go
func ParseAnyReference(ref string) (Reference, error) { if ok := anchoredIdentifierRegexp.MatchString(ref); ok { return digestReference("sha256:" + ref), nil } if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } return ParseNormalizedNamed(ref) }
[ "func", "ParseAnyReference", "(", "ref", "string", ")", "(", "Reference", ",", "error", ")", "{", "if", "ok", ":=", "anchoredIdentifierRegexp", ".", "MatchString", "(", "ref", ")", ";", "ok", "{", "return", "digestReference", "(", "\"sha256:\"", "+", "ref", ...
// ParseAnyReference parses a reference string as a possible identifier, // full digest, or familiar name.
[ "ParseAnyReference", "parses", "a", "reference", "string", "as", "a", "possible", "identifier", "full", "digest", "or", "familiar", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L173-L182
train
docker/distribution
reference/normalize.go
ParseAnyReferenceWithSet
func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { dgst, err := ds.Lookup(ref) if err == nil { return digestReference(dgst), nil } } else { if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } } return ParseNormalizedNamed(ref) }
go
func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { dgst, err := ds.Lookup(ref) if err == nil { return digestReference(dgst), nil } } else { if dgst, err := digest.Parse(ref); err == nil { return digestReference(dgst), nil } } return ParseNormalizedNamed(ref) }
[ "func", "ParseAnyReferenceWithSet", "(", "ref", "string", ",", "ds", "*", "digestset", ".", "Set", ")", "(", "Reference", ",", "error", ")", "{", "if", "ok", ":=", "anchoredShortIdentifierRegexp", ".", "MatchString", "(", "ref", ")", ";", "ok", "{", "dgst"...
// ParseAnyReferenceWithSet parses a reference string as a possible short // identifier to be matched in a digest set, a full digest, or familiar name.
[ "ParseAnyReferenceWithSet", "parses", "a", "reference", "string", "as", "a", "possible", "short", "identifier", "to", "be", "matched", "in", "a", "digest", "set", "a", "full", "digest", "or", "familiar", "name", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/reference/normalize.go#L186-L199
train
docker/distribution
registry/api/errcode/register.go
Register
func Register(group string, descriptor ErrorDescriptor) ErrorCode { registerLock.Lock() defer registerLock.Unlock() descriptor.Code = ErrorCode(nextCode) if _, ok := idToDescriptors[descriptor.Value]; ok { panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value)) } if _, ok := errorCodeToDescriptors[descriptor.Code]; ok { panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code)) } groupToDescriptors[group] = append(groupToDescriptors[group], descriptor) errorCodeToDescriptors[descriptor.Code] = descriptor idToDescriptors[descriptor.Value] = descriptor nextCode++ return descriptor.Code }
go
func Register(group string, descriptor ErrorDescriptor) ErrorCode { registerLock.Lock() defer registerLock.Unlock() descriptor.Code = ErrorCode(nextCode) if _, ok := idToDescriptors[descriptor.Value]; ok { panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value)) } if _, ok := errorCodeToDescriptors[descriptor.Code]; ok { panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code)) } groupToDescriptors[group] = append(groupToDescriptors[group], descriptor) errorCodeToDescriptors[descriptor.Code] = descriptor idToDescriptors[descriptor.Value] = descriptor nextCode++ return descriptor.Code }
[ "func", "Register", "(", "group", "string", ",", "descriptor", "ErrorDescriptor", ")", "ErrorCode", "{", "registerLock", ".", "Lock", "(", ")", "\n", "defer", "registerLock", ".", "Unlock", "(", ")", "\n", "descriptor", ".", "Code", "=", "ErrorCode", "(", ...
// Register will make the passed-in error known to the environment and // return a new ErrorCode
[ "Register", "will", "make", "the", "passed", "-", "in", "error", "known", "to", "the", "environment", "and", "return", "a", "new", "ErrorCode" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/register.go#L83-L102
train
docker/distribution
registry/api/errcode/register.go
GetGroupNames
func GetGroupNames() []string { keys := []string{} for k := range groupToDescriptors { keys = append(keys, k) } sort.Strings(keys) return keys }
go
func GetGroupNames() []string { keys := []string{} for k := range groupToDescriptors { keys = append(keys, k) } sort.Strings(keys) return keys }
[ "func", "GetGroupNames", "(", ")", "[", "]", "string", "{", "keys", ":=", "[", "]", "string", "{", "}", "\n", "for", "k", ":=", "range", "groupToDescriptors", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "...
// GetGroupNames returns the list of Error group names that are registered
[ "GetGroupNames", "returns", "the", "list", "of", "Error", "group", "names", "that", "are", "registered" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/register.go#L111-L119
train
docker/distribution
registry/api/errcode/register.go
GetErrorCodeGroup
func GetErrorCodeGroup(name string) []ErrorDescriptor { desc := groupToDescriptors[name] sort.Sort(byValue(desc)) return desc }
go
func GetErrorCodeGroup(name string) []ErrorDescriptor { desc := groupToDescriptors[name] sort.Sort(byValue(desc)) return desc }
[ "func", "GetErrorCodeGroup", "(", "name", "string", ")", "[", "]", "ErrorDescriptor", "{", "desc", ":=", "groupToDescriptors", "[", "name", "]", "\n", "sort", ".", "Sort", "(", "byValue", "(", "desc", ")", ")", "\n", "return", "desc", "\n", "}" ]
// GetErrorCodeGroup returns the named group of error descriptors
[ "GetErrorCodeGroup", "returns", "the", "named", "group", "of", "error", "descriptors" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/register.go#L122-L126
train
docker/distribution
registry/api/errcode/register.go
GetErrorAllDescriptors
func GetErrorAllDescriptors() []ErrorDescriptor { result := []ErrorDescriptor{} for _, group := range GetGroupNames() { result = append(result, GetErrorCodeGroup(group)...) } sort.Sort(byValue(result)) return result }
go
func GetErrorAllDescriptors() []ErrorDescriptor { result := []ErrorDescriptor{} for _, group := range GetGroupNames() { result = append(result, GetErrorCodeGroup(group)...) } sort.Sort(byValue(result)) return result }
[ "func", "GetErrorAllDescriptors", "(", ")", "[", "]", "ErrorDescriptor", "{", "result", ":=", "[", "]", "ErrorDescriptor", "{", "}", "\n", "for", "_", ",", "group", ":=", "range", "GetGroupNames", "(", ")", "{", "result", "=", "append", "(", "result", ",...
// GetErrorAllDescriptors returns a slice of all ErrorDescriptors that are // registered, irrespective of what group they're in
[ "GetErrorAllDescriptors", "returns", "a", "slice", "of", "all", "ErrorDescriptors", "that", "are", "registered", "irrespective", "of", "what", "group", "they", "re", "in" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/api/errcode/register.go#L130-L138
train
docker/distribution
registry/proxy/proxyregistry.go
NewRegistryPullThroughCache
func NewRegistryPullThroughCache(ctx context.Context, registry distribution.Namespace, driver driver.StorageDriver, config configuration.Proxy) (distribution.Namespace, error) { remoteURL, err := url.Parse(config.RemoteURL) if err != nil { return nil, err } v := storage.NewVacuum(ctx, driver) s := scheduler.New(ctx, driver, "/scheduler-state.json") s.OnBlobExpire(func(ref reference.Reference) error { var r reference.Canonical var ok bool if r, ok = ref.(reference.Canonical); !ok { return fmt.Errorf("unexpected reference type : %T", ref) } repo, err := registry.Repository(ctx, r) if err != nil { return err } blobs := repo.Blobs(ctx) // Clear the repository reference and descriptor caches err = blobs.Delete(ctx, r.Digest()) if err != nil { return err } err = v.RemoveBlob(r.Digest().String()) if err != nil { return err } return nil }) s.OnManifestExpire(func(ref reference.Reference) error { var r reference.Canonical var ok bool if r, ok = ref.(reference.Canonical); !ok { return fmt.Errorf("unexpected reference type : %T", ref) } repo, err := registry.Repository(ctx, r) if err != nil { return err } manifests, err := repo.Manifests(ctx) if err != nil { return err } err = manifests.Delete(ctx, r.Digest()) if err != nil { return err } return nil }) err = s.Start() if err != nil { return nil, err } cs, err := configureAuth(config.Username, config.Password, config.RemoteURL) if err != nil { return nil, err } return &proxyingRegistry{ embedded: registry, scheduler: s, remoteURL: *remoteURL, authChallenger: &remoteAuthChallenger{ remoteURL: *remoteURL, cm: challenge.NewSimpleManager(), cs: cs, }, }, nil }
go
func NewRegistryPullThroughCache(ctx context.Context, registry distribution.Namespace, driver driver.StorageDriver, config configuration.Proxy) (distribution.Namespace, error) { remoteURL, err := url.Parse(config.RemoteURL) if err != nil { return nil, err } v := storage.NewVacuum(ctx, driver) s := scheduler.New(ctx, driver, "/scheduler-state.json") s.OnBlobExpire(func(ref reference.Reference) error { var r reference.Canonical var ok bool if r, ok = ref.(reference.Canonical); !ok { return fmt.Errorf("unexpected reference type : %T", ref) } repo, err := registry.Repository(ctx, r) if err != nil { return err } blobs := repo.Blobs(ctx) // Clear the repository reference and descriptor caches err = blobs.Delete(ctx, r.Digest()) if err != nil { return err } err = v.RemoveBlob(r.Digest().String()) if err != nil { return err } return nil }) s.OnManifestExpire(func(ref reference.Reference) error { var r reference.Canonical var ok bool if r, ok = ref.(reference.Canonical); !ok { return fmt.Errorf("unexpected reference type : %T", ref) } repo, err := registry.Repository(ctx, r) if err != nil { return err } manifests, err := repo.Manifests(ctx) if err != nil { return err } err = manifests.Delete(ctx, r.Digest()) if err != nil { return err } return nil }) err = s.Start() if err != nil { return nil, err } cs, err := configureAuth(config.Username, config.Password, config.RemoteURL) if err != nil { return nil, err } return &proxyingRegistry{ embedded: registry, scheduler: s, remoteURL: *remoteURL, authChallenger: &remoteAuthChallenger{ remoteURL: *remoteURL, cm: challenge.NewSimpleManager(), cs: cs, }, }, nil }
[ "func", "NewRegistryPullThroughCache", "(", "ctx", "context", ".", "Context", ",", "registry", "distribution", ".", "Namespace", ",", "driver", "driver", ".", "StorageDriver", ",", "config", "configuration", ".", "Proxy", ")", "(", "distribution", ".", "Namespace"...
// NewRegistryPullThroughCache creates a registry acting as a pull through cache
[ "NewRegistryPullThroughCache", "creates", "a", "registry", "acting", "as", "a", "pull", "through", "cache" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxyregistry.go#L32-L111
train
docker/distribution
registry/proxy/proxyregistry.go
tryEstablishChallenges
func (r *remoteAuthChallenger) tryEstablishChallenges(ctx context.Context) error { r.Lock() defer r.Unlock() remoteURL := r.remoteURL remoteURL.Path = "/v2/" challenges, err := r.cm.GetChallenges(remoteURL) if err != nil { return err } if len(challenges) > 0 { return nil } // establish challenge type with upstream if err := ping(r.cm, remoteURL.String(), challengeHeader); err != nil { return err } dcontext.GetLogger(ctx).Infof("Challenge established with upstream : %s %s", remoteURL, r.cm) return nil }
go
func (r *remoteAuthChallenger) tryEstablishChallenges(ctx context.Context) error { r.Lock() defer r.Unlock() remoteURL := r.remoteURL remoteURL.Path = "/v2/" challenges, err := r.cm.GetChallenges(remoteURL) if err != nil { return err } if len(challenges) > 0 { return nil } // establish challenge type with upstream if err := ping(r.cm, remoteURL.String(), challengeHeader); err != nil { return err } dcontext.GetLogger(ctx).Infof("Challenge established with upstream : %s %s", remoteURL, r.cm) return nil }
[ "func", "(", "r", "*", "remoteAuthChallenger", ")", "tryEstablishChallenges", "(", "ctx", "context", ".", "Context", ")", "error", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "remoteURL", ":=", "r", ".", "remoteU...
// tryEstablishChallenges will attempt to get a challenge type for the upstream if none currently exist
[ "tryEstablishChallenges", "will", "attempt", "to", "get", "a", "challenge", "type", "for", "the", "upstream", "if", "none", "currently", "exist" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/proxy/proxyregistry.go#L215-L237
train
docker/distribution
manifests.go
ManifestMediaTypes
func ManifestMediaTypes() (mediaTypes []string) { for t := range mappings { if t != "" { mediaTypes = append(mediaTypes, t) } } return }
go
func ManifestMediaTypes() (mediaTypes []string) { for t := range mappings { if t != "" { mediaTypes = append(mediaTypes, t) } } return }
[ "func", "ManifestMediaTypes", "(", ")", "(", "mediaTypes", "[", "]", "string", ")", "{", "for", "t", ":=", "range", "mappings", "{", "if", "t", "!=", "\"\"", "{", "mediaTypes", "=", "append", "(", "mediaTypes", ",", "t", ")", "\n", "}", "\n", "}", ...
// ManifestMediaTypes returns the supported media types for manifests.
[ "ManifestMediaTypes", "returns", "the", "supported", "media", "types", "for", "manifests", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifests.go#L78-L85
train
docker/distribution
manifests.go
UnmarshalManifest
func UnmarshalManifest(ctHeader string, p []byte) (Manifest, Descriptor, error) { // Need to look up by the actual media type, not the raw contents of // the header. Strip semicolons and anything following them. var mediaType string if ctHeader != "" { var err error mediaType, _, err = mime.ParseMediaType(ctHeader) if err != nil { return nil, Descriptor{}, err } } unmarshalFunc, ok := mappings[mediaType] if !ok { unmarshalFunc, ok = mappings[""] if !ok { return nil, Descriptor{}, fmt.Errorf("unsupported manifest media type and no default available: %s", mediaType) } } return unmarshalFunc(p) }
go
func UnmarshalManifest(ctHeader string, p []byte) (Manifest, Descriptor, error) { // Need to look up by the actual media type, not the raw contents of // the header. Strip semicolons and anything following them. var mediaType string if ctHeader != "" { var err error mediaType, _, err = mime.ParseMediaType(ctHeader) if err != nil { return nil, Descriptor{}, err } } unmarshalFunc, ok := mappings[mediaType] if !ok { unmarshalFunc, ok = mappings[""] if !ok { return nil, Descriptor{}, fmt.Errorf("unsupported manifest media type and no default available: %s", mediaType) } } return unmarshalFunc(p) }
[ "func", "UnmarshalManifest", "(", "ctHeader", "string", ",", "p", "[", "]", "byte", ")", "(", "Manifest", ",", "Descriptor", ",", "error", ")", "{", "var", "mediaType", "string", "\n", "if", "ctHeader", "!=", "\"\"", "{", "var", "err", "error", "\n", "...
// UnmarshalManifest looks up manifest unmarshal functions based on // MediaType
[ "UnmarshalManifest", "looks", "up", "manifest", "unmarshal", "functions", "based", "on", "MediaType" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifests.go#L94-L115
train
docker/distribution
manifests.go
RegisterManifestSchema
func RegisterManifestSchema(mediaType string, u UnmarshalFunc) error { if _, ok := mappings[mediaType]; ok { return fmt.Errorf("manifest media type registration would overwrite existing: %s", mediaType) } mappings[mediaType] = u return nil }
go
func RegisterManifestSchema(mediaType string, u UnmarshalFunc) error { if _, ok := mappings[mediaType]; ok { return fmt.Errorf("manifest media type registration would overwrite existing: %s", mediaType) } mappings[mediaType] = u return nil }
[ "func", "RegisterManifestSchema", "(", "mediaType", "string", ",", "u", "UnmarshalFunc", ")", "error", "{", "if", "_", ",", "ok", ":=", "mappings", "[", "mediaType", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"manifest media type registration ...
// RegisterManifestSchema registers an UnmarshalFunc for a given schema type. This // should be called from specific
[ "RegisterManifestSchema", "registers", "an", "UnmarshalFunc", "for", "a", "given", "schema", "type", ".", "This", "should", "be", "called", "from", "specific" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifests.go#L119-L125
train
docker/distribution
registry/auth/silly/access.go
Authorized
func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) { req, err := dcontext.GetRequest(ctx) if err != nil { return nil, err } if req.Header.Get("Authorization") == "" { challenge := challenge{ realm: ac.realm, service: ac.service, } if len(accessRecords) > 0 { var scopes []string for _, access := range accessRecords { scopes = append(scopes, fmt.Sprintf("%s:%s:%s", access.Type, access.Resource.Name, access.Action)) } challenge.scope = strings.Join(scopes, " ") } return nil, &challenge } ctx = auth.WithUser(ctx, auth.UserInfo{Name: "silly"}) ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, auth.UserNameKey, auth.UserKey)) return ctx, nil }
go
func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) { req, err := dcontext.GetRequest(ctx) if err != nil { return nil, err } if req.Header.Get("Authorization") == "" { challenge := challenge{ realm: ac.realm, service: ac.service, } if len(accessRecords) > 0 { var scopes []string for _, access := range accessRecords { scopes = append(scopes, fmt.Sprintf("%s:%s:%s", access.Type, access.Resource.Name, access.Action)) } challenge.scope = strings.Join(scopes, " ") } return nil, &challenge } ctx = auth.WithUser(ctx, auth.UserInfo{Name: "silly"}) ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, auth.UserNameKey, auth.UserKey)) return ctx, nil }
[ "func", "(", "ac", "*", "accessController", ")", "Authorized", "(", "ctx", "context", ".", "Context", ",", "accessRecords", "...", "auth", ".", "Access", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "req", ",", "err", ":=", "dcontext", ...
// Authorized simply checks for the existence of the authorization header, // responding with a bearer challenge if it doesn't exist.
[ "Authorized", "simply", "checks", "for", "the", "existence", "of", "the", "authorization", "header", "responding", "with", "a", "bearer", "challenge", "if", "it", "doesn", "t", "exist", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/silly/access.go#L46-L74
train
docker/distribution
registry/auth/silly/access.go
SetHeaders
func (ch challenge) SetHeaders(r *http.Request, w http.ResponseWriter) { header := fmt.Sprintf("Bearer realm=%q,service=%q", ch.realm, ch.service) if ch.scope != "" { header = fmt.Sprintf("%s,scope=%q", header, ch.scope) } w.Header().Set("WWW-Authenticate", header) }
go
func (ch challenge) SetHeaders(r *http.Request, w http.ResponseWriter) { header := fmt.Sprintf("Bearer realm=%q,service=%q", ch.realm, ch.service) if ch.scope != "" { header = fmt.Sprintf("%s,scope=%q", header, ch.scope) } w.Header().Set("WWW-Authenticate", header) }
[ "func", "(", "ch", "challenge", ")", "SetHeaders", "(", "r", "*", "http", ".", "Request", ",", "w", "http", ".", "ResponseWriter", ")", "{", "header", ":=", "fmt", ".", "Sprintf", "(", "\"Bearer realm=%q,service=%q\"", ",", "ch", ".", "realm", ",", "ch",...
// SetHeaders sets a simple bearer challenge on the response.
[ "SetHeaders", "sets", "a", "simple", "bearer", "challenge", "on", "the", "response", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/silly/access.go#L85-L93
train
docker/distribution
registry/handlers/hmac.go
unpackUploadState
func (secret hmacKey) unpackUploadState(token string) (blobUploadState, error) { var state blobUploadState tokenBytes, err := base64.URLEncoding.DecodeString(token) if err != nil { return state, err } mac := hmac.New(sha256.New, []byte(secret)) if len(tokenBytes) < mac.Size() { return state, errInvalidSecret } macBytes := tokenBytes[:mac.Size()] messageBytes := tokenBytes[mac.Size():] mac.Write(messageBytes) if !hmac.Equal(mac.Sum(nil), macBytes) { return state, errInvalidSecret } if err := json.Unmarshal(messageBytes, &state); err != nil { return state, err } return state, nil }
go
func (secret hmacKey) unpackUploadState(token string) (blobUploadState, error) { var state blobUploadState tokenBytes, err := base64.URLEncoding.DecodeString(token) if err != nil { return state, err } mac := hmac.New(sha256.New, []byte(secret)) if len(tokenBytes) < mac.Size() { return state, errInvalidSecret } macBytes := tokenBytes[:mac.Size()] messageBytes := tokenBytes[mac.Size():] mac.Write(messageBytes) if !hmac.Equal(mac.Sum(nil), macBytes) { return state, errInvalidSecret } if err := json.Unmarshal(messageBytes, &state); err != nil { return state, err } return state, nil }
[ "func", "(", "secret", "hmacKey", ")", "unpackUploadState", "(", "token", "string", ")", "(", "blobUploadState", ",", "error", ")", "{", "var", "state", "blobUploadState", "\n", "tokenBytes", ",", "err", ":=", "base64", ".", "URLEncoding", ".", "DecodeString",...
// unpackUploadState unpacks and validates the blob upload state from the // token, using the hmacKey secret.
[ "unpackUploadState", "unpacks", "and", "validates", "the", "blob", "upload", "state", "from", "the", "token", "using", "the", "hmacKey", "secret", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/hmac.go#L33-L59
train
docker/distribution
registry/handlers/hmac.go
packUploadState
func (secret hmacKey) packUploadState(lus blobUploadState) (string, error) { mac := hmac.New(sha256.New, []byte(secret)) p, err := json.Marshal(lus) if err != nil { return "", err } mac.Write(p) return base64.URLEncoding.EncodeToString(append(mac.Sum(nil), p...)), nil }
go
func (secret hmacKey) packUploadState(lus blobUploadState) (string, error) { mac := hmac.New(sha256.New, []byte(secret)) p, err := json.Marshal(lus) if err != nil { return "", err } mac.Write(p) return base64.URLEncoding.EncodeToString(append(mac.Sum(nil), p...)), nil }
[ "func", "(", "secret", "hmacKey", ")", "packUploadState", "(", "lus", "blobUploadState", ")", "(", "string", ",", "error", ")", "{", "mac", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "[", "]", "byte", "(", "secret", ")", ")", "\n", "...
// packUploadState packs the upload state signed with and hmac digest using // the hmacKey secret, encoding to url safe base64. The resulting token can be // used to share data with minimized risk of external tampering.
[ "packUploadState", "packs", "the", "upload", "state", "signed", "with", "and", "hmac", "digest", "using", "the", "hmacKey", "secret", "encoding", "to", "url", "safe", "base64", ".", "The", "resulting", "token", "can", "be", "used", "to", "share", "data", "wi...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/hmac.go#L64-L74
train
docker/distribution
contrib/token-server/token.go
ResolveScopeSpecifiers
func ResolveScopeSpecifiers(ctx context.Context, scopeSpecs []string) []auth.Access { requestedAccessSet := make(map[auth.Access]struct{}, 2*len(scopeSpecs)) for _, scopeSpecifier := range scopeSpecs { // There should be 3 parts, separated by a `:` character. parts := strings.SplitN(scopeSpecifier, ":", 3) if len(parts) != 3 { dcontext.GetLogger(ctx).Infof("ignoring unsupported scope format %s", scopeSpecifier) continue } resourceType, resourceName, actions := parts[0], parts[1], parts[2] resourceType, resourceClass := splitResourceClass(resourceType) if resourceType == "" { continue } // Actions should be a comma-separated list of actions. for _, action := range strings.Split(actions, ",") { requestedAccess := auth.Access{ Resource: auth.Resource{ Type: resourceType, Class: resourceClass, Name: resourceName, }, Action: action, } // Add this access to the requested access set. requestedAccessSet[requestedAccess] = struct{}{} } } requestedAccessList := make([]auth.Access, 0, len(requestedAccessSet)) for requestedAccess := range requestedAccessSet { requestedAccessList = append(requestedAccessList, requestedAccess) } return requestedAccessList }
go
func ResolveScopeSpecifiers(ctx context.Context, scopeSpecs []string) []auth.Access { requestedAccessSet := make(map[auth.Access]struct{}, 2*len(scopeSpecs)) for _, scopeSpecifier := range scopeSpecs { // There should be 3 parts, separated by a `:` character. parts := strings.SplitN(scopeSpecifier, ":", 3) if len(parts) != 3 { dcontext.GetLogger(ctx).Infof("ignoring unsupported scope format %s", scopeSpecifier) continue } resourceType, resourceName, actions := parts[0], parts[1], parts[2] resourceType, resourceClass := splitResourceClass(resourceType) if resourceType == "" { continue } // Actions should be a comma-separated list of actions. for _, action := range strings.Split(actions, ",") { requestedAccess := auth.Access{ Resource: auth.Resource{ Type: resourceType, Class: resourceClass, Name: resourceName, }, Action: action, } // Add this access to the requested access set. requestedAccessSet[requestedAccess] = struct{}{} } } requestedAccessList := make([]auth.Access, 0, len(requestedAccessSet)) for requestedAccess := range requestedAccessSet { requestedAccessList = append(requestedAccessList, requestedAccess) } return requestedAccessList }
[ "func", "ResolveScopeSpecifiers", "(", "ctx", "context", ".", "Context", ",", "scopeSpecs", "[", "]", "string", ")", "[", "]", "auth", ".", "Access", "{", "requestedAccessSet", ":=", "make", "(", "map", "[", "auth", ".", "Access", "]", "struct", "{", "}"...
// ResolveScopeSpecifiers converts a list of scope specifiers from a token // request's `scope` query parameters into a list of standard access objects.
[ "ResolveScopeSpecifiers", "converts", "a", "list", "of", "scope", "specifiers", "from", "a", "token", "request", "s", "scope", "query", "parameters", "into", "a", "list", "of", "standard", "access", "objects", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/contrib/token-server/token.go#L23-L64
train
docker/distribution
contrib/token-server/token.go
ResolveScopeList
func ResolveScopeList(ctx context.Context, scopeList string) []auth.Access { scopes := strings.Split(scopeList, " ") return ResolveScopeSpecifiers(ctx, scopes) }
go
func ResolveScopeList(ctx context.Context, scopeList string) []auth.Access { scopes := strings.Split(scopeList, " ") return ResolveScopeSpecifiers(ctx, scopes) }
[ "func", "ResolveScopeList", "(", "ctx", "context", ".", "Context", ",", "scopeList", "string", ")", "[", "]", "auth", ".", "Access", "{", "scopes", ":=", "strings", ".", "Split", "(", "scopeList", ",", "\" \"", ")", "\n", "return", "ResolveScopeSpecifiers", ...
// ResolveScopeList converts a scope list from a token request's // `scope` parameter into a list of standard access objects.
[ "ResolveScopeList", "converts", "a", "scope", "list", "from", "a", "token", "request", "s", "scope", "parameter", "into", "a", "list", "of", "standard", "access", "objects", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/contrib/token-server/token.go#L81-L84
train
docker/distribution
contrib/token-server/token.go
ToScopeList
func ToScopeList(access []auth.Access) string { var s []string for _, a := range access { s = append(s, scopeString(a)) } return strings.Join(s, ",") }
go
func ToScopeList(access []auth.Access) string { var s []string for _, a := range access { s = append(s, scopeString(a)) } return strings.Join(s, ",") }
[ "func", "ToScopeList", "(", "access", "[", "]", "auth", ".", "Access", ")", "string", "{", "var", "s", "[", "]", "string", "\n", "for", "_", ",", "a", ":=", "range", "access", "{", "s", "=", "append", "(", "s", ",", "scopeString", "(", "a", ")", ...
// ToScopeList converts a list of access to a // scope list string
[ "ToScopeList", "converts", "a", "list", "of", "access", "to", "a", "scope", "list", "string" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/contrib/token-server/token.go#L95-L101
train
docker/distribution
registry/auth/htpasswd/access.go
SetHeaders
func (ch challenge) SetHeaders(r *http.Request, w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", ch.realm)) }
go
func (ch challenge) SetHeaders(r *http.Request, w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", ch.realm)) }
[ "func", "(", "ch", "challenge", ")", "SetHeaders", "(", "r", "*", "http", ".", "Request", ",", "w", "http", ".", "ResponseWriter", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"WWW-Authenticate\"", ",", "fmt", ".", "Sprintf", "(", "\"Ba...
// SetHeaders sets the basic challenge header on the response.
[ "SetHeaders", "sets", "the", "basic", "challenge", "header", "on", "the", "response", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/htpasswd/access.go#L114-L116
train
docker/distribution
registry/auth/htpasswd/access.go
createHtpasswdFile
func createHtpasswdFile(path string) error { if f, err := os.Open(path); err == nil { f.Close() return nil } else if !os.IsNotExist(err) { return err } if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { return err } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600) if err != nil { return fmt.Errorf("failed to open htpasswd path %s", err) } defer f.Close() var secretBytes [32]byte if _, err := rand.Read(secretBytes[:]); err != nil { return err } pass := base64.RawURLEncoding.EncodeToString(secretBytes[:]) encryptedPass, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost) if err != nil { return err } if _, err := f.Write([]byte(fmt.Sprintf("docker:%s", string(encryptedPass[:])))); err != nil { return err } dcontext.GetLoggerWithFields(context.Background(), map[interface{}]interface{}{ "user": "docker", "password": pass, }).Warnf("htpasswd is missing, provisioning with default user") return nil }
go
func createHtpasswdFile(path string) error { if f, err := os.Open(path); err == nil { f.Close() return nil } else if !os.IsNotExist(err) { return err } if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { return err } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600) if err != nil { return fmt.Errorf("failed to open htpasswd path %s", err) } defer f.Close() var secretBytes [32]byte if _, err := rand.Read(secretBytes[:]); err != nil { return err } pass := base64.RawURLEncoding.EncodeToString(secretBytes[:]) encryptedPass, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost) if err != nil { return err } if _, err := f.Write([]byte(fmt.Sprintf("docker:%s", string(encryptedPass[:])))); err != nil { return err } dcontext.GetLoggerWithFields(context.Background(), map[interface{}]interface{}{ "user": "docker", "password": pass, }).Warnf("htpasswd is missing, provisioning with default user") return nil }
[ "func", "createHtpasswdFile", "(", "path", "string", ")", "error", "{", "if", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", ";", "err", "==", "nil", "{", "f", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}", "else", "if", ...
// createHtpasswdFile creates and populates htpasswd file with a new user in case the file is missing
[ "createHtpasswdFile", "creates", "and", "populates", "htpasswd", "file", "with", "a", "new", "user", "in", "case", "the", "file", "is", "missing" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/htpasswd/access.go#L123-L156
train
docker/distribution
registry/handlers/hooks.go
Fire
func (hook *logHook) Fire(entry *logrus.Entry) error { addr := strings.Split(hook.Mail.Addr, ":") if len(addr) != 2 { return errors.New("invalid Mail Address") } host := addr[0] subject := fmt.Sprintf("[%s] %s: %s", entry.Level, host, entry.Message) html := ` {{.Message}} {{range $key, $value := .Data}} {{$key}}: {{$value}} {{end}} ` b := bytes.NewBuffer(make([]byte, 0)) t := template.Must(template.New("mail body").Parse(html)) if err := t.Execute(b, entry); err != nil { return err } body := b.String() return hook.Mail.sendMail(subject, body) }
go
func (hook *logHook) Fire(entry *logrus.Entry) error { addr := strings.Split(hook.Mail.Addr, ":") if len(addr) != 2 { return errors.New("invalid Mail Address") } host := addr[0] subject := fmt.Sprintf("[%s] %s: %s", entry.Level, host, entry.Message) html := ` {{.Message}} {{range $key, $value := .Data}} {{$key}}: {{$value}} {{end}} ` b := bytes.NewBuffer(make([]byte, 0)) t := template.Must(template.New("mail body").Parse(html)) if err := t.Execute(b, entry); err != nil { return err } body := b.String() return hook.Mail.sendMail(subject, body) }
[ "func", "(", "hook", "*", "logHook", ")", "Fire", "(", "entry", "*", "logrus", ".", "Entry", ")", "error", "{", "addr", ":=", "strings", ".", "Split", "(", "hook", ".", "Mail", ".", "Addr", ",", "\":\"", ")", "\n", "if", "len", "(", "addr", ")", ...
// Fire forwards an error to LogHook
[ "Fire", "forwards", "an", "error", "to", "LogHook" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/hooks.go#L20-L43
train
docker/distribution
registry/handlers/hooks.go
Levels
func (hook *logHook) Levels() []logrus.Level { levels := []logrus.Level{} for _, v := range hook.LevelsParam { lv, _ := logrus.ParseLevel(v) levels = append(levels, lv) } return levels }
go
func (hook *logHook) Levels() []logrus.Level { levels := []logrus.Level{} for _, v := range hook.LevelsParam { lv, _ := logrus.ParseLevel(v) levels = append(levels, lv) } return levels }
[ "func", "(", "hook", "*", "logHook", ")", "Levels", "(", ")", "[", "]", "logrus", ".", "Level", "{", "levels", ":=", "[", "]", "logrus", ".", "Level", "{", "}", "\n", "for", "_", ",", "v", ":=", "range", "hook", ".", "LevelsParam", "{", "lv", "...
// Levels contains hook levels to be catched
[ "Levels", "contains", "hook", "levels", "to", "be", "catched" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/hooks.go#L46-L53
train
docker/distribution
registry/listener/listener.go
NewListener
func NewListener(net, laddr string) (net.Listener, error) { switch net { case "unix": return newUnixListener(laddr) case "tcp", "": // an empty net means tcp return newTCPListener(laddr) default: return nil, fmt.Errorf("unknown address type %s", net) } }
go
func NewListener(net, laddr string) (net.Listener, error) { switch net { case "unix": return newUnixListener(laddr) case "tcp", "": // an empty net means tcp return newTCPListener(laddr) default: return nil, fmt.Errorf("unknown address type %s", net) } }
[ "func", "NewListener", "(", "net", ",", "laddr", "string", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "switch", "net", "{", "case", "\"unix\"", ":", "return", "newUnixListener", "(", "laddr", ")", "\n", "case", "\"tcp\"", ",", "\"\"", ":...
// NewListener announces on laddr and net. Accepted values of the net are // 'unix' and 'tcp'
[ "NewListener", "announces", "on", "laddr", "and", "net", ".", "Accepted", "values", "of", "the", "net", "are", "unix", "and", "tcp" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/listener/listener.go#L31-L40
train
docker/distribution
registry/storage/driver/oss/oss.go
New
func New(params DriverParameters) (*Driver, error) { client := oss.NewOSSClient(params.Region, params.Internal, params.AccessKeyID, params.AccessKeySecret, params.Secure) client.SetEndpoint(params.Endpoint) bucket := client.Bucket(params.Bucket) client.SetDebug(false) // Validate that the given credentials have at least read permissions in the // given bucket scope. if _, err := bucket.List(strings.TrimRight(params.RootDirectory, "/"), "", "", 1); err != nil { return nil, err } // TODO(tg123): Currently multipart uploads have no timestamps, so this would be unwise // if you initiated a new OSS client while another one is running on the same bucket. d := &driver{ Client: client, Bucket: bucket, ChunkSize: params.ChunkSize, Encrypt: params.Encrypt, RootDirectory: params.RootDirectory, EncryptionKeyID: params.EncryptionKeyID, } return &Driver{ baseEmbed: baseEmbed{ Base: base.Base{ StorageDriver: d, }, }, }, nil }
go
func New(params DriverParameters) (*Driver, error) { client := oss.NewOSSClient(params.Region, params.Internal, params.AccessKeyID, params.AccessKeySecret, params.Secure) client.SetEndpoint(params.Endpoint) bucket := client.Bucket(params.Bucket) client.SetDebug(false) // Validate that the given credentials have at least read permissions in the // given bucket scope. if _, err := bucket.List(strings.TrimRight(params.RootDirectory, "/"), "", "", 1); err != nil { return nil, err } // TODO(tg123): Currently multipart uploads have no timestamps, so this would be unwise // if you initiated a new OSS client while another one is running on the same bucket. d := &driver{ Client: client, Bucket: bucket, ChunkSize: params.ChunkSize, Encrypt: params.Encrypt, RootDirectory: params.RootDirectory, EncryptionKeyID: params.EncryptionKeyID, } return &Driver{ baseEmbed: baseEmbed{ Base: base.Base{ StorageDriver: d, }, }, }, nil }
[ "func", "New", "(", "params", "DriverParameters", ")", "(", "*", "Driver", ",", "error", ")", "{", "client", ":=", "oss", ".", "NewOSSClient", "(", "params", ".", "Region", ",", "params", ".", "Internal", ",", "params", ".", "AccessKeyID", ",", "params",...
// New constructs a new Driver with the given Aliyun credentials, region, encryption flag, and // bucketName
[ "New", "constructs", "a", "new", "Driver", "with", "the", "given", "Aliyun", "credentials", "region", "encryption", "flag", "and", "bucketName" ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/storage/driver/oss/oss.go#L203-L235
train
docker/distribution
registry/client/auth/api_version.go
APIVersions
func APIVersions(resp *http.Response, versionHeader string) []APIVersion { versions := []APIVersion{} if versionHeader != "" { for _, supportedVersions := range resp.Header[http.CanonicalHeaderKey(versionHeader)] { for _, version := range strings.Fields(supportedVersions) { versions = append(versions, ParseAPIVersion(version)) } } } return versions }
go
func APIVersions(resp *http.Response, versionHeader string) []APIVersion { versions := []APIVersion{} if versionHeader != "" { for _, supportedVersions := range resp.Header[http.CanonicalHeaderKey(versionHeader)] { for _, version := range strings.Fields(supportedVersions) { versions = append(versions, ParseAPIVersion(version)) } } } return versions }
[ "func", "APIVersions", "(", "resp", "*", "http", ".", "Response", ",", "versionHeader", "string", ")", "[", "]", "APIVersion", "{", "versions", ":=", "[", "]", "APIVersion", "{", "}", "\n", "if", "versionHeader", "!=", "\"\"", "{", "for", "_", ",", "su...
// APIVersions gets the API versions out of an HTTP response using the provided // version header as the key for the HTTP header.
[ "APIVersions", "gets", "the", "API", "versions", "out", "of", "an", "HTTP", "response", "using", "the", "provided", "version", "header", "as", "the", "key", "for", "the", "HTTP", "header", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/client/auth/api_version.go#L28-L38
train
docker/distribution
registry/handlers/mail.go
sendMail
func (mail *mailer) sendMail(subject, message string) error { addr := strings.Split(mail.Addr, ":") if len(addr) != 2 { return errors.New("invalid Mail Address") } host := addr[0] msg := []byte("To:" + strings.Join(mail.To, ";") + "\r\nFrom: " + mail.From + "\r\nSubject: " + subject + "\r\nContent-Type: text/plain\r\n\r\n" + message) auth := smtp.PlainAuth( "", mail.Username, mail.Password, host, ) err := smtp.SendMail( mail.Addr, auth, mail.From, mail.To, msg, ) if err != nil { return err } return nil }
go
func (mail *mailer) sendMail(subject, message string) error { addr := strings.Split(mail.Addr, ":") if len(addr) != 2 { return errors.New("invalid Mail Address") } host := addr[0] msg := []byte("To:" + strings.Join(mail.To, ";") + "\r\nFrom: " + mail.From + "\r\nSubject: " + subject + "\r\nContent-Type: text/plain\r\n\r\n" + message) auth := smtp.PlainAuth( "", mail.Username, mail.Password, host, ) err := smtp.SendMail( mail.Addr, auth, mail.From, mail.To, msg, ) if err != nil { return err } return nil }
[ "func", "(", "mail", "*", "mailer", ")", "sendMail", "(", "subject", ",", "message", "string", ")", "error", "{", "addr", ":=", "strings", ".", "Split", "(", "mail", ".", "Addr", ",", "\":\"", ")", "\n", "if", "len", "(", "addr", ")", "!=", "2", ...
// sendMail allows users to send email, only if mail parameters is configured correctly.
[ "sendMail", "allows", "users", "to", "send", "email", "only", "if", "mail", "parameters", "is", "configured", "correctly", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/handlers/mail.go#L17-L45
train
docker/distribution
registry/auth/token/accesscontroller.go
newAccessSet
func newAccessSet(accessItems ...auth.Access) accessSet { accessSet := make(accessSet, len(accessItems)) for _, access := range accessItems { resource := auth.Resource{ Type: access.Type, Name: access.Name, } set, exists := accessSet[resource] if !exists { set = newActionSet() accessSet[resource] = set } set.add(access.Action) } return accessSet }
go
func newAccessSet(accessItems ...auth.Access) accessSet { accessSet := make(accessSet, len(accessItems)) for _, access := range accessItems { resource := auth.Resource{ Type: access.Type, Name: access.Name, } set, exists := accessSet[resource] if !exists { set = newActionSet() accessSet[resource] = set } set.add(access.Action) } return accessSet }
[ "func", "newAccessSet", "(", "accessItems", "...", "auth", ".", "Access", ")", "accessSet", "{", "accessSet", ":=", "make", "(", "accessSet", ",", "len", "(", "accessItems", ")", ")", "\n", "for", "_", ",", "access", ":=", "range", "accessItems", "{", "r...
// newAccessSet constructs an accessSet from // a variable number of auth.Access items.
[ "newAccessSet", "constructs", "an", "accessSet", "from", "a", "variable", "number", "of", "auth", ".", "Access", "items", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/accesscontroller.go#L26-L45
train
docker/distribution
registry/auth/token/accesscontroller.go
contains
func (s accessSet) contains(access auth.Access) bool { actionSet, ok := s[access.Resource] if ok { return actionSet.contains(access.Action) } return false }
go
func (s accessSet) contains(access auth.Access) bool { actionSet, ok := s[access.Resource] if ok { return actionSet.contains(access.Action) } return false }
[ "func", "(", "s", "accessSet", ")", "contains", "(", "access", "auth", ".", "Access", ")", "bool", "{", "actionSet", ",", "ok", ":=", "s", "[", "access", ".", "Resource", "]", "\n", "if", "ok", "{", "return", "actionSet", ".", "contains", "(", "acces...
// contains returns whether or not the given access is in this accessSet.
[ "contains", "returns", "whether", "or", "not", "the", "given", "access", "is", "in", "this", "accessSet", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/accesscontroller.go#L48-L55
train
docker/distribution
registry/auth/token/accesscontroller.go
SetHeaders
func (ac authChallenge) SetHeaders(r *http.Request, w http.ResponseWriter) { w.Header().Add("WWW-Authenticate", ac.challengeParams(r)) }
go
func (ac authChallenge) SetHeaders(r *http.Request, w http.ResponseWriter) { w.Header().Add("WWW-Authenticate", ac.challengeParams(r)) }
[ "func", "(", "ac", "authChallenge", ")", "SetHeaders", "(", "r", "*", "http", ".", "Request", ",", "w", "http", ".", "ResponseWriter", ")", "{", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"WWW-Authenticate\"", ",", "ac", ".", "challengeParams", "...
// SetChallenge sets the WWW-Authenticate value for the response.
[ "SetChallenge", "sets", "the", "WWW", "-", "Authenticate", "value", "for", "the", "response", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/accesscontroller.go#L124-L126
train
docker/distribution
registry/auth/token/accesscontroller.go
checkOptions
func checkOptions(options map[string]interface{}) (tokenAccessOptions, error) { var opts tokenAccessOptions keys := []string{"realm", "issuer", "service", "rootcertbundle"} vals := make([]string, 0, len(keys)) for _, key := range keys { val, ok := options[key].(string) if !ok { return opts, fmt.Errorf("token auth requires a valid option string: %q", key) } vals = append(vals, val) } opts.realm, opts.issuer, opts.service, opts.rootCertBundle = vals[0], vals[1], vals[2], vals[3] autoRedirectVal, ok := options["autoredirect"] if ok { autoRedirect, ok := autoRedirectVal.(bool) if !ok { return opts, fmt.Errorf("token auth requires a valid option bool: autoredirect") } opts.autoRedirect = autoRedirect } return opts, nil }
go
func checkOptions(options map[string]interface{}) (tokenAccessOptions, error) { var opts tokenAccessOptions keys := []string{"realm", "issuer", "service", "rootcertbundle"} vals := make([]string, 0, len(keys)) for _, key := range keys { val, ok := options[key].(string) if !ok { return opts, fmt.Errorf("token auth requires a valid option string: %q", key) } vals = append(vals, val) } opts.realm, opts.issuer, opts.service, opts.rootCertBundle = vals[0], vals[1], vals[2], vals[3] autoRedirectVal, ok := options["autoredirect"] if ok { autoRedirect, ok := autoRedirectVal.(bool) if !ok { return opts, fmt.Errorf("token auth requires a valid option bool: autoredirect") } opts.autoRedirect = autoRedirect } return opts, nil }
[ "func", "checkOptions", "(", "options", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "tokenAccessOptions", ",", "error", ")", "{", "var", "opts", "tokenAccessOptions", "\n", "keys", ":=", "[", "]", "string", "{", "\"realm\"", ",", "\"issuer\...
// checkOptions gathers the necessary options // for an accessController from the given map.
[ "checkOptions", "gathers", "the", "necessary", "options", "for", "an", "accessController", "from", "the", "given", "map", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/accesscontroller.go#L150-L175
train
docker/distribution
registry/auth/token/accesscontroller.go
newAccessController
func newAccessController(options map[string]interface{}) (auth.AccessController, error) { config, err := checkOptions(options) if err != nil { return nil, err } fp, err := os.Open(config.rootCertBundle) if err != nil { return nil, fmt.Errorf("unable to open token auth root certificate bundle file %q: %s", config.rootCertBundle, err) } defer fp.Close() rawCertBundle, err := ioutil.ReadAll(fp) if err != nil { return nil, fmt.Errorf("unable to read token auth root certificate bundle file %q: %s", config.rootCertBundle, err) } var rootCerts []*x509.Certificate pemBlock, rawCertBundle := pem.Decode(rawCertBundle) for pemBlock != nil { if pemBlock.Type == "CERTIFICATE" { cert, err := x509.ParseCertificate(pemBlock.Bytes) if err != nil { return nil, fmt.Errorf("unable to parse token auth root certificate: %s", err) } rootCerts = append(rootCerts, cert) } pemBlock, rawCertBundle = pem.Decode(rawCertBundle) } if len(rootCerts) == 0 { return nil, errors.New("token auth requires at least one token signing root certificate") } rootPool := x509.NewCertPool() trustedKeys := make(map[string]libtrust.PublicKey, len(rootCerts)) for _, rootCert := range rootCerts { rootPool.AddCert(rootCert) pubKey, err := libtrust.FromCryptoPublicKey(crypto.PublicKey(rootCert.PublicKey)) if err != nil { return nil, fmt.Errorf("unable to get public key from token auth root certificate: %s", err) } trustedKeys[pubKey.KeyID()] = pubKey } return &accessController{ realm: config.realm, autoRedirect: config.autoRedirect, issuer: config.issuer, service: config.service, rootCerts: rootPool, trustedKeys: trustedKeys, }, nil }
go
func newAccessController(options map[string]interface{}) (auth.AccessController, error) { config, err := checkOptions(options) if err != nil { return nil, err } fp, err := os.Open(config.rootCertBundle) if err != nil { return nil, fmt.Errorf("unable to open token auth root certificate bundle file %q: %s", config.rootCertBundle, err) } defer fp.Close() rawCertBundle, err := ioutil.ReadAll(fp) if err != nil { return nil, fmt.Errorf("unable to read token auth root certificate bundle file %q: %s", config.rootCertBundle, err) } var rootCerts []*x509.Certificate pemBlock, rawCertBundle := pem.Decode(rawCertBundle) for pemBlock != nil { if pemBlock.Type == "CERTIFICATE" { cert, err := x509.ParseCertificate(pemBlock.Bytes) if err != nil { return nil, fmt.Errorf("unable to parse token auth root certificate: %s", err) } rootCerts = append(rootCerts, cert) } pemBlock, rawCertBundle = pem.Decode(rawCertBundle) } if len(rootCerts) == 0 { return nil, errors.New("token auth requires at least one token signing root certificate") } rootPool := x509.NewCertPool() trustedKeys := make(map[string]libtrust.PublicKey, len(rootCerts)) for _, rootCert := range rootCerts { rootPool.AddCert(rootCert) pubKey, err := libtrust.FromCryptoPublicKey(crypto.PublicKey(rootCert.PublicKey)) if err != nil { return nil, fmt.Errorf("unable to get public key from token auth root certificate: %s", err) } trustedKeys[pubKey.KeyID()] = pubKey } return &accessController{ realm: config.realm, autoRedirect: config.autoRedirect, issuer: config.issuer, service: config.service, rootCerts: rootPool, trustedKeys: trustedKeys, }, nil }
[ "func", "newAccessController", "(", "options", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "auth", ".", "AccessController", ",", "error", ")", "{", "config", ",", "err", ":=", "checkOptions", "(", "options", ")", "\n", "if", "err", "!=", ...
// newAccessController creates an accessController using the given options.
[ "newAccessController", "creates", "an", "accessController", "using", "the", "given", "options", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/accesscontroller.go#L178-L233
train
docker/distribution
registry/auth/token/accesscontroller.go
Authorized
func (ac *accessController) Authorized(ctx context.Context, accessItems ...auth.Access) (context.Context, error) { challenge := &authChallenge{ realm: ac.realm, autoRedirect: ac.autoRedirect, service: ac.service, accessSet: newAccessSet(accessItems...), } req, err := dcontext.GetRequest(ctx) if err != nil { return nil, err } parts := strings.Split(req.Header.Get("Authorization"), " ") if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" { challenge.err = ErrTokenRequired return nil, challenge } rawToken := parts[1] token, err := NewToken(rawToken) if err != nil { challenge.err = err return nil, challenge } verifyOpts := VerifyOptions{ TrustedIssuers: []string{ac.issuer}, AcceptedAudiences: []string{ac.service}, Roots: ac.rootCerts, TrustedKeys: ac.trustedKeys, } if err = token.Verify(verifyOpts); err != nil { challenge.err = err return nil, challenge } accessSet := token.accessSet() for _, access := range accessItems { if !accessSet.contains(access) { challenge.err = ErrInsufficientScope return nil, challenge } } ctx = auth.WithResources(ctx, token.resources()) return auth.WithUser(ctx, auth.UserInfo{Name: token.Claims.Subject}), nil }
go
func (ac *accessController) Authorized(ctx context.Context, accessItems ...auth.Access) (context.Context, error) { challenge := &authChallenge{ realm: ac.realm, autoRedirect: ac.autoRedirect, service: ac.service, accessSet: newAccessSet(accessItems...), } req, err := dcontext.GetRequest(ctx) if err != nil { return nil, err } parts := strings.Split(req.Header.Get("Authorization"), " ") if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" { challenge.err = ErrTokenRequired return nil, challenge } rawToken := parts[1] token, err := NewToken(rawToken) if err != nil { challenge.err = err return nil, challenge } verifyOpts := VerifyOptions{ TrustedIssuers: []string{ac.issuer}, AcceptedAudiences: []string{ac.service}, Roots: ac.rootCerts, TrustedKeys: ac.trustedKeys, } if err = token.Verify(verifyOpts); err != nil { challenge.err = err return nil, challenge } accessSet := token.accessSet() for _, access := range accessItems { if !accessSet.contains(access) { challenge.err = ErrInsufficientScope return nil, challenge } } ctx = auth.WithResources(ctx, token.resources()) return auth.WithUser(ctx, auth.UserInfo{Name: token.Claims.Subject}), nil }
[ "func", "(", "ac", "*", "accessController", ")", "Authorized", "(", "ctx", "context", ".", "Context", ",", "accessItems", "...", "auth", ".", "Access", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "challenge", ":=", "&", "authChallenge", ...
// Authorized handles checking whether the given request is authorized // for actions on resources described by the given access items.
[ "Authorized", "handles", "checking", "whether", "the", "given", "request", "is", "authorized", "for", "actions", "on", "resources", "described", "by", "the", "given", "access", "items", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/registry/auth/token/accesscontroller.go#L237-L288
train
docker/distribution
manifest/ocischema/builder.go
NewManifestBuilder
func NewManifestBuilder(bs distribution.BlobService, configJSON []byte, annotations map[string]string) distribution.ManifestBuilder { mb := &Builder{ bs: bs, configJSON: make([]byte, len(configJSON)), annotations: annotations, mediaType: v1.MediaTypeImageManifest, } copy(mb.configJSON, configJSON) return mb }
go
func NewManifestBuilder(bs distribution.BlobService, configJSON []byte, annotations map[string]string) distribution.ManifestBuilder { mb := &Builder{ bs: bs, configJSON: make([]byte, len(configJSON)), annotations: annotations, mediaType: v1.MediaTypeImageManifest, } copy(mb.configJSON, configJSON) return mb }
[ "func", "NewManifestBuilder", "(", "bs", "distribution", ".", "BlobService", ",", "configJSON", "[", "]", "byte", ",", "annotations", "map", "[", "string", "]", "string", ")", "distribution", ".", "ManifestBuilder", "{", "mb", ":=", "&", "Builder", "{", "bs"...
// NewManifestBuilder is used to build new manifests for the current schema // version. It takes a BlobService so it can publish the configuration blob // as part of the Build process, and annotations.
[ "NewManifestBuilder", "is", "used", "to", "build", "new", "manifests", "for", "the", "current", "schema", "version", ".", "It", "takes", "a", "BlobService", "so", "it", "can", "publish", "the", "configuration", "blob", "as", "part", "of", "the", "Build", "pr...
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/manifest/ocischema/builder.go#L35-L45
train
docker/distribution
notifications/metrics.go
newSafeMetrics
func newSafeMetrics() *safeMetrics { var sm safeMetrics sm.Statuses = make(map[string]int) return &sm }
go
func newSafeMetrics() *safeMetrics { var sm safeMetrics sm.Statuses = make(map[string]int) return &sm }
[ "func", "newSafeMetrics", "(", ")", "*", "safeMetrics", "{", "var", "sm", "safeMetrics", "\n", "sm", ".", "Statuses", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "return", "&", "sm", "\n", "}" ]
// newSafeMetrics returns safeMetrics with map allocated.
[ "newSafeMetrics", "returns", "safeMetrics", "with", "map", "allocated", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/metrics.go#L30-L34
train
docker/distribution
notifications/metrics.go
register
func register(e *Endpoint) { endpoints.mu.Lock() defer endpoints.mu.Unlock() endpoints.registered = append(endpoints.registered, e) }
go
func register(e *Endpoint) { endpoints.mu.Lock() defer endpoints.mu.Unlock() endpoints.registered = append(endpoints.registered, e) }
[ "func", "register", "(", "e", "*", "Endpoint", ")", "{", "endpoints", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "endpoints", ".", "mu", ".", "Unlock", "(", ")", "\n", "endpoints", ".", "registered", "=", "append", "(", "endpoints", ".", "regis...
// register places the endpoint into expvar so that stats are tracked.
[ "register", "places", "the", "endpoint", "into", "expvar", "so", "that", "stats", "are", "tracked", "." ]
3226863cbcba6dbc2f6c83a37b28126c934af3f8
https://github.com/docker/distribution/blob/3226863cbcba6dbc2f6c83a37b28126c934af3f8/notifications/metrics.go#L105-L110
train
prometheus/client_golang
prometheus/gauge.go
NewGaugeVec
func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &GaugeVec{ metricVec: newMetricVec(desc, func(lvs ...string) Metric { if len(lvs) != len(desc.variableLabels) { panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, lvs)) } result := &gauge{desc: desc, labelPairs: makeLabelPairs(desc, lvs)} result.init(result) // Init self-collection. return result }), } }
go
func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &GaugeVec{ metricVec: newMetricVec(desc, func(lvs ...string) Metric { if len(lvs) != len(desc.variableLabels) { panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, lvs)) } result := &gauge{desc: desc, labelPairs: makeLabelPairs(desc, lvs)} result.init(result) // Init self-collection. return result }), } }
[ "func", "NewGaugeVec", "(", "opts", "GaugeOpts", ",", "labelNames", "[", "]", "string", ")", "*", "GaugeVec", "{", "desc", ":=", "NewDesc", "(", "BuildFQName", "(", "opts", ".", "Namespace", ",", "opts", ".", "Subsystem", ",", "opts", ".", "Name", ")", ...
// NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and // partitioned by the given label names.
[ "NewGaugeVec", "creates", "a", "new", "GaugeVec", "based", "on", "the", "provided", "GaugeOpts", "and", "partitioned", "by", "the", "given", "label", "names", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/gauge.go#L140-L157
train
prometheus/client_golang
prometheus/gauge.go
NewGaugeFunc
func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc { return newValueFunc(NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, nil, opts.ConstLabels, ), GaugeValue, function) }
go
func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc { return newValueFunc(NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, nil, opts.ConstLabels, ), GaugeValue, function) }
[ "func", "NewGaugeFunc", "(", "opts", "GaugeOpts", ",", "function", "func", "(", ")", "float64", ")", "GaugeFunc", "{", "return", "newValueFunc", "(", "NewDesc", "(", "BuildFQName", "(", "opts", ".", "Namespace", ",", "opts", ".", "Subsystem", ",", "opts", ...
// NewGaugeFunc creates a new GaugeFunc based on the provided GaugeOpts. The // value reported is determined by calling the given function from within the // Write method. Take into account that metric collection may happen // concurrently. If that results in concurrent calls to Write, like in the case // where a GaugeFunc is directly registered with Prometheus, the provided // function must be concurrency-safe.
[ "NewGaugeFunc", "creates", "a", "new", "GaugeFunc", "based", "on", "the", "provided", "GaugeOpts", ".", "The", "value", "reported", "is", "determined", "by", "calling", "the", "given", "function", "from", "within", "the", "Write", "method", ".", "Take", "into"...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/gauge.go#L279-L286
train
prometheus/client_golang
prometheus/expvar_collector.go
Describe
func (e *expvarCollector) Describe(ch chan<- *Desc) { for _, desc := range e.exports { ch <- desc } }
go
func (e *expvarCollector) Describe(ch chan<- *Desc) { for _, desc := range e.exports { ch <- desc } }
[ "func", "(", "e", "*", "expvarCollector", ")", "Describe", "(", "ch", "chan", "<-", "*", "Desc", ")", "{", "for", "_", ",", "desc", ":=", "range", "e", ".", "exports", "{", "ch", "<-", "desc", "\n", "}", "\n", "}" ]
// Describe implements Collector.
[ "Describe", "implements", "Collector", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/expvar_collector.go#L69-L73
train
prometheus/client_golang
prometheus/promhttp/http.go
gzipAccepted
func gzipAccepted(header http.Header) bool { a := header.Get(acceptEncodingHeader) parts := strings.Split(a, ",") for _, part := range parts { part = strings.TrimSpace(part) if part == "gzip" || strings.HasPrefix(part, "gzip;") { return true } } return false }
go
func gzipAccepted(header http.Header) bool { a := header.Get(acceptEncodingHeader) parts := strings.Split(a, ",") for _, part := range parts { part = strings.TrimSpace(part) if part == "gzip" || strings.HasPrefix(part, "gzip;") { return true } } return false }
[ "func", "gzipAccepted", "(", "header", "http", ".", "Header", ")", "bool", "{", "a", ":=", "header", ".", "Get", "(", "acceptEncodingHeader", ")", "\n", "parts", ":=", "strings", ".", "Split", "(", "a", ",", "\",\"", ")", "\n", "for", "_", ",", "part...
// gzipAccepted returns whether the client will accept gzip-encoded content.
[ "gzipAccepted", "returns", "whether", "the", "client", "will", "accept", "gzip", "-", "encoded", "content", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promhttp/http.go#L285-L295
train
prometheus/client_golang
prometheus/promhttp/http.go
httpError
func httpError(rsp http.ResponseWriter, err error) { rsp.Header().Del(contentEncodingHeader) http.Error( rsp, "An error has occurred while serving metrics:\n\n"+err.Error(), http.StatusInternalServerError, ) }
go
func httpError(rsp http.ResponseWriter, err error) { rsp.Header().Del(contentEncodingHeader) http.Error( rsp, "An error has occurred while serving metrics:\n\n"+err.Error(), http.StatusInternalServerError, ) }
[ "func", "httpError", "(", "rsp", "http", ".", "ResponseWriter", ",", "err", "error", ")", "{", "rsp", ".", "Header", "(", ")", ".", "Del", "(", "contentEncodingHeader", ")", "\n", "http", ".", "Error", "(", "rsp", ",", "\"An error has occurred while serving ...
// httpError removes any content-encoding header and then calls http.Error with // the provided error and http.StatusInternalServerErrer. Error contents is // supposed to be uncompressed plain text. However, same as with a plain // http.Error, any header settings will be void if the header has already been // sent. The error message will still be written to the writer, but it will // probably be of limited use.
[ "httpError", "removes", "any", "content", "-", "encoding", "header", "and", "then", "calls", "http", ".", "Error", "with", "the", "provided", "error", "and", "http", ".", "StatusInternalServerErrer", ".", "Error", "contents", "is", "supposed", "to", "be", "unc...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promhttp/http.go#L303-L310
train
prometheus/client_golang
prometheus/timer.go
ObserveDuration
func (t *Timer) ObserveDuration() time.Duration { d := time.Since(t.begin) if t.observer != nil { t.observer.Observe(d.Seconds()) } return d }
go
func (t *Timer) ObserveDuration() time.Duration { d := time.Since(t.begin) if t.observer != nil { t.observer.Observe(d.Seconds()) } return d }
[ "func", "(", "t", "*", "Timer", ")", "ObserveDuration", "(", ")", "time", ".", "Duration", "{", "d", ":=", "time", ".", "Since", "(", "t", ".", "begin", ")", "\n", "if", "t", ".", "observer", "!=", "nil", "{", "t", ".", "observer", ".", "Observe"...
// ObserveDuration records the duration passed since the Timer was created with // NewTimer. It calls the Observe method of the Observer provided during // construction with the duration in seconds as an argument. The observed // duration is also returned. ObserveDuration is usually called with a defer // statement. // // Note that this method is only guaranteed to never observe negative durations // if used with Go1.9+.
[ "ObserveDuration", "records", "the", "duration", "passed", "since", "the", "Timer", "was", "created", "with", "NewTimer", ".", "It", "calls", "the", "Observe", "method", "of", "the", "Observer", "provided", "during", "construction", "with", "the", "duration", "i...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/timer.go#L48-L54
train
prometheus/client_golang
prometheus/promhttp/instrument_server.go
InstrumentHandlerInFlight
func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { g.Inc() defer g.Dec() next.ServeHTTP(w, r) }) }
go
func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { g.Inc() defer g.Dec() next.ServeHTTP(w, r) }) }
[ "func", "InstrumentHandlerInFlight", "(", "g", "prometheus", ".", "Gauge", ",", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "...
// InstrumentHandlerInFlight is a middleware that wraps the provided // http.Handler. It sets the provided prometheus.Gauge to the number of // requests currently handled by the wrapped http.Handler. // // See the example for InstrumentHandlerDuration for example usage.
[ "InstrumentHandlerInFlight", "is", "a", "middleware", "that", "wraps", "the", "provided", "http", ".", "Handler", ".", "It", "sets", "the", "provided", "prometheus", ".", "Gauge", "to", "the", "number", "of", "requests", "currently", "handled", "by", "the", "w...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promhttp/instrument_server.go#L36-L42
train
prometheus/client_golang
prometheus/vec.go
newMetricVec
func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec { return &metricVec{ metricMap: &metricMap{ metrics: map[uint64][]metricWithLabelValues{}, desc: desc, newMetric: newMetric, }, hashAdd: hashAdd, hashAddByte: hashAddByte, } }
go
func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec { return &metricVec{ metricMap: &metricMap{ metrics: map[uint64][]metricWithLabelValues{}, desc: desc, newMetric: newMetric, }, hashAdd: hashAdd, hashAddByte: hashAddByte, } }
[ "func", "newMetricVec", "(", "desc", "*", "Desc", ",", "newMetric", "func", "(", "lvs", "...", "string", ")", "Metric", ")", "*", "metricVec", "{", "return", "&", "metricVec", "{", "metricMap", ":", "&", "metricMap", "{", "metrics", ":", "map", "[", "u...
// newMetricVec returns an initialized metricVec.
[ "newMetricVec", "returns", "an", "initialized", "metricVec", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/vec.go#L39-L49
train
prometheus/client_golang
prometheus/vec.go
Reset
func (m *metricMap) Reset() { m.mtx.Lock() defer m.mtx.Unlock() for h := range m.metrics { delete(m.metrics, h) } }
go
func (m *metricMap) Reset() { m.mtx.Lock() defer m.mtx.Unlock() for h := range m.metrics { delete(m.metrics, h) } }
[ "func", "(", "m", "*", "metricMap", ")", "Reset", "(", ")", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx", ".", "Unlock", "(", ")", "\n", "for", "h", ":=", "range", "m", ".", "metrics", "{", "delete", "(", "m", ...
// Reset deletes all metrics in this vector.
[ "Reset", "deletes", "all", "metrics", "in", "this", "vector", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/vec.go#L238-L245
train
prometheus/client_golang
prometheus/vec.go
deleteByHashWithLabelValues
func (m *metricMap) deleteByHashWithLabelValues( h uint64, lvs []string, curry []curriedLabelValue, ) bool { m.mtx.Lock() defer m.mtx.Unlock() metrics, ok := m.metrics[h] if !ok { return false } i := findMetricWithLabelValues(metrics, lvs, curry) if i >= len(metrics) { return false } if len(metrics) > 1 { m.metrics[h] = append(metrics[:i], metrics[i+1:]...) } else { delete(m.metrics, h) } return true }
go
func (m *metricMap) deleteByHashWithLabelValues( h uint64, lvs []string, curry []curriedLabelValue, ) bool { m.mtx.Lock() defer m.mtx.Unlock() metrics, ok := m.metrics[h] if !ok { return false } i := findMetricWithLabelValues(metrics, lvs, curry) if i >= len(metrics) { return false } if len(metrics) > 1 { m.metrics[h] = append(metrics[:i], metrics[i+1:]...) } else { delete(m.metrics, h) } return true }
[ "func", "(", "m", "*", "metricMap", ")", "deleteByHashWithLabelValues", "(", "h", "uint64", ",", "lvs", "[", "]", "string", ",", "curry", "[", "]", "curriedLabelValue", ",", ")", "bool", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m"...
// deleteByHashWithLabelValues removes the metric from the hash bucket h. If // there are multiple matches in the bucket, use lvs to select a metric and // remove only that metric.
[ "deleteByHashWithLabelValues", "removes", "the", "metric", "from", "the", "hash", "bucket", "h", ".", "If", "there", "are", "multiple", "matches", "in", "the", "bucket", "use", "lvs", "to", "select", "a", "metric", "and", "remove", "only", "that", "metric", ...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/vec.go#L250-L272
train
prometheus/client_golang
prometheus/vec.go
deleteByHashWithLabels
func (m *metricMap) deleteByHashWithLabels( h uint64, labels Labels, curry []curriedLabelValue, ) bool { m.mtx.Lock() defer m.mtx.Unlock() metrics, ok := m.metrics[h] if !ok { return false } i := findMetricWithLabels(m.desc, metrics, labels, curry) if i >= len(metrics) { return false } if len(metrics) > 1 { m.metrics[h] = append(metrics[:i], metrics[i+1:]...) } else { delete(m.metrics, h) } return true }
go
func (m *metricMap) deleteByHashWithLabels( h uint64, labels Labels, curry []curriedLabelValue, ) bool { m.mtx.Lock() defer m.mtx.Unlock() metrics, ok := m.metrics[h] if !ok { return false } i := findMetricWithLabels(m.desc, metrics, labels, curry) if i >= len(metrics) { return false } if len(metrics) > 1 { m.metrics[h] = append(metrics[:i], metrics[i+1:]...) } else { delete(m.metrics, h) } return true }
[ "func", "(", "m", "*", "metricMap", ")", "deleteByHashWithLabels", "(", "h", "uint64", ",", "labels", "Labels", ",", "curry", "[", "]", "curriedLabelValue", ",", ")", "bool", "{", "m", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mtx"...
// deleteByHashWithLabels removes the metric from the hash bucket h. If there // are multiple matches in the bucket, use lvs to select a metric and remove // only that metric.
[ "deleteByHashWithLabels", "removes", "the", "metric", "from", "the", "hash", "bucket", "h", ".", "If", "there", "are", "multiple", "matches", "in", "the", "bucket", "use", "lvs", "to", "select", "a", "metric", "and", "remove", "only", "that", "metric", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/vec.go#L277-L298
train
prometheus/client_golang
prometheus/vec.go
getMetricWithHashAndLabelValues
func (m *metricMap) getMetricWithHashAndLabelValues( h uint64, lvs []string, curry []curriedLabelValue, ) (Metric, bool) { metrics, ok := m.metrics[h] if ok { if i := findMetricWithLabelValues(metrics, lvs, curry); i < len(metrics) { return metrics[i].metric, true } } return nil, false }
go
func (m *metricMap) getMetricWithHashAndLabelValues( h uint64, lvs []string, curry []curriedLabelValue, ) (Metric, bool) { metrics, ok := m.metrics[h] if ok { if i := findMetricWithLabelValues(metrics, lvs, curry); i < len(metrics) { return metrics[i].metric, true } } return nil, false }
[ "func", "(", "m", "*", "metricMap", ")", "getMetricWithHashAndLabelValues", "(", "h", "uint64", ",", "lvs", "[", "]", "string", ",", "curry", "[", "]", "curriedLabelValue", ",", ")", "(", "Metric", ",", "bool", ")", "{", "metrics", ",", "ok", ":=", "m"...
// getMetricWithHashAndLabelValues gets a metric while handling possible // collisions in the hash space. Must be called while holding the read mutex.
[ "getMetricWithHashAndLabelValues", "gets", "a", "metric", "while", "handling", "possible", "collisions", "in", "the", "hash", "space", ".", "Must", "be", "called", "while", "holding", "the", "read", "mutex", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/vec.go#L352-L362
train
prometheus/client_golang
prometheus/vec.go
getMetricWithHashAndLabels
func (m *metricMap) getMetricWithHashAndLabels( h uint64, labels Labels, curry []curriedLabelValue, ) (Metric, bool) { metrics, ok := m.metrics[h] if ok { if i := findMetricWithLabels(m.desc, metrics, labels, curry); i < len(metrics) { return metrics[i].metric, true } } return nil, false }
go
func (m *metricMap) getMetricWithHashAndLabels( h uint64, labels Labels, curry []curriedLabelValue, ) (Metric, bool) { metrics, ok := m.metrics[h] if ok { if i := findMetricWithLabels(m.desc, metrics, labels, curry); i < len(metrics) { return metrics[i].metric, true } } return nil, false }
[ "func", "(", "m", "*", "metricMap", ")", "getMetricWithHashAndLabels", "(", "h", "uint64", ",", "labels", "Labels", ",", "curry", "[", "]", "curriedLabelValue", ",", ")", "(", "Metric", ",", "bool", ")", "{", "metrics", ",", "ok", ":=", "m", ".", "metr...
// getMetricWithHashAndLabels gets a metric while handling possible collisions in // the hash space. Must be called while holding read mutex.
[ "getMetricWithHashAndLabels", "gets", "a", "metric", "while", "handling", "possible", "collisions", "in", "the", "hash", "space", ".", "Must", "be", "called", "while", "holding", "read", "mutex", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/vec.go#L366-L376
train
prometheus/client_golang
prometheus/summary.go
asyncFlush
func (s *summary) asyncFlush(now time.Time) { s.mtx.Lock() s.swapBufs(now) // Unblock the original goroutine that was responsible for the mutation // that triggered the compaction. But hold onto the global non-buffer // state mutex until the operation finishes. go func() { s.flushColdBuf() s.mtx.Unlock() }() }
go
func (s *summary) asyncFlush(now time.Time) { s.mtx.Lock() s.swapBufs(now) // Unblock the original goroutine that was responsible for the mutation // that triggered the compaction. But hold onto the global non-buffer // state mutex until the operation finishes. go func() { s.flushColdBuf() s.mtx.Unlock() }() }
[ "func", "(", "s", "*", "summary", ")", "asyncFlush", "(", "now", "time", ".", "Time", ")", "{", "s", ".", "mtx", ".", "Lock", "(", ")", "\n", "s", ".", "swapBufs", "(", "now", ")", "\n", "go", "func", "(", ")", "{", "s", ".", "flushColdBuf", ...
// asyncFlush needs bufMtx locked.
[ "asyncFlush", "needs", "bufMtx", "locked", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/summary.go#L347-L358
train
prometheus/client_golang
prometheus/summary.go
maybeRotateStreams
func (s *summary) maybeRotateStreams() { for !s.hotBufExpTime.Equal(s.headStreamExpTime) { s.headStream.Reset() s.headStreamIdx++ if s.headStreamIdx >= len(s.streams) { s.headStreamIdx = 0 } s.headStream = s.streams[s.headStreamIdx] s.headStreamExpTime = s.headStreamExpTime.Add(s.streamDuration) } }
go
func (s *summary) maybeRotateStreams() { for !s.hotBufExpTime.Equal(s.headStreamExpTime) { s.headStream.Reset() s.headStreamIdx++ if s.headStreamIdx >= len(s.streams) { s.headStreamIdx = 0 } s.headStream = s.streams[s.headStreamIdx] s.headStreamExpTime = s.headStreamExpTime.Add(s.streamDuration) } }
[ "func", "(", "s", "*", "summary", ")", "maybeRotateStreams", "(", ")", "{", "for", "!", "s", ".", "hotBufExpTime", ".", "Equal", "(", "s", ".", "headStreamExpTime", ")", "{", "s", ".", "headStream", ".", "Reset", "(", ")", "\n", "s", ".", "headStream...
// rotateStreams needs mtx AND bufMtx locked.
[ "rotateStreams", "needs", "mtx", "AND", "bufMtx", "locked", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/summary.go#L361-L371
train
prometheus/client_golang
prometheus/summary.go
flushColdBuf
func (s *summary) flushColdBuf() { for _, v := range s.coldBuf { for _, stream := range s.streams { stream.Insert(v) } s.cnt++ s.sum += v } s.coldBuf = s.coldBuf[0:0] s.maybeRotateStreams() }
go
func (s *summary) flushColdBuf() { for _, v := range s.coldBuf { for _, stream := range s.streams { stream.Insert(v) } s.cnt++ s.sum += v } s.coldBuf = s.coldBuf[0:0] s.maybeRotateStreams() }
[ "func", "(", "s", "*", "summary", ")", "flushColdBuf", "(", ")", "{", "for", "_", ",", "v", ":=", "range", "s", ".", "coldBuf", "{", "for", "_", ",", "stream", ":=", "range", "s", ".", "streams", "{", "stream", ".", "Insert", "(", "v", ")", "\n...
// flushColdBuf needs mtx locked.
[ "flushColdBuf", "needs", "mtx", "locked", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/summary.go#L374-L384
train
prometheus/client_golang
prometheus/summary.go
swapBufs
func (s *summary) swapBufs(now time.Time) { if len(s.coldBuf) != 0 { panic("coldBuf is not empty") } s.hotBuf, s.coldBuf = s.coldBuf, s.hotBuf // hotBuf is now empty and gets new expiration set. for now.After(s.hotBufExpTime) { s.hotBufExpTime = s.hotBufExpTime.Add(s.streamDuration) } }
go
func (s *summary) swapBufs(now time.Time) { if len(s.coldBuf) != 0 { panic("coldBuf is not empty") } s.hotBuf, s.coldBuf = s.coldBuf, s.hotBuf // hotBuf is now empty and gets new expiration set. for now.After(s.hotBufExpTime) { s.hotBufExpTime = s.hotBufExpTime.Add(s.streamDuration) } }
[ "func", "(", "s", "*", "summary", ")", "swapBufs", "(", "now", "time", ".", "Time", ")", "{", "if", "len", "(", "s", ".", "coldBuf", ")", "!=", "0", "{", "panic", "(", "\"coldBuf is not empty\"", ")", "\n", "}", "\n", "s", ".", "hotBuf", ",", "s"...
// swapBufs needs mtx AND bufMtx locked, coldBuf must be empty.
[ "swapBufs", "needs", "mtx", "AND", "bufMtx", "locked", "coldBuf", "must", "be", "empty", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/summary.go#L387-L396
train
prometheus/client_golang
prometheus/summary.go
MustNewConstSummary
func MustNewConstSummary( desc *Desc, count uint64, sum float64, quantiles map[float64]float64, labelValues ...string, ) Metric { m, err := NewConstSummary(desc, count, sum, quantiles, labelValues...) if err != nil { panic(err) } return m }
go
func MustNewConstSummary( desc *Desc, count uint64, sum float64, quantiles map[float64]float64, labelValues ...string, ) Metric { m, err := NewConstSummary(desc, count, sum, quantiles, labelValues...) if err != nil { panic(err) } return m }
[ "func", "MustNewConstSummary", "(", "desc", "*", "Desc", ",", "count", "uint64", ",", "sum", "float64", ",", "quantiles", "map", "[", "float64", "]", "float64", ",", "labelValues", "...", "string", ",", ")", "Metric", "{", "m", ",", "err", ":=", "NewCons...
// MustNewConstSummary is a version of NewConstSummary that panics where // NewConstMetric would have returned an error.
[ "MustNewConstSummary", "is", "a", "version", "of", "NewConstSummary", "that", "panics", "where", "NewConstMetric", "would", "have", "returned", "an", "error", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/summary.go#L737-L749
train
prometheus/client_golang
prometheus/promhttp/instrument_client.go
InstrumentRoundTripperInFlight
func InstrumentRoundTripperInFlight(gauge prometheus.Gauge, next http.RoundTripper) RoundTripperFunc { return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { gauge.Inc() defer gauge.Dec() return next.RoundTrip(r) }) }
go
func InstrumentRoundTripperInFlight(gauge prometheus.Gauge, next http.RoundTripper) RoundTripperFunc { return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { gauge.Inc() defer gauge.Dec() return next.RoundTrip(r) }) }
[ "func", "InstrumentRoundTripperInFlight", "(", "gauge", "prometheus", ".", "Gauge", ",", "next", "http", ".", "RoundTripper", ")", "RoundTripperFunc", "{", "return", "RoundTripperFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http",...
// InstrumentRoundTripperInFlight is a middleware that wraps the provided // http.RoundTripper. It sets the provided prometheus.Gauge to the number of // requests currently handled by the wrapped http.RoundTripper. // // See the example for ExampleInstrumentRoundTripperDuration for example usage.
[ "InstrumentRoundTripperInFlight", "is", "a", "middleware", "that", "wraps", "the", "provided", "http", ".", "RoundTripper", ".", "It", "sets", "the", "provided", "prometheus", ".", "Gauge", "to", "the", "number", "of", "requests", "currently", "handled", "by", "...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promhttp/instrument_client.go#L41-L47
train
prometheus/client_golang
prometheus/counter.go
NewCounterVec
func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &CounterVec{ metricVec: newMetricVec(desc, func(lvs ...string) Metric { if len(lvs) != len(desc.variableLabels) { panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, lvs)) } result := &counter{desc: desc, labelPairs: makeLabelPairs(desc, lvs)} result.init(result) // Init self-collection. return result }), } }
go
func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &CounterVec{ metricVec: newMetricVec(desc, func(lvs ...string) Metric { if len(lvs) != len(desc.variableLabels) { panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, lvs)) } result := &counter{desc: desc, labelPairs: makeLabelPairs(desc, lvs)} result.init(result) // Init self-collection. return result }), } }
[ "func", "NewCounterVec", "(", "opts", "CounterOpts", ",", "labelNames", "[", "]", "string", ")", "*", "CounterVec", "{", "desc", ":=", "NewDesc", "(", "BuildFQName", "(", "opts", ".", "Namespace", ",", "opts", ".", "Subsystem", ",", "opts", ".", "Name", ...
// NewCounterVec creates a new CounterVec based on the provided CounterOpts and // partitioned by the given label names.
[ "NewCounterVec", "creates", "a", "new", "CounterVec", "based", "on", "the", "provided", "CounterOpts", "and", "partitioned", "by", "the", "given", "label", "names", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/counter.go#L129-L146
train
prometheus/client_golang
api/client.go
DoGetFallback
func DoGetFallback(c Client, ctx context.Context, u *url.URL, args url.Values) (*http.Response, []byte, error) { req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(args.Encode())) if err != nil { return nil, nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, body, err := c.Do(ctx, req) if resp != nil && resp.StatusCode == http.StatusMethodNotAllowed { u.RawQuery = args.Encode() req, err = http.NewRequest(http.MethodGet, u.String(), nil) if err != nil { return nil, nil, err } } else { return resp, body, err } return c.Do(ctx, req) }
go
func DoGetFallback(c Client, ctx context.Context, u *url.URL, args url.Values) (*http.Response, []byte, error) { req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(args.Encode())) if err != nil { return nil, nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, body, err := c.Do(ctx, req) if resp != nil && resp.StatusCode == http.StatusMethodNotAllowed { u.RawQuery = args.Encode() req, err = http.NewRequest(http.MethodGet, u.String(), nil) if err != nil { return nil, nil, err } } else { return resp, body, err } return c.Do(ctx, req) }
[ "func", "DoGetFallback", "(", "c", "Client", ",", "ctx", "context", ".", "Context", ",", "u", "*", "url", ".", "URL", ",", "args", "url", ".", "Values", ")", "(", "*", "http", ".", "Response", ",", "[", "]", "byte", ",", "error", ")", "{", "req",...
// DoGetFallback will attempt to do the request as-is, and on a 405 it will fallback to a GET request.
[ "DoGetFallback", "will", "attempt", "to", "do", "the", "request", "as", "-", "is", "and", "on", "a", "405", "it", "will", "fallback", "to", "a", "GET", "request", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/api/client.go#L62-L81
train
prometheus/client_golang
api/client.go
NewClient
func NewClient(cfg Config) (Client, error) { u, err := url.Parse(cfg.Address) if err != nil { return nil, err } u.Path = strings.TrimRight(u.Path, "/") return &httpClient{ endpoint: u, client: http.Client{Transport: cfg.roundTripper()}, }, nil }
go
func NewClient(cfg Config) (Client, error) { u, err := url.Parse(cfg.Address) if err != nil { return nil, err } u.Path = strings.TrimRight(u.Path, "/") return &httpClient{ endpoint: u, client: http.Client{Transport: cfg.roundTripper()}, }, nil }
[ "func", "NewClient", "(", "cfg", "Config", ")", "(", "Client", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "cfg", ".", "Address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n...
// NewClient returns a new Client. // // It is safe to use the returned Client from multiple goroutines.
[ "NewClient", "returns", "a", "new", "Client", ".", "It", "is", "safe", "to", "use", "the", "returned", "Client", "from", "multiple", "goroutines", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/api/client.go#L86-L97
train
prometheus/client_golang
prometheus/fnv.go
hashAdd
func hashAdd(h uint64, s string) uint64 { for i := 0; i < len(s); i++ { h ^= uint64(s[i]) h *= prime64 } return h }
go
func hashAdd(h uint64, s string) uint64 { for i := 0; i < len(s); i++ { h ^= uint64(s[i]) h *= prime64 } return h }
[ "func", "hashAdd", "(", "h", "uint64", ",", "s", "string", ")", "uint64", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "h", "^=", "uint64", "(", "s", "[", "i", "]", ")", "\n", "h", "*=", "prime64", ...
// hashAdd adds a string to a fnv64a hash value, returning the updated hash.
[ "hashAdd", "adds", "a", "string", "to", "a", "fnv64a", "hash", "value", "returning", "the", "updated", "hash", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/fnv.go#L29-L35
train
prometheus/client_golang
prometheus/fnv.go
hashAddByte
func hashAddByte(h uint64, b byte) uint64 { h ^= uint64(b) h *= prime64 return h }
go
func hashAddByte(h uint64, b byte) uint64 { h ^= uint64(b) h *= prime64 return h }
[ "func", "hashAddByte", "(", "h", "uint64", ",", "b", "byte", ")", "uint64", "{", "h", "^=", "uint64", "(", "b", ")", "\n", "h", "*=", "prime64", "\n", "return", "h", "\n", "}" ]
// hashAddByte adds a byte to a fnv64a hash value, returning the updated hash.
[ "hashAddByte", "adds", "a", "byte", "to", "a", "fnv64a", "hash", "value", "returning", "the", "updated", "hash", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/fnv.go#L38-L42
train
prometheus/client_golang
prometheus/push/push.go
Gatherer
func (p *Pusher) Gatherer(g prometheus.Gatherer) *Pusher { p.gatherers = append(p.gatherers, g) return p }
go
func (p *Pusher) Gatherer(g prometheus.Gatherer) *Pusher { p.gatherers = append(p.gatherers, g) return p }
[ "func", "(", "p", "*", "Pusher", ")", "Gatherer", "(", "g", "prometheus", ".", "Gatherer", ")", "*", "Pusher", "{", "p", ".", "gatherers", "=", "append", "(", "p", ".", "gatherers", ",", "g", ")", "\n", "return", "p", "\n", "}" ]
// Gatherer adds a Gatherer to the Pusher, from which metrics will be gathered // to push them to the Pushgateway. The gathered metrics must not contain a job // label of their own. // // For convenience, this method returns a pointer to the Pusher itself.
[ "Gatherer", "adds", "a", "Gatherer", "to", "the", "Pusher", "from", "which", "metrics", "will", "be", "gathered", "to", "push", "them", "to", "the", "Pushgateway", ".", "The", "gathered", "metrics", "must", "not", "contain", "a", "job", "label", "of", "the...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/push/push.go#L130-L133
train
prometheus/client_golang
prometheus/push/push.go
Collector
func (p *Pusher) Collector(c prometheus.Collector) *Pusher { if p.error == nil { p.error = p.registerer.Register(c) } return p }
go
func (p *Pusher) Collector(c prometheus.Collector) *Pusher { if p.error == nil { p.error = p.registerer.Register(c) } return p }
[ "func", "(", "p", "*", "Pusher", ")", "Collector", "(", "c", "prometheus", ".", "Collector", ")", "*", "Pusher", "{", "if", "p", ".", "error", "==", "nil", "{", "p", ".", "error", "=", "p", ".", "registerer", ".", "Register", "(", "c", ")", "\n",...
// Collector adds a Collector to the Pusher, from which metrics will be // collected to push them to the Pushgateway. The collected metrics must not // contain a job label of their own. // // For convenience, this method returns a pointer to the Pusher itself.
[ "Collector", "adds", "a", "Collector", "to", "the", "Pusher", "from", "which", "metrics", "will", "be", "collected", "to", "push", "them", "to", "the", "Pushgateway", ".", "The", "collected", "metrics", "must", "not", "contain", "a", "job", "label", "of", ...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/push/push.go#L140-L145
train
prometheus/client_golang
prometheus/push/push.go
Client
func (p *Pusher) Client(c *http.Client) *Pusher { p.client = c return p }
go
func (p *Pusher) Client(c *http.Client) *Pusher { p.client = c return p }
[ "func", "(", "p", "*", "Pusher", ")", "Client", "(", "c", "*", "http", ".", "Client", ")", "*", "Pusher", "{", "p", ".", "client", "=", "c", "\n", "return", "p", "\n", "}" ]
// Client sets a custom HTTP client for the Pusher. For convenience, this method // returns a pointer to the Pusher itself.
[ "Client", "sets", "a", "custom", "HTTP", "client", "for", "the", "Pusher", ".", "For", "convenience", "this", "method", "returns", "a", "pointer", "to", "the", "Pusher", "itself", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/push/push.go#L173-L176
train
prometheus/client_golang
prometheus/push/push.go
BasicAuth
func (p *Pusher) BasicAuth(username, password string) *Pusher { p.useBasicAuth = true p.username = username p.password = password return p }
go
func (p *Pusher) BasicAuth(username, password string) *Pusher { p.useBasicAuth = true p.username = username p.password = password return p }
[ "func", "(", "p", "*", "Pusher", ")", "BasicAuth", "(", "username", ",", "password", "string", ")", "*", "Pusher", "{", "p", ".", "useBasicAuth", "=", "true", "\n", "p", ".", "username", "=", "username", "\n", "p", ".", "password", "=", "password", "...
// BasicAuth configures the Pusher to use HTTP Basic Authentication with the // provided username and password. For convenience, this method returns a // pointer to the Pusher itself.
[ "BasicAuth", "configures", "the", "Pusher", "to", "use", "HTTP", "Basic", "Authentication", "with", "the", "provided", "username", "and", "password", ".", "For", "convenience", "this", "method", "returns", "a", "pointer", "to", "the", "Pusher", "itself", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/push/push.go#L181-L186
train
prometheus/client_golang
prometheus/push/push.go
Format
func (p *Pusher) Format(format expfmt.Format) *Pusher { p.expfmt = format return p }
go
func (p *Pusher) Format(format expfmt.Format) *Pusher { p.expfmt = format return p }
[ "func", "(", "p", "*", "Pusher", ")", "Format", "(", "format", "expfmt", ".", "Format", ")", "*", "Pusher", "{", "p", ".", "expfmt", "=", "format", "\n", "return", "p", "\n", "}" ]
// Format configures the Pusher to use an encoding format given by the // provided expfmt.Format. The default format is expfmt.FmtProtoDelim and // should be used with the standard Prometheus Pushgateway. Custom // implementations may require different formats. For convenience, this // method returns a pointer to the Pusher itself.
[ "Format", "configures", "the", "Pusher", "to", "use", "an", "encoding", "format", "given", "by", "the", "provided", "expfmt", ".", "Format", ".", "The", "default", "format", "is", "expfmt", ".", "FmtProtoDelim", "and", "should", "be", "used", "with", "the", ...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/push/push.go#L193-L196
train
prometheus/client_golang
prometheus/internal/metric.go
NormalizeMetricFamilies
func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily { for _, mf := range metricFamiliesByName { sort.Sort(metricSorter(mf.Metric)) } names := make([]string, 0, len(metricFamiliesByName)) for name, mf := range metricFamiliesByName { if len(mf.Metric) > 0 { names = append(names, name) } } sort.Strings(names) result := make([]*dto.MetricFamily, 0, len(names)) for _, name := range names { result = append(result, metricFamiliesByName[name]) } return result }
go
func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily { for _, mf := range metricFamiliesByName { sort.Sort(metricSorter(mf.Metric)) } names := make([]string, 0, len(metricFamiliesByName)) for name, mf := range metricFamiliesByName { if len(mf.Metric) > 0 { names = append(names, name) } } sort.Strings(names) result := make([]*dto.MetricFamily, 0, len(names)) for _, name := range names { result = append(result, metricFamiliesByName[name]) } return result }
[ "func", "NormalizeMetricFamilies", "(", "metricFamiliesByName", "map", "[", "string", "]", "*", "dto", ".", "MetricFamily", ")", "[", "]", "*", "dto", ".", "MetricFamily", "{", "for", "_", ",", "mf", ":=", "range", "metricFamiliesByName", "{", "sort", ".", ...
// NormalizeMetricFamilies returns a MetricFamily slice with empty // MetricFamilies pruned and the remaining MetricFamilies sorted by name within // the slice, with the contained Metrics sorted within each MetricFamily.
[ "NormalizeMetricFamilies", "returns", "a", "MetricFamily", "slice", "with", "empty", "MetricFamilies", "pruned", "and", "the", "remaining", "MetricFamilies", "sorted", "by", "name", "within", "the", "slice", "with", "the", "contained", "Metrics", "sorted", "within", ...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/internal/metric.go#L69-L85
train
prometheus/client_golang
prometheus/histogram.go
LinearBuckets
func LinearBuckets(start, width float64, count int) []float64 { if count < 1 { panic("LinearBuckets needs a positive count") } buckets := make([]float64, count) for i := range buckets { buckets[i] = start start += width } return buckets }
go
func LinearBuckets(start, width float64, count int) []float64 { if count < 1 { panic("LinearBuckets needs a positive count") } buckets := make([]float64, count) for i := range buckets { buckets[i] = start start += width } return buckets }
[ "func", "LinearBuckets", "(", "start", ",", "width", "float64", ",", "count", "int", ")", "[", "]", "float64", "{", "if", "count", "<", "1", "{", "panic", "(", "\"LinearBuckets needs a positive count\"", ")", "\n", "}", "\n", "buckets", ":=", "make", "(", ...
// LinearBuckets creates 'count' buckets, each 'width' wide, where the lowest // bucket has an upper bound of 'start'. The final +Inf bucket is not counted // and not included in the returned slice. The returned slice is meant to be // used for the Buckets field of HistogramOpts. // // The function panics if 'count' is zero or negative.
[ "LinearBuckets", "creates", "count", "buckets", "each", "width", "wide", "where", "the", "lowest", "bucket", "has", "an", "upper", "bound", "of", "start", ".", "The", "final", "+", "Inf", "bucket", "is", "not", "counted", "and", "not", "included", "in", "t...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/histogram.go#L74-L84
train
prometheus/client_golang
prometheus/histogram.go
ExponentialBuckets
func ExponentialBuckets(start, factor float64, count int) []float64 { if count < 1 { panic("ExponentialBuckets needs a positive count") } if start <= 0 { panic("ExponentialBuckets needs a positive start value") } if factor <= 1 { panic("ExponentialBuckets needs a factor greater than 1") } buckets := make([]float64, count) for i := range buckets { buckets[i] = start start *= factor } return buckets }
go
func ExponentialBuckets(start, factor float64, count int) []float64 { if count < 1 { panic("ExponentialBuckets needs a positive count") } if start <= 0 { panic("ExponentialBuckets needs a positive start value") } if factor <= 1 { panic("ExponentialBuckets needs a factor greater than 1") } buckets := make([]float64, count) for i := range buckets { buckets[i] = start start *= factor } return buckets }
[ "func", "ExponentialBuckets", "(", "start", ",", "factor", "float64", ",", "count", "int", ")", "[", "]", "float64", "{", "if", "count", "<", "1", "{", "panic", "(", "\"ExponentialBuckets needs a positive count\"", ")", "\n", "}", "\n", "if", "start", "<=", ...
// ExponentialBuckets creates 'count' buckets, where the lowest bucket has an // upper bound of 'start' and each following bucket's upper bound is 'factor' // times the previous bucket's upper bound. The final +Inf bucket is not counted // and not included in the returned slice. The returned slice is meant to be // used for the Buckets field of HistogramOpts. // // The function panics if 'count' is 0 or negative, if 'start' is 0 or negative, // or if 'factor' is less than or equal 1.
[ "ExponentialBuckets", "creates", "count", "buckets", "where", "the", "lowest", "bucket", "has", "an", "upper", "bound", "of", "start", "and", "each", "following", "bucket", "s", "upper", "bound", "is", "factor", "times", "the", "previous", "bucket", "s", "uppe...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/histogram.go#L94-L110
train
prometheus/client_golang
prometheus/histogram.go
NewHistogram
func NewHistogram(opts HistogramOpts) Histogram { return newHistogram( NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, nil, opts.ConstLabels, ), opts, ) }
go
func NewHistogram(opts HistogramOpts) Histogram { return newHistogram( NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, nil, opts.ConstLabels, ), opts, ) }
[ "func", "NewHistogram", "(", "opts", "HistogramOpts", ")", "Histogram", "{", "return", "newHistogram", "(", "NewDesc", "(", "BuildFQName", "(", "opts", ".", "Namespace", ",", "opts", ".", "Subsystem", ",", "opts", ".", "Name", ")", ",", "opts", ".", "Help"...
// NewHistogram creates a new Histogram based on the provided HistogramOpts. It // panics if the buckets in HistogramOpts are not in strictly increasing order.
[ "NewHistogram", "creates", "a", "new", "Histogram", "based", "on", "the", "provided", "HistogramOpts", ".", "It", "panics", "if", "the", "buckets", "in", "HistogramOpts", "are", "not", "in", "strictly", "increasing", "order", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/histogram.go#L154-L164
train
prometheus/client_golang
prometheus/histogram.go
NewHistogramVec
func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &HistogramVec{ metricVec: newMetricVec(desc, func(lvs ...string) Metric { return newHistogram(desc, opts, lvs...) }), } }
go
func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &HistogramVec{ metricVec: newMetricVec(desc, func(lvs ...string) Metric { return newHistogram(desc, opts, lvs...) }), } }
[ "func", "NewHistogramVec", "(", "opts", "HistogramOpts", ",", "labelNames", "[", "]", "string", ")", "*", "HistogramVec", "{", "desc", ":=", "NewDesc", "(", "BuildFQName", "(", "opts", ".", "Namespace", ",", "opts", ".", "Subsystem", ",", "opts", ".", "Nam...
// NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and // partitioned by the given label names.
[ "NewHistogramVec", "creates", "a", "new", "HistogramVec", "based", "on", "the", "provided", "HistogramOpts", "and", "partitioned", "by", "the", "given", "label", "names", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/histogram.go#L366-L378
train
prometheus/client_golang
prometheus/histogram.go
MustNewConstHistogram
func MustNewConstHistogram( desc *Desc, count uint64, sum float64, buckets map[float64]uint64, labelValues ...string, ) Metric { m, err := NewConstHistogram(desc, count, sum, buckets, labelValues...) if err != nil { panic(err) } return m }
go
func MustNewConstHistogram( desc *Desc, count uint64, sum float64, buckets map[float64]uint64, labelValues ...string, ) Metric { m, err := NewConstHistogram(desc, count, sum, buckets, labelValues...) if err != nil { panic(err) } return m }
[ "func", "MustNewConstHistogram", "(", "desc", "*", "Desc", ",", "count", "uint64", ",", "sum", "float64", ",", "buckets", "map", "[", "float64", "]", "uint64", ",", "labelValues", "...", "string", ",", ")", "Metric", "{", "m", ",", "err", ":=", "NewConst...
// MustNewConstHistogram is a version of NewConstHistogram that panics where // NewConstMetric would have returned an error.
[ "MustNewConstHistogram", "is", "a", "version", "of", "NewConstHistogram", "that", "panics", "where", "NewConstMetric", "would", "have", "returned", "an", "error", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/histogram.go#L560-L572
train
prometheus/client_golang
prometheus/graphite/bridge.go
Push
func (b *Bridge) Push() error { mfs, err := b.g.Gather() if err != nil || len(mfs) == 0 { switch b.errorHandling { case AbortOnError: return err case ContinueOnError: if b.logger != nil { b.logger.Println("continue on error:", err) } default: panic("unrecognized error handling value") } } conn, err := net.DialTimeout("tcp", b.url, b.timeout) if err != nil { return err } defer conn.Close() return writeMetrics(conn, mfs, b.prefix, model.Now()) }
go
func (b *Bridge) Push() error { mfs, err := b.g.Gather() if err != nil || len(mfs) == 0 { switch b.errorHandling { case AbortOnError: return err case ContinueOnError: if b.logger != nil { b.logger.Println("continue on error:", err) } default: panic("unrecognized error handling value") } } conn, err := net.DialTimeout("tcp", b.url, b.timeout) if err != nil { return err } defer conn.Close() return writeMetrics(conn, mfs, b.prefix, model.Now()) }
[ "func", "(", "b", "*", "Bridge", ")", "Push", "(", ")", "error", "{", "mfs", ",", "err", ":=", "b", ".", "g", ".", "Gather", "(", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "mfs", ")", "==", "0", "{", "switch", "b", ".", "errorH...
// Push pushes Prometheus metrics to the configured Graphite server.
[ "Push", "pushes", "Prometheus", "metrics", "to", "the", "configured", "Graphite", "server", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/graphite/bridge.go#L160-L182
train
prometheus/client_golang
prometheus/promauto/auto.go
NewCounter
func NewCounter(opts prometheus.CounterOpts) prometheus.Counter { c := prometheus.NewCounter(opts) prometheus.MustRegister(c) return c }
go
func NewCounter(opts prometheus.CounterOpts) prometheus.Counter { c := prometheus.NewCounter(opts) prometheus.MustRegister(c) return c }
[ "func", "NewCounter", "(", "opts", "prometheus", ".", "CounterOpts", ")", "prometheus", ".", "Counter", "{", "c", ":=", "prometheus", ".", "NewCounter", "(", "opts", ")", "\n", "prometheus", ".", "MustRegister", "(", "c", ")", "\n", "return", "c", "\n", ...
// NewCounter works like the function of the same name in the prometheus package // but it automatically registers the Counter with the // prometheus.DefaultRegisterer. If the registration fails, NewCounter panics.
[ "NewCounter", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "Counter", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "registrati...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L134-L138
train
prometheus/client_golang
prometheus/promauto/auto.go
NewCounterVec
func NewCounterVec(opts prometheus.CounterOpts, labelNames []string) *prometheus.CounterVec { c := prometheus.NewCounterVec(opts, labelNames) prometheus.MustRegister(c) return c }
go
func NewCounterVec(opts prometheus.CounterOpts, labelNames []string) *prometheus.CounterVec { c := prometheus.NewCounterVec(opts, labelNames) prometheus.MustRegister(c) return c }
[ "func", "NewCounterVec", "(", "opts", "prometheus", ".", "CounterOpts", ",", "labelNames", "[", "]", "string", ")", "*", "prometheus", ".", "CounterVec", "{", "c", ":=", "prometheus", ".", "NewCounterVec", "(", "opts", ",", "labelNames", ")", "\n", "promethe...
// NewCounterVec works like the function of the same name in the prometheus // package but it automatically registers the CounterVec with the // prometheus.DefaultRegisterer. If the registration fails, NewCounterVec // panics.
[ "NewCounterVec", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "CounterVec", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "regi...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L144-L148
train
prometheus/client_golang
prometheus/promauto/auto.go
NewCounterFunc
func NewCounterFunc(opts prometheus.CounterOpts, function func() float64) prometheus.CounterFunc { g := prometheus.NewCounterFunc(opts, function) prometheus.MustRegister(g) return g }
go
func NewCounterFunc(opts prometheus.CounterOpts, function func() float64) prometheus.CounterFunc { g := prometheus.NewCounterFunc(opts, function) prometheus.MustRegister(g) return g }
[ "func", "NewCounterFunc", "(", "opts", "prometheus", ".", "CounterOpts", ",", "function", "func", "(", ")", "float64", ")", "prometheus", ".", "CounterFunc", "{", "g", ":=", "prometheus", ".", "NewCounterFunc", "(", "opts", ",", "function", ")", "\n", "prome...
// NewCounterFunc works like the function of the same name in the prometheus // package but it automatically registers the CounterFunc with the // prometheus.DefaultRegisterer. If the registration fails, NewCounterFunc // panics.
[ "NewCounterFunc", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "CounterFunc", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "re...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L154-L158
train
prometheus/client_golang
prometheus/promauto/auto.go
NewGauge
func NewGauge(opts prometheus.GaugeOpts) prometheus.Gauge { g := prometheus.NewGauge(opts) prometheus.MustRegister(g) return g }
go
func NewGauge(opts prometheus.GaugeOpts) prometheus.Gauge { g := prometheus.NewGauge(opts) prometheus.MustRegister(g) return g }
[ "func", "NewGauge", "(", "opts", "prometheus", ".", "GaugeOpts", ")", "prometheus", ".", "Gauge", "{", "g", ":=", "prometheus", ".", "NewGauge", "(", "opts", ")", "\n", "prometheus", ".", "MustRegister", "(", "g", ")", "\n", "return", "g", "\n", "}" ]
// NewGauge works like the function of the same name in the prometheus package // but it automatically registers the Gauge with the // prometheus.DefaultRegisterer. If the registration fails, NewGauge panics.
[ "NewGauge", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "Gauge", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "registration",...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L163-L167
train
prometheus/client_golang
prometheus/promauto/auto.go
NewGaugeVec
func NewGaugeVec(opts prometheus.GaugeOpts, labelNames []string) *prometheus.GaugeVec { g := prometheus.NewGaugeVec(opts, labelNames) prometheus.MustRegister(g) return g }
go
func NewGaugeVec(opts prometheus.GaugeOpts, labelNames []string) *prometheus.GaugeVec { g := prometheus.NewGaugeVec(opts, labelNames) prometheus.MustRegister(g) return g }
[ "func", "NewGaugeVec", "(", "opts", "prometheus", ".", "GaugeOpts", ",", "labelNames", "[", "]", "string", ")", "*", "prometheus", ".", "GaugeVec", "{", "g", ":=", "prometheus", ".", "NewGaugeVec", "(", "opts", ",", "labelNames", ")", "\n", "prometheus", "...
// NewGaugeVec works like the function of the same name in the prometheus // package but it automatically registers the GaugeVec with the // prometheus.DefaultRegisterer. If the registration fails, NewGaugeVec panics.
[ "NewGaugeVec", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "GaugeVec", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "registra...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L172-L176
train
prometheus/client_golang
prometheus/promauto/auto.go
NewGaugeFunc
func NewGaugeFunc(opts prometheus.GaugeOpts, function func() float64) prometheus.GaugeFunc { g := prometheus.NewGaugeFunc(opts, function) prometheus.MustRegister(g) return g }
go
func NewGaugeFunc(opts prometheus.GaugeOpts, function func() float64) prometheus.GaugeFunc { g := prometheus.NewGaugeFunc(opts, function) prometheus.MustRegister(g) return g }
[ "func", "NewGaugeFunc", "(", "opts", "prometheus", ".", "GaugeOpts", ",", "function", "func", "(", ")", "float64", ")", "prometheus", ".", "GaugeFunc", "{", "g", ":=", "prometheus", ".", "NewGaugeFunc", "(", "opts", ",", "function", ")", "\n", "prometheus", ...
// NewGaugeFunc works like the function of the same name in the prometheus // package but it automatically registers the GaugeFunc with the // prometheus.DefaultRegisterer. If the registration fails, NewGaugeFunc panics.
[ "NewGaugeFunc", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "GaugeFunc", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "regist...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L181-L185
train
prometheus/client_golang
prometheus/promauto/auto.go
NewSummary
func NewSummary(opts prometheus.SummaryOpts) prometheus.Summary { s := prometheus.NewSummary(opts) prometheus.MustRegister(s) return s }
go
func NewSummary(opts prometheus.SummaryOpts) prometheus.Summary { s := prometheus.NewSummary(opts) prometheus.MustRegister(s) return s }
[ "func", "NewSummary", "(", "opts", "prometheus", ".", "SummaryOpts", ")", "prometheus", ".", "Summary", "{", "s", ":=", "prometheus", ".", "NewSummary", "(", "opts", ")", "\n", "prometheus", ".", "MustRegister", "(", "s", ")", "\n", "return", "s", "\n", ...
// NewSummary works like the function of the same name in the prometheus package // but it automatically registers the Summary with the // prometheus.DefaultRegisterer. If the registration fails, NewSummary panics.
[ "NewSummary", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "Summary", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "registrati...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L190-L194
train
prometheus/client_golang
prometheus/promauto/auto.go
NewSummaryVec
func NewSummaryVec(opts prometheus.SummaryOpts, labelNames []string) *prometheus.SummaryVec { s := prometheus.NewSummaryVec(opts, labelNames) prometheus.MustRegister(s) return s }
go
func NewSummaryVec(opts prometheus.SummaryOpts, labelNames []string) *prometheus.SummaryVec { s := prometheus.NewSummaryVec(opts, labelNames) prometheus.MustRegister(s) return s }
[ "func", "NewSummaryVec", "(", "opts", "prometheus", ".", "SummaryOpts", ",", "labelNames", "[", "]", "string", ")", "*", "prometheus", ".", "SummaryVec", "{", "s", ":=", "prometheus", ".", "NewSummaryVec", "(", "opts", ",", "labelNames", ")", "\n", "promethe...
// NewSummaryVec works like the function of the same name in the prometheus // package but it automatically registers the SummaryVec with the // prometheus.DefaultRegisterer. If the registration fails, NewSummaryVec // panics.
[ "NewSummaryVec", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "SummaryVec", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "regi...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L200-L204
train
prometheus/client_golang
prometheus/promauto/auto.go
NewHistogram
func NewHistogram(opts prometheus.HistogramOpts) prometheus.Histogram { h := prometheus.NewHistogram(opts) prometheus.MustRegister(h) return h }
go
func NewHistogram(opts prometheus.HistogramOpts) prometheus.Histogram { h := prometheus.NewHistogram(opts) prometheus.MustRegister(h) return h }
[ "func", "NewHistogram", "(", "opts", "prometheus", ".", "HistogramOpts", ")", "prometheus", ".", "Histogram", "{", "h", ":=", "prometheus", ".", "NewHistogram", "(", "opts", ")", "\n", "prometheus", ".", "MustRegister", "(", "h", ")", "\n", "return", "h", ...
// NewHistogram works like the function of the same name in the prometheus // package but it automatically registers the Histogram with the // prometheus.DefaultRegisterer. If the registration fails, NewHistogram panics.
[ "NewHistogram", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "Histogram", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "regist...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L209-L213
train
prometheus/client_golang
prometheus/promauto/auto.go
NewHistogramVec
func NewHistogramVec(opts prometheus.HistogramOpts, labelNames []string) *prometheus.HistogramVec { h := prometheus.NewHistogramVec(opts, labelNames) prometheus.MustRegister(h) return h }
go
func NewHistogramVec(opts prometheus.HistogramOpts, labelNames []string) *prometheus.HistogramVec { h := prometheus.NewHistogramVec(opts, labelNames) prometheus.MustRegister(h) return h }
[ "func", "NewHistogramVec", "(", "opts", "prometheus", ".", "HistogramOpts", ",", "labelNames", "[", "]", "string", ")", "*", "prometheus", ".", "HistogramVec", "{", "h", ":=", "prometheus", ".", "NewHistogramVec", "(", "opts", ",", "labelNames", ")", "\n", "...
// NewHistogramVec works like the function of the same name in the prometheus // package but it automatically registers the HistogramVec with the // prometheus.DefaultRegisterer. If the registration fails, NewHistogramVec // panics.
[ "NewHistogramVec", "works", "like", "the", "function", "of", "the", "same", "name", "in", "the", "prometheus", "package", "but", "it", "automatically", "registers", "the", "HistogramVec", "with", "the", "prometheus", ".", "DefaultRegisterer", ".", "If", "the", "...
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/promauto/auto.go#L219-L223
train
prometheus/client_golang
prometheus/registry.go
NewRegistry
func NewRegistry() *Registry { return &Registry{ collectorsByID: map[uint64]Collector{}, descIDs: map[uint64]struct{}{}, dimHashesByName: map[string]uint64{}, } }
go
func NewRegistry() *Registry { return &Registry{ collectorsByID: map[uint64]Collector{}, descIDs: map[uint64]struct{}{}, dimHashesByName: map[string]uint64{}, } }
[ "func", "NewRegistry", "(", ")", "*", "Registry", "{", "return", "&", "Registry", "{", "collectorsByID", ":", "map", "[", "uint64", "]", "Collector", "{", "}", ",", "descIDs", ":", "map", "[", "uint64", "]", "struct", "{", "}", "{", "}", ",", "dimHas...
// NewRegistry creates a new vanilla Registry without any Collectors // pre-registered.
[ "NewRegistry", "creates", "a", "new", "vanilla", "Registry", "without", "any", "Collectors", "pre", "-", "registered", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/registry.go#L66-L72
train
prometheus/client_golang
prometheus/registry.go
Append
func (errs *MultiError) Append(err error) { if err != nil { *errs = append(*errs, err) } }
go
func (errs *MultiError) Append(err error) { if err != nil { *errs = append(*errs, err) } }
[ "func", "(", "errs", "*", "MultiError", ")", "Append", "(", "err", "error", ")", "{", "if", "err", "!=", "nil", "{", "*", "errs", "=", "append", "(", "*", "errs", ",", "err", ")", "\n", "}", "\n", "}" ]
// Append appends the provided error if it is not nil.
[ "Append", "appends", "the", "provided", "error", "if", "it", "is", "not", "nil", "." ]
6aba2189ebe6959268894366998500defefa2907
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/registry.go#L229-L233
train