repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
docker/distribution
|
registry/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\n",
"for",
"_",
",",
"group",
":=",
"range",
"GetGroupNames",
"(",
")",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"GetErrorCodeGroup",
"(",
"group",
")",
"...",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"byValue",
"(",
"result",
")",
")",
"\n",
"return",
"result",
"\n",
"}"
] |
// 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",
",",
"error",
")",
"{",
"remoteURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"config",
".",
"RemoteURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"v",
":=",
"storage",
".",
"NewVacuum",
"(",
"ctx",
",",
"driver",
")",
"\n",
"s",
":=",
"scheduler",
".",
"New",
"(",
"ctx",
",",
"driver",
",",
"\"",
"\"",
")",
"\n",
"s",
".",
"OnBlobExpire",
"(",
"func",
"(",
"ref",
"reference",
".",
"Reference",
")",
"error",
"{",
"var",
"r",
"reference",
".",
"Canonical",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"r",
",",
"ok",
"=",
"ref",
".",
"(",
"reference",
".",
"Canonical",
")",
";",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ref",
")",
"\n",
"}",
"\n\n",
"repo",
",",
"err",
":=",
"registry",
".",
"Repository",
"(",
"ctx",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"blobs",
":=",
"repo",
".",
"Blobs",
"(",
"ctx",
")",
"\n\n",
"// Clear the repository reference and descriptor caches",
"err",
"=",
"blobs",
".",
"Delete",
"(",
"ctx",
",",
"r",
".",
"Digest",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"v",
".",
"RemoveBlob",
"(",
"r",
".",
"Digest",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"s",
".",
"OnManifestExpire",
"(",
"func",
"(",
"ref",
"reference",
".",
"Reference",
")",
"error",
"{",
"var",
"r",
"reference",
".",
"Canonical",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"r",
",",
"ok",
"=",
"ref",
".",
"(",
"reference",
".",
"Canonical",
")",
";",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ref",
")",
"\n",
"}",
"\n\n",
"repo",
",",
"err",
":=",
"registry",
".",
"Repository",
"(",
"ctx",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"manifests",
",",
"err",
":=",
"repo",
".",
"Manifests",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"manifests",
".",
"Delete",
"(",
"ctx",
",",
"r",
".",
"Digest",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"err",
"=",
"s",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"cs",
",",
"err",
":=",
"configureAuth",
"(",
"config",
".",
"Username",
",",
"config",
".",
"Password",
",",
"config",
".",
"RemoteURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"proxyingRegistry",
"{",
"embedded",
":",
"registry",
",",
"scheduler",
":",
"s",
",",
"remoteURL",
":",
"*",
"remoteURL",
",",
"authChallenger",
":",
"&",
"remoteAuthChallenger",
"{",
"remoteURL",
":",
"*",
"remoteURL",
",",
"cm",
":",
"challenge",
".",
"NewSimpleManager",
"(",
")",
",",
"cs",
":",
"cs",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// 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\n",
"remoteURL",
":=",
"r",
".",
"remoteURL",
"\n",
"remoteURL",
".",
"Path",
"=",
"\"",
"\"",
"\n",
"challenges",
",",
"err",
":=",
"r",
".",
"cm",
".",
"GetChallenges",
"(",
"remoteURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"challenges",
")",
">",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// establish challenge type with upstream",
"if",
"err",
":=",
"ping",
"(",
"r",
".",
"cm",
",",
"remoteURL",
".",
"String",
"(",
")",
",",
"challengeHeader",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"remoteURL",
",",
"r",
".",
"cm",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// 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",
"}",
"\n",
"return",
"\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",
")",
"{",
"// 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",
"\n",
"if",
"ctHeader",
"!=",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"mediaType",
",",
"_",
",",
"err",
"=",
"mime",
".",
"ParseMediaType",
"(",
"ctHeader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"Descriptor",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"unmarshalFunc",
",",
"ok",
":=",
"mappings",
"[",
"mediaType",
"]",
"\n",
"if",
"!",
"ok",
"{",
"unmarshalFunc",
",",
"ok",
"=",
"mappings",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"Descriptor",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"mediaType",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"unmarshalFunc",
"(",
"p",
")",
"\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",
"(",
"\"",
"\"",
",",
"mediaType",
")",
"\n",
"}",
"\n",
"mappings",
"[",
"mediaType",
"]",
"=",
"u",
"\n",
"return",
"nil",
"\n",
"}"
] |
// 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",
".",
"GetRequest",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"challenge",
":=",
"challenge",
"{",
"realm",
":",
"ac",
".",
"realm",
",",
"service",
":",
"ac",
".",
"service",
",",
"}",
"\n\n",
"if",
"len",
"(",
"accessRecords",
")",
">",
"0",
"{",
"var",
"scopes",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"access",
":=",
"range",
"accessRecords",
"{",
"scopes",
"=",
"append",
"(",
"scopes",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"access",
".",
"Type",
",",
"access",
".",
"Resource",
".",
"Name",
",",
"access",
".",
"Action",
")",
")",
"\n",
"}",
"\n",
"challenge",
".",
"scope",
"=",
"strings",
".",
"Join",
"(",
"scopes",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"&",
"challenge",
"\n",
"}",
"\n\n",
"ctx",
"=",
"auth",
".",
"WithUser",
"(",
"ctx",
",",
"auth",
".",
"UserInfo",
"{",
"Name",
":",
"\"",
"\"",
"}",
")",
"\n",
"ctx",
"=",
"dcontext",
".",
"WithLogger",
"(",
"ctx",
",",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
",",
"auth",
".",
"UserNameKey",
",",
"auth",
".",
"UserKey",
")",
")",
"\n\n",
"return",
"ctx",
",",
"nil",
"\n\n",
"}"
] |
// 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",
"(",
"\"",
"\"",
",",
"ch",
".",
"realm",
",",
"ch",
".",
"service",
")",
"\n\n",
"if",
"ch",
".",
"scope",
"!=",
"\"",
"\"",
"{",
"header",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"header",
",",
"ch",
".",
"scope",
")",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"header",
")",
"\n",
"}"
] |
// 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\n",
"tokenBytes",
",",
"err",
":=",
"base64",
".",
"URLEncoding",
".",
"DecodeString",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"state",
",",
"err",
"\n",
"}",
"\n",
"mac",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"[",
"]",
"byte",
"(",
"secret",
")",
")",
"\n\n",
"if",
"len",
"(",
"tokenBytes",
")",
"<",
"mac",
".",
"Size",
"(",
")",
"{",
"return",
"state",
",",
"errInvalidSecret",
"\n",
"}",
"\n\n",
"macBytes",
":=",
"tokenBytes",
"[",
":",
"mac",
".",
"Size",
"(",
")",
"]",
"\n",
"messageBytes",
":=",
"tokenBytes",
"[",
"mac",
".",
"Size",
"(",
")",
":",
"]",
"\n\n",
"mac",
".",
"Write",
"(",
"messageBytes",
")",
"\n",
"if",
"!",
"hmac",
".",
"Equal",
"(",
"mac",
".",
"Sum",
"(",
"nil",
")",
",",
"macBytes",
")",
"{",
"return",
"state",
",",
"errInvalidSecret",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"messageBytes",
",",
"&",
"state",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"state",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"state",
",",
"nil",
"\n",
"}"
] |
// 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",
"p",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"lus",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"mac",
".",
"Write",
"(",
"p",
")",
"\n\n",
"return",
"base64",
".",
"URLEncoding",
".",
"EncodeToString",
"(",
"append",
"(",
"mac",
".",
"Sum",
"(",
"nil",
")",
",",
"p",
"...",
")",
")",
",",
"nil",
"\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",
"with",
"minimized",
"risk",
"of",
"external",
"tampering",
"."
] |
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",
"{",
"}",
",",
"2",
"*",
"len",
"(",
"scopeSpecs",
")",
")",
"\n\n",
"for",
"_",
",",
"scopeSpecifier",
":=",
"range",
"scopeSpecs",
"{",
"// There should be 3 parts, separated by a `:` character.",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"scopeSpecifier",
",",
"\"",
"\"",
",",
"3",
")",
"\n\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"{",
"dcontext",
".",
"GetLogger",
"(",
"ctx",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"scopeSpecifier",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"resourceType",
",",
"resourceName",
",",
"actions",
":=",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
"]",
",",
"parts",
"[",
"2",
"]",
"\n\n",
"resourceType",
",",
"resourceClass",
":=",
"splitResourceClass",
"(",
"resourceType",
")",
"\n",
"if",
"resourceType",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"// 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",
",",
"}",
"\n\n",
"// Add this access to the requested access set.",
"requestedAccessSet",
"[",
"requestedAccess",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"requestedAccessList",
":=",
"make",
"(",
"[",
"]",
"auth",
".",
"Access",
",",
"0",
",",
"len",
"(",
"requestedAccessSet",
")",
")",
"\n",
"for",
"requestedAccess",
":=",
"range",
"requestedAccessSet",
"{",
"requestedAccessList",
"=",
"append",
"(",
"requestedAccessList",
",",
"requestedAccess",
")",
"\n",
"}",
"\n\n",
"return",
"requestedAccessList",
"\n",
"}"
] |
// 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",
"(",
"ctx",
",",
"scopes",
")",
"\n",
"}"
] |
// 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",
")",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// 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",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ch",
".",
"realm",
")",
")",
"\n",
"}"
] |
// 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",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Dir",
"(",
"path",
")",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"path",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREATE",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"var",
"secretBytes",
"[",
"32",
"]",
"byte",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"secretBytes",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pass",
":=",
"base64",
".",
"RawURLEncoding",
".",
"EncodeToString",
"(",
"secretBytes",
"[",
":",
"]",
")",
"\n",
"encryptedPass",
",",
"err",
":=",
"bcrypt",
".",
"GenerateFromPassword",
"(",
"[",
"]",
"byte",
"(",
"pass",
")",
",",
"bcrypt",
".",
"DefaultCost",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"f",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"string",
"(",
"encryptedPass",
"[",
":",
"]",
")",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"dcontext",
".",
"GetLoggerWithFields",
"(",
"context",
".",
"Background",
"(",
")",
",",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"pass",
",",
"}",
")",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// 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",
")",
"!=",
"2",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"host",
":=",
"addr",
"[",
"0",
"]",
"\n",
"subject",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"entry",
".",
"Level",
",",
"host",
",",
"entry",
".",
"Message",
")",
"\n\n",
"html",
":=",
"`\n\t{{.Message}}\n\n\t{{range $key, $value := .Data}}\n\t{{$key}}: {{$value}}\n\t{{end}}\n\t`",
"\n",
"b",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
")",
"\n",
"t",
":=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"html",
")",
")",
"\n",
"if",
"err",
":=",
"t",
".",
"Execute",
"(",
"b",
",",
"entry",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"body",
":=",
"b",
".",
"String",
"(",
")",
"\n\n",
"return",
"hook",
".",
"Mail",
".",
"sendMail",
"(",
"subject",
",",
"body",
")",
"\n",
"}"
] |
// 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",
",",
"_",
":=",
"logrus",
".",
"ParseLevel",
"(",
"v",
")",
"\n",
"levels",
"=",
"append",
"(",
"levels",
",",
"lv",
")",
"\n",
"}",
"\n",
"return",
"levels",
"\n",
"}"
] |
// 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",
"\"",
"\"",
":",
"return",
"newUnixListener",
"(",
"laddr",
")",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"// an empty net means tcp",
"return",
"newTCPListener",
"(",
"laddr",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"net",
")",
"\n",
"}",
"\n",
"}"
] |
// 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",
".",
"AccessKeySecret",
",",
"params",
".",
"Secure",
")",
"\n",
"client",
".",
"SetEndpoint",
"(",
"params",
".",
"Endpoint",
")",
"\n",
"bucket",
":=",
"client",
".",
"Bucket",
"(",
"params",
".",
"Bucket",
")",
"\n",
"client",
".",
"SetDebug",
"(",
"false",
")",
"\n\n",
"// 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",
"\n",
"}",
"\n\n",
"// 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",
",",
"}",
"\n\n",
"return",
"&",
"Driver",
"{",
"baseEmbed",
":",
"baseEmbed",
"{",
"Base",
":",
"base",
".",
"Base",
"{",
"StorageDriver",
":",
"d",
",",
"}",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// 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",
"_",
",",
"supportedVersions",
":=",
"range",
"resp",
".",
"Header",
"[",
"http",
".",
"CanonicalHeaderKey",
"(",
"versionHeader",
")",
"]",
"{",
"for",
"_",
",",
"version",
":=",
"range",
"strings",
".",
"Fields",
"(",
"supportedVersions",
")",
"{",
"versions",
"=",
"append",
"(",
"versions",
",",
"ParseAPIVersion",
"(",
"version",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"versions",
"\n",
"}"
] |
// 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",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"host",
":=",
"addr",
"[",
"0",
"]",
"\n",
"msg",
":=",
"[",
"]",
"byte",
"(",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"mail",
".",
"To",
",",
"\"",
"\"",
")",
"+",
"\"",
"\\r",
"\\n",
"\"",
"+",
"mail",
".",
"From",
"+",
"\"",
"\\r",
"\\n",
"\"",
"+",
"subject",
"+",
"\"",
"\\r",
"\\n",
"\\r",
"\\n",
"\\r",
"\\n",
"\"",
"+",
"message",
")",
"\n",
"auth",
":=",
"smtp",
".",
"PlainAuth",
"(",
"\"",
"\"",
",",
"mail",
".",
"Username",
",",
"mail",
".",
"Password",
",",
"host",
",",
")",
"\n",
"err",
":=",
"smtp",
".",
"SendMail",
"(",
"mail",
".",
"Addr",
",",
"auth",
",",
"mail",
".",
"From",
",",
"mail",
".",
"To",
",",
"msg",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// 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\n",
"for",
"_",
",",
"access",
":=",
"range",
"accessItems",
"{",
"resource",
":=",
"auth",
".",
"Resource",
"{",
"Type",
":",
"access",
".",
"Type",
",",
"Name",
":",
"access",
".",
"Name",
",",
"}",
"\n\n",
"set",
",",
"exists",
":=",
"accessSet",
"[",
"resource",
"]",
"\n",
"if",
"!",
"exists",
"{",
"set",
"=",
"newActionSet",
"(",
")",
"\n",
"accessSet",
"[",
"resource",
"]",
"=",
"set",
"\n",
"}",
"\n\n",
"set",
".",
"add",
"(",
"access",
".",
"Action",
")",
"\n",
"}",
"\n\n",
"return",
"accessSet",
"\n",
"}"
] |
// 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",
"(",
"access",
".",
"Action",
")",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] |
// 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",
"(",
"\"",
"\"",
",",
"ac",
".",
"challengeParams",
"(",
"r",
")",
")",
"\n",
"}"
] |
// 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\n",
"keys",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"vals",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"keys",
")",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"val",
",",
"ok",
":=",
"options",
"[",
"key",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"opts",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"vals",
"=",
"append",
"(",
"vals",
",",
"val",
")",
"\n",
"}",
"\n\n",
"opts",
".",
"realm",
",",
"opts",
".",
"issuer",
",",
"opts",
".",
"service",
",",
"opts",
".",
"rootCertBundle",
"=",
"vals",
"[",
"0",
"]",
",",
"vals",
"[",
"1",
"]",
",",
"vals",
"[",
"2",
"]",
",",
"vals",
"[",
"3",
"]",
"\n\n",
"autoRedirectVal",
",",
"ok",
":=",
"options",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"autoRedirect",
",",
"ok",
":=",
"autoRedirectVal",
".",
"(",
"bool",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"opts",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"opts",
".",
"autoRedirect",
"=",
"autoRedirect",
"\n",
"}",
"\n\n",
"return",
"opts",
",",
"nil",
"\n",
"}"
] |
// 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",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"fp",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"config",
".",
"rootCertBundle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"config",
".",
"rootCertBundle",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"fp",
".",
"Close",
"(",
")",
"\n\n",
"rawCertBundle",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"fp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"config",
".",
"rootCertBundle",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"rootCerts",
"[",
"]",
"*",
"x509",
".",
"Certificate",
"\n",
"pemBlock",
",",
"rawCertBundle",
":=",
"pem",
".",
"Decode",
"(",
"rawCertBundle",
")",
"\n",
"for",
"pemBlock",
"!=",
"nil",
"{",
"if",
"pemBlock",
".",
"Type",
"==",
"\"",
"\"",
"{",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"pemBlock",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"rootCerts",
"=",
"append",
"(",
"rootCerts",
",",
"cert",
")",
"\n",
"}",
"\n\n",
"pemBlock",
",",
"rawCertBundle",
"=",
"pem",
".",
"Decode",
"(",
"rawCertBundle",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"rootCerts",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"rootPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"trustedKeys",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"libtrust",
".",
"PublicKey",
",",
"len",
"(",
"rootCerts",
")",
")",
"\n",
"for",
"_",
",",
"rootCert",
":=",
"range",
"rootCerts",
"{",
"rootPool",
".",
"AddCert",
"(",
"rootCert",
")",
"\n",
"pubKey",
",",
"err",
":=",
"libtrust",
".",
"FromCryptoPublicKey",
"(",
"crypto",
".",
"PublicKey",
"(",
"rootCert",
".",
"PublicKey",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"trustedKeys",
"[",
"pubKey",
".",
"KeyID",
"(",
")",
"]",
"=",
"pubKey",
"\n",
"}",
"\n\n",
"return",
"&",
"accessController",
"{",
"realm",
":",
"config",
".",
"realm",
",",
"autoRedirect",
":",
"config",
".",
"autoRedirect",
",",
"issuer",
":",
"config",
".",
"issuer",
",",
"service",
":",
"config",
".",
"service",
",",
"rootCerts",
":",
"rootPool",
",",
"trustedKeys",
":",
"trustedKeys",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// 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",
"{",
"realm",
":",
"ac",
".",
"realm",
",",
"autoRedirect",
":",
"ac",
".",
"autoRedirect",
",",
"service",
":",
"ac",
".",
"service",
",",
"accessSet",
":",
"newAccessSet",
"(",
"accessItems",
"...",
")",
",",
"}",
"\n\n",
"req",
",",
"err",
":=",
"dcontext",
".",
"GetRequest",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"parts",
":=",
"strings",
".",
"Split",
"(",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
"||",
"strings",
".",
"ToLower",
"(",
"parts",
"[",
"0",
"]",
")",
"!=",
"\"",
"\"",
"{",
"challenge",
".",
"err",
"=",
"ErrTokenRequired",
"\n",
"return",
"nil",
",",
"challenge",
"\n",
"}",
"\n\n",
"rawToken",
":=",
"parts",
"[",
"1",
"]",
"\n\n",
"token",
",",
"err",
":=",
"NewToken",
"(",
"rawToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"challenge",
".",
"err",
"=",
"err",
"\n",
"return",
"nil",
",",
"challenge",
"\n",
"}",
"\n\n",
"verifyOpts",
":=",
"VerifyOptions",
"{",
"TrustedIssuers",
":",
"[",
"]",
"string",
"{",
"ac",
".",
"issuer",
"}",
",",
"AcceptedAudiences",
":",
"[",
"]",
"string",
"{",
"ac",
".",
"service",
"}",
",",
"Roots",
":",
"ac",
".",
"rootCerts",
",",
"TrustedKeys",
":",
"ac",
".",
"trustedKeys",
",",
"}",
"\n\n",
"if",
"err",
"=",
"token",
".",
"Verify",
"(",
"verifyOpts",
")",
";",
"err",
"!=",
"nil",
"{",
"challenge",
".",
"err",
"=",
"err",
"\n",
"return",
"nil",
",",
"challenge",
"\n",
"}",
"\n\n",
"accessSet",
":=",
"token",
".",
"accessSet",
"(",
")",
"\n",
"for",
"_",
",",
"access",
":=",
"range",
"accessItems",
"{",
"if",
"!",
"accessSet",
".",
"contains",
"(",
"access",
")",
"{",
"challenge",
".",
"err",
"=",
"ErrInsufficientScope",
"\n",
"return",
"nil",
",",
"challenge",
"\n",
"}",
"\n",
"}",
"\n\n",
"ctx",
"=",
"auth",
".",
"WithResources",
"(",
"ctx",
",",
"token",
".",
"resources",
"(",
")",
")",
"\n\n",
"return",
"auth",
".",
"WithUser",
"(",
"ctx",
",",
"auth",
".",
"UserInfo",
"{",
"Name",
":",
"token",
".",
"Claims",
".",
"Subject",
"}",
")",
",",
"nil",
"\n",
"}"
] |
// 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",
":",
"bs",
",",
"configJSON",
":",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"configJSON",
")",
")",
",",
"annotations",
":",
"annotations",
",",
"mediaType",
":",
"v1",
".",
"MediaTypeImageManifest",
",",
"}",
"\n",
"copy",
"(",
"mb",
".",
"configJSON",
",",
"configJSON",
")",
"\n\n",
"return",
"mb",
"\n",
"}"
] |
// NewManifestBuilder is used to build new manifests for the current schema
// version. It takes a BlobService so it can publish the configuration blob
// as part of the Build process, 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",
"process",
"and",
"annotations",
"."
] |
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\n",
"endpoints",
".",
"registered",
"=",
"append",
"(",
"endpoints",
".",
"registered",
",",
"e",
")",
"\n",
"}"
] |
// 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",
")",
",",
"opts",
".",
"Help",
",",
"labelNames",
",",
"opts",
".",
"ConstLabels",
",",
")",
"\n",
"return",
"&",
"GaugeVec",
"{",
"metricVec",
":",
"newMetricVec",
"(",
"desc",
",",
"func",
"(",
"lvs",
"...",
"string",
")",
"Metric",
"{",
"if",
"len",
"(",
"lvs",
")",
"!=",
"len",
"(",
"desc",
".",
"variableLabels",
")",
"{",
"panic",
"(",
"makeInconsistentCardinalityError",
"(",
"desc",
".",
"fqName",
",",
"desc",
".",
"variableLabels",
",",
"lvs",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"&",
"gauge",
"{",
"desc",
":",
"desc",
",",
"labelPairs",
":",
"makeLabelPairs",
"(",
"desc",
",",
"lvs",
")",
"}",
"\n",
"result",
".",
"init",
"(",
"result",
")",
"// Init self-collection.",
"\n",
"return",
"result",
"\n",
"}",
")",
",",
"}",
"\n",
"}"
] |
// 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",
".",
"Name",
")",
",",
"opts",
".",
"Help",
",",
"nil",
",",
"opts",
".",
"ConstLabels",
",",
")",
",",
"GaugeValue",
",",
"function",
")",
"\n",
"}"
] |
// 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",
"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",
"."
] |
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",
":=",
"range",
"parts",
"{",
"part",
"=",
"strings",
".",
"TrimSpace",
"(",
"part",
")",
"\n",
"if",
"part",
"==",
"\"",
"\"",
"||",
"strings",
".",
"HasPrefix",
"(",
"part",
",",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// 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",
",",
"\"",
"\\n",
"\\n",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
",",
")",
"\n",
"}"
] |
// 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",
"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",
"."
] |
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",
"(",
"d",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"d",
"\n",
"}"
] |
// 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",
"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",
"+",
"."
] |
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",
"*",
"http",
".",
"Request",
")",
"{",
"g",
".",
"Inc",
"(",
")",
"\n",
"defer",
"g",
".",
"Dec",
"(",
")",
"\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// 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",
"wrapped",
"http",
".",
"Handler",
".",
"See",
"the",
"example",
"for",
"InstrumentHandlerDuration",
"for",
"example",
"usage",
"."
] |
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",
"[",
"uint64",
"]",
"[",
"]",
"metricWithLabelValues",
"{",
"}",
",",
"desc",
":",
"desc",
",",
"newMetric",
":",
"newMetric",
",",
"}",
",",
"hashAdd",
":",
"hashAdd",
",",
"hashAddByte",
":",
"hashAddByte",
",",
"}",
"\n",
"}"
] |
// 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\n",
"for",
"h",
":=",
"range",
"m",
".",
"metrics",
"{",
"delete",
"(",
"m",
".",
"metrics",
",",
"h",
")",
"\n",
"}",
"\n",
"}"
] |
// 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",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"metrics",
",",
"ok",
":=",
"m",
".",
"metrics",
"[",
"h",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"i",
":=",
"findMetricWithLabelValues",
"(",
"metrics",
",",
"lvs",
",",
"curry",
")",
"\n",
"if",
"i",
">=",
"len",
"(",
"metrics",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"metrics",
")",
">",
"1",
"{",
"m",
".",
"metrics",
"[",
"h",
"]",
"=",
"append",
"(",
"metrics",
"[",
":",
"i",
"]",
",",
"metrics",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"else",
"{",
"delete",
"(",
"m",
".",
"metrics",
",",
"h",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// 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",
".",
"Unlock",
"(",
")",
"\n\n",
"metrics",
",",
"ok",
":=",
"m",
".",
"metrics",
"[",
"h",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"i",
":=",
"findMetricWithLabels",
"(",
"m",
".",
"desc",
",",
"metrics",
",",
"labels",
",",
"curry",
")",
"\n",
"if",
"i",
">=",
"len",
"(",
"metrics",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"metrics",
")",
">",
"1",
"{",
"m",
".",
"metrics",
"[",
"h",
"]",
"=",
"append",
"(",
"metrics",
"[",
":",
"i",
"]",
",",
"metrics",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"else",
"{",
"delete",
"(",
"m",
".",
"metrics",
",",
"h",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// 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",
".",
"metrics",
"[",
"h",
"]",
"\n",
"if",
"ok",
"{",
"if",
"i",
":=",
"findMetricWithLabelValues",
"(",
"metrics",
",",
"lvs",
",",
"curry",
")",
";",
"i",
"<",
"len",
"(",
"metrics",
")",
"{",
"return",
"metrics",
"[",
"i",
"]",
".",
"metric",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] |
// 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",
".",
"metrics",
"[",
"h",
"]",
"\n",
"if",
"ok",
"{",
"if",
"i",
":=",
"findMetricWithLabels",
"(",
"m",
".",
"desc",
",",
"metrics",
",",
"labels",
",",
"curry",
")",
";",
"i",
"<",
"len",
"(",
"metrics",
")",
"{",
"return",
"metrics",
"[",
"i",
"]",
".",
"metric",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] |
// 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\n",
"// 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",
"(",
")",
"\n",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] |
// 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",
".",
"headStreamIdx",
"++",
"\n",
"if",
"s",
".",
"headStreamIdx",
">=",
"len",
"(",
"s",
".",
"streams",
")",
"{",
"s",
".",
"headStreamIdx",
"=",
"0",
"\n",
"}",
"\n",
"s",
".",
"headStream",
"=",
"s",
".",
"streams",
"[",
"s",
".",
"headStreamIdx",
"]",
"\n",
"s",
".",
"headStreamExpTime",
"=",
"s",
".",
"headStreamExpTime",
".",
"Add",
"(",
"s",
".",
"streamDuration",
")",
"\n",
"}",
"\n",
"}"
] |
// 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",
"}",
"\n",
"s",
".",
"cnt",
"++",
"\n",
"s",
".",
"sum",
"+=",
"v",
"\n",
"}",
"\n",
"s",
".",
"coldBuf",
"=",
"s",
".",
"coldBuf",
"[",
"0",
":",
"0",
"]",
"\n",
"s",
".",
"maybeRotateStreams",
"(",
")",
"\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",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"s",
".",
"hotBuf",
",",
"s",
".",
"coldBuf",
"=",
"s",
".",
"coldBuf",
",",
"s",
".",
"hotBuf",
"\n",
"// hotBuf is now empty and gets new expiration set.",
"for",
"now",
".",
"After",
"(",
"s",
".",
"hotBufExpTime",
")",
"{",
"s",
".",
"hotBufExpTime",
"=",
"s",
".",
"hotBufExpTime",
".",
"Add",
"(",
"s",
".",
"streamDuration",
")",
"\n",
"}",
"\n",
"}"
] |
// 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",
":=",
"NewConstSummary",
"(",
"desc",
",",
"count",
",",
"sum",
",",
"quantiles",
",",
"labelValues",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] |
// 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",
".",
"Response",
",",
"error",
")",
"{",
"gauge",
".",
"Inc",
"(",
")",
"\n",
"defer",
"gauge",
".",
"Dec",
"(",
")",
"\n",
"return",
"next",
".",
"RoundTrip",
"(",
"r",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// 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",
"the",
"wrapped",
"http",
".",
"RoundTripper",
".",
"See",
"the",
"example",
"for",
"ExampleInstrumentRoundTripperDuration",
"for",
"example",
"usage",
"."
] |
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",
")",
",",
"opts",
".",
"Help",
",",
"labelNames",
",",
"opts",
".",
"ConstLabels",
",",
")",
"\n",
"return",
"&",
"CounterVec",
"{",
"metricVec",
":",
"newMetricVec",
"(",
"desc",
",",
"func",
"(",
"lvs",
"...",
"string",
")",
"Metric",
"{",
"if",
"len",
"(",
"lvs",
")",
"!=",
"len",
"(",
"desc",
".",
"variableLabels",
")",
"{",
"panic",
"(",
"makeInconsistentCardinalityError",
"(",
"desc",
".",
"fqName",
",",
"desc",
".",
"variableLabels",
",",
"lvs",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"&",
"counter",
"{",
"desc",
":",
"desc",
",",
"labelPairs",
":",
"makeLabelPairs",
"(",
"desc",
",",
"lvs",
")",
"}",
"\n",
"result",
".",
"init",
"(",
"result",
")",
"// Init self-collection.",
"\n",
"return",
"result",
"\n",
"}",
")",
",",
"}",
"\n",
"}"
] |
// 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",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"http",
".",
"MethodPost",
",",
"u",
".",
"String",
"(",
")",
",",
"strings",
".",
"NewReader",
"(",
"args",
".",
"Encode",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"resp",
",",
"body",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"ctx",
",",
"req",
")",
"\n",
"if",
"resp",
"!=",
"nil",
"&&",
"resp",
".",
"StatusCode",
"==",
"http",
".",
"StatusMethodNotAllowed",
"{",
"u",
".",
"RawQuery",
"=",
"args",
".",
"Encode",
"(",
")",
"\n",
"req",
",",
"err",
"=",
"http",
".",
"NewRequest",
"(",
"http",
".",
"MethodGet",
",",
"u",
".",
"String",
"(",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"}",
"else",
"{",
"return",
"resp",
",",
"body",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"Do",
"(",
"ctx",
",",
"req",
")",
"\n",
"}"
] |
// 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",
"u",
".",
"Path",
"=",
"strings",
".",
"TrimRight",
"(",
"u",
".",
"Path",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"&",
"httpClient",
"{",
"endpoint",
":",
"u",
",",
"client",
":",
"http",
".",
"Client",
"{",
"Transport",
":",
"cfg",
".",
"roundTripper",
"(",
")",
"}",
",",
"}",
",",
"nil",
"\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",
"\n",
"}",
"\n",
"return",
"h",
"\n",
"}"
] |
// 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",
"their",
"own",
".",
"For",
"convenience",
"this",
"method",
"returns",
"a",
"pointer",
"to",
"the",
"Pusher",
"itself",
"."
] |
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",
"}",
"\n",
"return",
"p",
"\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",
"their",
"own",
".",
"For",
"convenience",
"this",
"method",
"returns",
"a",
"pointer",
"to",
"the",
"Pusher",
"itself",
"."
] |
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",
"\n",
"return",
"p",
"\n",
"}"
] |
// 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",
"standard",
"Prometheus",
"Pushgateway",
".",
"Custom",
"implementations",
"may",
"require",
"different",
"formats",
".",
"For",
"convenience",
"this",
"method",
"returns",
"a",
"pointer",
"to",
"the",
"Pusher",
"itself",
"."
] |
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",
".",
"Sort",
"(",
"metricSorter",
"(",
"mf",
".",
"Metric",
")",
")",
"\n",
"}",
"\n",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"metricFamiliesByName",
")",
")",
"\n",
"for",
"name",
",",
"mf",
":=",
"range",
"metricFamiliesByName",
"{",
"if",
"len",
"(",
"mf",
".",
"Metric",
")",
">",
"0",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"*",
"dto",
".",
"MetricFamily",
",",
"0",
",",
"len",
"(",
"names",
")",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"metricFamiliesByName",
"[",
"name",
"]",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] |
// 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",
"each",
"MetricFamily",
"."
] |
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",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"buckets",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"count",
")",
"\n",
"for",
"i",
":=",
"range",
"buckets",
"{",
"buckets",
"[",
"i",
"]",
"=",
"start",
"\n",
"start",
"+=",
"width",
"\n",
"}",
"\n",
"return",
"buckets",
"\n",
"}"
] |
// 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",
"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",
"."
] |
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",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"start",
"<=",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"factor",
"<=",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"buckets",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"count",
")",
"\n",
"for",
"i",
":=",
"range",
"buckets",
"{",
"buckets",
"[",
"i",
"]",
"=",
"start",
"\n",
"start",
"*=",
"factor",
"\n",
"}",
"\n",
"return",
"buckets",
"\n",
"}"
] |
// 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",
"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",
"."
] |
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",
",",
"nil",
",",
"opts",
".",
"ConstLabels",
",",
")",
",",
"opts",
",",
")",
"\n",
"}"
] |
// 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",
".",
"Name",
")",
",",
"opts",
".",
"Help",
",",
"labelNames",
",",
"opts",
".",
"ConstLabels",
",",
")",
"\n",
"return",
"&",
"HistogramVec",
"{",
"metricVec",
":",
"newMetricVec",
"(",
"desc",
",",
"func",
"(",
"lvs",
"...",
"string",
")",
"Metric",
"{",
"return",
"newHistogram",
"(",
"desc",
",",
"opts",
",",
"lvs",
"...",
")",
"\n",
"}",
")",
",",
"}",
"\n",
"}"
] |
// 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",
":=",
"NewConstHistogram",
"(",
"desc",
",",
"count",
",",
"sum",
",",
"buckets",
",",
"labelValues",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] |
// 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",
".",
"errorHandling",
"{",
"case",
"AbortOnError",
":",
"return",
"err",
"\n",
"case",
"ContinueOnError",
":",
"if",
"b",
".",
"logger",
"!=",
"nil",
"{",
"b",
".",
"logger",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"conn",
",",
"err",
":=",
"net",
".",
"DialTimeout",
"(",
"\"",
"\"",
",",
"b",
".",
"url",
",",
"b",
".",
"timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"return",
"writeMetrics",
"(",
"conn",
",",
"mfs",
",",
"b",
".",
"prefix",
",",
"model",
".",
"Now",
"(",
")",
")",
"\n",
"}"
] |
// 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",
"registration",
"fails",
"NewCounter",
"panics",
"."
] |
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",
"prometheus",
".",
"MustRegister",
"(",
"c",
")",
"\n",
"return",
"c",
"\n",
"}"
] |
// 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",
"registration",
"fails",
"NewCounterVec",
"panics",
"."
] |
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",
"prometheus",
".",
"MustRegister",
"(",
"g",
")",
"\n",
"return",
"g",
"\n",
"}"
] |
// 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",
"registration",
"fails",
"NewCounterFunc",
"panics",
"."
] |
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",
"fails",
"NewGauge",
"panics",
"."
] |
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",
".",
"MustRegister",
"(",
"g",
")",
"\n",
"return",
"g",
"\n",
"}"
] |
// 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",
"registration",
"fails",
"NewGaugeVec",
"panics",
"."
] |
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",
".",
"MustRegister",
"(",
"g",
")",
"\n",
"return",
"g",
"\n",
"}"
] |
// 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",
"registration",
"fails",
"NewGaugeFunc",
"panics",
"."
] |
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",
"registration",
"fails",
"NewSummary",
"panics",
"."
] |
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",
"prometheus",
".",
"MustRegister",
"(",
"s",
")",
"\n",
"return",
"s",
"\n",
"}"
] |
// 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",
"registration",
"fails",
"NewSummaryVec",
"panics",
"."
] |
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",
"\n",
"}"
] |
// 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",
"registration",
"fails",
"NewHistogram",
"panics",
"."
] |
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",
"prometheus",
".",
"MustRegister",
"(",
"h",
")",
"\n",
"return",
"h",
"\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",
"registration",
"fails",
"NewHistogramVec",
"panics",
"."
] |
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",
"{",
"}",
"{",
"}",
",",
"dimHashesByName",
":",
"map",
"[",
"string",
"]",
"uint64",
"{",
"}",
",",
"}",
"\n",
"}"
] |
// 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
|
prometheus/client_golang
|
prometheus/registry.go
|
Register
|
func (r *Registry) Register(c Collector) error {
var (
descChan = make(chan *Desc, capDescChan)
newDescIDs = map[uint64]struct{}{}
newDimHashesByName = map[string]uint64{}
collectorID uint64 // Just a sum of all desc IDs.
duplicateDescErr error
)
go func() {
c.Describe(descChan)
close(descChan)
}()
r.mtx.Lock()
defer func() {
// Drain channel in case of premature return to not leak a goroutine.
for range descChan {
}
r.mtx.Unlock()
}()
// Conduct various tests...
for desc := range descChan {
// Is the descriptor valid at all?
if desc.err != nil {
return fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err)
}
// Is the descID unique?
// (In other words: Is the fqName + constLabel combination unique?)
if _, exists := r.descIDs[desc.id]; exists {
duplicateDescErr = fmt.Errorf("descriptor %s already exists with the same fully-qualified name and const label values", desc)
}
// If it is not a duplicate desc in this collector, add it to
// the collectorID. (We allow duplicate descs within the same
// collector, but their existence must be a no-op.)
if _, exists := newDescIDs[desc.id]; !exists {
newDescIDs[desc.id] = struct{}{}
collectorID += desc.id
}
// Are all the label names and the help string consistent with
// previous descriptors of the same name?
// First check existing descriptors...
if dimHash, exists := r.dimHashesByName[desc.fqName]; exists {
if dimHash != desc.dimHash {
return fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", desc)
}
} else {
// ...then check the new descriptors already seen.
if dimHash, exists := newDimHashesByName[desc.fqName]; exists {
if dimHash != desc.dimHash {
return fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", desc)
}
} else {
newDimHashesByName[desc.fqName] = desc.dimHash
}
}
}
// A Collector yielding no Desc at all is considered unchecked.
if len(newDescIDs) == 0 {
r.uncheckedCollectors = append(r.uncheckedCollectors, c)
return nil
}
if existing, exists := r.collectorsByID[collectorID]; exists {
return AlreadyRegisteredError{
ExistingCollector: existing,
NewCollector: c,
}
}
// If the collectorID is new, but at least one of the descs existed
// before, we are in trouble.
if duplicateDescErr != nil {
return duplicateDescErr
}
// Only after all tests have passed, actually register.
r.collectorsByID[collectorID] = c
for hash := range newDescIDs {
r.descIDs[hash] = struct{}{}
}
for name, dimHash := range newDimHashesByName {
r.dimHashesByName[name] = dimHash
}
return nil
}
|
go
|
func (r *Registry) Register(c Collector) error {
var (
descChan = make(chan *Desc, capDescChan)
newDescIDs = map[uint64]struct{}{}
newDimHashesByName = map[string]uint64{}
collectorID uint64 // Just a sum of all desc IDs.
duplicateDescErr error
)
go func() {
c.Describe(descChan)
close(descChan)
}()
r.mtx.Lock()
defer func() {
// Drain channel in case of premature return to not leak a goroutine.
for range descChan {
}
r.mtx.Unlock()
}()
// Conduct various tests...
for desc := range descChan {
// Is the descriptor valid at all?
if desc.err != nil {
return fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err)
}
// Is the descID unique?
// (In other words: Is the fqName + constLabel combination unique?)
if _, exists := r.descIDs[desc.id]; exists {
duplicateDescErr = fmt.Errorf("descriptor %s already exists with the same fully-qualified name and const label values", desc)
}
// If it is not a duplicate desc in this collector, add it to
// the collectorID. (We allow duplicate descs within the same
// collector, but their existence must be a no-op.)
if _, exists := newDescIDs[desc.id]; !exists {
newDescIDs[desc.id] = struct{}{}
collectorID += desc.id
}
// Are all the label names and the help string consistent with
// previous descriptors of the same name?
// First check existing descriptors...
if dimHash, exists := r.dimHashesByName[desc.fqName]; exists {
if dimHash != desc.dimHash {
return fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", desc)
}
} else {
// ...then check the new descriptors already seen.
if dimHash, exists := newDimHashesByName[desc.fqName]; exists {
if dimHash != desc.dimHash {
return fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", desc)
}
} else {
newDimHashesByName[desc.fqName] = desc.dimHash
}
}
}
// A Collector yielding no Desc at all is considered unchecked.
if len(newDescIDs) == 0 {
r.uncheckedCollectors = append(r.uncheckedCollectors, c)
return nil
}
if existing, exists := r.collectorsByID[collectorID]; exists {
return AlreadyRegisteredError{
ExistingCollector: existing,
NewCollector: c,
}
}
// If the collectorID is new, but at least one of the descs existed
// before, we are in trouble.
if duplicateDescErr != nil {
return duplicateDescErr
}
// Only after all tests have passed, actually register.
r.collectorsByID[collectorID] = c
for hash := range newDescIDs {
r.descIDs[hash] = struct{}{}
}
for name, dimHash := range newDimHashesByName {
r.dimHashesByName[name] = dimHash
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"Registry",
")",
"Register",
"(",
"c",
"Collector",
")",
"error",
"{",
"var",
"(",
"descChan",
"=",
"make",
"(",
"chan",
"*",
"Desc",
",",
"capDescChan",
")",
"\n",
"newDescIDs",
"=",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"newDimHashesByName",
"=",
"map",
"[",
"string",
"]",
"uint64",
"{",
"}",
"\n",
"collectorID",
"uint64",
"// Just a sum of all desc IDs.",
"\n",
"duplicateDescErr",
"error",
"\n",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"c",
".",
"Describe",
"(",
"descChan",
")",
"\n",
"close",
"(",
"descChan",
")",
"\n",
"}",
"(",
")",
"\n",
"r",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"// Drain channel in case of premature return to not leak a goroutine.",
"for",
"range",
"descChan",
"{",
"}",
"\n",
"r",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"// Conduct various tests...",
"for",
"desc",
":=",
"range",
"descChan",
"{",
"// Is the descriptor valid at all?",
"if",
"desc",
".",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"desc",
",",
"desc",
".",
"err",
")",
"\n",
"}",
"\n\n",
"// Is the descID unique?",
"// (In other words: Is the fqName + constLabel combination unique?)",
"if",
"_",
",",
"exists",
":=",
"r",
".",
"descIDs",
"[",
"desc",
".",
"id",
"]",
";",
"exists",
"{",
"duplicateDescErr",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"desc",
")",
"\n",
"}",
"\n",
"// If it is not a duplicate desc in this collector, add it to",
"// the collectorID. (We allow duplicate descs within the same",
"// collector, but their existence must be a no-op.)",
"if",
"_",
",",
"exists",
":=",
"newDescIDs",
"[",
"desc",
".",
"id",
"]",
";",
"!",
"exists",
"{",
"newDescIDs",
"[",
"desc",
".",
"id",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"collectorID",
"+=",
"desc",
".",
"id",
"\n",
"}",
"\n\n",
"// Are all the label names and the help string consistent with",
"// previous descriptors of the same name?",
"// First check existing descriptors...",
"if",
"dimHash",
",",
"exists",
":=",
"r",
".",
"dimHashesByName",
"[",
"desc",
".",
"fqName",
"]",
";",
"exists",
"{",
"if",
"dimHash",
"!=",
"desc",
".",
"dimHash",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"desc",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// ...then check the new descriptors already seen.",
"if",
"dimHash",
",",
"exists",
":=",
"newDimHashesByName",
"[",
"desc",
".",
"fqName",
"]",
";",
"exists",
"{",
"if",
"dimHash",
"!=",
"desc",
".",
"dimHash",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"desc",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"newDimHashesByName",
"[",
"desc",
".",
"fqName",
"]",
"=",
"desc",
".",
"dimHash",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// A Collector yielding no Desc at all is considered unchecked.",
"if",
"len",
"(",
"newDescIDs",
")",
"==",
"0",
"{",
"r",
".",
"uncheckedCollectors",
"=",
"append",
"(",
"r",
".",
"uncheckedCollectors",
",",
"c",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"existing",
",",
"exists",
":=",
"r",
".",
"collectorsByID",
"[",
"collectorID",
"]",
";",
"exists",
"{",
"return",
"AlreadyRegisteredError",
"{",
"ExistingCollector",
":",
"existing",
",",
"NewCollector",
":",
"c",
",",
"}",
"\n",
"}",
"\n",
"// If the collectorID is new, but at least one of the descs existed",
"// before, we are in trouble.",
"if",
"duplicateDescErr",
"!=",
"nil",
"{",
"return",
"duplicateDescErr",
"\n",
"}",
"\n\n",
"// Only after all tests have passed, actually register.",
"r",
".",
"collectorsByID",
"[",
"collectorID",
"]",
"=",
"c",
"\n",
"for",
"hash",
":=",
"range",
"newDescIDs",
"{",
"r",
".",
"descIDs",
"[",
"hash",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"for",
"name",
",",
"dimHash",
":=",
"range",
"newDimHashesByName",
"{",
"r",
".",
"dimHashesByName",
"[",
"name",
"]",
"=",
"dimHash",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Register implements Registerer.
|
[
"Register",
"implements",
"Registerer",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/registry.go#L264-L348
|
train
|
prometheus/client_golang
|
prometheus/registry.go
|
Unregister
|
func (r *Registry) Unregister(c Collector) bool {
var (
descChan = make(chan *Desc, capDescChan)
descIDs = map[uint64]struct{}{}
collectorID uint64 // Just a sum of the desc IDs.
)
go func() {
c.Describe(descChan)
close(descChan)
}()
for desc := range descChan {
if _, exists := descIDs[desc.id]; !exists {
collectorID += desc.id
descIDs[desc.id] = struct{}{}
}
}
r.mtx.RLock()
if _, exists := r.collectorsByID[collectorID]; !exists {
r.mtx.RUnlock()
return false
}
r.mtx.RUnlock()
r.mtx.Lock()
defer r.mtx.Unlock()
delete(r.collectorsByID, collectorID)
for id := range descIDs {
delete(r.descIDs, id)
}
// dimHashesByName is left untouched as those must be consistent
// throughout the lifetime of a program.
return true
}
|
go
|
func (r *Registry) Unregister(c Collector) bool {
var (
descChan = make(chan *Desc, capDescChan)
descIDs = map[uint64]struct{}{}
collectorID uint64 // Just a sum of the desc IDs.
)
go func() {
c.Describe(descChan)
close(descChan)
}()
for desc := range descChan {
if _, exists := descIDs[desc.id]; !exists {
collectorID += desc.id
descIDs[desc.id] = struct{}{}
}
}
r.mtx.RLock()
if _, exists := r.collectorsByID[collectorID]; !exists {
r.mtx.RUnlock()
return false
}
r.mtx.RUnlock()
r.mtx.Lock()
defer r.mtx.Unlock()
delete(r.collectorsByID, collectorID)
for id := range descIDs {
delete(r.descIDs, id)
}
// dimHashesByName is left untouched as those must be consistent
// throughout the lifetime of a program.
return true
}
|
[
"func",
"(",
"r",
"*",
"Registry",
")",
"Unregister",
"(",
"c",
"Collector",
")",
"bool",
"{",
"var",
"(",
"descChan",
"=",
"make",
"(",
"chan",
"*",
"Desc",
",",
"capDescChan",
")",
"\n",
"descIDs",
"=",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"collectorID",
"uint64",
"// Just a sum of the desc IDs.",
"\n",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"c",
".",
"Describe",
"(",
"descChan",
")",
"\n",
"close",
"(",
"descChan",
")",
"\n",
"}",
"(",
")",
"\n",
"for",
"desc",
":=",
"range",
"descChan",
"{",
"if",
"_",
",",
"exists",
":=",
"descIDs",
"[",
"desc",
".",
"id",
"]",
";",
"!",
"exists",
"{",
"collectorID",
"+=",
"desc",
".",
"id",
"\n",
"descIDs",
"[",
"desc",
".",
"id",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"r",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"r",
".",
"collectorsByID",
"[",
"collectorID",
"]",
";",
"!",
"exists",
"{",
"r",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"r",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"r",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"delete",
"(",
"r",
".",
"collectorsByID",
",",
"collectorID",
")",
"\n",
"for",
"id",
":=",
"range",
"descIDs",
"{",
"delete",
"(",
"r",
".",
"descIDs",
",",
"id",
")",
"\n",
"}",
"\n",
"// dimHashesByName is left untouched as those must be consistent",
"// throughout the lifetime of a program.",
"return",
"true",
"\n",
"}"
] |
// Unregister implements Registerer.
|
[
"Unregister",
"implements",
"Registerer",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/registry.go#L351-L385
|
train
|
prometheus/client_golang
|
prometheus/registry.go
|
MustRegister
|
func (r *Registry) MustRegister(cs ...Collector) {
for _, c := range cs {
if err := r.Register(c); err != nil {
panic(err)
}
}
}
|
go
|
func (r *Registry) MustRegister(cs ...Collector) {
for _, c := range cs {
if err := r.Register(c); err != nil {
panic(err)
}
}
}
|
[
"func",
"(",
"r",
"*",
"Registry",
")",
"MustRegister",
"(",
"cs",
"...",
"Collector",
")",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"cs",
"{",
"if",
"err",
":=",
"r",
".",
"Register",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// MustRegister implements Registerer.
|
[
"MustRegister",
"implements",
"Registerer",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/registry.go#L388-L394
|
train
|
prometheus/client_golang
|
prometheus/registry.go
|
WriteToTextfile
|
func WriteToTextfile(filename string, g Gatherer) error {
tmp, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
if err != nil {
return err
}
defer os.Remove(tmp.Name())
mfs, err := g.Gather()
if err != nil {
return err
}
for _, mf := range mfs {
if _, err := expfmt.MetricFamilyToText(tmp, mf); err != nil {
return err
}
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Chmod(tmp.Name(), 0644); err != nil {
return err
}
return os.Rename(tmp.Name(), filename)
}
|
go
|
func WriteToTextfile(filename string, g Gatherer) error {
tmp, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
if err != nil {
return err
}
defer os.Remove(tmp.Name())
mfs, err := g.Gather()
if err != nil {
return err
}
for _, mf := range mfs {
if _, err := expfmt.MetricFamilyToText(tmp, mf); err != nil {
return err
}
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Chmod(tmp.Name(), 0644); err != nil {
return err
}
return os.Rename(tmp.Name(), filename)
}
|
[
"func",
"WriteToTextfile",
"(",
"filename",
"string",
",",
"g",
"Gatherer",
")",
"error",
"{",
"tmp",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"filepath",
".",
"Dir",
"(",
"filename",
")",
",",
"filepath",
".",
"Base",
"(",
"filename",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"os",
".",
"Remove",
"(",
"tmp",
".",
"Name",
"(",
")",
")",
"\n\n",
"mfs",
",",
"err",
":=",
"g",
".",
"Gather",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"mf",
":=",
"range",
"mfs",
"{",
"if",
"_",
",",
"err",
":=",
"expfmt",
".",
"MetricFamilyToText",
"(",
"tmp",
",",
"mf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tmp",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"os",
".",
"Chmod",
"(",
"tmp",
".",
"Name",
"(",
")",
",",
"0644",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"os",
".",
"Rename",
"(",
"tmp",
".",
"Name",
"(",
")",
",",
"filename",
")",
"\n",
"}"
] |
// WriteToTextfile calls Gather on the provided Gatherer, encodes the result in the
// Prometheus text format, and writes it to a temporary file. Upon success, the
// temporary file is renamed to the provided filename.
//
// This is intended for use with the textfile collector of the node exporter.
// Note that the node exporter expects the filename to be suffixed with ".prom".
|
[
"WriteToTextfile",
"calls",
"Gather",
"on",
"the",
"provided",
"Gatherer",
"encodes",
"the",
"result",
"in",
"the",
"Prometheus",
"text",
"format",
"and",
"writes",
"it",
"to",
"a",
"temporary",
"file",
".",
"Upon",
"success",
"the",
"temporary",
"file",
"is",
"renamed",
"to",
"the",
"provided",
"filename",
".",
"This",
"is",
"intended",
"for",
"use",
"with",
"the",
"textfile",
"collector",
"of",
"the",
"node",
"exporter",
".",
"Note",
"that",
"the",
"node",
"exporter",
"expects",
"the",
"filename",
"to",
"be",
"suffixed",
"with",
".",
"prom",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/registry.go#L546-L570
|
train
|
prometheus/client_golang
|
prometheus/registry.go
|
checkMetricConsistency
|
func checkMetricConsistency(
metricFamily *dto.MetricFamily,
dtoMetric *dto.Metric,
metricHashes map[uint64]struct{},
) error {
name := metricFamily.GetName()
// Type consistency with metric family.
if metricFamily.GetType() == dto.MetricType_GAUGE && dtoMetric.Gauge == nil ||
metricFamily.GetType() == dto.MetricType_COUNTER && dtoMetric.Counter == nil ||
metricFamily.GetType() == dto.MetricType_SUMMARY && dtoMetric.Summary == nil ||
metricFamily.GetType() == dto.MetricType_HISTOGRAM && dtoMetric.Histogram == nil ||
metricFamily.GetType() == dto.MetricType_UNTYPED && dtoMetric.Untyped == nil {
return fmt.Errorf(
"collected metric %q { %s} is not a %s",
name, dtoMetric, metricFamily.GetType(),
)
}
previousLabelName := ""
for _, labelPair := range dtoMetric.GetLabel() {
labelName := labelPair.GetName()
if labelName == previousLabelName {
return fmt.Errorf(
"collected metric %q { %s} has two or more labels with the same name: %s",
name, dtoMetric, labelName,
)
}
if !checkLabelName(labelName) {
return fmt.Errorf(
"collected metric %q { %s} has a label with an invalid name: %s",
name, dtoMetric, labelName,
)
}
if dtoMetric.Summary != nil && labelName == quantileLabel {
return fmt.Errorf(
"collected metric %q { %s} must not have an explicit %q label",
name, dtoMetric, quantileLabel,
)
}
if !utf8.ValidString(labelPair.GetValue()) {
return fmt.Errorf(
"collected metric %q { %s} has a label named %q whose value is not utf8: %#v",
name, dtoMetric, labelName, labelPair.GetValue())
}
previousLabelName = labelName
}
// Is the metric unique (i.e. no other metric with the same name and the same labels)?
h := hashNew()
h = hashAdd(h, name)
h = hashAddByte(h, separatorByte)
// Make sure label pairs are sorted. We depend on it for the consistency
// check.
if !sort.IsSorted(labelPairSorter(dtoMetric.Label)) {
// We cannot sort dtoMetric.Label in place as it is immutable by contract.
copiedLabels := make([]*dto.LabelPair, len(dtoMetric.Label))
copy(copiedLabels, dtoMetric.Label)
sort.Sort(labelPairSorter(copiedLabels))
dtoMetric.Label = copiedLabels
}
for _, lp := range dtoMetric.Label {
h = hashAdd(h, lp.GetName())
h = hashAddByte(h, separatorByte)
h = hashAdd(h, lp.GetValue())
h = hashAddByte(h, separatorByte)
}
if _, exists := metricHashes[h]; exists {
return fmt.Errorf(
"collected metric %q { %s} was collected before with the same name and label values",
name, dtoMetric,
)
}
metricHashes[h] = struct{}{}
return nil
}
|
go
|
func checkMetricConsistency(
metricFamily *dto.MetricFamily,
dtoMetric *dto.Metric,
metricHashes map[uint64]struct{},
) error {
name := metricFamily.GetName()
// Type consistency with metric family.
if metricFamily.GetType() == dto.MetricType_GAUGE && dtoMetric.Gauge == nil ||
metricFamily.GetType() == dto.MetricType_COUNTER && dtoMetric.Counter == nil ||
metricFamily.GetType() == dto.MetricType_SUMMARY && dtoMetric.Summary == nil ||
metricFamily.GetType() == dto.MetricType_HISTOGRAM && dtoMetric.Histogram == nil ||
metricFamily.GetType() == dto.MetricType_UNTYPED && dtoMetric.Untyped == nil {
return fmt.Errorf(
"collected metric %q { %s} is not a %s",
name, dtoMetric, metricFamily.GetType(),
)
}
previousLabelName := ""
for _, labelPair := range dtoMetric.GetLabel() {
labelName := labelPair.GetName()
if labelName == previousLabelName {
return fmt.Errorf(
"collected metric %q { %s} has two or more labels with the same name: %s",
name, dtoMetric, labelName,
)
}
if !checkLabelName(labelName) {
return fmt.Errorf(
"collected metric %q { %s} has a label with an invalid name: %s",
name, dtoMetric, labelName,
)
}
if dtoMetric.Summary != nil && labelName == quantileLabel {
return fmt.Errorf(
"collected metric %q { %s} must not have an explicit %q label",
name, dtoMetric, quantileLabel,
)
}
if !utf8.ValidString(labelPair.GetValue()) {
return fmt.Errorf(
"collected metric %q { %s} has a label named %q whose value is not utf8: %#v",
name, dtoMetric, labelName, labelPair.GetValue())
}
previousLabelName = labelName
}
// Is the metric unique (i.e. no other metric with the same name and the same labels)?
h := hashNew()
h = hashAdd(h, name)
h = hashAddByte(h, separatorByte)
// Make sure label pairs are sorted. We depend on it for the consistency
// check.
if !sort.IsSorted(labelPairSorter(dtoMetric.Label)) {
// We cannot sort dtoMetric.Label in place as it is immutable by contract.
copiedLabels := make([]*dto.LabelPair, len(dtoMetric.Label))
copy(copiedLabels, dtoMetric.Label)
sort.Sort(labelPairSorter(copiedLabels))
dtoMetric.Label = copiedLabels
}
for _, lp := range dtoMetric.Label {
h = hashAdd(h, lp.GetName())
h = hashAddByte(h, separatorByte)
h = hashAdd(h, lp.GetValue())
h = hashAddByte(h, separatorByte)
}
if _, exists := metricHashes[h]; exists {
return fmt.Errorf(
"collected metric %q { %s} was collected before with the same name and label values",
name, dtoMetric,
)
}
metricHashes[h] = struct{}{}
return nil
}
|
[
"func",
"checkMetricConsistency",
"(",
"metricFamily",
"*",
"dto",
".",
"MetricFamily",
",",
"dtoMetric",
"*",
"dto",
".",
"Metric",
",",
"metricHashes",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
",",
")",
"error",
"{",
"name",
":=",
"metricFamily",
".",
"GetName",
"(",
")",
"\n\n",
"// Type consistency with metric family.",
"if",
"metricFamily",
".",
"GetType",
"(",
")",
"==",
"dto",
".",
"MetricType_GAUGE",
"&&",
"dtoMetric",
".",
"Gauge",
"==",
"nil",
"||",
"metricFamily",
".",
"GetType",
"(",
")",
"==",
"dto",
".",
"MetricType_COUNTER",
"&&",
"dtoMetric",
".",
"Counter",
"==",
"nil",
"||",
"metricFamily",
".",
"GetType",
"(",
")",
"==",
"dto",
".",
"MetricType_SUMMARY",
"&&",
"dtoMetric",
".",
"Summary",
"==",
"nil",
"||",
"metricFamily",
".",
"GetType",
"(",
")",
"==",
"dto",
".",
"MetricType_HISTOGRAM",
"&&",
"dtoMetric",
".",
"Histogram",
"==",
"nil",
"||",
"metricFamily",
".",
"GetType",
"(",
")",
"==",
"dto",
".",
"MetricType_UNTYPED",
"&&",
"dtoMetric",
".",
"Untyped",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"dtoMetric",
",",
"metricFamily",
".",
"GetType",
"(",
")",
",",
")",
"\n",
"}",
"\n\n",
"previousLabelName",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"labelPair",
":=",
"range",
"dtoMetric",
".",
"GetLabel",
"(",
")",
"{",
"labelName",
":=",
"labelPair",
".",
"GetName",
"(",
")",
"\n",
"if",
"labelName",
"==",
"previousLabelName",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"dtoMetric",
",",
"labelName",
",",
")",
"\n",
"}",
"\n",
"if",
"!",
"checkLabelName",
"(",
"labelName",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"dtoMetric",
",",
"labelName",
",",
")",
"\n",
"}",
"\n",
"if",
"dtoMetric",
".",
"Summary",
"!=",
"nil",
"&&",
"labelName",
"==",
"quantileLabel",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"dtoMetric",
",",
"quantileLabel",
",",
")",
"\n",
"}",
"\n",
"if",
"!",
"utf8",
".",
"ValidString",
"(",
"labelPair",
".",
"GetValue",
"(",
")",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"dtoMetric",
",",
"labelName",
",",
"labelPair",
".",
"GetValue",
"(",
")",
")",
"\n",
"}",
"\n",
"previousLabelName",
"=",
"labelName",
"\n",
"}",
"\n\n",
"// Is the metric unique (i.e. no other metric with the same name and the same labels)?",
"h",
":=",
"hashNew",
"(",
")",
"\n",
"h",
"=",
"hashAdd",
"(",
"h",
",",
"name",
")",
"\n",
"h",
"=",
"hashAddByte",
"(",
"h",
",",
"separatorByte",
")",
"\n",
"// Make sure label pairs are sorted. We depend on it for the consistency",
"// check.",
"if",
"!",
"sort",
".",
"IsSorted",
"(",
"labelPairSorter",
"(",
"dtoMetric",
".",
"Label",
")",
")",
"{",
"// We cannot sort dtoMetric.Label in place as it is immutable by contract.",
"copiedLabels",
":=",
"make",
"(",
"[",
"]",
"*",
"dto",
".",
"LabelPair",
",",
"len",
"(",
"dtoMetric",
".",
"Label",
")",
")",
"\n",
"copy",
"(",
"copiedLabels",
",",
"dtoMetric",
".",
"Label",
")",
"\n",
"sort",
".",
"Sort",
"(",
"labelPairSorter",
"(",
"copiedLabels",
")",
")",
"\n",
"dtoMetric",
".",
"Label",
"=",
"copiedLabels",
"\n",
"}",
"\n",
"for",
"_",
",",
"lp",
":=",
"range",
"dtoMetric",
".",
"Label",
"{",
"h",
"=",
"hashAdd",
"(",
"h",
",",
"lp",
".",
"GetName",
"(",
")",
")",
"\n",
"h",
"=",
"hashAddByte",
"(",
"h",
",",
"separatorByte",
")",
"\n",
"h",
"=",
"hashAdd",
"(",
"h",
",",
"lp",
".",
"GetValue",
"(",
")",
")",
"\n",
"h",
"=",
"hashAddByte",
"(",
"h",
",",
"separatorByte",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"exists",
":=",
"metricHashes",
"[",
"h",
"]",
";",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"dtoMetric",
",",
")",
"\n",
"}",
"\n",
"metricHashes",
"[",
"h",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// checkMetricConsistency checks if the provided Metric is consistent with the
// provided MetricFamily. It also hashes the Metric labels and the MetricFamily
// name. If the resulting hash is already in the provided metricHashes, an error
// is returned. If not, it is added to metricHashes.
|
[
"checkMetricConsistency",
"checks",
"if",
"the",
"provided",
"Metric",
"is",
"consistent",
"with",
"the",
"provided",
"MetricFamily",
".",
"It",
"also",
"hashes",
"the",
"Metric",
"labels",
"and",
"the",
"MetricFamily",
"name",
".",
"If",
"the",
"resulting",
"hash",
"is",
"already",
"in",
"the",
"provided",
"metricHashes",
"an",
"error",
"is",
"returned",
".",
"If",
"not",
"it",
"is",
"added",
"to",
"metricHashes",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/registry.go#L821-L896
|
train
|
prometheus/client_golang
|
prometheus/metric.go
|
NewMetricWithTimestamp
|
func NewMetricWithTimestamp(t time.Time, m Metric) Metric {
return timestampedMetric{Metric: m, t: t}
}
|
go
|
func NewMetricWithTimestamp(t time.Time, m Metric) Metric {
return timestampedMetric{Metric: m, t: t}
}
|
[
"func",
"NewMetricWithTimestamp",
"(",
"t",
"time",
".",
"Time",
",",
"m",
"Metric",
")",
"Metric",
"{",
"return",
"timestampedMetric",
"{",
"Metric",
":",
"m",
",",
"t",
":",
"t",
"}",
"\n",
"}"
] |
// NewMetricWithTimestamp returns a new Metric wrapping the provided Metric in a
// way that it has an explicit timestamp set to the provided Time. This is only
// useful in rare cases as the timestamp of a Prometheus metric should usually
// be set by the Prometheus server during scraping. Exceptions include mirroring
// metrics with given timestamps from other metric
// sources.
//
// NewMetricWithTimestamp works best with MustNewConstMetric,
// MustNewConstHistogram, and MustNewConstSummary, see example.
//
// Currently, the exposition formats used by Prometheus are limited to
// millisecond resolution. Thus, the provided time will be rounded down to the
// next full millisecond value.
|
[
"NewMetricWithTimestamp",
"returns",
"a",
"new",
"Metric",
"wrapping",
"the",
"provided",
"Metric",
"in",
"a",
"way",
"that",
"it",
"has",
"an",
"explicit",
"timestamp",
"set",
"to",
"the",
"provided",
"Time",
".",
"This",
"is",
"only",
"useful",
"in",
"rare",
"cases",
"as",
"the",
"timestamp",
"of",
"a",
"Prometheus",
"metric",
"should",
"usually",
"be",
"set",
"by",
"the",
"Prometheus",
"server",
"during",
"scraping",
".",
"Exceptions",
"include",
"mirroring",
"metrics",
"with",
"given",
"timestamps",
"from",
"other",
"metric",
"sources",
".",
"NewMetricWithTimestamp",
"works",
"best",
"with",
"MustNewConstMetric",
"MustNewConstHistogram",
"and",
"MustNewConstSummary",
"see",
"example",
".",
"Currently",
"the",
"exposition",
"formats",
"used",
"by",
"Prometheus",
"are",
"limited",
"to",
"millisecond",
"resolution",
".",
"Thus",
"the",
"provided",
"time",
"will",
"be",
"rounded",
"down",
"to",
"the",
"next",
"full",
"millisecond",
"value",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/metric.go#L172-L174
|
train
|
prometheus/client_golang
|
prometheus/value.go
|
newValueFunc
|
func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *valueFunc {
result := &valueFunc{
desc: desc,
valType: valueType,
function: function,
labelPairs: makeLabelPairs(desc, nil),
}
result.init(result)
return result
}
|
go
|
func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *valueFunc {
result := &valueFunc{
desc: desc,
valType: valueType,
function: function,
labelPairs: makeLabelPairs(desc, nil),
}
result.init(result)
return result
}
|
[
"func",
"newValueFunc",
"(",
"desc",
"*",
"Desc",
",",
"valueType",
"ValueType",
",",
"function",
"func",
"(",
")",
"float64",
")",
"*",
"valueFunc",
"{",
"result",
":=",
"&",
"valueFunc",
"{",
"desc",
":",
"desc",
",",
"valType",
":",
"valueType",
",",
"function",
":",
"function",
",",
"labelPairs",
":",
"makeLabelPairs",
"(",
"desc",
",",
"nil",
")",
",",
"}",
"\n",
"result",
".",
"init",
"(",
"result",
")",
"\n",
"return",
"result",
"\n",
"}"
] |
// newValueFunc returns a newly allocated valueFunc with the given Desc and
// ValueType. 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 valueFunc is directly registered with Prometheus, the
// provided function must be concurrency-safe.
|
[
"newValueFunc",
"returns",
"a",
"newly",
"allocated",
"valueFunc",
"with",
"the",
"given",
"Desc",
"and",
"ValueType",
".",
"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",
"valueFunc",
"is",
"directly",
"registered",
"with",
"Prometheus",
"the",
"provided",
"function",
"must",
"be",
"concurrency",
"-",
"safe",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/value.go#L56-L65
|
train
|
prometheus/client_golang
|
prometheus/value.go
|
NewConstMetric
|
func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error) {
if desc.err != nil {
return nil, desc.err
}
if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil {
return nil, err
}
return &constMetric{
desc: desc,
valType: valueType,
val: value,
labelPairs: makeLabelPairs(desc, labelValues),
}, nil
}
|
go
|
func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error) {
if desc.err != nil {
return nil, desc.err
}
if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil {
return nil, err
}
return &constMetric{
desc: desc,
valType: valueType,
val: value,
labelPairs: makeLabelPairs(desc, labelValues),
}, nil
}
|
[
"func",
"NewConstMetric",
"(",
"desc",
"*",
"Desc",
",",
"valueType",
"ValueType",
",",
"value",
"float64",
",",
"labelValues",
"...",
"string",
")",
"(",
"Metric",
",",
"error",
")",
"{",
"if",
"desc",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"desc",
".",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"validateLabelValues",
"(",
"labelValues",
",",
"len",
"(",
"desc",
".",
"variableLabels",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"constMetric",
"{",
"desc",
":",
"desc",
",",
"valType",
":",
"valueType",
",",
"val",
":",
"value",
",",
"labelPairs",
":",
"makeLabelPairs",
"(",
"desc",
",",
"labelValues",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewConstMetric returns a metric with one fixed value that cannot be
// changed. Users of this package will not have much use for it in regular
// operations. However, when implementing custom Collectors, it is useful as a
// throw-away metric that is generated on the fly to send it to Prometheus in
// the Collect method. NewConstMetric returns an error if the length of
// labelValues is not consistent with the variable labels in Desc or if Desc is
// invalid.
|
[
"NewConstMetric",
"returns",
"a",
"metric",
"with",
"one",
"fixed",
"value",
"that",
"cannot",
"be",
"changed",
".",
"Users",
"of",
"this",
"package",
"will",
"not",
"have",
"much",
"use",
"for",
"it",
"in",
"regular",
"operations",
".",
"However",
"when",
"implementing",
"custom",
"Collectors",
"it",
"is",
"useful",
"as",
"a",
"throw",
"-",
"away",
"metric",
"that",
"is",
"generated",
"on",
"the",
"fly",
"to",
"send",
"it",
"to",
"Prometheus",
"in",
"the",
"Collect",
"method",
".",
"NewConstMetric",
"returns",
"an",
"error",
"if",
"the",
"length",
"of",
"labelValues",
"is",
"not",
"consistent",
"with",
"the",
"variable",
"labels",
"in",
"Desc",
"or",
"if",
"Desc",
"is",
"invalid",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/value.go#L82-L95
|
train
|
prometheus/client_golang
|
prometheus/value.go
|
MustNewConstMetric
|
func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric {
m, err := NewConstMetric(desc, valueType, value, labelValues...)
if err != nil {
panic(err)
}
return m
}
|
go
|
func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric {
m, err := NewConstMetric(desc, valueType, value, labelValues...)
if err != nil {
panic(err)
}
return m
}
|
[
"func",
"MustNewConstMetric",
"(",
"desc",
"*",
"Desc",
",",
"valueType",
"ValueType",
",",
"value",
"float64",
",",
"labelValues",
"...",
"string",
")",
"Metric",
"{",
"m",
",",
"err",
":=",
"NewConstMetric",
"(",
"desc",
",",
"valueType",
",",
"value",
",",
"labelValues",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] |
// MustNewConstMetric is a version of NewConstMetric that panics where
// NewConstMetric would have returned an error.
|
[
"MustNewConstMetric",
"is",
"a",
"version",
"of",
"NewConstMetric",
"that",
"panics",
"where",
"NewConstMetric",
"would",
"have",
"returned",
"an",
"error",
"."
] |
6aba2189ebe6959268894366998500defefa2907
|
https://github.com/prometheus/client_golang/blob/6aba2189ebe6959268894366998500defefa2907/prometheus/value.go#L99-L105
|
train
|
pkg/errors
|
stack.go
|
name
|
func (f Frame) name() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
return fn.Name()
}
|
go
|
func (f Frame) name() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
return fn.Name()
}
|
[
"func",
"(",
"f",
"Frame",
")",
"name",
"(",
")",
"string",
"{",
"fn",
":=",
"runtime",
".",
"FuncForPC",
"(",
"f",
".",
"pc",
"(",
")",
")",
"\n",
"if",
"fn",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fn",
".",
"Name",
"(",
")",
"\n",
"}"
] |
// name returns the name of this function, if known.
|
[
"name",
"returns",
"the",
"name",
"of",
"this",
"function",
"if",
"known",
"."
] |
27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7
|
https://github.com/pkg/errors/blob/27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7/stack.go#L44-L50
|
train
|
pkg/errors
|
stack.go
|
formatSlice
|
func (st StackTrace) formatSlice(s fmt.State, verb rune) {
io.WriteString(s, "[")
for i, f := range st {
if i > 0 {
io.WriteString(s, " ")
}
f.Format(s, verb)
}
io.WriteString(s, "]")
}
|
go
|
func (st StackTrace) formatSlice(s fmt.State, verb rune) {
io.WriteString(s, "[")
for i, f := range st {
if i > 0 {
io.WriteString(s, " ")
}
f.Format(s, verb)
}
io.WriteString(s, "]")
}
|
[
"func",
"(",
"st",
"StackTrace",
")",
"formatSlice",
"(",
"s",
"fmt",
".",
"State",
",",
"verb",
"rune",
")",
"{",
"io",
".",
"WriteString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"st",
"{",
"if",
"i",
">",
"0",
"{",
"io",
".",
"WriteString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"f",
".",
"Format",
"(",
"s",
",",
"verb",
")",
"\n",
"}",
"\n",
"io",
".",
"WriteString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// formatSlice will format this StackTrace into the given buffer as a slice of
// Frame, only valid when called with '%s' or '%v'.
|
[
"formatSlice",
"will",
"format",
"this",
"StackTrace",
"into",
"the",
"given",
"buffer",
"as",
"a",
"slice",
"of",
"Frame",
"only",
"valid",
"when",
"called",
"with",
"%s",
"or",
"%v",
"."
] |
27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7
|
https://github.com/pkg/errors/blob/27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7/stack.go#L128-L137
|
train
|
pkg/errors
|
errors.go
|
WithMessage
|
func WithMessage(err error, message string) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: message,
}
}
|
go
|
func WithMessage(err error, message string) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: message,
}
}
|
[
"func",
"WithMessage",
"(",
"err",
"error",
",",
"message",
"string",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"withMessage",
"{",
"cause",
":",
"err",
",",
"msg",
":",
"message",
",",
"}",
"\n",
"}"
] |
// WithMessage annotates err with a new message.
// If err is nil, WithMessage returns nil.
|
[
"WithMessage",
"annotates",
"err",
"with",
"a",
"new",
"message",
".",
"If",
"err",
"is",
"nil",
"WithMessage",
"returns",
"nil",
"."
] |
27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7
|
https://github.com/pkg/errors/blob/27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7/errors.go#L214-L222
|
train
|
pkg/errors
|
errors.go
|
WithMessagef
|
func WithMessagef(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
}
|
go
|
func WithMessagef(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
}
|
[
"func",
"WithMessagef",
"(",
"err",
"error",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"withMessage",
"{",
"cause",
":",
"err",
",",
"msg",
":",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
",",
"}",
"\n",
"}"
] |
// WithMessagef annotates err with the format specifier.
// If err is nil, WithMessagef returns nil.
|
[
"WithMessagef",
"annotates",
"err",
"with",
"the",
"format",
"specifier",
".",
"If",
"err",
"is",
"nil",
"WithMessagef",
"returns",
"nil",
"."
] |
27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7
|
https://github.com/pkg/errors/blob/27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7/errors.go#L226-L234
|
train
|
awslabs/goformation
|
generate/resource.go
|
Required
|
func (r Resource) Required() string {
required := []string{}
for name, property := range r.Properties {
if property.Required {
required = append(required, `"`+name+`"`)
}
}
// As Go doesn't provide ordering guarentees for maps, we should
// sort the required property names by alphabetical order so that
// they don't shuffle on every generation, and cause annoying commit diffs
sort.Strings(required)
return strings.Join(required, ", ")
}
|
go
|
func (r Resource) Required() string {
required := []string{}
for name, property := range r.Properties {
if property.Required {
required = append(required, `"`+name+`"`)
}
}
// As Go doesn't provide ordering guarentees for maps, we should
// sort the required property names by alphabetical order so that
// they don't shuffle on every generation, and cause annoying commit diffs
sort.Strings(required)
return strings.Join(required, ", ")
}
|
[
"func",
"(",
"r",
"Resource",
")",
"Required",
"(",
")",
"string",
"{",
"required",
":=",
"[",
"]",
"string",
"{",
"}",
"\n\n",
"for",
"name",
",",
"property",
":=",
"range",
"r",
".",
"Properties",
"{",
"if",
"property",
".",
"Required",
"{",
"required",
"=",
"append",
"(",
"required",
",",
"`\"`",
"+",
"name",
"+",
"`\"`",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// As Go doesn't provide ordering guarentees for maps, we should",
"// sort the required property names by alphabetical order so that",
"// they don't shuffle on every generation, and cause annoying commit diffs",
"sort",
".",
"Strings",
"(",
"required",
")",
"\n\n",
"return",
"strings",
".",
"Join",
"(",
"required",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// Required returns a comma separated list of the required properties for this resource
|
[
"Required",
"returns",
"a",
"comma",
"separated",
"list",
"of",
"the",
"required",
"properties",
"for",
"this",
"resource"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/generate/resource.go#L57-L72
|
train
|
awslabs/goformation
|
intrinsics/intrinsics.go
|
overrideParameters
|
func overrideParameters(input interface{}, options *ProcessorOptions) {
if options == nil || len(options.ParameterOverrides) == 0 {
return
}
// Check the template is a map
if template, ok := input.(map[string]interface{}); ok {
// Check there is a parameters section
if uparameters, ok := template["Parameters"]; ok {
// Check the parameters section is a map
if parameters, ok := uparameters.(map[string]interface{}); ok {
for name, value := range options.ParameterOverrides {
// Check there is a parameter with the same name as the Ref
if uparameter, ok := parameters[name]; ok {
// Check the parameter is a map
if parameter, ok := uparameter.(map[string]interface{}); ok {
// Set the default value
parameter["Default"] = value
}
}
}
}
}
}
}
|
go
|
func overrideParameters(input interface{}, options *ProcessorOptions) {
if options == nil || len(options.ParameterOverrides) == 0 {
return
}
// Check the template is a map
if template, ok := input.(map[string]interface{}); ok {
// Check there is a parameters section
if uparameters, ok := template["Parameters"]; ok {
// Check the parameters section is a map
if parameters, ok := uparameters.(map[string]interface{}); ok {
for name, value := range options.ParameterOverrides {
// Check there is a parameter with the same name as the Ref
if uparameter, ok := parameters[name]; ok {
// Check the parameter is a map
if parameter, ok := uparameter.(map[string]interface{}); ok {
// Set the default value
parameter["Default"] = value
}
}
}
}
}
}
}
|
[
"func",
"overrideParameters",
"(",
"input",
"interface",
"{",
"}",
",",
"options",
"*",
"ProcessorOptions",
")",
"{",
"if",
"options",
"==",
"nil",
"||",
"len",
"(",
"options",
".",
"ParameterOverrides",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"// Check the template is a map",
"if",
"template",
",",
"ok",
":=",
"input",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"// Check there is a parameters section",
"if",
"uparameters",
",",
"ok",
":=",
"template",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"// Check the parameters section is a map",
"if",
"parameters",
",",
"ok",
":=",
"uparameters",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"name",
",",
"value",
":=",
"range",
"options",
".",
"ParameterOverrides",
"{",
"// Check there is a parameter with the same name as the Ref",
"if",
"uparameter",
",",
"ok",
":=",
"parameters",
"[",
"name",
"]",
";",
"ok",
"{",
"// Check the parameter is a map",
"if",
"parameter",
",",
"ok",
":=",
"uparameter",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"// Set the default value",
"parameter",
"[",
"\"",
"\"",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// overrideParameters replaces the default values of Parameters with the specified ones
|
[
"overrideParameters",
"replaces",
"the",
"default",
"values",
"of",
"Parameters",
"with",
"the",
"specified",
"ones"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/intrinsics/intrinsics.go#L108-L132
|
train
|
awslabs/goformation
|
intrinsics/intrinsics.go
|
applyGlobals
|
func applyGlobals(input interface{}, options *ProcessorOptions) {
if template, ok := input.(map[string]interface{}); ok {
if uglobals, ok := template["Globals"]; ok {
if globals, ok := uglobals.(map[string]interface{}); ok {
for name, globalValues := range globals {
for supportedGlobalName, supportedGlobalType := range supportedGlobalResources {
if name == supportedGlobalName {
if uresources, ok := template["Resources"]; ok {
if resources, ok := uresources.(map[string]interface{}); ok {
for _, uresource := range resources {
if resource, ok := uresource.(map[string]interface{}); ok {
if resource["Type"] == supportedGlobalType {
properties := resource["Properties"].(map[string]interface{})
for globalProp, globalPropValue := range globalValues.(map[string]interface{}) {
if _, ok := properties[globalProp]; !ok {
properties[globalProp] = globalPropValue
} else if gArray, ok := globalPropValue.([]interface{}); ok {
if pArray, ok := properties[globalProp].([]interface{}); ok {
properties[globalProp] = append(pArray, gArray...)
}
} else if gMap, ok := globalPropValue.(map[string]interface{}); ok {
if pMap, ok := properties[globalProp].(map[string]interface{}); ok {
mergo.Merge(&pMap, gMap)
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
|
go
|
func applyGlobals(input interface{}, options *ProcessorOptions) {
if template, ok := input.(map[string]interface{}); ok {
if uglobals, ok := template["Globals"]; ok {
if globals, ok := uglobals.(map[string]interface{}); ok {
for name, globalValues := range globals {
for supportedGlobalName, supportedGlobalType := range supportedGlobalResources {
if name == supportedGlobalName {
if uresources, ok := template["Resources"]; ok {
if resources, ok := uresources.(map[string]interface{}); ok {
for _, uresource := range resources {
if resource, ok := uresource.(map[string]interface{}); ok {
if resource["Type"] == supportedGlobalType {
properties := resource["Properties"].(map[string]interface{})
for globalProp, globalPropValue := range globalValues.(map[string]interface{}) {
if _, ok := properties[globalProp]; !ok {
properties[globalProp] = globalPropValue
} else if gArray, ok := globalPropValue.([]interface{}); ok {
if pArray, ok := properties[globalProp].([]interface{}); ok {
properties[globalProp] = append(pArray, gArray...)
}
} else if gMap, ok := globalPropValue.(map[string]interface{}); ok {
if pMap, ok := properties[globalProp].(map[string]interface{}); ok {
mergo.Merge(&pMap, gMap)
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
|
[
"func",
"applyGlobals",
"(",
"input",
"interface",
"{",
"}",
",",
"options",
"*",
"ProcessorOptions",
")",
"{",
"if",
"template",
",",
"ok",
":=",
"input",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"uglobals",
",",
"ok",
":=",
"template",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"globals",
",",
"ok",
":=",
"uglobals",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"name",
",",
"globalValues",
":=",
"range",
"globals",
"{",
"for",
"supportedGlobalName",
",",
"supportedGlobalType",
":=",
"range",
"supportedGlobalResources",
"{",
"if",
"name",
"==",
"supportedGlobalName",
"{",
"if",
"uresources",
",",
"ok",
":=",
"template",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"resources",
",",
"ok",
":=",
"uresources",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"_",
",",
"uresource",
":=",
"range",
"resources",
"{",
"if",
"resource",
",",
"ok",
":=",
"uresource",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"resource",
"[",
"\"",
"\"",
"]",
"==",
"supportedGlobalType",
"{",
"properties",
":=",
"resource",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"globalProp",
",",
"globalPropValue",
":=",
"range",
"globalValues",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"properties",
"[",
"globalProp",
"]",
";",
"!",
"ok",
"{",
"properties",
"[",
"globalProp",
"]",
"=",
"globalPropValue",
"\n",
"}",
"else",
"if",
"gArray",
",",
"ok",
":=",
"globalPropValue",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"pArray",
",",
"ok",
":=",
"properties",
"[",
"globalProp",
"]",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"properties",
"[",
"globalProp",
"]",
"=",
"append",
"(",
"pArray",
",",
"gArray",
"...",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"gMap",
",",
"ok",
":=",
"globalPropValue",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"pMap",
",",
"ok",
":=",
"properties",
"[",
"globalProp",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"mergo",
".",
"Merge",
"(",
"&",
"pMap",
",",
"gMap",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// applyGlobals adds AWS SAM Globals into resources
|
[
"applyGlobals",
"adds",
"AWS",
"SAM",
"Globals",
"into",
"resources"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/intrinsics/intrinsics.go#L140-L177
|
train
|
awslabs/goformation
|
intrinsics/intrinsics.go
|
evaluateConditions
|
func evaluateConditions(input interface{}, options *ProcessorOptions) {
if template, ok := input.(map[string]interface{}); ok {
// Check there is a conditions section
if uconditions, ok := template["Conditions"]; ok {
// Check the conditions section is a map
if conditions, ok := uconditions.(map[string]interface{}); ok {
for name, expr := range conditions {
conditions[name] = search(expr, input, options)
}
}
}
}
}
|
go
|
func evaluateConditions(input interface{}, options *ProcessorOptions) {
if template, ok := input.(map[string]interface{}); ok {
// Check there is a conditions section
if uconditions, ok := template["Conditions"]; ok {
// Check the conditions section is a map
if conditions, ok := uconditions.(map[string]interface{}); ok {
for name, expr := range conditions {
conditions[name] = search(expr, input, options)
}
}
}
}
}
|
[
"func",
"evaluateConditions",
"(",
"input",
"interface",
"{",
"}",
",",
"options",
"*",
"ProcessorOptions",
")",
"{",
"if",
"template",
",",
"ok",
":=",
"input",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"// Check there is a conditions section",
"if",
"uconditions",
",",
"ok",
":=",
"template",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"// Check the conditions section is a map",
"if",
"conditions",
",",
"ok",
":=",
"uconditions",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"name",
",",
"expr",
":=",
"range",
"conditions",
"{",
"conditions",
"[",
"name",
"]",
"=",
"search",
"(",
"expr",
",",
"input",
",",
"options",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// evaluateConditions replaces each condition in the template with its corresponding
// value
|
[
"evaluateConditions",
"replaces",
"each",
"condition",
"in",
"the",
"template",
"with",
"its",
"corresponding",
"value"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/intrinsics/intrinsics.go#L181-L193
|
train
|
awslabs/goformation
|
intrinsics/intrinsics.go
|
handler
|
func handler(name string, options *ProcessorOptions) (IntrinsicHandler, bool) {
// Check if we have a handler for this intrinsic type in the instrinsic handler
// overrides in the options provided to Process()
if options != nil {
if h, ok := options.IntrinsicHandlerOverrides[name]; ok {
return h, true
}
}
if h, ok := defaultIntrinsicHandlers[name]; ok {
return h, true
}
return nil, false
}
|
go
|
func handler(name string, options *ProcessorOptions) (IntrinsicHandler, bool) {
// Check if we have a handler for this intrinsic type in the instrinsic handler
// overrides in the options provided to Process()
if options != nil {
if h, ok := options.IntrinsicHandlerOverrides[name]; ok {
return h, true
}
}
if h, ok := defaultIntrinsicHandlers[name]; ok {
return h, true
}
return nil, false
}
|
[
"func",
"handler",
"(",
"name",
"string",
",",
"options",
"*",
"ProcessorOptions",
")",
"(",
"IntrinsicHandler",
",",
"bool",
")",
"{",
"// Check if we have a handler for this intrinsic type in the instrinsic handler",
"// overrides in the options provided to Process()",
"if",
"options",
"!=",
"nil",
"{",
"if",
"h",
",",
"ok",
":=",
"options",
".",
"IntrinsicHandlerOverrides",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"h",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"h",
",",
"ok",
":=",
"defaultIntrinsicHandlers",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"h",
",",
"true",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"false",
"\n\n",
"}"
] |
// handler looks up the correct intrinsic function handler for an object key, if there is one.
// If not, it returns nil, false.
|
[
"handler",
"looks",
"up",
"the",
"correct",
"intrinsic",
"function",
"handler",
"for",
"an",
"object",
"key",
"if",
"there",
"is",
"one",
".",
"If",
"not",
"it",
"returns",
"nil",
"false",
"."
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/intrinsics/intrinsics.go#L289-L305
|
train
|
awslabs/goformation
|
cloudformation/template.go
|
NewTemplate
|
func NewTemplate() *Template {
return &Template{
AWSTemplateFormatVersion: "2010-09-09",
Description: "",
Metadata: map[string]interface{}{},
Parameters: map[string]interface{}{},
Mappings: map[string]interface{}{},
Conditions: map[string]interface{}{},
Resources: Resources{},
Outputs: map[string]interface{}{},
}
}
|
go
|
func NewTemplate() *Template {
return &Template{
AWSTemplateFormatVersion: "2010-09-09",
Description: "",
Metadata: map[string]interface{}{},
Parameters: map[string]interface{}{},
Mappings: map[string]interface{}{},
Conditions: map[string]interface{}{},
Resources: Resources{},
Outputs: map[string]interface{}{},
}
}
|
[
"func",
"NewTemplate",
"(",
")",
"*",
"Template",
"{",
"return",
"&",
"Template",
"{",
"AWSTemplateFormatVersion",
":",
"\"",
"\"",
",",
"Description",
":",
"\"",
"\"",
",",
"Metadata",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"Parameters",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"Mappings",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"Conditions",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"Resources",
":",
"Resources",
"{",
"}",
",",
"Outputs",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"}",
"\n",
"}"
] |
// NewTemplate creates a new AWS CloudFormation template struct
|
[
"NewTemplate",
"creates",
"a",
"new",
"AWS",
"CloudFormation",
"template",
"struct"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/cloudformation/template.go#L120-L131
|
train
|
awslabs/goformation
|
cloudformation/template.go
|
JSON
|
func (t *Template) JSON() ([]byte, error) {
j, err := json.MarshalIndent(t, "", " ")
if err != nil {
return nil, err
}
return intrinsics.ProcessJSON(j, nil)
}
|
go
|
func (t *Template) JSON() ([]byte, error) {
j, err := json.MarshalIndent(t, "", " ")
if err != nil {
return nil, err
}
return intrinsics.ProcessJSON(j, nil)
}
|
[
"func",
"(",
"t",
"*",
"Template",
")",
"JSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"j",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"t",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"intrinsics",
".",
"ProcessJSON",
"(",
"j",
",",
"nil",
")",
"\n\n",
"}"
] |
// JSON converts an AWS CloudFormation template object to JSON
|
[
"JSON",
"converts",
"an",
"AWS",
"CloudFormation",
"template",
"object",
"to",
"JSON"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/cloudformation/template.go#L134-L143
|
train
|
awslabs/goformation
|
cloudformation/template.go
|
YAML
|
func (t *Template) YAML() ([]byte, error) {
j, err := t.JSON()
if err != nil {
return nil, err
}
return yaml.JSONToYAML(j)
}
|
go
|
func (t *Template) YAML() ([]byte, error) {
j, err := t.JSON()
if err != nil {
return nil, err
}
return yaml.JSONToYAML(j)
}
|
[
"func",
"(",
"t",
"*",
"Template",
")",
"YAML",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"j",
",",
"err",
":=",
"t",
".",
"JSON",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"yaml",
".",
"JSONToYAML",
"(",
"j",
")",
"\n\n",
"}"
] |
// YAML converts an AWS CloudFormation template object to YAML
|
[
"YAML",
"converts",
"an",
"AWS",
"CloudFormation",
"template",
"object",
"to",
"YAML"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/cloudformation/template.go#L146-L155
|
train
|
awslabs/goformation
|
generate/property.go
|
IsPolymorphic
|
func (p Property) IsPolymorphic() bool {
return len(p.PrimitiveTypes) > 0 || len(p.PrimitiveItemTypes) > 0 || len(p.PrimitiveItemTypes) > 0 || len(p.ItemTypes) > 0 || len(p.Types) > 0
}
|
go
|
func (p Property) IsPolymorphic() bool {
return len(p.PrimitiveTypes) > 0 || len(p.PrimitiveItemTypes) > 0 || len(p.PrimitiveItemTypes) > 0 || len(p.ItemTypes) > 0 || len(p.Types) > 0
}
|
[
"func",
"(",
"p",
"Property",
")",
"IsPolymorphic",
"(",
")",
"bool",
"{",
"return",
"len",
"(",
"p",
".",
"PrimitiveTypes",
")",
">",
"0",
"||",
"len",
"(",
"p",
".",
"PrimitiveItemTypes",
")",
">",
"0",
"||",
"len",
"(",
"p",
".",
"PrimitiveItemTypes",
")",
">",
"0",
"||",
"len",
"(",
"p",
".",
"ItemTypes",
")",
">",
"0",
"||",
"len",
"(",
"p",
".",
"Types",
")",
">",
"0",
"\n",
"}"
] |
// IsPolymorphic checks whether a property can be multiple different types
|
[
"IsPolymorphic",
"checks",
"whether",
"a",
"property",
"can",
"be",
"multiple",
"different",
"types"
] |
8898b813a27809556420fcf0427a32765a567302
|
https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/generate/property.go#L105-L107
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.