id int32 0 167k | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8,600 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | Params | func (k *Key) Params() backend.Params {
return backend.Params{
Content: k.Content,
Authority: k.Authority,
FormatSpec: config.FormatSpec{k.Formatter, k.FormatData},
}
} | go | func (k *Key) Params() backend.Params {
return backend.Params{
Content: k.Content,
Authority: k.Authority,
FormatSpec: config.FormatSpec{k.Formatter, k.FormatData},
}
} | [
"func",
"(",
"k",
"*",
"Key",
")",
"Params",
"(",
")",
"backend",
".",
"Params",
"{",
"return",
"backend",
".",
"Params",
"{",
"Content",
":",
"k",
".",
"Content",
",",
"Authority",
":",
"k",
".",
"Authority",
",",
"FormatSpec",
":",
"config",
".",
... | // Params returns the backend.Params that are encoded in this Key. | [
"Params",
"returns",
"the",
"backend",
".",
"Params",
"that",
"are",
"encoded",
"in",
"this",
"Key",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L93-L99 |
8,601 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | MakeValueItem | func MakeValueItem(it *config.Config) ValueItem {
return ValueItem{
ConfigSet: string(it.ConfigSet),
Path: it.Path,
ContentHash: it.ContentHash,
Revision: it.Revision,
ViewURL: it.Meta.ViewURL,
Content: []byte(it.Content),
Formatter: it.FormatSpec.Formatter,
FormatData: []byte(it.FormatSpec.Data),
}
} | go | func MakeValueItem(it *config.Config) ValueItem {
return ValueItem{
ConfigSet: string(it.ConfigSet),
Path: it.Path,
ContentHash: it.ContentHash,
Revision: it.Revision,
ViewURL: it.Meta.ViewURL,
Content: []byte(it.Content),
Formatter: it.FormatSpec.Formatter,
FormatData: []byte(it.FormatSpec.Data),
}
} | [
"func",
"MakeValueItem",
"(",
"it",
"*",
"config",
".",
"Config",
")",
"ValueItem",
"{",
"return",
"ValueItem",
"{",
"ConfigSet",
":",
"string",
"(",
"it",
".",
"ConfigSet",
")",
",",
"Path",
":",
"it",
".",
"Path",
",",
"ContentHash",
":",
"it",
".",
... | // MakeValueItem builds a caching ValueItem from a config.Config. | [
"MakeValueItem",
"builds",
"a",
"caching",
"ValueItem",
"from",
"a",
"config",
".",
"Config",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L126-L137 |
8,602 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | ConfigItem | func (vi *ValueItem) ConfigItem() *config.Config {
return &config.Config{
Meta: config.Meta{
ConfigSet: config.Set(vi.ConfigSet),
Path: vi.Path,
ContentHash: vi.ContentHash,
Revision: vi.Revision,
ViewURL: vi.ViewURL,
},
Content: string(vi.Content),
FormatSpec: config.FormatSpec{vi.Formatter, string(vi.FormatData)},
}
} | go | func (vi *ValueItem) ConfigItem() *config.Config {
return &config.Config{
Meta: config.Meta{
ConfigSet: config.Set(vi.ConfigSet),
Path: vi.Path,
ContentHash: vi.ContentHash,
Revision: vi.Revision,
ViewURL: vi.ViewURL,
},
Content: string(vi.Content),
FormatSpec: config.FormatSpec{vi.Formatter, string(vi.FormatData)},
}
} | [
"func",
"(",
"vi",
"*",
"ValueItem",
")",
"ConfigItem",
"(",
")",
"*",
"config",
".",
"Config",
"{",
"return",
"&",
"config",
".",
"Config",
"{",
"Meta",
":",
"config",
".",
"Meta",
"{",
"ConfigSet",
":",
"config",
".",
"Set",
"(",
"vi",
".",
"Conf... | // ConfigItem returns the config.Config equivalent of vi. | [
"ConfigItem",
"returns",
"the",
"config",
".",
"Config",
"equivalent",
"of",
"vi",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L140-L152 |
8,603 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | descriptionToken | func (vi *ValueItem) descriptionToken() string {
return fmt.Sprintf("[%s:%s@%s]", vi.ConfigSet, vi.Path, vi.Revision)
} | go | func (vi *ValueItem) descriptionToken() string {
return fmt.Sprintf("[%s:%s@%s]", vi.ConfigSet, vi.Path, vi.Revision)
} | [
"func",
"(",
"vi",
"*",
"ValueItem",
")",
"descriptionToken",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"vi",
".",
"ConfigSet",
",",
"vi",
".",
"Path",
",",
"vi",
".",
"Revision",
")",
"\n",
"}"
] | // descriptionToken returns a human-readable string describing the contents of
// this item. | [
"descriptionToken",
"returns",
"a",
"human",
"-",
"readable",
"string",
"describing",
"the",
"contents",
"of",
"this",
"item",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L156-L158 |
8,604 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | LoadItems | func (v *Value) LoadItems(items ...*config.Config) {
if len(items) == 0 {
v.Items = nil
return
}
v.Items = make([]ValueItem, len(items))
for i, it := range items {
v.Items[i] = MakeValueItem(it)
}
} | go | func (v *Value) LoadItems(items ...*config.Config) {
if len(items) == 0 {
v.Items = nil
return
}
v.Items = make([]ValueItem, len(items))
for i, it := range items {
v.Items[i] = MakeValueItem(it)
}
} | [
"func",
"(",
"v",
"*",
"Value",
")",
"LoadItems",
"(",
"items",
"...",
"*",
"config",
".",
"Config",
")",
"{",
"if",
"len",
"(",
"items",
")",
"==",
"0",
"{",
"v",
".",
"Items",
"=",
"nil",
"\n",
"return",
"\n",
"}",
"\n\n",
"v",
".",
"Items",
... | // LoadItems loads a set of config.Config into v's Items field. If items is nil,
// v.Items will be nil. | [
"LoadItems",
"loads",
"a",
"set",
"of",
"config",
".",
"Config",
"into",
"v",
"s",
"Items",
"field",
".",
"If",
"items",
"is",
"nil",
"v",
".",
"Items",
"will",
"be",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L171-L181 |
8,605 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | SingleItem | func (v *Value) SingleItem() *config.Config {
if len(v.Items) == 0 {
return nil
}
return v.Items[0].ConfigItem()
} | go | func (v *Value) SingleItem() *config.Config {
if len(v.Items) == 0 {
return nil
}
return v.Items[0].ConfigItem()
} | [
"func",
"(",
"v",
"*",
"Value",
")",
"SingleItem",
"(",
")",
"*",
"config",
".",
"Config",
"{",
"if",
"len",
"(",
"v",
".",
"Items",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"v",
".",
"Items",
"[",
"0",
"]",
".",
"Conf... | // SingleItem returns the first config.Config in v's Items slice. If the Items
// slice is empty, SingleItem will return nil. | [
"SingleItem",
"returns",
"the",
"first",
"config",
".",
"Config",
"in",
"v",
"s",
"Items",
"slice",
".",
"If",
"the",
"Items",
"slice",
"is",
"empty",
"SingleItem",
"will",
"return",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L185-L190 |
8,606 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | ConfigItems | func (v *Value) ConfigItems() []*config.Config {
if len(v.Items) == 0 {
return nil
}
res := make([]*config.Config, len(v.Items))
for i := range v.Items {
res[i] = v.Items[i].ConfigItem()
}
return res
} | go | func (v *Value) ConfigItems() []*config.Config {
if len(v.Items) == 0 {
return nil
}
res := make([]*config.Config, len(v.Items))
for i := range v.Items {
res[i] = v.Items[i].ConfigItem()
}
return res
} | [
"func",
"(",
"v",
"*",
"Value",
")",
"ConfigItems",
"(",
")",
"[",
"]",
"*",
"config",
".",
"Config",
"{",
"if",
"len",
"(",
"v",
".",
"Items",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"res",
":=",
"make",
"(",
"[",
"]",
"*",
... | // ConfigItems returns the config.Config projection of v's Items slice. | [
"ConfigItems",
"returns",
"the",
"config",
".",
"Config",
"projection",
"of",
"v",
"s",
"Items",
"slice",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L193-L203 |
8,607 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | DecodeValue | func DecodeValue(d []byte) (*Value, error) {
var v Value
if err := Decode(d, &v); err != nil {
return nil, errors.Annotate(err, "").Err()
}
return &v, nil
} | go | func DecodeValue(d []byte) (*Value, error) {
var v Value
if err := Decode(d, &v); err != nil {
return nil, errors.Annotate(err, "").Err()
}
return &v, nil
} | [
"func",
"DecodeValue",
"(",
"d",
"[",
"]",
"byte",
")",
"(",
"*",
"Value",
",",
"error",
")",
"{",
"var",
"v",
"Value",
"\n",
"if",
"err",
":=",
"Decode",
"(",
"d",
",",
"&",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"erro... | // DecodeValue loads a Value from is encoded representation. | [
"DecodeValue",
"loads",
"a",
"Value",
"from",
"is",
"encoded",
"representation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L206-L212 |
8,608 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | Description | func (v *Value) Description() string {
parts := make([]string, 0, len(v.Items))
for _, it := range v.Items {
parts = append(parts, it.descriptionToken())
}
return strings.Join(parts, ", ")
} | go | func (v *Value) Description() string {
parts := make([]string, 0, len(v.Items))
for _, it := range v.Items {
parts = append(parts, it.descriptionToken())
}
return strings.Join(parts, ", ")
} | [
"func",
"(",
"v",
"*",
"Value",
")",
"Description",
"(",
")",
"string",
"{",
"parts",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"v",
".",
"Items",
")",
")",
"\n",
"for",
"_",
",",
"it",
":=",
"range",
"v",
".",
"Items"... | // Description returns a human-readable string describing the contents of this
// value. | [
"Description",
"returns",
"a",
"human",
"-",
"readable",
"string",
"describing",
"the",
"contents",
"of",
"this",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L224-L231 |
8,609 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | GetAll | func (b *Backend) GetAll(c context.Context, t backend.GetAllTarget, path string, p backend.Params) ([]*config.Config, error) {
key := Key{
Schema: Schema,
ServiceURL: b.keyServiceURL(c),
Authority: p.Authority,
Op: OpGetAll,
Content: p.Content,
Path: path,
GetAllTarget: t,
Formatter: p.FormatSpec.Formatter,
FormatData: p.FormatSpec.Data,
}
value, err := b.CacheGet(c, key, b.loader)
if err != nil {
if b.FailOnError {
log.Fields{
log.ErrorKey: err,
"authority": p.Authority,
"type": t,
"path": path,
}.Errorf(c, "(Hard Failure) failed to load cache value.")
return nil, errors.Annotate(err, "").Err()
}
log.Fields{
log.ErrorKey: err,
"authority": p.Authority,
"type": t,
"path": path,
}.Warningf(c, "Failed to load cache value.")
return b.B.GetAll(c, t, path, p)
}
return value.ConfigItems(), nil
} | go | func (b *Backend) GetAll(c context.Context, t backend.GetAllTarget, path string, p backend.Params) ([]*config.Config, error) {
key := Key{
Schema: Schema,
ServiceURL: b.keyServiceURL(c),
Authority: p.Authority,
Op: OpGetAll,
Content: p.Content,
Path: path,
GetAllTarget: t,
Formatter: p.FormatSpec.Formatter,
FormatData: p.FormatSpec.Data,
}
value, err := b.CacheGet(c, key, b.loader)
if err != nil {
if b.FailOnError {
log.Fields{
log.ErrorKey: err,
"authority": p.Authority,
"type": t,
"path": path,
}.Errorf(c, "(Hard Failure) failed to load cache value.")
return nil, errors.Annotate(err, "").Err()
}
log.Fields{
log.ErrorKey: err,
"authority": p.Authority,
"type": t,
"path": path,
}.Warningf(c, "Failed to load cache value.")
return b.B.GetAll(c, t, path, p)
}
return value.ConfigItems(), nil
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"GetAll",
"(",
"c",
"context",
".",
"Context",
",",
"t",
"backend",
".",
"GetAllTarget",
",",
"path",
"string",
",",
"p",
"backend",
".",
"Params",
")",
"(",
"[",
"]",
"*",
"config",
".",
"Config",
",",
"error... | // GetAll implements config.Backend. | [
"GetAll",
"implements",
"config",
".",
"Backend",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L314-L347 |
8,610 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | loader | func (b *Backend) loader(c context.Context, k Key, v *Value) (*Value, error) {
return CacheLoad(c, b.B, k, v)
} | go | func (b *Backend) loader(c context.Context, k Key, v *Value) (*Value, error) {
return CacheLoad(c, b.B, k, v)
} | [
"func",
"(",
"b",
"*",
"Backend",
")",
"loader",
"(",
"c",
"context",
".",
"Context",
",",
"k",
"Key",
",",
"v",
"*",
"Value",
")",
"(",
"*",
"Value",
",",
"error",
")",
"{",
"return",
"CacheLoad",
"(",
"c",
",",
"b",
".",
"B",
",",
"k",
",",... | // loader runs a cache get against the configured Base backend.
//
// This should be used by caches that do not have the cached value. | [
"loader",
"runs",
"a",
"cache",
"get",
"against",
"the",
"configured",
"Base",
"backend",
".",
"This",
"should",
"be",
"used",
"by",
"caches",
"that",
"do",
"not",
"have",
"the",
"cached",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L352-L354 |
8,611 | luci/luci-go | config/server/cfgclient/backend/caching/config.go | CacheLoad | func CacheLoad(c context.Context, b backend.B, k Key, v *Value) (rv *Value, err error) {
switch k.Op {
case OpGet:
rv, err = doGet(c, b, k.ConfigSet, k.Path, v, k.Params())
case OpGetAll:
rv, err = doGetAll(c, b, k.GetAllTarget, k.Path, v, k.Params())
default:
return nil, errors.Reason("unknown operation: %v", k.Op).Err()
}
if err != nil {
return nil, err
}
return
} | go | func CacheLoad(c context.Context, b backend.B, k Key, v *Value) (rv *Value, err error) {
switch k.Op {
case OpGet:
rv, err = doGet(c, b, k.ConfigSet, k.Path, v, k.Params())
case OpGetAll:
rv, err = doGetAll(c, b, k.GetAllTarget, k.Path, v, k.Params())
default:
return nil, errors.Reason("unknown operation: %v", k.Op).Err()
}
if err != nil {
return nil, err
}
return
} | [
"func",
"CacheLoad",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"backend",
".",
"B",
",",
"k",
"Key",
",",
"v",
"*",
"Value",
")",
"(",
"rv",
"*",
"Value",
",",
"err",
"error",
")",
"{",
"switch",
"k",
".",
"Op",
"{",
"case",
"OpGet",
":",
... | // CacheLoad loads k from backend b.
//
// If an existing cache value is known, it should be supplied as v. Otherwise,
// v should be nil.
//
// This is effectively a Loader function that is detached from a given cache
// instance. | [
"CacheLoad",
"loads",
"k",
"from",
"backend",
"b",
".",
"If",
"an",
"existing",
"cache",
"value",
"is",
"known",
"it",
"should",
"be",
"supplied",
"as",
"v",
".",
"Otherwise",
"v",
"should",
"be",
"nil",
".",
"This",
"is",
"effectively",
"a",
"Loader",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L363-L376 |
8,612 | luci/luci-go | appengine/meta/eg.go | GetEntityGroupVersion | func GetEntityGroupVersion(c context.Context, key *ds.Key) (int64, error) {
egm := &EntityGroupMeta{Parent: key.Root()}
err := ds.Get(c, egm)
ret := egm.Version
if err == ds.ErrNoSuchEntity {
// this is OK for callers. The version of the entity group is effectively 0
// in this case.
err = nil
}
return ret, err
} | go | func GetEntityGroupVersion(c context.Context, key *ds.Key) (int64, error) {
egm := &EntityGroupMeta{Parent: key.Root()}
err := ds.Get(c, egm)
ret := egm.Version
if err == ds.ErrNoSuchEntity {
// this is OK for callers. The version of the entity group is effectively 0
// in this case.
err = nil
}
return ret, err
} | [
"func",
"GetEntityGroupVersion",
"(",
"c",
"context",
".",
"Context",
",",
"key",
"*",
"ds",
".",
"Key",
")",
"(",
"int64",
",",
"error",
")",
"{",
"egm",
":=",
"&",
"EntityGroupMeta",
"{",
"Parent",
":",
"key",
".",
"Root",
"(",
")",
"}",
"\n",
"e... | // GetEntityGroupVersion returns the entity group version for the entity group
// containing root. If the entity group doesn't exist, this function will return
// zero and a nil error. | [
"GetEntityGroupVersion",
"returns",
"the",
"entity",
"group",
"version",
"for",
"the",
"entity",
"group",
"containing",
"root",
".",
"If",
"the",
"entity",
"group",
"doesn",
"t",
"exist",
"this",
"function",
"will",
"return",
"zero",
"and",
"a",
"nil",
"error"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/meta/eg.go#L37-L47 |
8,613 | luci/luci-go | vpython/cipd/pep425.go | PlatformForPEP425Tag | func PlatformForPEP425Tag(t *vpython.PEP425Tag) string {
switch platSplit := strings.SplitN(t.Platform, "_", 2); platSplit[0] {
case "linux", "manylinux1":
// Grab the remainder.
//
// Examples:
// - linux_i686
// - manylinux1_x86_64
// - linux_arm64
cpu := ""
if len(platSplit) > 1 {
cpu = platSplit[1]
}
switch cpu {
case "i686":
return "linux-386"
case "x86_64":
return "linux-amd64"
case "arm64", "aarch64":
return "linux-arm64"
case "mipsel", "mips":
return "linux-mips32"
case "mips64":
return "linux-mips64"
default:
// All remaining "arm*" get the "armv6l" CIPD platform.
if strings.HasPrefix(cpu, "arm") {
return "linux-armv6l"
}
return ""
}
case "macosx":
// Grab the last token.
//
// Examples:
// - macosx_10_10_intel
// - macosx_10_10_i386
if len(platSplit) == 1 {
return ""
}
suffixSplit := strings.SplitN(platSplit[1], "_", -1)
switch suffixSplit[len(suffixSplit)-1] {
case "intel", "x86_64", "fat64", "universal":
return "mac-amd64"
case "i386", "fat32":
return "mac-386"
default:
return ""
}
case "win32":
// win32
return "windows-386"
case "win":
// Examples:
// - win_amd64
if len(platSplit) == 1 {
return ""
}
switch platSplit[1] {
case "amd64":
return "windows-amd64"
default:
return ""
}
default:
return ""
}
} | go | func PlatformForPEP425Tag(t *vpython.PEP425Tag) string {
switch platSplit := strings.SplitN(t.Platform, "_", 2); platSplit[0] {
case "linux", "manylinux1":
// Grab the remainder.
//
// Examples:
// - linux_i686
// - manylinux1_x86_64
// - linux_arm64
cpu := ""
if len(platSplit) > 1 {
cpu = platSplit[1]
}
switch cpu {
case "i686":
return "linux-386"
case "x86_64":
return "linux-amd64"
case "arm64", "aarch64":
return "linux-arm64"
case "mipsel", "mips":
return "linux-mips32"
case "mips64":
return "linux-mips64"
default:
// All remaining "arm*" get the "armv6l" CIPD platform.
if strings.HasPrefix(cpu, "arm") {
return "linux-armv6l"
}
return ""
}
case "macosx":
// Grab the last token.
//
// Examples:
// - macosx_10_10_intel
// - macosx_10_10_i386
if len(platSplit) == 1 {
return ""
}
suffixSplit := strings.SplitN(platSplit[1], "_", -1)
switch suffixSplit[len(suffixSplit)-1] {
case "intel", "x86_64", "fat64", "universal":
return "mac-amd64"
case "i386", "fat32":
return "mac-386"
default:
return ""
}
case "win32":
// win32
return "windows-386"
case "win":
// Examples:
// - win_amd64
if len(platSplit) == 1 {
return ""
}
switch platSplit[1] {
case "amd64":
return "windows-amd64"
default:
return ""
}
default:
return ""
}
} | [
"func",
"PlatformForPEP425Tag",
"(",
"t",
"*",
"vpython",
".",
"PEP425Tag",
")",
"string",
"{",
"switch",
"platSplit",
":=",
"strings",
".",
"SplitN",
"(",
"t",
".",
"Platform",
",",
"\"",
"\"",
",",
"2",
")",
";",
"platSplit",
"[",
"0",
"]",
"{",
"c... | // PlatformForPEP425Tag returns the CIPD platform inferred from a given Python
// PEP425 tag.
//
// If the platform could not be determined, an empty string will be returned. | [
"PlatformForPEP425Tag",
"returns",
"the",
"CIPD",
"platform",
"inferred",
"from",
"a",
"given",
"Python",
"PEP425",
"tag",
".",
"If",
"the",
"platform",
"could",
"not",
"be",
"determined",
"an",
"empty",
"string",
"will",
"be",
"returned",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/cipd/pep425.go#L27-L97 |
8,614 | luci/luci-go | logdog/appengine/coordinator/endpoints/services/loadStream.go | LoadStream | func (s *server) LoadStream(c context.Context, req *logdog.LoadStreamRequest) (*logdog.LoadStreamResponse, error) {
log.Fields{
"project": req.Project,
"id": req.Id,
}.Infof(c, "Loading log stream state.")
id := coordinator.HashID(req.Id)
if err := id.Normalize(); err != nil {
log.WithError(err).Errorf(c, "Invalid stream ID.")
return nil, grpcutil.Errf(codes.InvalidArgument, "Invalid ID (%s): %s", id, err)
}
ls := &coordinator.LogStream{ID: coordinator.HashID(req.Id)}
lst := ls.State(c)
if err := ds.Get(c, lst, ls); err != nil {
if anyNoSuchEntity(err) {
log.WithError(err).Errorf(c, "No such entity in datastore.")
// The state isn't registered, so this stream does not exist.
return nil, grpcutil.Errf(codes.NotFound, "Log stream was not found.")
}
log.WithError(err).Errorf(c, "Failed to load log stream.")
return nil, grpcutil.Internal
}
// The log stream and state loaded successfully.
resp := logdog.LoadStreamResponse{
State: buildLogStreamState(ls, lst),
}
if req.Desc {
resp.Desc = ls.Descriptor
}
resp.ArchivalKey = lst.ArchivalKey
resp.Age = google.NewDuration(ds.RoundTime(clock.Now(c)).Sub(lst.Updated))
log.Fields{
"id": lst.ID(),
"terminalIndex": resp.State.TerminalIndex,
"archived": resp.State.Archived,
"purged": resp.State.Purged,
"age": google.DurationFromProto(resp.Age),
"archivalKeySize": len(resp.ArchivalKey),
}.Infof(c, "Successfully loaded log stream state.")
return &resp, nil
} | go | func (s *server) LoadStream(c context.Context, req *logdog.LoadStreamRequest) (*logdog.LoadStreamResponse, error) {
log.Fields{
"project": req.Project,
"id": req.Id,
}.Infof(c, "Loading log stream state.")
id := coordinator.HashID(req.Id)
if err := id.Normalize(); err != nil {
log.WithError(err).Errorf(c, "Invalid stream ID.")
return nil, grpcutil.Errf(codes.InvalidArgument, "Invalid ID (%s): %s", id, err)
}
ls := &coordinator.LogStream{ID: coordinator.HashID(req.Id)}
lst := ls.State(c)
if err := ds.Get(c, lst, ls); err != nil {
if anyNoSuchEntity(err) {
log.WithError(err).Errorf(c, "No such entity in datastore.")
// The state isn't registered, so this stream does not exist.
return nil, grpcutil.Errf(codes.NotFound, "Log stream was not found.")
}
log.WithError(err).Errorf(c, "Failed to load log stream.")
return nil, grpcutil.Internal
}
// The log stream and state loaded successfully.
resp := logdog.LoadStreamResponse{
State: buildLogStreamState(ls, lst),
}
if req.Desc {
resp.Desc = ls.Descriptor
}
resp.ArchivalKey = lst.ArchivalKey
resp.Age = google.NewDuration(ds.RoundTime(clock.Now(c)).Sub(lst.Updated))
log.Fields{
"id": lst.ID(),
"terminalIndex": resp.State.TerminalIndex,
"archived": resp.State.Archived,
"purged": resp.State.Purged,
"age": google.DurationFromProto(resp.Age),
"archivalKeySize": len(resp.ArchivalKey),
}.Infof(c, "Successfully loaded log stream state.")
return &resp, nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"LoadStream",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"logdog",
".",
"LoadStreamRequest",
")",
"(",
"*",
"logdog",
".",
"LoadStreamResponse",
",",
"error",
")",
"{",
"log",
".",
"Fields",
"{",
"\"",
... | // LoadStream loads the log stream state. | [
"LoadStream",
"loads",
"the",
"log",
"stream",
"state",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/loadStream.go#L35-L81 |
8,615 | luci/luci-go | tokenserver/appengine/impl/certconfig/rpc_get_ca_status_rpc.go | GetCAStatus | func (r *GetCAStatusRPC) GetCAStatus(c context.Context, req *admin.GetCAStatusRequest) (*admin.GetCAStatusResponse, error) {
// Entities to fetch.
ca := CA{CN: req.Cn}
crl := CRL{Parent: ds.KeyForObj(c, &ca)}
// Fetch them at the same revision. It is fine if CRL is not there yet. Don't
// bother doing it in parallel: GetCAStatus is used only by admins, manually.
err := ds.RunInTransaction(c, func(c context.Context) error {
if err := ds.Get(c, &ca); err != nil {
return err // can be ErrNoSuchEntity
}
if err := ds.Get(c, &crl); err != nil && err != ds.ErrNoSuchEntity {
return err // only transient errors
}
return nil
}, nil)
switch {
case err == ds.ErrNoSuchEntity:
return &admin.GetCAStatusResponse{}, nil
case err != nil:
return nil, status.Errorf(codes.Internal, "datastore error - %s", err)
}
cfgMsg, err := ca.ParseConfig()
if err != nil {
return nil, status.Errorf(codes.Internal, "broken config in the datastore - %s", err)
}
return &admin.GetCAStatusResponse{
Config: cfgMsg,
Cert: utils.DumpPEM(ca.Cert, "CERTIFICATE"),
Removed: ca.Removed,
Ready: ca.Ready,
AddedRev: ca.AddedRev,
UpdatedRev: ca.UpdatedRev,
RemovedRev: ca.RemovedRev,
CrlStatus: crl.GetStatusProto(),
}, nil
} | go | func (r *GetCAStatusRPC) GetCAStatus(c context.Context, req *admin.GetCAStatusRequest) (*admin.GetCAStatusResponse, error) {
// Entities to fetch.
ca := CA{CN: req.Cn}
crl := CRL{Parent: ds.KeyForObj(c, &ca)}
// Fetch them at the same revision. It is fine if CRL is not there yet. Don't
// bother doing it in parallel: GetCAStatus is used only by admins, manually.
err := ds.RunInTransaction(c, func(c context.Context) error {
if err := ds.Get(c, &ca); err != nil {
return err // can be ErrNoSuchEntity
}
if err := ds.Get(c, &crl); err != nil && err != ds.ErrNoSuchEntity {
return err // only transient errors
}
return nil
}, nil)
switch {
case err == ds.ErrNoSuchEntity:
return &admin.GetCAStatusResponse{}, nil
case err != nil:
return nil, status.Errorf(codes.Internal, "datastore error - %s", err)
}
cfgMsg, err := ca.ParseConfig()
if err != nil {
return nil, status.Errorf(codes.Internal, "broken config in the datastore - %s", err)
}
return &admin.GetCAStatusResponse{
Config: cfgMsg,
Cert: utils.DumpPEM(ca.Cert, "CERTIFICATE"),
Removed: ca.Removed,
Ready: ca.Ready,
AddedRev: ca.AddedRev,
UpdatedRev: ca.UpdatedRev,
RemovedRev: ca.RemovedRev,
CrlStatus: crl.GetStatusProto(),
}, nil
} | [
"func",
"(",
"r",
"*",
"GetCAStatusRPC",
")",
"GetCAStatus",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"admin",
".",
"GetCAStatusRequest",
")",
"(",
"*",
"admin",
".",
"GetCAStatusResponse",
",",
"error",
")",
"{",
"// Entities to fetch.",
"ca",
... | // GetCAStatus returns configuration of some CA defined in the config. | [
"GetCAStatus",
"returns",
"configuration",
"of",
"some",
"CA",
"defined",
"in",
"the",
"config",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/rpc_get_ca_status_rpc.go#L34-L72 |
8,616 | luci/luci-go | cipd/appengine/impl/repo/repo.go | Public | func Public(internalCAS cas.StorageServer, d *tq.Dispatcher) Server {
impl := &repoImpl{
tq: d,
meta: metadata.GetStorage(),
cas: internalCAS,
}
impl.registerTasks()
impl.registerProcessor(&processing.ClientExtractor{CAS: internalCAS})
return impl
} | go | func Public(internalCAS cas.StorageServer, d *tq.Dispatcher) Server {
impl := &repoImpl{
tq: d,
meta: metadata.GetStorage(),
cas: internalCAS,
}
impl.registerTasks()
impl.registerProcessor(&processing.ClientExtractor{CAS: internalCAS})
return impl
} | [
"func",
"Public",
"(",
"internalCAS",
"cas",
".",
"StorageServer",
",",
"d",
"*",
"tq",
".",
"Dispatcher",
")",
"Server",
"{",
"impl",
":=",
"&",
"repoImpl",
"{",
"tq",
":",
"d",
",",
"meta",
":",
"metadata",
".",
"GetStorage",
"(",
")",
",",
"cas",
... | // Public returns publicly exposed implementation of cipd.Repository service.
//
// It checks ACLs. | [
"Public",
"returns",
"publicly",
"exposed",
"implementation",
"of",
"cipd",
".",
"Repository",
"service",
".",
"It",
"checks",
"ACLs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L60-L69 |
8,617 | luci/luci-go | cipd/appengine/impl/repo/repo.go | registerProcessor | func (impl *repoImpl) registerProcessor(p processing.Processor) {
if impl.procsMap == nil {
impl.procsMap = map[string]processing.Processor{}
}
id := p.ID()
if impl.procsMap[id] != nil {
panic(fmt.Sprintf("processor %q has already been registered", id))
}
impl.procs = append(impl.procs, p)
impl.procsMap[id] = p
} | go | func (impl *repoImpl) registerProcessor(p processing.Processor) {
if impl.procsMap == nil {
impl.procsMap = map[string]processing.Processor{}
}
id := p.ID()
if impl.procsMap[id] != nil {
panic(fmt.Sprintf("processor %q has already been registered", id))
}
impl.procs = append(impl.procs, p)
impl.procsMap[id] = p
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"registerProcessor",
"(",
"p",
"processing",
".",
"Processor",
")",
"{",
"if",
"impl",
".",
"procsMap",
"==",
"nil",
"{",
"impl",
".",
"procsMap",
"=",
"map",
"[",
"string",
"]",
"processing",
".",
"Processor",
... | // registerProcessor adds a new processor. | [
"registerProcessor",
"adds",
"a",
"new",
"processor",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L101-L113 |
8,618 | luci/luci-go | cipd/appengine/impl/repo/repo.go | packageReader | func (impl *repoImpl) packageReader(c context.Context, ref *api.ObjectRef) (*processing.PackageReader, error) {
// Get slow Google Storage based ReaderAt.
rawReader, err := impl.cas.GetReader(c, ref)
switch code := grpc.Code(err); {
case code == codes.NotFound:
return nil, errors.Annotate(err, "package instance is not in the storage").Err()
case code != codes.OK:
return nil, errors.Annotate(err, "failed to open the object for reading").Tag(transient.Tag).Err()
}
// Read in 512 Kb chunks, keep 2 of them buffered.
pkg, err := processing.NewPackageReader(
iotools.NewBufferingReaderAt(rawReader, 512*1024, 2),
rawReader.Size())
if err != nil {
return nil, errors.Annotate(err, "error when opening the package").Err()
}
return pkg, nil
} | go | func (impl *repoImpl) packageReader(c context.Context, ref *api.ObjectRef) (*processing.PackageReader, error) {
// Get slow Google Storage based ReaderAt.
rawReader, err := impl.cas.GetReader(c, ref)
switch code := grpc.Code(err); {
case code == codes.NotFound:
return nil, errors.Annotate(err, "package instance is not in the storage").Err()
case code != codes.OK:
return nil, errors.Annotate(err, "failed to open the object for reading").Tag(transient.Tag).Err()
}
// Read in 512 Kb chunks, keep 2 of them buffered.
pkg, err := processing.NewPackageReader(
iotools.NewBufferingReaderAt(rawReader, 512*1024, 2),
rawReader.Size())
if err != nil {
return nil, errors.Annotate(err, "error when opening the package").Err()
}
return pkg, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"packageReader",
"(",
"c",
"context",
".",
"Context",
",",
"ref",
"*",
"api",
".",
"ObjectRef",
")",
"(",
"*",
"processing",
".",
"PackageReader",
",",
"error",
")",
"{",
"// Get slow Google Storage based ReaderAt.",
... | // packageReader opens a package instance for reading. | [
"packageReader",
"opens",
"a",
"package",
"instance",
"for",
"reading",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L116-L134 |
8,619 | luci/luci-go | cipd/appengine/impl/repo/repo.go | UpdatePrefixMetadata | func (impl *repoImpl) UpdatePrefixMetadata(c context.Context, r *api.PrefixMetadata) (resp *api.PrefixMetadata, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Fill in server-assigned fields.
r.UpdateTime = google.NewTimestamp(clock.Now(c))
r.UpdateUser = string(auth.CurrentIdentity(c))
// Normalize and validate format of the PrefixMetadata.
if err := common.NormalizePrefixMetadata(r); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad prefix metadata - %s", err)
}
// The root metadata is not modifiable through API.
if r.Prefix == "" {
return nil, status.Errorf(codes.InvalidArgument, "the root metadata is not modifiable")
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Prefix, api.Role_OWNER); err != nil {
return nil, err
}
// Transactionally check the fingerprint and update the metadata. impl.meta
// will recalculate the new fingerprint. Note there's a small chance the
// caller no longer has OWNER role to modify the metadata inside the
// transaction. We ignore it. It happens when caller's permissions are revoked
// by someone else exactly during UpdatePrefixMetadata call.
return impl.meta.UpdateMetadata(c, r.Prefix, func(cur *api.PrefixMetadata) error {
if cur.Fingerprint != r.Fingerprint {
switch {
case cur.Fingerprint == "":
// The metadata was deleted while the caller was messing with it.
return noMetadataErr(r.Prefix)
case r.Fingerprint == "":
// Caller tries to make a new one, but we already have it.
return status.Errorf(
codes.AlreadyExists, "metadata for prefix %q already exists and has fingerprint %q, "+
"use combination of GetPrefixMetadata and UpdatePrefixMetadata to "+
"update it", r.Prefix, cur.Fingerprint)
default:
// The fingerprint has changed while the caller was messing with
// the metadata.
return status.Errorf(
codes.FailedPrecondition, "metadata for prefix %q was updated concurrently "+
"(the fingerprint in the request %q doesn't match the current fingerprint %q), "+
"fetch new metadata with GetPrefixMetadata and reapply your "+
"changes", r.Prefix, r.Fingerprint, cur.Fingerprint)
}
}
prev := *cur
*cur = *r
return model.EmitMetadataEvents(c, &prev, cur)
})
} | go | func (impl *repoImpl) UpdatePrefixMetadata(c context.Context, r *api.PrefixMetadata) (resp *api.PrefixMetadata, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Fill in server-assigned fields.
r.UpdateTime = google.NewTimestamp(clock.Now(c))
r.UpdateUser = string(auth.CurrentIdentity(c))
// Normalize and validate format of the PrefixMetadata.
if err := common.NormalizePrefixMetadata(r); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad prefix metadata - %s", err)
}
// The root metadata is not modifiable through API.
if r.Prefix == "" {
return nil, status.Errorf(codes.InvalidArgument, "the root metadata is not modifiable")
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Prefix, api.Role_OWNER); err != nil {
return nil, err
}
// Transactionally check the fingerprint and update the metadata. impl.meta
// will recalculate the new fingerprint. Note there's a small chance the
// caller no longer has OWNER role to modify the metadata inside the
// transaction. We ignore it. It happens when caller's permissions are revoked
// by someone else exactly during UpdatePrefixMetadata call.
return impl.meta.UpdateMetadata(c, r.Prefix, func(cur *api.PrefixMetadata) error {
if cur.Fingerprint != r.Fingerprint {
switch {
case cur.Fingerprint == "":
// The metadata was deleted while the caller was messing with it.
return noMetadataErr(r.Prefix)
case r.Fingerprint == "":
// Caller tries to make a new one, but we already have it.
return status.Errorf(
codes.AlreadyExists, "metadata for prefix %q already exists and has fingerprint %q, "+
"use combination of GetPrefixMetadata and UpdatePrefixMetadata to "+
"update it", r.Prefix, cur.Fingerprint)
default:
// The fingerprint has changed while the caller was messing with
// the metadata.
return status.Errorf(
codes.FailedPrecondition, "metadata for prefix %q was updated concurrently "+
"(the fingerprint in the request %q doesn't match the current fingerprint %q), "+
"fetch new metadata with GetPrefixMetadata and reapply your "+
"changes", r.Prefix, r.Fingerprint, cur.Fingerprint)
}
}
prev := *cur
*cur = *r
return model.EmitMetadataEvents(c, &prev, cur)
})
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"UpdatePrefixMetadata",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"PrefixMetadata",
")",
"(",
"resp",
"*",
"api",
".",
"PrefixMetadata",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(... | // UpdatePrefixMetadata implements the corresponding RPC method, see the proto doc. | [
"UpdatePrefixMetadata",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L177-L230 |
8,620 | luci/luci-go | cipd/appengine/impl/repo/repo.go | GetRolesInPrefix | func (impl *repoImpl) GetRolesInPrefix(c context.Context, r *api.PrefixRequest) (resp *api.RolesInPrefixResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
r.Prefix, err = common.ValidatePackagePrefix(r.Prefix)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'prefix' - %s", err)
}
metas, err := impl.meta.GetMetadata(c, r.Prefix)
if err != nil {
return nil, err
}
roles, err := rolesInPrefix(c, metas)
if err != nil {
return nil, err
}
resp = &api.RolesInPrefixResponse{
Roles: make([]*api.RolesInPrefixResponse_RoleInPrefix, len(roles)),
}
for i, r := range roles {
resp.Roles[i] = &api.RolesInPrefixResponse_RoleInPrefix{Role: r}
}
return resp, nil
} | go | func (impl *repoImpl) GetRolesInPrefix(c context.Context, r *api.PrefixRequest) (resp *api.RolesInPrefixResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
r.Prefix, err = common.ValidatePackagePrefix(r.Prefix)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'prefix' - %s", err)
}
metas, err := impl.meta.GetMetadata(c, r.Prefix)
if err != nil {
return nil, err
}
roles, err := rolesInPrefix(c, metas)
if err != nil {
return nil, err
}
resp = &api.RolesInPrefixResponse{
Roles: make([]*api.RolesInPrefixResponse_RoleInPrefix, len(roles)),
}
for i, r := range roles {
resp.Roles[i] = &api.RolesInPrefixResponse_RoleInPrefix{Role: r}
}
return resp, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"GetRolesInPrefix",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"PrefixRequest",
")",
"(",
"resp",
"*",
"api",
".",
"RolesInPrefixResponse",
",",
"err",
"error",
")",
"{",
"defer",
"func",
... | // GetRolesInPrefix implements the corresponding RPC method, see the proto doc. | [
"GetRolesInPrefix",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L233-L258 |
8,621 | luci/luci-go | cipd/appengine/impl/repo/repo.go | noAccessErr | func noAccessErr(c context.Context, prefix string) error {
return status.Errorf(
codes.PermissionDenied, "prefix %q doesn't exist or %q is not allowed to see it",
prefix, auth.CurrentIdentity(c))
} | go | func noAccessErr(c context.Context, prefix string) error {
return status.Errorf(
codes.PermissionDenied, "prefix %q doesn't exist or %q is not allowed to see it",
prefix, auth.CurrentIdentity(c))
} | [
"func",
"noAccessErr",
"(",
"c",
"context",
".",
"Context",
",",
"prefix",
"string",
")",
"error",
"{",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"PermissionDenied",
",",
"\"",
"\"",
",",
"prefix",
",",
"auth",
".",
"CurrentIdentity",
"(",
"c... | // noAccessErr produces a grpc error saying that the given prefix doesn't
// exist or the caller has no access to it. This is generic error message that
// should not give away prefix presence to non-readers. | [
"noAccessErr",
"produces",
"a",
"grpc",
"error",
"saying",
"that",
"the",
"given",
"prefix",
"doesn",
"t",
"exist",
"or",
"the",
"caller",
"has",
"no",
"access",
"to",
"it",
".",
"This",
"is",
"generic",
"error",
"message",
"that",
"should",
"not",
"give",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L304-L308 |
8,622 | luci/luci-go | cipd/appengine/impl/repo/repo.go | UnhidePackage | func (impl *repoImpl) UnhidePackage(c context.Context, r *api.PackageRequest) (*empty.Empty, error) {
return impl.setPackageHidden(c, r, model.Visible)
} | go | func (impl *repoImpl) UnhidePackage(c context.Context, r *api.PackageRequest) (*empty.Empty, error) {
return impl.setPackageHidden(c, r, model.Visible)
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"UnhidePackage",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"PackageRequest",
")",
"(",
"*",
"empty",
".",
"Empty",
",",
"error",
")",
"{",
"return",
"impl",
".",
"setPackageHidden",
"(",
... | // UnhidePackage implements the corresponding RPC method, see the proto doc. | [
"UnhidePackage",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L474-L476 |
8,623 | luci/luci-go | cipd/appengine/impl/repo/repo.go | setPackageHidden | func (impl *repoImpl) setPackageHidden(c context.Context, r *api.PackageRequest, hidden bool) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
if _, err := impl.checkRole(c, r.Package, api.Role_OWNER); err != nil {
return nil, err
}
switch err := model.SetPackageHidden(c, r.Package, hidden); {
case err == datastore.ErrNoSuchEntity:
return nil, status.Errorf(codes.NotFound, "no such package")
case err != nil:
return nil, errors.Annotate(err, "failed to update the package").Err()
}
return &empty.Empty{}, nil
} | go | func (impl *repoImpl) setPackageHidden(c context.Context, r *api.PackageRequest, hidden bool) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
if _, err := impl.checkRole(c, r.Package, api.Role_OWNER); err != nil {
return nil, err
}
switch err := model.SetPackageHidden(c, r.Package, hidden); {
case err == datastore.ErrNoSuchEntity:
return nil, status.Errorf(codes.NotFound, "no such package")
case err != nil:
return nil, errors.Annotate(err, "failed to update the package").Err()
}
return &empty.Empty{}, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"setPackageHidden",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"PackageRequest",
",",
"hidden",
"bool",
")",
"(",
"resp",
"*",
"empty",
".",
"Empty",
",",
"err",
"error",
")",
"{",
"defe... | // setPackageHidden is common implementation of HidePackage and UnhidePackage. | [
"setPackageHidden",
"is",
"common",
"implementation",
"of",
"HidePackage",
"and",
"UnhidePackage",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L479-L496 |
8,624 | luci/luci-go | cipd/appengine/impl/repo/repo.go | onInstanceRegistration | func (impl *repoImpl) onInstanceRegistration(c context.Context, inst *model.Instance) error {
// Collect IDs of applicable processors.
var procs []string
for _, p := range impl.procs {
if p.Applicable(inst) {
procs = append(procs, p.ID())
}
}
if len(procs) == 0 {
return nil
}
// Mark the instance as being processed now.
inst.ProcessorsPending = procs
// Launch the TQ task that does the processing (see runProcessorsTask below).
return impl.tq.AddTask(c, &tq.Task{
Payload: &tasks.RunProcessors{Instance: inst.Proto()},
Title: inst.InstanceID,
})
} | go | func (impl *repoImpl) onInstanceRegistration(c context.Context, inst *model.Instance) error {
// Collect IDs of applicable processors.
var procs []string
for _, p := range impl.procs {
if p.Applicable(inst) {
procs = append(procs, p.ID())
}
}
if len(procs) == 0 {
return nil
}
// Mark the instance as being processed now.
inst.ProcessorsPending = procs
// Launch the TQ task that does the processing (see runProcessorsTask below).
return impl.tq.AddTask(c, &tq.Task{
Payload: &tasks.RunProcessors{Instance: inst.Proto()},
Title: inst.InstanceID,
})
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"onInstanceRegistration",
"(",
"c",
"context",
".",
"Context",
",",
"inst",
"*",
"model",
".",
"Instance",
")",
"error",
"{",
"// Collect IDs of applicable processors.",
"var",
"procs",
"[",
"]",
"string",
"\n",
"for"... | // onInstanceRegistration is called in a txn when registering an instance. | [
"onInstanceRegistration",
"is",
"called",
"in",
"a",
"txn",
"when",
"registering",
"an",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L607-L627 |
8,625 | luci/luci-go | cipd/appengine/impl/repo/repo.go | runProcessorsTask | func (impl *repoImpl) runProcessorsTask(c context.Context, t *tasks.RunProcessors) error {
// Fetch the instance to see what processors are still pending.
inst := (&model.Instance{}).FromProto(c, t.Instance)
switch err := datastore.Get(c, inst); {
case err == datastore.ErrNoSuchEntity:
return fmt.Errorf("instance %q is unexpectedly gone from the datastore", inst.InstanceID)
case err != nil:
return transient.Tag.Apply(err)
}
results := map[string]processing.Result{}
// Grab processors we haven't ran yet.
var run []processing.Processor
for _, id := range inst.ProcessorsPending {
if proc := impl.procsMap[id]; proc != nil {
run = append(run, proc)
} else {
logging.Errorf(c, "Skipping unknown processor %q", id)
results[id] = processing.Result{Err: fmt.Errorf("unknown processor %q", id)}
}
}
// Exit early if there's nothing to run.
if len(run) == 0 {
return impl.updateProcessors(c, t.Instance, results)
}
// Open the package for reading.
pkg, err := impl.packageReader(c, t.Instance.Instance)
switch {
case transient.Tag.In(err):
return err // retry the whole thing
case err != nil:
// The package is fatally broken, give up.
logging.WithError(err).Errorf(c, "The package can't be opened, failing all processors")
for _, proc := range run {
results[proc.ID()] = processing.Result{Err: err}
}
return impl.updateProcessors(c, t.Instance, results)
}
// Run the processors sequentially, since PackageReader is not very friendly
// to concurrent access.
var transientErrs errors.MultiError
for _, proc := range run {
logging.Infof(c, "Running processor %q", proc.ID())
res, err := proc.Run(c, inst, pkg)
if err != nil {
logging.WithError(err).Errorf(c, "Processor %q failed transiently", proc.ID())
transientErrs = append(transientErrs, err)
} else {
if res.Err != nil {
logging.WithError(res.Err).Errorf(c, "Processor %q failed fatally", proc.ID())
}
results[proc.ID()] = res
}
}
// Store what we've got, even if some processor may have failed to run.
updErr := impl.updateProcessors(c, t.Instance, results)
// Prefer errors from processors over 'updErr' if both happen. Processor
// errors are more interesting.
switch {
case len(transientErrs) != 0:
return transient.Tag.Apply(transientErrs)
case updErr != nil:
return updErr
}
return nil
} | go | func (impl *repoImpl) runProcessorsTask(c context.Context, t *tasks.RunProcessors) error {
// Fetch the instance to see what processors are still pending.
inst := (&model.Instance{}).FromProto(c, t.Instance)
switch err := datastore.Get(c, inst); {
case err == datastore.ErrNoSuchEntity:
return fmt.Errorf("instance %q is unexpectedly gone from the datastore", inst.InstanceID)
case err != nil:
return transient.Tag.Apply(err)
}
results := map[string]processing.Result{}
// Grab processors we haven't ran yet.
var run []processing.Processor
for _, id := range inst.ProcessorsPending {
if proc := impl.procsMap[id]; proc != nil {
run = append(run, proc)
} else {
logging.Errorf(c, "Skipping unknown processor %q", id)
results[id] = processing.Result{Err: fmt.Errorf("unknown processor %q", id)}
}
}
// Exit early if there's nothing to run.
if len(run) == 0 {
return impl.updateProcessors(c, t.Instance, results)
}
// Open the package for reading.
pkg, err := impl.packageReader(c, t.Instance.Instance)
switch {
case transient.Tag.In(err):
return err // retry the whole thing
case err != nil:
// The package is fatally broken, give up.
logging.WithError(err).Errorf(c, "The package can't be opened, failing all processors")
for _, proc := range run {
results[proc.ID()] = processing.Result{Err: err}
}
return impl.updateProcessors(c, t.Instance, results)
}
// Run the processors sequentially, since PackageReader is not very friendly
// to concurrent access.
var transientErrs errors.MultiError
for _, proc := range run {
logging.Infof(c, "Running processor %q", proc.ID())
res, err := proc.Run(c, inst, pkg)
if err != nil {
logging.WithError(err).Errorf(c, "Processor %q failed transiently", proc.ID())
transientErrs = append(transientErrs, err)
} else {
if res.Err != nil {
logging.WithError(res.Err).Errorf(c, "Processor %q failed fatally", proc.ID())
}
results[proc.ID()] = res
}
}
// Store what we've got, even if some processor may have failed to run.
updErr := impl.updateProcessors(c, t.Instance, results)
// Prefer errors from processors over 'updErr' if both happen. Processor
// errors are more interesting.
switch {
case len(transientErrs) != 0:
return transient.Tag.Apply(transientErrs)
case updErr != nil:
return updErr
}
return nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"runProcessorsTask",
"(",
"c",
"context",
".",
"Context",
",",
"t",
"*",
"tasks",
".",
"RunProcessors",
")",
"error",
"{",
"// Fetch the instance to see what processors are still pending.",
"inst",
":=",
"(",
"&",
"model"... | // runProcessorsTask executes a post-upload processing step.
//
// Returning a transient error here causes the task queue service to retry the
// task. | [
"runProcessorsTask",
"executes",
"a",
"post",
"-",
"upload",
"processing",
"step",
".",
"Returning",
"a",
"transient",
"error",
"here",
"causes",
"the",
"task",
"queue",
"service",
"to",
"retry",
"the",
"task",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L633-L704 |
8,626 | luci/luci-go | cipd/appengine/impl/repo/repo.go | paginatedQuery | func (impl *repoImpl) paginatedQuery(c context.Context, opts paginatedQueryOpts) (out []*api.Instance, nextTok string, err error) {
// Validate the request, decode the cursor.
if err := common.ValidatePackageName(opts.Package); err != nil {
return nil, "", status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
switch {
case opts.PageSize < 0:
return nil, "", status.Errorf(codes.InvalidArgument, "bad 'page_size' %d - it should be non-negative", opts.PageSize)
case opts.PageSize == 0:
opts.PageSize = 100
}
var cursor datastore.Cursor
if opts.PageToken != "" {
if cursor, err = datastore.DecodeCursor(c, opts.PageToken); err != nil {
return nil, "", status.Errorf(codes.InvalidArgument, "bad 'page_token' - %s", err)
}
}
if opts.Validator != nil {
if err := opts.Validator(); err != nil {
return nil, "", err
}
}
// Check ACLs.
if _, err := impl.checkRole(c, opts.Package, api.Role_READER); err != nil {
return nil, "", err
}
// Check that the package is registered.
if err := model.CheckPackageExists(c, opts.Package); err != nil {
return nil, "", err
}
// Do the actual listing.
inst, cursor, err := opts.Handler(cursor, opts.PageSize)
if err != nil {
return nil, "", errors.Annotate(err, "failed to query instances").Err()
}
// Convert results to proto.
out = make([]*api.Instance, len(inst))
for i, ent := range inst {
out[i] = ent.Proto()
}
if cursor != nil {
nextTok = cursor.String()
}
return
} | go | func (impl *repoImpl) paginatedQuery(c context.Context, opts paginatedQueryOpts) (out []*api.Instance, nextTok string, err error) {
// Validate the request, decode the cursor.
if err := common.ValidatePackageName(opts.Package); err != nil {
return nil, "", status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
switch {
case opts.PageSize < 0:
return nil, "", status.Errorf(codes.InvalidArgument, "bad 'page_size' %d - it should be non-negative", opts.PageSize)
case opts.PageSize == 0:
opts.PageSize = 100
}
var cursor datastore.Cursor
if opts.PageToken != "" {
if cursor, err = datastore.DecodeCursor(c, opts.PageToken); err != nil {
return nil, "", status.Errorf(codes.InvalidArgument, "bad 'page_token' - %s", err)
}
}
if opts.Validator != nil {
if err := opts.Validator(); err != nil {
return nil, "", err
}
}
// Check ACLs.
if _, err := impl.checkRole(c, opts.Package, api.Role_READER); err != nil {
return nil, "", err
}
// Check that the package is registered.
if err := model.CheckPackageExists(c, opts.Package); err != nil {
return nil, "", err
}
// Do the actual listing.
inst, cursor, err := opts.Handler(cursor, opts.PageSize)
if err != nil {
return nil, "", errors.Annotate(err, "failed to query instances").Err()
}
// Convert results to proto.
out = make([]*api.Instance, len(inst))
for i, ent := range inst {
out[i] = ent.Proto()
}
if cursor != nil {
nextTok = cursor.String()
}
return
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"paginatedQuery",
"(",
"c",
"context",
".",
"Context",
",",
"opts",
"paginatedQueryOpts",
")",
"(",
"out",
"[",
"]",
"*",
"api",
".",
"Instance",
",",
"nextTok",
"string",
",",
"err",
"error",
")",
"{",
"// Va... | // paginatedQuery is a common part of ListInstances and SearchInstances. | [
"paginatedQuery",
"is",
"a",
"common",
"part",
"of",
"ListInstances",
"and",
"SearchInstances",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L792-L843 |
8,627 | luci/luci-go | cipd/appengine/impl/repo/repo.go | ListInstances | func (impl *repoImpl) ListInstances(c context.Context, r *api.ListInstancesRequest) (resp *api.ListInstancesResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
result, nextPage, err := impl.paginatedQuery(c, paginatedQueryOpts{
Package: r.Package,
PageSize: r.PageSize,
PageToken: r.PageToken,
Handler: func(cur datastore.Cursor, pageSize int32) ([]*model.Instance, datastore.Cursor, error) {
return model.ListInstances(c, r.Package, pageSize, cur)
},
})
if err != nil {
return nil, err
}
return &api.ListInstancesResponse{
Instances: result,
NextPageToken: nextPage,
}, nil
} | go | func (impl *repoImpl) ListInstances(c context.Context, r *api.ListInstancesRequest) (resp *api.ListInstancesResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
result, nextPage, err := impl.paginatedQuery(c, paginatedQueryOpts{
Package: r.Package,
PageSize: r.PageSize,
PageToken: r.PageToken,
Handler: func(cur datastore.Cursor, pageSize int32) ([]*model.Instance, datastore.Cursor, error) {
return model.ListInstances(c, r.Package, pageSize, cur)
},
})
if err != nil {
return nil, err
}
return &api.ListInstancesResponse{
Instances: result,
NextPageToken: nextPage,
}, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"ListInstances",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"ListInstancesRequest",
")",
"(",
"resp",
"*",
"api",
".",
"ListInstancesResponse",
",",
"err",
"error",
")",
"{",
"defer",
"func"... | // ListInstances implements the corresponding RPC method, see the proto doc. | [
"ListInstances",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L846-L865 |
8,628 | luci/luci-go | cipd/appengine/impl/repo/repo.go | SearchInstances | func (impl *repoImpl) SearchInstances(c context.Context, r *api.SearchInstancesRequest) (resp *api.SearchInstancesResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
result, nextPage, err := impl.paginatedQuery(c, paginatedQueryOpts{
Package: r.Package,
PageSize: r.PageSize,
PageToken: r.PageToken,
Validator: func() error { return validateTagList(r.Tags) },
Handler: func(cur datastore.Cursor, pageSize int32) ([]*model.Instance, datastore.Cursor, error) {
return model.SearchInstances(c, r.Package, r.Tags, pageSize, cur)
},
})
if err != nil {
return nil, err
}
return &api.SearchInstancesResponse{
Instances: result,
NextPageToken: nextPage,
}, nil
} | go | func (impl *repoImpl) SearchInstances(c context.Context, r *api.SearchInstancesRequest) (resp *api.SearchInstancesResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
result, nextPage, err := impl.paginatedQuery(c, paginatedQueryOpts{
Package: r.Package,
PageSize: r.PageSize,
PageToken: r.PageToken,
Validator: func() error { return validateTagList(r.Tags) },
Handler: func(cur datastore.Cursor, pageSize int32) ([]*model.Instance, datastore.Cursor, error) {
return model.SearchInstances(c, r.Package, r.Tags, pageSize, cur)
},
})
if err != nil {
return nil, err
}
return &api.SearchInstancesResponse{
Instances: result,
NextPageToken: nextPage,
}, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"SearchInstances",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"SearchInstancesRequest",
")",
"(",
"resp",
"*",
"api",
".",
"SearchInstancesResponse",
",",
"err",
"error",
")",
"{",
"defer",
... | // SearchInstances implements the corresponding RPC method, see the proto doc. | [
"SearchInstances",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L868-L888 |
8,629 | luci/luci-go | cipd/appengine/impl/repo/repo.go | DeleteRef | func (impl *repoImpl) DeleteRef(c context.Context, r *api.DeleteRefRequest) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageRef(r.Name); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'name' - %s", err)
}
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_WRITER); err != nil {
return nil, err
}
// Verify the package actually exists, per DeleteRef contract.
if err := model.CheckPackageExists(c, r.Package); err != nil {
return nil, err
}
// Actually delete the ref.
if err := model.DeleteRef(c, r.Package, r.Name); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | go | func (impl *repoImpl) DeleteRef(c context.Context, r *api.DeleteRefRequest) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageRef(r.Name); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'name' - %s", err)
}
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_WRITER); err != nil {
return nil, err
}
// Verify the package actually exists, per DeleteRef contract.
if err := model.CheckPackageExists(c, r.Package); err != nil {
return nil, err
}
// Actually delete the ref.
if err := model.DeleteRef(c, r.Package, r.Name); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"DeleteRef",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"DeleteRefRequest",
")",
"(",
"resp",
"*",
"empty",
".",
"Empty",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",... | // DeleteRef implements the corresponding RPC method, see the proto doc. | [
"DeleteRef",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L926-L952 |
8,630 | luci/luci-go | cipd/appengine/impl/repo/repo.go | ListRefs | func (impl *repoImpl) ListRefs(c context.Context, r *api.ListRefsRequest) (resp *api.ListRefsResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_READER); err != nil {
return nil, err
}
// Verify the package actually exists, per ListPackageRefs contract.
if err := model.CheckPackageExists(c, r.Package); err != nil {
return nil, err
}
// Actually list refs.
refs, err := model.ListPackageRefs(c, r.Package)
if err != nil {
return nil, errors.Annotate(err, "failed to list refs").Err()
}
resp = &api.ListRefsResponse{Refs: make([]*api.Ref, len(refs))}
for i, ref := range refs {
resp.Refs[i] = ref.Proto()
}
return resp, nil
} | go | func (impl *repoImpl) ListRefs(c context.Context, r *api.ListRefsRequest) (resp *api.ListRefsResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_READER); err != nil {
return nil, err
}
// Verify the package actually exists, per ListPackageRefs contract.
if err := model.CheckPackageExists(c, r.Package); err != nil {
return nil, err
}
// Actually list refs.
refs, err := model.ListPackageRefs(c, r.Package)
if err != nil {
return nil, errors.Annotate(err, "failed to list refs").Err()
}
resp = &api.ListRefsResponse{Refs: make([]*api.Ref, len(refs))}
for i, ref := range refs {
resp.Refs[i] = ref.Proto()
}
return resp, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"ListRefs",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"ListRefsRequest",
")",
"(",
"resp",
"*",
"api",
".",
"ListRefsResponse",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",... | // ListRefs implements the corresponding RPC method, see the proto doc. | [
"ListRefs",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L955-L983 |
8,631 | luci/luci-go | cipd/appengine/impl/repo/repo.go | AttachTags | func (impl *repoImpl) AttachTags(c context.Context, r *api.AttachTagsRequest) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := validateMultiTagReq(r.Package, r.Instance, r.Tags); err != nil {
return nil, err
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_WRITER); err != nil {
return nil, err
}
// Actually attach the tags. This will also transactionally check the instance
// exists and it has passed the processing successfully.
inst := &model.Instance{
InstanceID: common.ObjectRefToInstanceID(r.Instance),
Package: model.PackageKey(c, r.Package),
}
if err := model.AttachTags(c, inst, r.Tags); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | go | func (impl *repoImpl) AttachTags(c context.Context, r *api.AttachTagsRequest) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := validateMultiTagReq(r.Package, r.Instance, r.Tags); err != nil {
return nil, err
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_WRITER); err != nil {
return nil, err
}
// Actually attach the tags. This will also transactionally check the instance
// exists and it has passed the processing successfully.
inst := &model.Instance{
InstanceID: common.ObjectRefToInstanceID(r.Instance),
Package: model.PackageKey(c, r.Package),
}
if err := model.AttachTags(c, inst, r.Tags); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"AttachTags",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"AttachTagsRequest",
")",
"(",
"resp",
"*",
"empty",
".",
"Empty",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{... | // AttachTags implements the corresponding RPC method, see the proto doc. | [
"AttachTags",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L1012-L1035 |
8,632 | luci/luci-go | cipd/appengine/impl/repo/repo.go | DetachTags | func (impl *repoImpl) DetachTags(c context.Context, r *api.DetachTagsRequest) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := validateMultiTagReq(r.Package, r.Instance, r.Tags); err != nil {
return nil, err
}
// Check ACLs. Note this is scoped to OWNERS, see the proto doc.
if _, err := impl.checkRole(c, r.Package, api.Role_OWNER); err != nil {
return nil, err
}
// Verify the instance exists, per DetachTags contract.
inst := &model.Instance{
InstanceID: common.ObjectRefToInstanceID(r.Instance),
Package: model.PackageKey(c, r.Package),
}
if err := model.CheckInstanceExists(c, inst); err != nil {
return nil, err
}
// Actually detach the tags.
if err := model.DetachTags(c, inst, r.Tags); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | go | func (impl *repoImpl) DetachTags(c context.Context, r *api.DetachTagsRequest) (resp *empty.Empty, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := validateMultiTagReq(r.Package, r.Instance, r.Tags); err != nil {
return nil, err
}
// Check ACLs. Note this is scoped to OWNERS, see the proto doc.
if _, err := impl.checkRole(c, r.Package, api.Role_OWNER); err != nil {
return nil, err
}
// Verify the instance exists, per DetachTags contract.
inst := &model.Instance{
InstanceID: common.ObjectRefToInstanceID(r.Instance),
Package: model.PackageKey(c, r.Package),
}
if err := model.CheckInstanceExists(c, inst); err != nil {
return nil, err
}
// Actually detach the tags.
if err := model.DetachTags(c, inst, r.Tags); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"DetachTags",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"DetachTagsRequest",
")",
"(",
"resp",
"*",
"empty",
".",
"Empty",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{... | // DetachTags implements the corresponding RPC method, see the proto doc. | [
"DetachTags",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L1038-L1065 |
8,633 | luci/luci-go | cipd/appengine/impl/repo/repo.go | GetInstanceURL | func (impl *repoImpl) GetInstanceURL(c context.Context, r *api.GetInstanceURLRequest) (resp *api.ObjectURL, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
if err := common.ValidateObjectRef(r.Instance, common.KnownHash); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'instance' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_READER); err != nil {
return nil, err
}
// Make sure this instance actually exists (without this check the caller
// would be able to "probe" CAS namespace unrestricted).
inst := (&model.Instance{}).FromProto(c, &api.Instance{
Package: r.Package,
Instance: r.Instance,
})
if err := model.CheckInstanceExists(c, inst); err != nil {
return nil, err
}
// Ask CAS generate an URL for us. Note that CAS does caching internally.
return impl.cas.GetObjectURL(c, &api.GetObjectURLRequest{
Object: r.Instance,
})
} | go | func (impl *repoImpl) GetInstanceURL(c context.Context, r *api.GetInstanceURLRequest) (resp *api.ObjectURL, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
if err := common.ValidateObjectRef(r.Instance, common.KnownHash); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'instance' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_READER); err != nil {
return nil, err
}
// Make sure this instance actually exists (without this check the caller
// would be able to "probe" CAS namespace unrestricted).
inst := (&model.Instance{}).FromProto(c, &api.Instance{
Package: r.Package,
Instance: r.Instance,
})
if err := model.CheckInstanceExists(c, inst); err != nil {
return nil, err
}
// Ask CAS generate an URL for us. Note that CAS does caching internally.
return impl.cas.GetObjectURL(c, &api.GetObjectURLRequest{
Object: r.Instance,
})
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"GetInstanceURL",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"GetInstanceURLRequest",
")",
"(",
"resp",
"*",
"api",
".",
"ObjectURL",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
... | // GetInstanceURL implements the corresponding RPC method, see the proto doc. | [
"GetInstanceURL",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L1097-L1127 |
8,634 | luci/luci-go | cipd/appengine/impl/repo/repo.go | DescribeClient | func (impl *repoImpl) DescribeClient(c context.Context, r *api.DescribeClientRequest) (resp *api.DescribeClientResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
if !processing.IsClientPackage(r.Package) {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - not a CIPD client package")
}
if err := common.ValidateObjectRef(r.Instance, common.KnownHash); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'instance' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_READER); err != nil {
return nil, err
}
// Make sure this instance exists, has all processors finished and fetch
// basic details about it.
inst := (&model.Instance{}).FromProto(c, &api.Instance{
Package: r.Package,
Instance: r.Instance,
})
if err := model.CheckInstanceReady(c, inst); err != nil {
return nil, err
}
// Grab the location of the extracted CIPD client from the post-processor.
// This must succeed, since CheckInstanceReady above verified processors have
// finished. Thus treat any error here as internal, as it will require an
// investigation.
proc, err := processing.GetClientExtractorResult(c, inst.Proto())
if err != nil {
return nil, errors.Annotate(err, "failed to get client extractor results").Tag(grpcutil.InternalTag).Err()
}
ref, err := proc.ToObjectRef()
if err != nil {
return nil, errors.Annotate(err, "malformed or unrecognized ref in the client extractor results").Tag(grpcutil.InternalTag).Err()
}
// refAliases (and SHA1 in particular, as hash supported by oldest code) is
// required to allow older clients to self-update to a newer client. See the
// doc for DescribeClientResponse proto message.
refAliases := proc.ObjectRefAliases()
sha1 := ""
for _, ref := range refAliases {
if ref.HashAlgo == api.HashAlgo_SHA1 {
sha1 = ref.HexDigest
break
}
}
if sha1 == "" {
return nil, errors.Reason("malformed client extraction results, missing SHA1 digest").Tag(grpcutil.InternalTag).Err()
}
// Grab the signed URL of the client binary.
signedURL, err := impl.cas.GetObjectURL(c, &api.GetObjectURLRequest{
Object: ref,
DownloadFilename: processing.GetClientBinaryName(r.Package), // e.g. 'cipd.exe'
})
if err != nil {
return nil, errors.Annotate(err, "failed to get signed URL to the client binary").Tag(grpcutil.InternalTag).Err()
}
return &api.DescribeClientResponse{
Instance: inst.Proto(),
ClientRef: ref,
ClientBinary: signedURL,
ClientSize: proc.ClientBinary.Size,
LegacySha1: sha1,
ClientRefAliases: refAliases,
}, nil
} | go | func (impl *repoImpl) DescribeClient(c context.Context, r *api.DescribeClientRequest) (resp *api.DescribeClientResponse, err error) {
defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()
// Validate the request.
if err := common.ValidatePackageName(r.Package); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
}
if !processing.IsClientPackage(r.Package) {
return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - not a CIPD client package")
}
if err := common.ValidateObjectRef(r.Instance, common.KnownHash); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "bad 'instance' - %s", err)
}
// Check ACLs.
if _, err := impl.checkRole(c, r.Package, api.Role_READER); err != nil {
return nil, err
}
// Make sure this instance exists, has all processors finished and fetch
// basic details about it.
inst := (&model.Instance{}).FromProto(c, &api.Instance{
Package: r.Package,
Instance: r.Instance,
})
if err := model.CheckInstanceReady(c, inst); err != nil {
return nil, err
}
// Grab the location of the extracted CIPD client from the post-processor.
// This must succeed, since CheckInstanceReady above verified processors have
// finished. Thus treat any error here as internal, as it will require an
// investigation.
proc, err := processing.GetClientExtractorResult(c, inst.Proto())
if err != nil {
return nil, errors.Annotate(err, "failed to get client extractor results").Tag(grpcutil.InternalTag).Err()
}
ref, err := proc.ToObjectRef()
if err != nil {
return nil, errors.Annotate(err, "malformed or unrecognized ref in the client extractor results").Tag(grpcutil.InternalTag).Err()
}
// refAliases (and SHA1 in particular, as hash supported by oldest code) is
// required to allow older clients to self-update to a newer client. See the
// doc for DescribeClientResponse proto message.
refAliases := proc.ObjectRefAliases()
sha1 := ""
for _, ref := range refAliases {
if ref.HashAlgo == api.HashAlgo_SHA1 {
sha1 = ref.HexDigest
break
}
}
if sha1 == "" {
return nil, errors.Reason("malformed client extraction results, missing SHA1 digest").Tag(grpcutil.InternalTag).Err()
}
// Grab the signed URL of the client binary.
signedURL, err := impl.cas.GetObjectURL(c, &api.GetObjectURLRequest{
Object: ref,
DownloadFilename: processing.GetClientBinaryName(r.Package), // e.g. 'cipd.exe'
})
if err != nil {
return nil, errors.Annotate(err, "failed to get signed URL to the client binary").Tag(grpcutil.InternalTag).Err()
}
return &api.DescribeClientResponse{
Instance: inst.Proto(),
ClientRef: ref,
ClientBinary: signedURL,
ClientSize: proc.ClientBinary.Size,
LegacySha1: sha1,
ClientRefAliases: refAliases,
}, nil
} | [
"func",
"(",
"impl",
"*",
"repoImpl",
")",
"DescribeClient",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"api",
".",
"DescribeClientRequest",
")",
"(",
"resp",
"*",
"api",
".",
"DescribeClientResponse",
",",
"err",
"error",
")",
"{",
"defer",
"fu... | // DescribeClient implements the corresponding RPC method, see the proto doc. | [
"DescribeClient",
"implements",
"the",
"corresponding",
"RPC",
"method",
"see",
"the",
"proto",
"doc",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L1208-L1282 |
8,635 | luci/luci-go | cipd/appengine/impl/repo/repo.go | FromInstance | func (l *legacyInstance) FromInstance(inst *api.Instance) *legacyInstance {
l.PackageName = inst.Package
l.InstanceID = common.ObjectRefToInstanceID(inst.Instance)
l.RegisteredBy = inst.RegisteredBy
if ts := inst.RegisteredTs; ts != nil {
l.RegisteredTs = fmt.Sprintf("%d", ts.Seconds*1e6+int64(ts.Nanos/1e3))
} else {
l.RegisteredTs = ""
}
return l
} | go | func (l *legacyInstance) FromInstance(inst *api.Instance) *legacyInstance {
l.PackageName = inst.Package
l.InstanceID = common.ObjectRefToInstanceID(inst.Instance)
l.RegisteredBy = inst.RegisteredBy
if ts := inst.RegisteredTs; ts != nil {
l.RegisteredTs = fmt.Sprintf("%d", ts.Seconds*1e6+int64(ts.Nanos/1e3))
} else {
l.RegisteredTs = ""
}
return l
} | [
"func",
"(",
"l",
"*",
"legacyInstance",
")",
"FromInstance",
"(",
"inst",
"*",
"api",
".",
"Instance",
")",
"*",
"legacyInstance",
"{",
"l",
".",
"PackageName",
"=",
"inst",
".",
"Package",
"\n",
"l",
".",
"InstanceID",
"=",
"common",
".",
"ObjectRefToI... | // FromInstance fills in legacyInstance based on data from Instance proto. | [
"FromInstance",
"fills",
"in",
"legacyInstance",
"based",
"on",
"data",
"from",
"Instance",
"proto",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L1300-L1310 |
8,636 | luci/luci-go | cipd/appengine/impl/repo/repo.go | replyWithJSON | func replyWithJSON(w http.ResponseWriter, obj interface{}) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
return enc.Encode(obj)
} | go | func replyWithJSON(w http.ResponseWriter, obj interface{}) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
return enc.Encode(obj)
} | [
"func",
"replyWithJSON",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"obj",
"interface",
"{",
"}",
")",
"error",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
"... | // replyWithJSON sends StatusOK with JSON body. | [
"replyWithJSON",
"sends",
"StatusOK",
"with",
"JSON",
"body",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L1327-L1334 |
8,637 | luci/luci-go | cipd/appengine/impl/repo/repo.go | replyWithError | func replyWithError(w http.ResponseWriter, status, message string, args ...interface{}) error {
return replyWithJSON(w, map[string]string{
"status": status,
"error_message": fmt.Sprintf(message, args...),
})
} | go | func replyWithError(w http.ResponseWriter, status, message string, args ...interface{}) error {
return replyWithJSON(w, map[string]string{
"status": status,
"error_message": fmt.Sprintf(message, args...),
})
} | [
"func",
"replyWithError",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"status",
",",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"replyWithJSON",
"(",
"w",
",",
"map",
"[",
"string",
"]",
"string",
"{",
... | // replyWithError sends StatusOK with JSON body containing an error.
//
// Due to Cloud Endpoints limitations, legacy API used StatusOK for some not-OK
// responses and communicated the actual error through 'status' response field. | [
"replyWithError",
"sends",
"StatusOK",
"with",
"JSON",
"body",
"containing",
"an",
"error",
".",
"Due",
"to",
"Cloud",
"Endpoints",
"limitations",
"legacy",
"API",
"used",
"StatusOK",
"for",
"some",
"not",
"-",
"OK",
"responses",
"and",
"communicated",
"the",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/repo.go#L1340-L1345 |
8,638 | luci/luci-go | gce/appengine/backend/bots.go | setConnected | func setConnected(c context.Context, id, hostname string, at time.Time) error {
// Check dscache in case vm.Connected is set now, to avoid a costly transaction.
vm := &model.VM{
ID: id,
}
switch err := datastore.Get(c, vm); {
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != hostname:
return errors.Reason("bot %q does not exist", hostname).Err()
case vm.Connected > 0:
return nil
}
return datastore.RunInTransaction(c, func(c context.Context) error {
switch err := datastore.Get(c, vm); {
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != hostname:
return errors.Reason("bot %q does not exist", hostname).Err()
case vm.Connected > 0:
return nil
}
vm.Connected = at.Unix()
if err := datastore.Put(c, vm); err != nil {
return errors.Annotate(err, "failed to store VM").Err()
}
return nil
}, nil)
} | go | func setConnected(c context.Context, id, hostname string, at time.Time) error {
// Check dscache in case vm.Connected is set now, to avoid a costly transaction.
vm := &model.VM{
ID: id,
}
switch err := datastore.Get(c, vm); {
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != hostname:
return errors.Reason("bot %q does not exist", hostname).Err()
case vm.Connected > 0:
return nil
}
return datastore.RunInTransaction(c, func(c context.Context) error {
switch err := datastore.Get(c, vm); {
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != hostname:
return errors.Reason("bot %q does not exist", hostname).Err()
case vm.Connected > 0:
return nil
}
vm.Connected = at.Unix()
if err := datastore.Put(c, vm); err != nil {
return errors.Annotate(err, "failed to store VM").Err()
}
return nil
}, nil)
} | [
"func",
"setConnected",
"(",
"c",
"context",
".",
"Context",
",",
"id",
",",
"hostname",
"string",
",",
"at",
"time",
".",
"Time",
")",
"error",
"{",
"// Check dscache in case vm.Connected is set now, to avoid a costly transaction.",
"vm",
":=",
"&",
"model",
".",
... | // setConnected sets the Swarming bot as connected in the datastore if it isn't already. | [
"setConnected",
"sets",
"the",
"Swarming",
"bot",
"as",
"connected",
"in",
"the",
"datastore",
"if",
"it",
"isn",
"t",
"already",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/bots.go#L41-L69 |
8,639 | luci/luci-go | gce/appengine/backend/bots.go | manageMissingBot | func manageMissingBot(c context.Context, vm *model.VM) error {
// Set that the bot has not yet connected to Swarming.
switch {
case vm.Lifetime > 0 && vm.Created+vm.Lifetime < time.Now().Unix():
logging.Debugf(c, "deadline %d exceeded", vm.Created+vm.Lifetime)
return destroyInstanceAsync(c, vm.ID, vm.URL)
case vm.Drained:
logging.Debugf(c, "VM drained")
return destroyInstanceAsync(c, vm.ID, vm.URL)
case vm.Timeout > 0 && vm.Created+vm.Timeout < time.Now().Unix():
logging.Debugf(c, "timeout %d exceeded", vm.Created+vm.Timeout)
return destroyInstanceAsync(c, vm.ID, vm.URL)
default:
return nil
}
} | go | func manageMissingBot(c context.Context, vm *model.VM) error {
// Set that the bot has not yet connected to Swarming.
switch {
case vm.Lifetime > 0 && vm.Created+vm.Lifetime < time.Now().Unix():
logging.Debugf(c, "deadline %d exceeded", vm.Created+vm.Lifetime)
return destroyInstanceAsync(c, vm.ID, vm.URL)
case vm.Drained:
logging.Debugf(c, "VM drained")
return destroyInstanceAsync(c, vm.ID, vm.URL)
case vm.Timeout > 0 && vm.Created+vm.Timeout < time.Now().Unix():
logging.Debugf(c, "timeout %d exceeded", vm.Created+vm.Timeout)
return destroyInstanceAsync(c, vm.ID, vm.URL)
default:
return nil
}
} | [
"func",
"manageMissingBot",
"(",
"c",
"context",
".",
"Context",
",",
"vm",
"*",
"model",
".",
"VM",
")",
"error",
"{",
"// Set that the bot has not yet connected to Swarming.",
"switch",
"{",
"case",
"vm",
".",
"Lifetime",
">",
"0",
"&&",
"vm",
".",
"Created"... | // manageMissingBot manages a missing Swarming bot. | [
"manageMissingBot",
"manages",
"a",
"missing",
"Swarming",
"bot",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/bots.go#L72-L87 |
8,640 | luci/luci-go | gce/appengine/backend/bots.go | manageExistingBot | func manageExistingBot(c context.Context, bot *swarming.SwarmingRpcsBotInfo, vm *model.VM) error {
// This value of vm.Connected may be several seconds old, because the VM was fetched
// prior to sending an RPC to Swarming. Still, check it here to save a costly operation
// in setConnected, since manageExistingBot may be called thousands of times per minute.
if vm.Connected == 0 {
t, err := time.Parse(utcRFC3339, bot.FirstSeenTs)
if err != nil {
return errors.Annotate(err, "failed to parse bot connection time").Err()
}
if err := setConnected(c, vm.ID, vm.Hostname, t); err != nil {
return err
}
}
// A bot connected to Swarming may be executing workload.
// To destroy the instance, terminate the bot first to avoid interruptions.
// Termination can be skipped if the bot is deleted, dead, or already terminated.
switch {
case bot.Deleted:
logging.Debugf(c, "bot deleted")
return destroyInstanceAsync(c, vm.ID, vm.URL)
case bot.IsDead:
logging.Debugf(c, "bot dead")
return destroyInstanceAsync(c, vm.ID, vm.URL)
}
srv := getSwarming(c, vm.Swarming).Bot
// bot_terminate occurs when the bot starts the termination task and is normally followed
// by task_completed and bot_shutdown. A terminated bot has no further events. Responses
// also include the full set of dimensions when the event was recorded. Limit response size
// by fetching only recent events, and only the type of each.
events, err := srv.Events(vm.Hostname).Context(c).Fields("items/event_type").Limit(5).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok {
logErrors(c, gerr)
return errors.Reason("failed to fetch bot events").Err()
}
return errors.Annotate(err, "failed to fetch bot events").Err()
}
for _, e := range events.Items {
if e.EventType == "bot_terminate" {
logging.Debugf(c, "bot terminated")
return destroyInstanceAsync(c, vm.ID, vm.URL)
}
}
switch {
case vm.Lifetime > 0 && vm.Created+vm.Lifetime < time.Now().Unix():
logging.Debugf(c, "deadline %d exceeded", vm.Created+vm.Lifetime)
return terminateBotAsync(c, vm.ID, vm.Hostname)
case vm.Drained:
logging.Debugf(c, "VM drained")
return terminateBotAsync(c, vm.ID, vm.Hostname)
}
return nil
} | go | func manageExistingBot(c context.Context, bot *swarming.SwarmingRpcsBotInfo, vm *model.VM) error {
// This value of vm.Connected may be several seconds old, because the VM was fetched
// prior to sending an RPC to Swarming. Still, check it here to save a costly operation
// in setConnected, since manageExistingBot may be called thousands of times per minute.
if vm.Connected == 0 {
t, err := time.Parse(utcRFC3339, bot.FirstSeenTs)
if err != nil {
return errors.Annotate(err, "failed to parse bot connection time").Err()
}
if err := setConnected(c, vm.ID, vm.Hostname, t); err != nil {
return err
}
}
// A bot connected to Swarming may be executing workload.
// To destroy the instance, terminate the bot first to avoid interruptions.
// Termination can be skipped if the bot is deleted, dead, or already terminated.
switch {
case bot.Deleted:
logging.Debugf(c, "bot deleted")
return destroyInstanceAsync(c, vm.ID, vm.URL)
case bot.IsDead:
logging.Debugf(c, "bot dead")
return destroyInstanceAsync(c, vm.ID, vm.URL)
}
srv := getSwarming(c, vm.Swarming).Bot
// bot_terminate occurs when the bot starts the termination task and is normally followed
// by task_completed and bot_shutdown. A terminated bot has no further events. Responses
// also include the full set of dimensions when the event was recorded. Limit response size
// by fetching only recent events, and only the type of each.
events, err := srv.Events(vm.Hostname).Context(c).Fields("items/event_type").Limit(5).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok {
logErrors(c, gerr)
return errors.Reason("failed to fetch bot events").Err()
}
return errors.Annotate(err, "failed to fetch bot events").Err()
}
for _, e := range events.Items {
if e.EventType == "bot_terminate" {
logging.Debugf(c, "bot terminated")
return destroyInstanceAsync(c, vm.ID, vm.URL)
}
}
switch {
case vm.Lifetime > 0 && vm.Created+vm.Lifetime < time.Now().Unix():
logging.Debugf(c, "deadline %d exceeded", vm.Created+vm.Lifetime)
return terminateBotAsync(c, vm.ID, vm.Hostname)
case vm.Drained:
logging.Debugf(c, "VM drained")
return terminateBotAsync(c, vm.ID, vm.Hostname)
}
return nil
} | [
"func",
"manageExistingBot",
"(",
"c",
"context",
".",
"Context",
",",
"bot",
"*",
"swarming",
".",
"SwarmingRpcsBotInfo",
",",
"vm",
"*",
"model",
".",
"VM",
")",
"error",
"{",
"// This value of vm.Connected may be several seconds old, because the VM was fetched",
"// ... | // manageExistingBot manages an existing Swarming bot. | [
"manageExistingBot",
"manages",
"an",
"existing",
"Swarming",
"bot",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/bots.go#L90-L142 |
8,641 | luci/luci-go | gce/appengine/backend/bots.go | manageBot | func manageBot(c context.Context, payload proto.Message) error {
task, ok := payload.(*tasks.ManageBot)
switch {
case !ok:
return errors.Reason("unexpected payload %q", payload).Err()
case task.GetId() == "":
return errors.Reason("ID is required").Err()
}
vm := &model.VM{
ID: task.Id,
}
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.URL == "":
logging.Debugf(c, "instance %q does not exist", vm.Hostname)
return nil
}
logging.Debugf(c, "fetching bot %q: %s", vm.Hostname, vm.Swarming)
bot, err := getSwarming(c, vm.Swarming).Bot.Get(vm.Hostname).Context(c).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok {
if gerr.Code == http.StatusNotFound {
logging.Debugf(c, "bot not found")
return manageMissingBot(c, vm)
}
logErrors(c, gerr)
return errors.Reason("failed to fetch bot").Err()
}
return errors.Annotate(err, "failed to fetch bot").Err()
}
logging.Debugf(c, "found bot")
return manageExistingBot(c, bot, vm)
} | go | func manageBot(c context.Context, payload proto.Message) error {
task, ok := payload.(*tasks.ManageBot)
switch {
case !ok:
return errors.Reason("unexpected payload %q", payload).Err()
case task.GetId() == "":
return errors.Reason("ID is required").Err()
}
vm := &model.VM{
ID: task.Id,
}
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.URL == "":
logging.Debugf(c, "instance %q does not exist", vm.Hostname)
return nil
}
logging.Debugf(c, "fetching bot %q: %s", vm.Hostname, vm.Swarming)
bot, err := getSwarming(c, vm.Swarming).Bot.Get(vm.Hostname).Context(c).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok {
if gerr.Code == http.StatusNotFound {
logging.Debugf(c, "bot not found")
return manageMissingBot(c, vm)
}
logErrors(c, gerr)
return errors.Reason("failed to fetch bot").Err()
}
return errors.Annotate(err, "failed to fetch bot").Err()
}
logging.Debugf(c, "found bot")
return manageExistingBot(c, bot, vm)
} | [
"func",
"manageBot",
"(",
"c",
"context",
".",
"Context",
",",
"payload",
"proto",
".",
"Message",
")",
"error",
"{",
"task",
",",
"ok",
":=",
"payload",
".",
"(",
"*",
"tasks",
".",
"ManageBot",
")",
"\n",
"switch",
"{",
"case",
"!",
"ok",
":",
"r... | // manageBot manages a Swarming bot. | [
"manageBot",
"manages",
"a",
"Swarming",
"bot",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/bots.go#L148-L183 |
8,642 | luci/luci-go | gce/appengine/backend/bots.go | terminateBotAsync | func terminateBotAsync(c context.Context, id, hostname string) error {
t := &tq.Task{
Payload: &tasks.TerminateBot{
Id: id,
Hostname: hostname,
},
}
if err := getDispatcher(c).AddTask(c, t); err != nil {
return errors.Annotate(err, "failed to schedule terminate task").Err()
}
return nil
} | go | func terminateBotAsync(c context.Context, id, hostname string) error {
t := &tq.Task{
Payload: &tasks.TerminateBot{
Id: id,
Hostname: hostname,
},
}
if err := getDispatcher(c).AddTask(c, t); err != nil {
return errors.Annotate(err, "failed to schedule terminate task").Err()
}
return nil
} | [
"func",
"terminateBotAsync",
"(",
"c",
"context",
".",
"Context",
",",
"id",
",",
"hostname",
"string",
")",
"error",
"{",
"t",
":=",
"&",
"tq",
".",
"Task",
"{",
"Payload",
":",
"&",
"tasks",
".",
"TerminateBot",
"{",
"Id",
":",
"id",
",",
"Hostname... | // terminateBotAsync schedules a task queue task to terminate a Swarming bot. | [
"terminateBotAsync",
"schedules",
"a",
"task",
"queue",
"task",
"to",
"terminate",
"a",
"Swarming",
"bot",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/bots.go#L186-L197 |
8,643 | luci/luci-go | gce/appengine/backend/bots.go | terminateBot | func terminateBot(c context.Context, payload proto.Message) error {
task, ok := payload.(*tasks.TerminateBot)
switch {
case !ok:
return errors.Reason("unexpected payload %q", payload).Err()
case task.GetId() == "":
return errors.Reason("ID is required").Err()
case task.GetHostname() == "":
return errors.Reason("hostname is required").Err()
}
vm := &model.VM{
ID: task.Id,
}
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != task.Hostname:
// Instance is already destroyed and replaced. Don't terminate the new bot.
return errors.Reason("bot %q does not exist", task.Hostname).Err()
}
logging.Debugf(c, "terminating bot %q: %s", vm.Hostname, vm.Swarming)
srv := getSwarming(c, vm.Swarming)
_, err := srv.Bot.Terminate(vm.Hostname).Context(c).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok {
if gerr.Code == http.StatusNotFound {
// Bot is already deleted.
logging.Debugf(c, "bot not found")
return nil
}
logErrors(c, gerr)
return errors.Reason("failed to terminate bot").Err()
}
return errors.Annotate(err, "failed to terminate bot").Err()
}
return nil
} | go | func terminateBot(c context.Context, payload proto.Message) error {
task, ok := payload.(*tasks.TerminateBot)
switch {
case !ok:
return errors.Reason("unexpected payload %q", payload).Err()
case task.GetId() == "":
return errors.Reason("ID is required").Err()
case task.GetHostname() == "":
return errors.Reason("hostname is required").Err()
}
vm := &model.VM{
ID: task.Id,
}
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != task.Hostname:
// Instance is already destroyed and replaced. Don't terminate the new bot.
return errors.Reason("bot %q does not exist", task.Hostname).Err()
}
logging.Debugf(c, "terminating bot %q: %s", vm.Hostname, vm.Swarming)
srv := getSwarming(c, vm.Swarming)
_, err := srv.Bot.Terminate(vm.Hostname).Context(c).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok {
if gerr.Code == http.StatusNotFound {
// Bot is already deleted.
logging.Debugf(c, "bot not found")
return nil
}
logErrors(c, gerr)
return errors.Reason("failed to terminate bot").Err()
}
return errors.Annotate(err, "failed to terminate bot").Err()
}
return nil
} | [
"func",
"terminateBot",
"(",
"c",
"context",
".",
"Context",
",",
"payload",
"proto",
".",
"Message",
")",
"error",
"{",
"task",
",",
"ok",
":=",
"payload",
".",
"(",
"*",
"tasks",
".",
"TerminateBot",
")",
"\n",
"switch",
"{",
"case",
"!",
"ok",
":"... | // terminateBot terminates an existing Swarming bot. | [
"terminateBot",
"terminates",
"an",
"existing",
"Swarming",
"bot",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/bots.go#L203-L241 |
8,644 | luci/luci-go | gce/appengine/backend/bots.go | deleteVM | func deleteVM(c context.Context, id, hostname string) error {
vm := &model.VM{
ID: id,
}
return datastore.RunInTransaction(c, func(c context.Context) error {
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != hostname:
logging.Debugf(c, "VM %q does not exist", hostname)
return nil
}
if err := datastore.Delete(c, vm); err != nil {
return errors.Annotate(err, "failed to delete VM").Err()
}
return nil
}, nil)
} | go | func deleteVM(c context.Context, id, hostname string) error {
vm := &model.VM{
ID: id,
}
return datastore.RunInTransaction(c, func(c context.Context) error {
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Hostname != hostname:
logging.Debugf(c, "VM %q does not exist", hostname)
return nil
}
if err := datastore.Delete(c, vm); err != nil {
return errors.Annotate(err, "failed to delete VM").Err()
}
return nil
}, nil)
} | [
"func",
"deleteVM",
"(",
"c",
"context",
".",
"Context",
",",
"id",
",",
"hostname",
"string",
")",
"error",
"{",
"vm",
":=",
"&",
"model",
".",
"VM",
"{",
"ID",
":",
"id",
",",
"}",
"\n",
"return",
"datastore",
".",
"RunInTransaction",
"(",
"c",
"... | // deleteVM deletes the given VM from the datastore if it exists. | [
"deleteVM",
"deletes",
"the",
"given",
"VM",
"from",
"the",
"datastore",
"if",
"it",
"exists",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/bots.go#L302-L321 |
8,645 | luci/luci-go | server/tsmon/settings.go | canActAsProdX | func canActAsProdX(c context.Context, account string) error {
ts, err := auth.GetTokenSource(
c, auth.AsActor,
auth.WithServiceAccount(account),
auth.WithScopes(monitor.ProdxmonScopes...))
if err != nil {
return err
}
_, err = ts.Token()
return err
} | go | func canActAsProdX(c context.Context, account string) error {
ts, err := auth.GetTokenSource(
c, auth.AsActor,
auth.WithServiceAccount(account),
auth.WithScopes(monitor.ProdxmonScopes...))
if err != nil {
return err
}
_, err = ts.Token()
return err
} | [
"func",
"canActAsProdX",
"(",
"c",
"context",
".",
"Context",
",",
"account",
"string",
")",
"error",
"{",
"ts",
",",
"err",
":=",
"auth",
".",
"GetTokenSource",
"(",
"c",
",",
"auth",
".",
"AsActor",
",",
"auth",
".",
"WithServiceAccount",
"(",
"account... | // canActAsProdX attempts to grab ProdX scoped access token for the given
// account. | [
"canActAsProdX",
"attempts",
"to",
"grab",
"ProdX",
"scoped",
"access",
"token",
"for",
"the",
"given",
"account",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tsmon/settings.go#L201-L211 |
8,646 | luci/luci-go | milo/frontend/routes.go | handleError | func handleError(handler func(c *router.Context) error) func(c *router.Context) {
return func(c *router.Context) {
if err := handler(c); err != nil {
ErrorHandler(c, err)
}
}
} | go | func handleError(handler func(c *router.Context) error) func(c *router.Context) {
return func(c *router.Context) {
if err := handler(c); err != nil {
ErrorHandler(c, err)
}
}
} | [
"func",
"handleError",
"(",
"handler",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"error",
")",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"return",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"if",
"err",
... | // handleError is a wrapper for a handler so that the handler can return an error
// rather than call ErrorHandler directly.
// This should be used for handlers that render webpages. | [
"handleError",
"is",
"a",
"wrapper",
"for",
"a",
"handler",
"so",
"that",
"the",
"handler",
"can",
"return",
"an",
"error",
"rather",
"than",
"call",
"ErrorHandler",
"directly",
".",
"This",
"should",
"be",
"used",
"for",
"handlers",
"that",
"render",
"webpa... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/routes.go#L216-L222 |
8,647 | luci/luci-go | milo/frontend/routes.go | cronHandler | func cronHandler(handler func(c context.Context) error) func(c *router.Context) {
return func(ctx *router.Context) {
if err := handler(ctx.Context); err != nil {
logging.WithError(err).Errorf(ctx.Context, "failed to run")
ctx.Writer.WriteHeader(http.StatusInternalServerError)
return
}
ctx.Writer.WriteHeader(http.StatusOK)
}
} | go | func cronHandler(handler func(c context.Context) error) func(c *router.Context) {
return func(ctx *router.Context) {
if err := handler(ctx.Context); err != nil {
logging.WithError(err).Errorf(ctx.Context, "failed to run")
ctx.Writer.WriteHeader(http.StatusInternalServerError)
return
}
ctx.Writer.WriteHeader(http.StatusOK)
}
} | [
"func",
"cronHandler",
"(",
"handler",
"func",
"(",
"c",
"context",
".",
"Context",
")",
"error",
")",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"return",
"func",
"(",
"ctx",
"*",
"router",
".",
"Context",
")",
"{",
"if",
"err",
":... | // cronHandler is a wrapper for cron handlers which do not require template rendering. | [
"cronHandler",
"is",
"a",
"wrapper",
"for",
"cron",
"handlers",
"which",
"do",
"not",
"require",
"template",
"rendering",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/routes.go#L225-L234 |
8,648 | luci/luci-go | milo/frontend/routes.go | redirect | func redirect(pathTemplate string, status int) router.Handler {
if !strings.HasPrefix(pathTemplate, "/") {
panic("pathTemplate must start with /")
}
return func(c *router.Context) {
parts := strings.Split(pathTemplate, "/")
for i, p := range parts {
if strings.HasPrefix(p, ":") {
parts[i] = c.Params.ByName(p[1:])
}
}
u := *c.Request.URL
u.Path = strings.Join(parts, "/")
http.Redirect(c.Writer, c.Request, u.String(), status)
}
} | go | func redirect(pathTemplate string, status int) router.Handler {
if !strings.HasPrefix(pathTemplate, "/") {
panic("pathTemplate must start with /")
}
return func(c *router.Context) {
parts := strings.Split(pathTemplate, "/")
for i, p := range parts {
if strings.HasPrefix(p, ":") {
parts[i] = c.Params.ByName(p[1:])
}
}
u := *c.Request.URL
u.Path = strings.Join(parts, "/")
http.Redirect(c.Writer, c.Request, u.String(), status)
}
} | [
"func",
"redirect",
"(",
"pathTemplate",
"string",
",",
"status",
"int",
")",
"router",
".",
"Handler",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"pathTemplate",
",",
"\"",
"\"",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"re... | // redirect returns a handler that responds with given HTTP status
// with a location specified by the pathTemplate. | [
"redirect",
"returns",
"a",
"handler",
"that",
"responds",
"with",
"given",
"HTTP",
"status",
"with",
"a",
"location",
"specified",
"by",
"the",
"pathTemplate",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/routes.go#L238-L254 |
8,649 | luci/luci-go | machine-db/appengine/rpc/ips.go | ListFreeIPs | func (*Service) ListFreeIPs(c context.Context, req *crimson.ListFreeIPsRequest) (*crimson.ListIPsResponse, error) {
switch {
case req.Vlan < 1:
return nil, status.Error(codes.InvalidArgument, "VLAN is required and must be positive")
case req.PageSize < 0:
return nil, status.Error(codes.InvalidArgument, "page size must be non-negative")
case req.PageSize == 0:
req.PageSize = defaultIPsPageSize
}
ips, err := listFreeIPs(c, req.Vlan, req.PageSize)
if err != nil {
return nil, err
}
return &crimson.ListIPsResponse{
Ips: ips,
}, nil
} | go | func (*Service) ListFreeIPs(c context.Context, req *crimson.ListFreeIPsRequest) (*crimson.ListIPsResponse, error) {
switch {
case req.Vlan < 1:
return nil, status.Error(codes.InvalidArgument, "VLAN is required and must be positive")
case req.PageSize < 0:
return nil, status.Error(codes.InvalidArgument, "page size must be non-negative")
case req.PageSize == 0:
req.PageSize = defaultIPsPageSize
}
ips, err := listFreeIPs(c, req.Vlan, req.PageSize)
if err != nil {
return nil, err
}
return &crimson.ListIPsResponse{
Ips: ips,
}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"ListFreeIPs",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"ListFreeIPsRequest",
")",
"(",
"*",
"crimson",
".",
"ListIPsResponse",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"req",
".",
"V... | // ListFreeIPs handles a request to list free IP addresses. | [
"ListFreeIPs",
"handles",
"a",
"request",
"to",
"list",
"free",
"IP",
"addresses",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/ips.go#L34-L50 |
8,650 | luci/luci-go | machine-db/appengine/rpc/ips.go | listFreeIPs | func listFreeIPs(c context.Context, vlan int64, limit int32) ([]*crimson.IP, error) {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT ipv4
FROM ips
WHERE vlan_id = ? AND hostname_id IS NULL
LIMIT ?
`, vlan, limit)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch IP addresses").Err()
}
defer rows.Close()
var ips []*crimson.IP
for rows.Next() {
ip := &crimson.IP{}
var ipv4 common.IPv4
if err = rows.Scan(&ipv4); err != nil {
return nil, errors.Annotate(err, "failed to fetch IP address").Err()
}
ip.Ipv4 = ipv4.String()
ip.Vlan = vlan
ips = append(ips, ip)
}
return ips, nil
} | go | func listFreeIPs(c context.Context, vlan int64, limit int32) ([]*crimson.IP, error) {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT ipv4
FROM ips
WHERE vlan_id = ? AND hostname_id IS NULL
LIMIT ?
`, vlan, limit)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch IP addresses").Err()
}
defer rows.Close()
var ips []*crimson.IP
for rows.Next() {
ip := &crimson.IP{}
var ipv4 common.IPv4
if err = rows.Scan(&ipv4); err != nil {
return nil, errors.Annotate(err, "failed to fetch IP address").Err()
}
ip.Ipv4 = ipv4.String()
ip.Vlan = vlan
ips = append(ips, ip)
}
return ips, nil
} | [
"func",
"listFreeIPs",
"(",
"c",
"context",
".",
"Context",
",",
"vlan",
"int64",
",",
"limit",
"int32",
")",
"(",
"[",
"]",
"*",
"crimson",
".",
"IP",
",",
"error",
")",
"{",
"db",
":=",
"database",
".",
"Get",
"(",
"c",
")",
"\n",
"rows",
",",
... | // listFreeIPs returns a slice of free IP addresses in the database. | [
"listFreeIPs",
"returns",
"a",
"slice",
"of",
"free",
"IP",
"addresses",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/ips.go#L53-L78 |
8,651 | luci/luci-go | machine-db/appengine/rpc/ips.go | parseIPv4s | func parseIPv4s(ips []string) ([]int64, error) {
ipv4s := make([]int64, len(ips))
for i, ip := range ips {
ipv4, err := common.ParseIPv4(ip)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", ip)
}
ipv4s[i] = int64(ipv4)
}
return ipv4s, nil
} | go | func parseIPv4s(ips []string) ([]int64, error) {
ipv4s := make([]int64, len(ips))
for i, ip := range ips {
ipv4, err := common.ParseIPv4(ip)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", ip)
}
ipv4s[i] = int64(ipv4)
}
return ipv4s, nil
} | [
"func",
"parseIPv4s",
"(",
"ips",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"int64",
",",
"error",
")",
"{",
"ipv4s",
":=",
"make",
"(",
"[",
"]",
"int64",
",",
"len",
"(",
"ips",
")",
")",
"\n",
"for",
"i",
",",
"ip",
":=",
"range",
"ips",
"{"... | // parseIPv4s returns a slice of int64 IP addresses. | [
"parseIPv4s",
"returns",
"a",
"slice",
"of",
"int64",
"IP",
"addresses",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/ips.go#L81-L91 |
8,652 | luci/luci-go | milo/common/model/builder_summary.go | SelfLink | func (b *BuilderSummary) SelfLink() string {
if b == nil {
return InvalidBuilderIDURL
}
return BuilderIDLink(b.BuilderID, b.ProjectID)
} | go | func (b *BuilderSummary) SelfLink() string {
if b == nil {
return InvalidBuilderIDURL
}
return BuilderIDLink(b.BuilderID, b.ProjectID)
} | [
"func",
"(",
"b",
"*",
"BuilderSummary",
")",
"SelfLink",
"(",
")",
"string",
"{",
"if",
"b",
"==",
"nil",
"{",
"return",
"InvalidBuilderIDURL",
"\n",
"}",
"\n",
"return",
"BuilderIDLink",
"(",
"b",
".",
"BuilderID",
",",
"b",
".",
"ProjectID",
")",
"\... | // SelfLink returns a link to the associated builder. | [
"SelfLink",
"returns",
"a",
"link",
"to",
"the",
"associated",
"builder",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/builder_summary.go#L84-L89 |
8,653 | luci/luci-go | milo/common/model/builder_summary.go | BuilderIDLink | func BuilderIDLink(b, project string) string {
parts := strings.Split(b, "/")
if len(parts) != 3 {
return InvalidBuilderIDURL
}
switch source := parts[0]; source {
case "buildbot":
return fmt.Sprintf("/buildbot/%s/%s", parts[1], parts[2])
case "buildbucket":
return fmt.Sprintf("/p/%s/builders/%s/%s", project, parts[1], parts[2])
default:
return InvalidBuilderIDURL
}
} | go | func BuilderIDLink(b, project string) string {
parts := strings.Split(b, "/")
if len(parts) != 3 {
return InvalidBuilderIDURL
}
switch source := parts[0]; source {
case "buildbot":
return fmt.Sprintf("/buildbot/%s/%s", parts[1], parts[2])
case "buildbucket":
return fmt.Sprintf("/p/%s/builders/%s/%s", project, parts[1], parts[2])
default:
return InvalidBuilderIDURL
}
} | [
"func",
"BuilderIDLink",
"(",
"b",
",",
"project",
"string",
")",
"string",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"b",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
"{",
"return",
"InvalidBuilderIDURL",
"\n",
"}",... | // BuilderIDLink gets a builder link from builder ID and project.
// Depends on routes.go. | [
"BuilderIDLink",
"gets",
"a",
"builder",
"link",
"from",
"builder",
"ID",
"and",
"project",
".",
"Depends",
"on",
"routes",
".",
"go",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/builder_summary.go#L93-L107 |
8,654 | luci/luci-go | milo/common/model/builder_summary.go | UpdateBuilderForBuild | func UpdateBuilderForBuild(c context.Context, build *BuildSummary) error {
if datastore.CurrentTransaction(c) == nil {
panic("UpdateBuilderForBuild was called outside of a transaction")
}
if !build.Summary.Status.Terminal() {
// this build did not complete yet.
// There is no new info for the builder.
// Do not even bother starting a transaction.
return nil
}
// Get or create the relevant BuilderSummary.
builder := &BuilderSummary{BuilderID: build.BuilderID}
switch err := datastore.Get(c, builder); {
case err == datastore.ErrNoSuchEntity:
logging.Warningf(c, "creating new BuilderSummary for BuilderID: %s", build.BuilderID)
case err != nil:
return err
case build.Created.Before(builder.LastFinishedCreated):
logging.Warningf(c, "message for build %s is out of order", build.BuildID)
return nil
}
// Overwrite previous value of ProjectID in case a builder has moved to
// another project.
builder.ProjectID = build.ProjectID
builder.LastFinishedBuildID = build.BuildID
builder.LastFinishedCreated = build.Created
builder.LastFinishedExperimental = build.Experimental
builder.LastFinishedStatus = build.Summary.Status
return datastore.Put(c, builder)
} | go | func UpdateBuilderForBuild(c context.Context, build *BuildSummary) error {
if datastore.CurrentTransaction(c) == nil {
panic("UpdateBuilderForBuild was called outside of a transaction")
}
if !build.Summary.Status.Terminal() {
// this build did not complete yet.
// There is no new info for the builder.
// Do not even bother starting a transaction.
return nil
}
// Get or create the relevant BuilderSummary.
builder := &BuilderSummary{BuilderID: build.BuilderID}
switch err := datastore.Get(c, builder); {
case err == datastore.ErrNoSuchEntity:
logging.Warningf(c, "creating new BuilderSummary for BuilderID: %s", build.BuilderID)
case err != nil:
return err
case build.Created.Before(builder.LastFinishedCreated):
logging.Warningf(c, "message for build %s is out of order", build.BuildID)
return nil
}
// Overwrite previous value of ProjectID in case a builder has moved to
// another project.
builder.ProjectID = build.ProjectID
builder.LastFinishedBuildID = build.BuildID
builder.LastFinishedCreated = build.Created
builder.LastFinishedExperimental = build.Experimental
builder.LastFinishedStatus = build.Summary.Status
return datastore.Put(c, builder)
} | [
"func",
"UpdateBuilderForBuild",
"(",
"c",
"context",
".",
"Context",
",",
"build",
"*",
"BuildSummary",
")",
"error",
"{",
"if",
"datastore",
".",
"CurrentTransaction",
"(",
"c",
")",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
... | // UpdateBuilderForBuild updates the appropriate BuilderSummary for the
// provided BuildSummary, if needed.
// In particular, a BuilderSummary is updated with a BuildSummary if the latter is marked complete
// and has a more recent creation time than the one stored in the BuilderSummary.
// If there is no existing BuilderSummary for the BuildSummary provided, one is created.
// Idempotent.
// c must have a current datastore transaction. | [
"UpdateBuilderForBuild",
"updates",
"the",
"appropriate",
"BuilderSummary",
"for",
"the",
"provided",
"BuildSummary",
"if",
"needed",
".",
"In",
"particular",
"a",
"BuilderSummary",
"is",
"updated",
"with",
"a",
"BuildSummary",
"if",
"the",
"latter",
"is",
"marked",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/builder_summary.go#L116-L148 |
8,655 | luci/luci-go | examples/appengine/helloworld_standard/frontend/handler.go | pageBase | func pageBase() router.MiddlewareChain {
return standard.Base().Extend(
templates.WithTemplates(templateBundle),
auth.Authenticate(server.UsersAPIAuthMethod{}),
)
} | go | func pageBase() router.MiddlewareChain {
return standard.Base().Extend(
templates.WithTemplates(templateBundle),
auth.Authenticate(server.UsersAPIAuthMethod{}),
)
} | [
"func",
"pageBase",
"(",
")",
"router",
".",
"MiddlewareChain",
"{",
"return",
"standard",
".",
"Base",
"(",
")",
".",
"Extend",
"(",
"templates",
".",
"WithTemplates",
"(",
"templateBundle",
")",
",",
"auth",
".",
"Authenticate",
"(",
"server",
".",
"User... | // pageBase returns the middleware chain for page handlers. | [
"pageBase",
"returns",
"the",
"middleware",
"chain",
"for",
"page",
"handlers",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/examples/appengine/helloworld_standard/frontend/handler.go#L67-L72 |
8,656 | luci/luci-go | tokenserver/client/default.go | New | func New(params Parameters) (*Client, error) {
signer, err := LoadX509Signer(params.PrivateKeyPath, params.CertificatePath)
if err != nil {
return nil, err
}
return &Client{
Client: minter.NewTokenMinterPRPCClient(&prpc.Client{
C: params.Client,
Host: params.Backend,
Options: &prpc.Options{
Retry: params.Retry,
Insecure: params.Insecure,
},
}),
Signer: signer,
}, nil
} | go | func New(params Parameters) (*Client, error) {
signer, err := LoadX509Signer(params.PrivateKeyPath, params.CertificatePath)
if err != nil {
return nil, err
}
return &Client{
Client: minter.NewTokenMinterPRPCClient(&prpc.Client{
C: params.Client,
Host: params.Backend,
Options: &prpc.Options{
Retry: params.Retry,
Insecure: params.Insecure,
},
}),
Signer: signer,
}, nil
} | [
"func",
"New",
"(",
"params",
"Parameters",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"signer",
",",
"err",
":=",
"LoadX509Signer",
"(",
"params",
".",
"PrivateKeyPath",
",",
"params",
".",
"CertificatePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // New returns new Client that uses PEM encoded keys and talks
// to the server via pRPC. | [
"New",
"returns",
"new",
"Client",
"that",
"uses",
"PEM",
"encoded",
"keys",
"and",
"talks",
"to",
"the",
"server",
"via",
"pRPC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/client/default.go#L61-L77 |
8,657 | luci/luci-go | vpython/spec/match.go | PEP425Matches | func PEP425Matches(match *vpython.PEP425Tag, tags []*vpython.PEP425Tag) bool {
// Special case: empty match matches nothing.
if match.IsZero() {
return false
}
for _, tag := range tags {
if v := match.Python; v != "" && tag.Python != v {
continue
}
if v := match.Abi; v != "" && tag.Abi != v {
continue
}
if v := match.Platform; v != "" && tag.Platform != v {
continue
}
return true
}
return false
} | go | func PEP425Matches(match *vpython.PEP425Tag, tags []*vpython.PEP425Tag) bool {
// Special case: empty match matches nothing.
if match.IsZero() {
return false
}
for _, tag := range tags {
if v := match.Python; v != "" && tag.Python != v {
continue
}
if v := match.Abi; v != "" && tag.Abi != v {
continue
}
if v := match.Platform; v != "" && tag.Platform != v {
continue
}
return true
}
return false
} | [
"func",
"PEP425Matches",
"(",
"match",
"*",
"vpython",
".",
"PEP425Tag",
",",
"tags",
"[",
"]",
"*",
"vpython",
".",
"PEP425Tag",
")",
"bool",
"{",
"// Special case: empty match matches nothing.",
"if",
"match",
".",
"IsZero",
"(",
")",
"{",
"return",
"false",... | // PEP425Matches returns true if match matches at least one of the tags in tags.
//
// A match is determined if the non-zero fields in match equal the equivalent
// fields in a tag. | [
"PEP425Matches",
"returns",
"true",
"if",
"match",
"matches",
"at",
"least",
"one",
"of",
"the",
"tags",
"in",
"tags",
".",
"A",
"match",
"is",
"determined",
"if",
"the",
"non",
"-",
"zero",
"fields",
"in",
"match",
"equal",
"the",
"equivalent",
"fields",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/match.go#L57-L77 |
8,658 | luci/luci-go | vpython/python/version.go | PythonBase | func (v *Version) PythonBase() string {
switch {
case v.IsZero():
return "python"
case v.Minor > 0:
return fmt.Sprintf("python%d.%d", v.Major, v.Minor)
default:
return fmt.Sprintf("python%d", v.Major)
}
} | go | func (v *Version) PythonBase() string {
switch {
case v.IsZero():
return "python"
case v.Minor > 0:
return fmt.Sprintf("python%d.%d", v.Major, v.Minor)
default:
return fmt.Sprintf("python%d", v.Major)
}
} | [
"func",
"(",
"v",
"*",
"Version",
")",
"PythonBase",
"(",
")",
"string",
"{",
"switch",
"{",
"case",
"v",
".",
"IsZero",
"(",
")",
":",
"return",
"\"",
"\"",
"\n",
"case",
"v",
".",
"Minor",
">",
"0",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
... | // PythonBase returns the base Python interpreter name for this version. | [
"PythonBase",
"returns",
"the",
"base",
"Python",
"interpreter",
"name",
"for",
"this",
"version",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/version.go#L99-L108 |
8,659 | luci/luci-go | vpython/python/version.go | Less | func (v *Version) Less(other *Version) bool {
switch {
case v.Major < other.Major:
return true
case v.Major > other.Major:
return false
case v.Minor < other.Minor:
return true
case v.Minor > other.Minor:
return false
default:
return (v.Patch < other.Patch)
}
} | go | func (v *Version) Less(other *Version) bool {
switch {
case v.Major < other.Major:
return true
case v.Major > other.Major:
return false
case v.Minor < other.Minor:
return true
case v.Minor > other.Minor:
return false
default:
return (v.Patch < other.Patch)
}
} | [
"func",
"(",
"v",
"*",
"Version",
")",
"Less",
"(",
"other",
"*",
"Version",
")",
"bool",
"{",
"switch",
"{",
"case",
"v",
".",
"Major",
"<",
"other",
".",
"Major",
":",
"return",
"true",
"\n",
"case",
"v",
".",
"Major",
">",
"other",
".",
"Major... | // Less returns true if "v"'s Version semantically precedes "other". | [
"Less",
"returns",
"true",
"if",
"v",
"s",
"Version",
"semantically",
"precedes",
"other",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/version.go#L143-L156 |
8,660 | luci/luci-go | dm/appengine/model/quest.go | Equals | func (q *Quest) Equals(a *Quest) bool {
return q == a || (q.ID == a.ID &&
proto.Equal(&q.Desc, &a.Desc) &&
q.BuiltBy.Equals(a.BuiltBy) &&
q.Created.Equal(a.Created))
} | go | func (q *Quest) Equals(a *Quest) bool {
return q == a || (q.ID == a.ID &&
proto.Equal(&q.Desc, &a.Desc) &&
q.BuiltBy.Equals(a.BuiltBy) &&
q.Created.Equal(a.Created))
} | [
"func",
"(",
"q",
"*",
"Quest",
")",
"Equals",
"(",
"a",
"*",
"Quest",
")",
"bool",
"{",
"return",
"q",
"==",
"a",
"||",
"(",
"q",
".",
"ID",
"==",
"a",
".",
"ID",
"&&",
"proto",
".",
"Equal",
"(",
"&",
"q",
".",
"Desc",
",",
"&",
"a",
".... | // Equals is true if q and a and equal. | [
"Equals",
"is",
"true",
"if",
"q",
"and",
"a",
"and",
"equal",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/quest.go#L51-L56 |
8,661 | luci/luci-go | dm/appengine/model/quest.go | QueryAttemptsForQuest | func QueryAttemptsForQuest(c context.Context, qid string) *ds.Query {
from := ds.MakeKey(c, "Attempt", qid+"|")
to := ds.MakeKey(c, "Attempt", qid+"~")
return ds.NewQuery("Attempt").Gt("__key__", from).Lt("__key__", to)
} | go | func QueryAttemptsForQuest(c context.Context, qid string) *ds.Query {
from := ds.MakeKey(c, "Attempt", qid+"|")
to := ds.MakeKey(c, "Attempt", qid+"~")
return ds.NewQuery("Attempt").Gt("__key__", from).Lt("__key__", to)
} | [
"func",
"QueryAttemptsForQuest",
"(",
"c",
"context",
".",
"Context",
",",
"qid",
"string",
")",
"*",
"ds",
".",
"Query",
"{",
"from",
":=",
"ds",
".",
"MakeKey",
"(",
"c",
",",
"\"",
"\"",
",",
"qid",
"+",
"\"",
"\"",
")",
"\n",
"to",
":=",
"ds"... | // QueryAttemptsForQuest returns all Attempt objects that exist for this Quest. | [
"QueryAttemptsForQuest",
"returns",
"all",
"Attempt",
"objects",
"that",
"exist",
"for",
"this",
"Quest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/quest.go#L59-L63 |
8,662 | luci/luci-go | dm/appengine/model/quest.go | ToProto | func (q *Quest) ToProto() *dm.Quest {
return &dm.Quest{
Id: dm.NewQuestID(q.ID),
Data: q.DataProto(),
}
} | go | func (q *Quest) ToProto() *dm.Quest {
return &dm.Quest{
Id: dm.NewQuestID(q.ID),
Data: q.DataProto(),
}
} | [
"func",
"(",
"q",
"*",
"Quest",
")",
"ToProto",
"(",
")",
"*",
"dm",
".",
"Quest",
"{",
"return",
"&",
"dm",
".",
"Quest",
"{",
"Id",
":",
"dm",
".",
"NewQuestID",
"(",
"q",
".",
"ID",
")",
",",
"Data",
":",
"q",
".",
"DataProto",
"(",
")",
... | // ToProto converts this Quest into its display equivalent. | [
"ToProto",
"converts",
"this",
"Quest",
"into",
"its",
"display",
"equivalent",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/quest.go#L66-L71 |
8,663 | luci/luci-go | dm/appengine/model/quest.go | DataProto | func (q *Quest) DataProto() *dm.Quest_Data {
spec := make([]*dm.Quest_TemplateSpec, len(q.BuiltBy))
for i := range q.BuiltBy {
spec[i] = &q.BuiltBy[i]
}
return &dm.Quest_Data{
Created: google_pb.NewTimestamp(q.Created),
Desc: &q.Desc,
BuiltBy: spec,
}
} | go | func (q *Quest) DataProto() *dm.Quest_Data {
spec := make([]*dm.Quest_TemplateSpec, len(q.BuiltBy))
for i := range q.BuiltBy {
spec[i] = &q.BuiltBy[i]
}
return &dm.Quest_Data{
Created: google_pb.NewTimestamp(q.Created),
Desc: &q.Desc,
BuiltBy: spec,
}
} | [
"func",
"(",
"q",
"*",
"Quest",
")",
"DataProto",
"(",
")",
"*",
"dm",
".",
"Quest_Data",
"{",
"spec",
":=",
"make",
"(",
"[",
"]",
"*",
"dm",
".",
"Quest_TemplateSpec",
",",
"len",
"(",
"q",
".",
"BuiltBy",
")",
")",
"\n",
"for",
"i",
":=",
"r... | // DataProto gets the Quest.Data proto message for this Quest. | [
"DataProto",
"gets",
"the",
"Quest",
".",
"Data",
"proto",
"message",
"for",
"this",
"Quest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/quest.go#L74-L85 |
8,664 | luci/luci-go | machine-db/client/cli/datacenters.go | printDatacenters | func printDatacenters(tsv bool, datacenters ...*crimson.Datacenter) {
if len(datacenters) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Description")
}
for _, dc := range datacenters {
p.Row(dc.Name, dc.Description)
}
}
} | go | func printDatacenters(tsv bool, datacenters ...*crimson.Datacenter) {
if len(datacenters) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Description")
}
for _, dc := range datacenters {
p.Row(dc.Name, dc.Description)
}
}
} | [
"func",
"printDatacenters",
"(",
"tsv",
"bool",
",",
"datacenters",
"...",
"*",
"crimson",
".",
"Datacenter",
")",
"{",
"if",
"len",
"(",
"datacenters",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush... | // printDatacenters prints datacenter data to stdout in tab-separated columns. | [
"printDatacenters",
"prints",
"datacenter",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/datacenters.go#L28-L39 |
8,665 | luci/luci-go | machine-db/client/cli/datacenters.go | Run | func (c *GetDatacentersCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListDatacenters(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printDatacenters(c.f.tsv, resp.Datacenters...)
return 0
} | go | func (c *GetDatacentersCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListDatacenters(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printDatacenters(c.f.tsv, resp.Datacenters...)
return 0
} | [
"func",
"(",
"c",
"*",
"GetDatacentersCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c... | // Run runs the command to get datacenters. | [
"Run",
"runs",
"the",
"command",
"to",
"get",
"datacenters",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/datacenters.go#L48-L58 |
8,666 | luci/luci-go | cipd/appengine/ui/errors.go | renderErr | func renderErr(h func(*router.Context) error) router.Handler {
return func(ctx *router.Context) {
err := h(ctx)
if err == nil {
return
}
s, _ := status.FromError(err)
message := s.Message()
if message != "" {
// Convert the first rune to upper case.
r, n := utf8.DecodeRuneInString(message)
message = string(unicode.ToUpper(r)) + message[n:]
} else {
message = "Unspecified error" // this should not really happen
}
ctx.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx.Writer.WriteHeader(grpcutil.CodeStatus(s.Code()))
templates.MustRender(ctx.Context, ctx.Writer, "pages/error.html", map[string]interface{}{
"Message": message,
})
}
} | go | func renderErr(h func(*router.Context) error) router.Handler {
return func(ctx *router.Context) {
err := h(ctx)
if err == nil {
return
}
s, _ := status.FromError(err)
message := s.Message()
if message != "" {
// Convert the first rune to upper case.
r, n := utf8.DecodeRuneInString(message)
message = string(unicode.ToUpper(r)) + message[n:]
} else {
message = "Unspecified error" // this should not really happen
}
ctx.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx.Writer.WriteHeader(grpcutil.CodeStatus(s.Code()))
templates.MustRender(ctx.Context, ctx.Writer, "pages/error.html", map[string]interface{}{
"Message": message,
})
}
} | [
"func",
"renderErr",
"(",
"h",
"func",
"(",
"*",
"router",
".",
"Context",
")",
"error",
")",
"router",
".",
"Handler",
"{",
"return",
"func",
"(",
"ctx",
"*",
"router",
".",
"Context",
")",
"{",
"err",
":=",
"h",
"(",
"ctx",
")",
"\n",
"if",
"er... | // renderErr is a handler wrapper converts gRPC errors into HTML pages. | [
"renderErr",
"is",
"a",
"handler",
"wrapper",
"converts",
"gRPC",
"errors",
"into",
"HTML",
"pages",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/ui/errors.go#L29-L52 |
8,667 | luci/luci-go | logdog/appengine/coordinator/storage.go | HasWork | func (r *URLSigningRequest) HasWork() bool {
return (r.Stream || r.Index) && (r.Lifetime > 0)
} | go | func (r *URLSigningRequest) HasWork() bool {
return (r.Stream || r.Index) && (r.Lifetime > 0)
} | [
"func",
"(",
"r",
"*",
"URLSigningRequest",
")",
"HasWork",
"(",
")",
"bool",
"{",
"return",
"(",
"r",
".",
"Stream",
"||",
"r",
".",
"Index",
")",
"&&",
"(",
"r",
".",
"Lifetime",
">",
"0",
")",
"\n",
"}"
] | // HasWork returns true if this signing request actually has work that is
// requested. | [
"HasWork",
"returns",
"true",
"if",
"this",
"signing",
"request",
"actually",
"has",
"work",
"that",
"is",
"requested",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/storage.go#L51-L53 |
8,668 | luci/luci-go | common/tsmon/config.go | loadConfig | func loadConfig(path string) (config, error) {
var ret config
if path == "" {
return ret, nil
}
file, err := os.Open(path)
switch {
case err == nil:
defer file.Close()
decoder := json.NewDecoder(file)
if err = decoder.Decode(&ret); err != nil {
return ret, errors.Annotate(err, "failed to decode file").Err()
}
return ret, nil
case os.IsNotExist(err):
// The file does not exist. We don't consider this an error, since the file
// is optional.
return ret, nil
default:
// An unexpected failure occurred.
return ret, errors.Annotate(err, "failed to open file").Err()
}
} | go | func loadConfig(path string) (config, error) {
var ret config
if path == "" {
return ret, nil
}
file, err := os.Open(path)
switch {
case err == nil:
defer file.Close()
decoder := json.NewDecoder(file)
if err = decoder.Decode(&ret); err != nil {
return ret, errors.Annotate(err, "failed to decode file").Err()
}
return ret, nil
case os.IsNotExist(err):
// The file does not exist. We don't consider this an error, since the file
// is optional.
return ret, nil
default:
// An unexpected failure occurred.
return ret, errors.Annotate(err, "failed to open file").Err()
}
} | [
"func",
"loadConfig",
"(",
"path",
"string",
")",
"(",
"config",
",",
"error",
")",
"{",
"var",
"ret",
"config",
"\n\n",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"ret",
",",
"nil",
"\n",
"}",
"\n\n",
"file",
",",
"err",
":=",
"os",
".",
"Op... | // loadConfig loads a tsmon JSON config from a file. | [
"loadConfig",
"loads",
"a",
"tsmon",
"JSON",
"config",
"from",
"a",
"file",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/config.go#L36-L63 |
8,669 | luci/luci-go | common/data/caching/cacheContext/context.go | Wrap | func Wrap(c context.Context) context.Context {
if _, ok := c.(*cacheContext); ok {
return c
}
return &cacheContext{Context: c}
} | go | func Wrap(c context.Context) context.Context {
if _, ok := c.(*cacheContext); ok {
return c
}
return &cacheContext{Context: c}
} | [
"func",
"Wrap",
"(",
"c",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"(",
"*",
"cacheContext",
")",
";",
"ok",
"{",
"return",
"c",
"\n",
"}",
"\n",
"return",
"&",
"cacheContext",
"{",
"Co... | // Wrap wraps the supplied Context in a caching Context. All Value lookups will
// be cached at this level, avoiding the expense of future Context traversals
// for that same key. | [
"Wrap",
"wraps",
"the",
"supplied",
"Context",
"in",
"a",
"caching",
"Context",
".",
"All",
"Value",
"lookups",
"will",
"be",
"cached",
"at",
"this",
"level",
"avoiding",
"the",
"expense",
"of",
"future",
"Context",
"traversals",
"for",
"that",
"same",
"key"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/cacheContext/context.go#L47-L52 |
8,670 | luci/luci-go | common/api/gitiles/common.go | ValidateRepoURL | func ValidateRepoURL(repoURL string) error {
_, _, err := ParseRepoURL(repoURL)
return err
} | go | func ValidateRepoURL(repoURL string) error {
_, _, err := ParseRepoURL(repoURL)
return err
} | [
"func",
"ValidateRepoURL",
"(",
"repoURL",
"string",
")",
"error",
"{",
"_",
",",
"_",
",",
"err",
":=",
"ParseRepoURL",
"(",
"repoURL",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // ValidateRepoURL validates gitiles repository URL. | [
"ValidateRepoURL",
"validates",
"gitiles",
"repository",
"URL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/common.go#L30-L33 |
8,671 | luci/luci-go | common/api/gitiles/common.go | ParseRepoURL | func ParseRepoURL(repoURL string) (host, project string, err error) {
var u *url.URL
u, err = url.Parse(repoURL)
switch {
case err != nil:
err = errors.Annotate(err, "invalid URL").Err()
case u.Scheme != "https":
err = errors.New("only https scheme is supported")
case !strings.HasSuffix(u.Host, ".googlesource.com"):
err = errors.New("only .googlesource.com repos are supported")
case strings.Contains(u.Path, "+"):
err = errors.New("repo URL path must not contain +")
case !strings.HasPrefix(u.Path, "/"):
err = errors.New("repo URL path must start with a slash")
case u.Path == "/":
err = errors.New("repo URL path must be not just a slash")
case u.RawQuery != "":
err = errors.New("repo URL must not have query")
case u.Fragment != "":
err = errors.New("repo URL must not have fragment")
default:
host = u.Host
if strings.HasPrefix(u.Path, "/a/") {
u.Path = strings.TrimPrefix(u.Path, "/a")
}
project = strings.Trim(u.Path, "/")
project = strings.TrimSuffix(project, ".git")
}
return
} | go | func ParseRepoURL(repoURL string) (host, project string, err error) {
var u *url.URL
u, err = url.Parse(repoURL)
switch {
case err != nil:
err = errors.Annotate(err, "invalid URL").Err()
case u.Scheme != "https":
err = errors.New("only https scheme is supported")
case !strings.HasSuffix(u.Host, ".googlesource.com"):
err = errors.New("only .googlesource.com repos are supported")
case strings.Contains(u.Path, "+"):
err = errors.New("repo URL path must not contain +")
case !strings.HasPrefix(u.Path, "/"):
err = errors.New("repo URL path must start with a slash")
case u.Path == "/":
err = errors.New("repo URL path must be not just a slash")
case u.RawQuery != "":
err = errors.New("repo URL must not have query")
case u.Fragment != "":
err = errors.New("repo URL must not have fragment")
default:
host = u.Host
if strings.HasPrefix(u.Path, "/a/") {
u.Path = strings.TrimPrefix(u.Path, "/a")
}
project = strings.Trim(u.Path, "/")
project = strings.TrimSuffix(project, ".git")
}
return
} | [
"func",
"ParseRepoURL",
"(",
"repoURL",
"string",
")",
"(",
"host",
",",
"project",
"string",
",",
"err",
"error",
")",
"{",
"var",
"u",
"*",
"url",
".",
"URL",
"\n",
"u",
",",
"err",
"=",
"url",
".",
"Parse",
"(",
"repoURL",
")",
"\n",
"switch",
... | // ParseRepoURL parses a Gitiles repository URL. | [
"ParseRepoURL",
"parses",
"a",
"Gitiles",
"repository",
"URL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/common.go#L36-L65 |
8,672 | luci/luci-go | common/api/gitiles/common.go | NormalizeRepoURL | func NormalizeRepoURL(repoURL string, auth bool) (*url.URL, error) {
host, project, err := ParseRepoURL(repoURL)
if err != nil {
return nil, err
}
u := FormatRepoURL(host, project, auth)
return &u, nil
} | go | func NormalizeRepoURL(repoURL string, auth bool) (*url.URL, error) {
host, project, err := ParseRepoURL(repoURL)
if err != nil {
return nil, err
}
u := FormatRepoURL(host, project, auth)
return &u, nil
} | [
"func",
"NormalizeRepoURL",
"(",
"repoURL",
"string",
",",
"auth",
"bool",
")",
"(",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"host",
",",
"project",
",",
"err",
":=",
"ParseRepoURL",
"(",
"repoURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // NormalizeRepoURL is a shortcut for ParseRepoURL and FormatRepoURL. | [
"NormalizeRepoURL",
"is",
"a",
"shortcut",
"for",
"ParseRepoURL",
"and",
"FormatRepoURL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/common.go#L83-L90 |
8,673 | luci/luci-go | tokenserver/appengine/impl/machinetoken/machinetoken.go | Validate | func (p *MintParams) Validate() error {
// Check FDQN.
fqdn, err := p.MachineFQDN()
if err != nil {
return err
}
chunks := strings.SplitN(fqdn, ".", 2)
if len(chunks) != 2 {
return fmt.Errorf("not a valid FQDN %q", fqdn)
}
domain := chunks[1] // e.g. "us-central1-a.c.project-id.internal"
// Check DomainConfig for given domain.
domainCfg := domainConfig(p.Config, domain)
if domainCfg == nil {
return fmt.Errorf("the domain %q is not whitelisted in the config", domain)
}
if domainCfg.MachineTokenLifetime <= 0 {
return fmt.Errorf("machine tokens for machines in domain %q are not allowed", domain)
}
// Make sure cert serial number fits into uint64. We don't support negative or
// giant SNs.
sn := p.Cert.SerialNumber
if sn.Sign() <= 0 || sn.Cmp(maxUint64) >= 0 {
return fmt.Errorf("invalid certificate serial number: %s", sn)
}
return nil
} | go | func (p *MintParams) Validate() error {
// Check FDQN.
fqdn, err := p.MachineFQDN()
if err != nil {
return err
}
chunks := strings.SplitN(fqdn, ".", 2)
if len(chunks) != 2 {
return fmt.Errorf("not a valid FQDN %q", fqdn)
}
domain := chunks[1] // e.g. "us-central1-a.c.project-id.internal"
// Check DomainConfig for given domain.
domainCfg := domainConfig(p.Config, domain)
if domainCfg == nil {
return fmt.Errorf("the domain %q is not whitelisted in the config", domain)
}
if domainCfg.MachineTokenLifetime <= 0 {
return fmt.Errorf("machine tokens for machines in domain %q are not allowed", domain)
}
// Make sure cert serial number fits into uint64. We don't support negative or
// giant SNs.
sn := p.Cert.SerialNumber
if sn.Sign() <= 0 || sn.Cmp(maxUint64) >= 0 {
return fmt.Errorf("invalid certificate serial number: %s", sn)
}
return nil
} | [
"func",
"(",
"p",
"*",
"MintParams",
")",
"Validate",
"(",
")",
"error",
"{",
"// Check FDQN.",
"fqdn",
",",
"err",
":=",
"p",
".",
"MachineFQDN",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"chunks",
":=",
"str... | // Validate checks that token minting parameters are allowed. | [
"Validate",
"checks",
"that",
"token",
"minting",
"parameters",
"are",
"allowed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/machinetoken/machinetoken.go#L106-L134 |
8,674 | luci/luci-go | tokenserver/appengine/impl/machinetoken/machinetoken.go | Mint | func Mint(c context.Context, params *MintParams) (*tokenserver.MachineTokenBody, string, error) {
if err := params.Validate(); err != nil {
return nil, "", err
}
fqdn, err := params.MachineFQDN()
if err != nil {
panic("impossible") // checked in Validate already
}
chunks := strings.SplitN(fqdn, ".", 2)
if len(chunks) != 2 {
panic("impossible") // checked in Validate already
}
cfg := domainConfig(params.Config, chunks[1])
if cfg == nil {
panic("impossible") // checked in Validate already
}
srvInfo, err := params.Signer.ServiceInfo(c)
if err != nil {
return nil, "", transient.Tag.Apply(err)
}
body := &tokenserver.MachineTokenBody{
MachineFqdn: fqdn,
IssuedBy: srvInfo.ServiceAccountName,
IssuedAt: uint64(clock.Now(c).Unix()),
Lifetime: uint64(cfg.MachineTokenLifetime),
CaId: params.Config.UniqueId,
CertSn: params.Cert.SerialNumber.Uint64(), // already validated, fits uint64
}
signed, err := SignToken(c, params.Signer, body)
if err != nil {
return nil, "", err
}
return body, signed, nil
} | go | func Mint(c context.Context, params *MintParams) (*tokenserver.MachineTokenBody, string, error) {
if err := params.Validate(); err != nil {
return nil, "", err
}
fqdn, err := params.MachineFQDN()
if err != nil {
panic("impossible") // checked in Validate already
}
chunks := strings.SplitN(fqdn, ".", 2)
if len(chunks) != 2 {
panic("impossible") // checked in Validate already
}
cfg := domainConfig(params.Config, chunks[1])
if cfg == nil {
panic("impossible") // checked in Validate already
}
srvInfo, err := params.Signer.ServiceInfo(c)
if err != nil {
return nil, "", transient.Tag.Apply(err)
}
body := &tokenserver.MachineTokenBody{
MachineFqdn: fqdn,
IssuedBy: srvInfo.ServiceAccountName,
IssuedAt: uint64(clock.Now(c).Unix()),
Lifetime: uint64(cfg.MachineTokenLifetime),
CaId: params.Config.UniqueId,
CertSn: params.Cert.SerialNumber.Uint64(), // already validated, fits uint64
}
signed, err := SignToken(c, params.Signer, body)
if err != nil {
return nil, "", err
}
return body, signed, nil
} | [
"func",
"Mint",
"(",
"c",
"context",
".",
"Context",
",",
"params",
"*",
"MintParams",
")",
"(",
"*",
"tokenserver",
".",
"MachineTokenBody",
",",
"string",
",",
"error",
")",
"{",
"if",
"err",
":=",
"params",
".",
"Validate",
"(",
")",
";",
"err",
"... | // Mint generates a new machine token proto, signs and serializes it.
//
// Returns its body as a proto, and as a signed base64-encoded final token. | [
"Mint",
"generates",
"a",
"new",
"machine",
"token",
"proto",
"signs",
"and",
"serializes",
"it",
".",
"Returns",
"its",
"body",
"as",
"a",
"proto",
"and",
"as",
"a",
"signed",
"base64",
"-",
"encoded",
"final",
"token",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/machinetoken/machinetoken.go#L156-L191 |
8,675 | luci/luci-go | tokenserver/appengine/impl/machinetoken/machinetoken.go | SignToken | func SignToken(c context.Context, signer signing.Signer, body *tokenserver.MachineTokenBody) (string, error) {
s := tokensigning.Signer{
Signer: signer,
SigningContext: tokenSigningContext,
Encoding: base64.RawStdEncoding,
Wrap: func(w *tokensigning.Unwrapped) proto.Message {
return &tokenserver.MachineTokenEnvelope{
TokenBody: w.Body,
RsaSha256: w.RsaSHA256Sig,
KeyId: w.KeyID,
}
},
}
return s.SignToken(c, body)
} | go | func SignToken(c context.Context, signer signing.Signer, body *tokenserver.MachineTokenBody) (string, error) {
s := tokensigning.Signer{
Signer: signer,
SigningContext: tokenSigningContext,
Encoding: base64.RawStdEncoding,
Wrap: func(w *tokensigning.Unwrapped) proto.Message {
return &tokenserver.MachineTokenEnvelope{
TokenBody: w.Body,
RsaSha256: w.RsaSHA256Sig,
KeyId: w.KeyID,
}
},
}
return s.SignToken(c, body)
} | [
"func",
"SignToken",
"(",
"c",
"context",
".",
"Context",
",",
"signer",
"signing",
".",
"Signer",
",",
"body",
"*",
"tokenserver",
".",
"MachineTokenBody",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
":=",
"tokensigning",
".",
"Signer",
"{",
"Signe... | // SignToken signs and serializes the machine subtoken.
//
// It doesn't do any validation. Assumes the prepared subtoken is valid.
//
// Produces base64-encoded token or a transient error. | [
"SignToken",
"signs",
"and",
"serializes",
"the",
"machine",
"subtoken",
".",
"It",
"doesn",
"t",
"do",
"any",
"validation",
".",
"Assumes",
"the",
"prepared",
"subtoken",
"is",
"valid",
".",
"Produces",
"base64",
"-",
"encoded",
"token",
"or",
"a",
"transie... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/machinetoken/machinetoken.go#L198-L212 |
8,676 | luci/luci-go | logdog/client/butler/bundler/stream.go | noMoreDataLocked | func (s *streamImpl) noMoreDataLocked() bool {
if !s.closed {
return false
}
// If we have an append error, we will no longer accept or consume data.
if s.appendErr != nil {
return true
}
var bufSize int64
s.withParserLock(func() error {
bufSize = s.c.parser.bufferedBytes()
return nil
})
return bufSize == 0
} | go | func (s *streamImpl) noMoreDataLocked() bool {
if !s.closed {
return false
}
// If we have an append error, we will no longer accept or consume data.
if s.appendErr != nil {
return true
}
var bufSize int64
s.withParserLock(func() error {
bufSize = s.c.parser.bufferedBytes()
return nil
})
return bufSize == 0
} | [
"func",
"(",
"s",
"*",
"streamImpl",
")",
"noMoreDataLocked",
"(",
")",
"bool",
"{",
"if",
"!",
"s",
".",
"closed",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// If we have an append error, we will no longer accept or consume data.",
"if",
"s",
".",
"appendErr",
... | // noMoreDataLocked returns true if our stream has been closed and its buffer
// is empty.
//
// The stream's stateLock must be held when calling this method. | [
"noMoreDataLocked",
"returns",
"true",
"if",
"our",
"stream",
"has",
"been",
"closed",
"and",
"its",
"buffer",
"is",
"empty",
".",
"The",
"stream",
"s",
"stateLock",
"must",
"be",
"held",
"when",
"calling",
"this",
"method",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/stream.go#L226-L242 |
8,677 | luci/luci-go | logdog/client/butler/bundler/stream.go | nextBundleEntry | func (s *streamImpl) nextBundleEntry(bb *builder, aggressive bool) bool {
s.stateLock.Lock()
defer s.stateLock.Unlock()
// If we're not drained, try and get the next bundle.
modified := false
if !s.noMoreDataLocked() {
err := error(nil)
modified, err = s.nextBundleEntryLocked(bb, aggressive)
if err != nil {
s.setAppendErrorLocked(err)
}
if modified {
s.signalDataConsumed()
}
}
// If we're drained, populate our terminal state.
if s.noMoreDataLocked() {
if s.lastLogEntry != nil {
bb.setStreamTerminal(&s.c.template, s.lastLogEntry.StreamIndex)
}
s.setDrained()
}
return modified
} | go | func (s *streamImpl) nextBundleEntry(bb *builder, aggressive bool) bool {
s.stateLock.Lock()
defer s.stateLock.Unlock()
// If we're not drained, try and get the next bundle.
modified := false
if !s.noMoreDataLocked() {
err := error(nil)
modified, err = s.nextBundleEntryLocked(bb, aggressive)
if err != nil {
s.setAppendErrorLocked(err)
}
if modified {
s.signalDataConsumed()
}
}
// If we're drained, populate our terminal state.
if s.noMoreDataLocked() {
if s.lastLogEntry != nil {
bb.setStreamTerminal(&s.c.template, s.lastLogEntry.StreamIndex)
}
s.setDrained()
}
return modified
} | [
"func",
"(",
"s",
"*",
"streamImpl",
")",
"nextBundleEntry",
"(",
"bb",
"*",
"builder",
",",
"aggressive",
"bool",
")",
"bool",
"{",
"s",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n\n",
... | // nextBundleEntry generates bundles for this stream. The total bundle data size
// must not exceed the supplied size.
//
// If no bundle entry could be generated given the constraints, nil will be
// returned.
//
// It is possible for some entries to be returned alongside an error. | [
"nextBundleEntry",
"generates",
"bundles",
"for",
"this",
"stream",
".",
"The",
"total",
"bundle",
"data",
"size",
"must",
"not",
"exceed",
"the",
"supplied",
"size",
".",
"If",
"no",
"bundle",
"entry",
"could",
"be",
"generated",
"given",
"the",
"constraints"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/stream.go#L268-L295 |
8,678 | luci/luci-go | logdog/client/butler/bundler/stream.go | fixupLogEntry | func (s *streamImpl) fixupLogEntry(prev, cur *logpb.LogEntry) error {
if prev == nil {
if cur.StreamIndex != 0 {
return fmt.Errorf("first log entry is not zero index (%d)", cur.StreamIndex)
}
} else {
if cur.StreamIndex != prev.StreamIndex+1 {
return fmt.Errorf("non-contiguous stream indices (%d != %d)", cur.StreamIndex, prev.StreamIndex+1)
}
if google.DurationFromProto(cur.TimeOffset) < google.DurationFromProto(prev.TimeOffset) {
to := *prev.TimeOffset
cur.TimeOffset = &to
}
}
return nil
} | go | func (s *streamImpl) fixupLogEntry(prev, cur *logpb.LogEntry) error {
if prev == nil {
if cur.StreamIndex != 0 {
return fmt.Errorf("first log entry is not zero index (%d)", cur.StreamIndex)
}
} else {
if cur.StreamIndex != prev.StreamIndex+1 {
return fmt.Errorf("non-contiguous stream indices (%d != %d)", cur.StreamIndex, prev.StreamIndex+1)
}
if google.DurationFromProto(cur.TimeOffset) < google.DurationFromProto(prev.TimeOffset) {
to := *prev.TimeOffset
cur.TimeOffset = &to
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"streamImpl",
")",
"fixupLogEntry",
"(",
"prev",
",",
"cur",
"*",
"logpb",
".",
"LogEntry",
")",
"error",
"{",
"if",
"prev",
"==",
"nil",
"{",
"if",
"cur",
".",
"StreamIndex",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"... | // fixupLogEntry asserts and corrects a log entry's stream offset and ordering
// given the previous entry in the stream.
//
// If prev is nil, that means that cur is expected to be the first log entry
// in the stream. | [
"fixupLogEntry",
"asserts",
"and",
"corrects",
"a",
"log",
"entry",
"s",
"stream",
"offset",
"and",
"ordering",
"given",
"the",
"previous",
"entry",
"in",
"the",
"stream",
".",
"If",
"prev",
"is",
"nil",
"that",
"means",
"that",
"cur",
"is",
"expected",
"t... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bundler/stream.go#L352-L369 |
8,679 | luci/luci-go | logdog/client/butler/output/log/logOutput.go | New | func New(ctx context.Context, bundleSize int) output.Output {
o := logOutput{
ctx: ctx,
bundleSize: bundleSize,
}
o.ctx = log.SetFields(o.ctx, log.Fields{
"output": &o,
})
return &o
} | go | func New(ctx context.Context, bundleSize int) output.Output {
o := logOutput{
ctx: ctx,
bundleSize: bundleSize,
}
o.ctx = log.SetFields(o.ctx, log.Fields{
"output": &o,
})
return &o
} | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"bundleSize",
"int",
")",
"output",
".",
"Output",
"{",
"o",
":=",
"logOutput",
"{",
"ctx",
":",
"ctx",
",",
"bundleSize",
":",
"bundleSize",
",",
"}",
"\n",
"o",
".",
"ctx",
"=",
"log",
".... | // New instantes a new log output instance. | [
"New",
"instantes",
"a",
"new",
"log",
"output",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/log/logOutput.go#L48-L57 |
8,680 | luci/luci-go | common/sync/mutexpool/pool.go | WithMutex | func (pc *P) WithMutex(key interface{}, fn func()) {
// Get a lock for this config key, and increment its reference.
me := pc.getConfigLock(key)
defer pc.decRef(me, key)
// Hold this lock's mutex and call "fn".
me.Lock()
defer me.Unlock()
fn()
} | go | func (pc *P) WithMutex(key interface{}, fn func()) {
// Get a lock for this config key, and increment its reference.
me := pc.getConfigLock(key)
defer pc.decRef(me, key)
// Hold this lock's mutex and call "fn".
me.Lock()
defer me.Unlock()
fn()
} | [
"func",
"(",
"pc",
"*",
"P",
")",
"WithMutex",
"(",
"key",
"interface",
"{",
"}",
",",
"fn",
"func",
"(",
")",
")",
"{",
"// Get a lock for this config key, and increment its reference.",
"me",
":=",
"pc",
".",
"getConfigLock",
"(",
"key",
")",
"\n",
"defer"... | // WithMutex locks the Mutex matching the specified key and executes fn while
// holding its lock.
//
// If a mutex for key doesn't exist, one will be created, and will be
// automatically cleaned up when no longer referenced. | [
"WithMutex",
"locks",
"the",
"Mutex",
"matching",
"the",
"specified",
"key",
"and",
"executes",
"fn",
"while",
"holding",
"its",
"lock",
".",
"If",
"a",
"mutex",
"for",
"key",
"doesn",
"t",
"exist",
"one",
"will",
"be",
"created",
"and",
"will",
"be",
"a... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/mutexpool/pool.go#L78-L88 |
8,681 | luci/luci-go | scheduler/appengine/engine/policy/greedy_batching.go | GreedyBatchingPolicy | func GreedyBatchingPolicy(maxConcurrentInvs, maxBatchSize int) (Func, error) {
return basePolicy(maxConcurrentInvs, maxBatchSize, func(triggers []*internal.Trigger) int {
return len(triggers)
})
} | go | func GreedyBatchingPolicy(maxConcurrentInvs, maxBatchSize int) (Func, error) {
return basePolicy(maxConcurrentInvs, maxBatchSize, func(triggers []*internal.Trigger) int {
return len(triggers)
})
} | [
"func",
"GreedyBatchingPolicy",
"(",
"maxConcurrentInvs",
",",
"maxBatchSize",
"int",
")",
"(",
"Func",
",",
"error",
")",
"{",
"return",
"basePolicy",
"(",
"maxConcurrentInvs",
",",
"maxBatchSize",
",",
"func",
"(",
"triggers",
"[",
"]",
"*",
"internal",
".",... | // GreedyBatchingPolicy instantiates new GREEDY_BATCHING policy function.
//
// It takes all pending triggers and collapses them into one new invocation,
// deriving its properties from the most recent trigger alone. | [
"GreedyBatchingPolicy",
"instantiates",
"new",
"GREEDY_BATCHING",
"policy",
"function",
".",
"It",
"takes",
"all",
"pending",
"triggers",
"and",
"collapses",
"them",
"into",
"one",
"new",
"invocation",
"deriving",
"its",
"properties",
"from",
"the",
"most",
"recent"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/policy/greedy_batching.go#L25-L29 |
8,682 | luci/luci-go | server/warmup/warmup.go | Register | func Register(name string, cb Callback) {
if name == "" {
panic("warmup callback name is required")
}
state.Lock()
defer state.Unlock()
state.callbacks = append(state.callbacks, callbackWithName{cb, name})
} | go | func Register(name string, cb Callback) {
if name == "" {
panic("warmup callback name is required")
}
state.Lock()
defer state.Unlock()
state.callbacks = append(state.callbacks, callbackWithName{cb, name})
} | [
"func",
"Register",
"(",
"name",
"string",
",",
"cb",
"Callback",
")",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"state",
".",
"Lock",
"(",
")",
"\n",
"defer",
"state",
".",
"Unlock",
"(",
")",
"\... | // Register adds a callback called during warmup. | [
"Register",
"adds",
"a",
"callback",
"called",
"during",
"warmup",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/warmup/warmup.go#L44-L51 |
8,683 | luci/luci-go | server/warmup/warmup.go | Warmup | func Warmup(c context.Context) error {
state.Lock()
defer state.Unlock()
var merr errors.MultiError
for _, cb := range state.callbacks {
logging.Infof(c, "Warming up %q", cb.name)
if err := cb.Callback(c); err != nil {
logging.WithError(err).Errorf(c, "Error when warming up %q", cb.name)
merr = append(merr, err)
}
}
logging.Infof(c, "Finished warming up")
if len(merr) == 0 {
return nil
}
return merr
} | go | func Warmup(c context.Context) error {
state.Lock()
defer state.Unlock()
var merr errors.MultiError
for _, cb := range state.callbacks {
logging.Infof(c, "Warming up %q", cb.name)
if err := cb.Callback(c); err != nil {
logging.WithError(err).Errorf(c, "Error when warming up %q", cb.name)
merr = append(merr, err)
}
}
logging.Infof(c, "Finished warming up")
if len(merr) == 0 {
return nil
}
return merr
} | [
"func",
"Warmup",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"state",
".",
"Lock",
"(",
")",
"\n",
"defer",
"state",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"merr",
"errors",
".",
"MultiError",
"\n",
"for",
"_",
",",
"cb",
":=",
"range... | // Warmup executes all registered warmup callbacks, sequentially.
//
// Doesn't abort on individual callback errors, just collects and returns them
// all. | [
"Warmup",
"executes",
"all",
"registered",
"warmup",
"callbacks",
"sequentially",
".",
"Doesn",
"t",
"abort",
"on",
"individual",
"callback",
"errors",
"just",
"collects",
"and",
"returns",
"them",
"all",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/warmup/warmup.go#L57-L75 |
8,684 | luci/luci-go | vpython/venv/prune.go | prune | func prune(c context.Context, cfg *Config, exempt stringset.Set) error {
pruneThreshold := cfg.PruneThreshold
if pruneThreshold <= 0 {
// Pruning is disabled.
return nil
}
now := clock.Now(c)
minPruneAge := now.Add(-pruneThreshold)
// Run a series of independent scan/prune operations.
logging.Debugf(c, "Pruning entries in [%s] older than %s (%s).", cfg.BaseDir, pruneThreshold, minPruneAge)
// Iterate over all of our VirtualEnv candidates.
//
// Any pruning errors will be accumulated in "allErrs", so ForEach will only
// receive nil return values from the callback. This means that any error
// returned by ForEach was an actual error with the iteration itself.
var (
allErrs errors.MultiError
totalPruned = 0
hitLimitStr = ""
)
// We need to cancel if we hit our prune limit.
c, cancelFunc := context.WithCancel(c)
defer cancelFunc()
// Iterate over all VirtualEnv directories, regardless of their completion
// status.
it := Iterator{
// Shuffle the slice randomly. We do this in case others are also processing
// this directory simultaneously.
Shuffle: true,
}
err := it.ForEach(c, cfg, func(c context.Context, e *Env) error {
if exempt != nil && exempt.Has(e.Name) {
logging.Debugf(c, "Not pruning currently in-use environment: %s", e.Name)
return nil
}
if ts, err := e.completionFlagTimestamp(); err == nil && ts.After(minPruneAge) {
logging.Debugf(c, "Environment [%s] is younger than minimum prune age (%s).", e.Name, ts)
return nil
}
switch err := e.Delete(c); errors.Unwrap(err) {
case nil:
totalPruned++
if cfg.MaxPrunesPerSweep > 0 && totalPruned >= cfg.MaxPrunesPerSweep {
logging.Debugf(c, "Hit prune limit of %d.", cfg.MaxPrunesPerSweep)
hitLimitStr = " (limit)"
cancelFunc()
}
case fslock.ErrLockHeld:
logging.WithError(err).Debugf(c, "Environment [%s] is in use.", e.Name)
default:
err = errors.Annotate(err, "failed to prune file: %s", e.Name).
InternalReason("dir(%q)", e.Config.BaseDir).Err()
allErrs = append(allErrs, err)
}
return nil
})
if err != nil {
// Error during iteration.
return err
}
logging.Infof(c, "Pruned %d environment(s)%s with %d error(s)", totalPruned, hitLimitStr, len(allErrs))
if len(allErrs) > 0 {
return allErrs
}
return nil
} | go | func prune(c context.Context, cfg *Config, exempt stringset.Set) error {
pruneThreshold := cfg.PruneThreshold
if pruneThreshold <= 0 {
// Pruning is disabled.
return nil
}
now := clock.Now(c)
minPruneAge := now.Add(-pruneThreshold)
// Run a series of independent scan/prune operations.
logging.Debugf(c, "Pruning entries in [%s] older than %s (%s).", cfg.BaseDir, pruneThreshold, minPruneAge)
// Iterate over all of our VirtualEnv candidates.
//
// Any pruning errors will be accumulated in "allErrs", so ForEach will only
// receive nil return values from the callback. This means that any error
// returned by ForEach was an actual error with the iteration itself.
var (
allErrs errors.MultiError
totalPruned = 0
hitLimitStr = ""
)
// We need to cancel if we hit our prune limit.
c, cancelFunc := context.WithCancel(c)
defer cancelFunc()
// Iterate over all VirtualEnv directories, regardless of their completion
// status.
it := Iterator{
// Shuffle the slice randomly. We do this in case others are also processing
// this directory simultaneously.
Shuffle: true,
}
err := it.ForEach(c, cfg, func(c context.Context, e *Env) error {
if exempt != nil && exempt.Has(e.Name) {
logging.Debugf(c, "Not pruning currently in-use environment: %s", e.Name)
return nil
}
if ts, err := e.completionFlagTimestamp(); err == nil && ts.After(minPruneAge) {
logging.Debugf(c, "Environment [%s] is younger than minimum prune age (%s).", e.Name, ts)
return nil
}
switch err := e.Delete(c); errors.Unwrap(err) {
case nil:
totalPruned++
if cfg.MaxPrunesPerSweep > 0 && totalPruned >= cfg.MaxPrunesPerSweep {
logging.Debugf(c, "Hit prune limit of %d.", cfg.MaxPrunesPerSweep)
hitLimitStr = " (limit)"
cancelFunc()
}
case fslock.ErrLockHeld:
logging.WithError(err).Debugf(c, "Environment [%s] is in use.", e.Name)
default:
err = errors.Annotate(err, "failed to prune file: %s", e.Name).
InternalReason("dir(%q)", e.Config.BaseDir).Err()
allErrs = append(allErrs, err)
}
return nil
})
if err != nil {
// Error during iteration.
return err
}
logging.Infof(c, "Pruned %d environment(s)%s with %d error(s)", totalPruned, hitLimitStr, len(allErrs))
if len(allErrs) > 0 {
return allErrs
}
return nil
} | [
"func",
"prune",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
",",
"exempt",
"stringset",
".",
"Set",
")",
"error",
"{",
"pruneThreshold",
":=",
"cfg",
".",
"PruneThreshold",
"\n",
"if",
"pruneThreshold",
"<=",
"0",
"{",
"// Pruning is d... | // prune examines environments in cfg's BaseDir. If any are found that are older
// than the prune threshold in "cfg", they will be safely deleted.
//
// If exempt is not nil, it contains a list of VirtualEnv names that will be
// exempted from pruning. This is used to prevent pruning from modifying
// environments that are known to be recently used, and to completely avoid a
// case where an environment could be pruned while it's in use by this program. | [
"prune",
"examines",
"environments",
"in",
"cfg",
"s",
"BaseDir",
".",
"If",
"any",
"are",
"found",
"that",
"are",
"older",
"than",
"the",
"prune",
"threshold",
"in",
"cfg",
"they",
"will",
"be",
"safely",
"deleted",
".",
"If",
"exempt",
"is",
"not",
"ni... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/prune.go#L39-L114 |
8,685 | luci/luci-go | milo/buildsource/buildbot/buildstore/blame.go | blame | func blame(c context.Context, b *buildbot.Build) error {
if err := fetchChangesCached(c, b); err != nil {
return err
}
blame := stringset.New(len(b.Sourcestamp.Changes))
b.Blame = make([]string, 0, len(b.Sourcestamp.Changes))
for _, c := range b.Sourcestamp.Changes {
if blame.Add(c.Who) {
b.Blame = append(b.Blame, c.Who)
}
}
return nil
} | go | func blame(c context.Context, b *buildbot.Build) error {
if err := fetchChangesCached(c, b); err != nil {
return err
}
blame := stringset.New(len(b.Sourcestamp.Changes))
b.Blame = make([]string, 0, len(b.Sourcestamp.Changes))
for _, c := range b.Sourcestamp.Changes {
if blame.Add(c.Who) {
b.Blame = append(b.Blame, c.Who)
}
}
return nil
} | [
"func",
"blame",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"*",
"buildbot",
".",
"Build",
")",
"error",
"{",
"if",
"err",
":=",
"fetchChangesCached",
"(",
"c",
",",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"b... | // blame loads changes from gitiles and computes b.Blame and
// b.SourceStamp.Changes from b.SourceStamp.Repository,
// b.SourceStamp.Revision and builds previous to b.
//
// Memcaches results. | [
"blame",
"loads",
"changes",
"from",
"gitiles",
"and",
"computes",
"b",
".",
"Blame",
"and",
"b",
".",
"SourceStamp",
".",
"Changes",
"from",
"b",
".",
"SourceStamp",
".",
"Repository",
"b",
".",
"SourceStamp",
".",
"Revision",
"and",
"builds",
"previous",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/blame.go#L49-L61 |
8,686 | luci/luci-go | milo/buildsource/buildbot/buildstore/blame.go | fetchChangesCached | func fetchChangesCached(c context.Context, b *buildbot.Build) error {
report := func(err error, msg string) {
logging.WithError(err).Errorf(c, "build %q change memcaching: %s", b.ID(), msg)
}
cache := memcache.NewItem(c, "buildbot_changes/"+b.ID().String())
if err := memcache.Get(c, cache); err == nil {
err := json.Unmarshal(cache.Value(), &b.Sourcestamp.Changes)
if err == nil {
return nil
}
b.Sourcestamp.Changes = nil
report(err, "failed to unmarshal memcached changes")
} else if err != memcache.ErrCacheMiss {
report(err, "failed to load")
}
if err := fetchChanges(c, b); err != nil {
return err
}
marshaled, err := json.Marshal(b.Sourcestamp.Changes)
if err != nil {
return err
}
if len(marshaled) > 1<<20 {
report(nil, "cannot save > 1MB")
} else {
cache.SetValue(marshaled)
if err := memcache.Set(c, cache); err != nil {
report(err, "failed to save")
}
}
return nil
} | go | func fetchChangesCached(c context.Context, b *buildbot.Build) error {
report := func(err error, msg string) {
logging.WithError(err).Errorf(c, "build %q change memcaching: %s", b.ID(), msg)
}
cache := memcache.NewItem(c, "buildbot_changes/"+b.ID().String())
if err := memcache.Get(c, cache); err == nil {
err := json.Unmarshal(cache.Value(), &b.Sourcestamp.Changes)
if err == nil {
return nil
}
b.Sourcestamp.Changes = nil
report(err, "failed to unmarshal memcached changes")
} else if err != memcache.ErrCacheMiss {
report(err, "failed to load")
}
if err := fetchChanges(c, b); err != nil {
return err
}
marshaled, err := json.Marshal(b.Sourcestamp.Changes)
if err != nil {
return err
}
if len(marshaled) > 1<<20 {
report(nil, "cannot save > 1MB")
} else {
cache.SetValue(marshaled)
if err := memcache.Set(c, cache); err != nil {
report(err, "failed to save")
}
}
return nil
} | [
"func",
"fetchChangesCached",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"*",
"buildbot",
".",
"Build",
")",
"error",
"{",
"report",
":=",
"func",
"(",
"err",
"error",
",",
"msg",
"string",
")",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
... | // fetchChangesCached is same as fetchChanges, but with memcaching. | [
"fetchChangesCached",
"is",
"same",
"as",
"fetchChanges",
"but",
"with",
"memcaching",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/blame.go#L64-L98 |
8,687 | luci/luci-go | milo/buildsource/buildbot/buildstore/blame.go | fetchChanges | func fetchChanges(c context.Context, b *buildbot.Build) error {
memcache.Set(c, buildRevCache(c, b))
// initialize the slice so that when serialized to JSON, it is [], not null.
b.Sourcestamp.Changes = []buildbot.Change{}
host, project, err := gitiles.ParseRepoURL(b.Sourcestamp.Repository)
if err != nil {
logging.Warningf(
c,
"build %q does not have a valid Gitiles repository URL, %q. Skipping blamelist computation",
b.ID(), b.Sourcestamp.Repository)
return nil
}
if !commitHashRe.MatchString(b.Sourcestamp.Revision) {
logging.Warningf(
c,
"build %q revision %q is not a commit hash. Skipping blamelist computation",
b.Sourcestamp.Revision, b.ID())
return nil
}
prevRev, err := getPrevRev(c, b, 100)
switch {
case err != nil:
return errors.Annotate(err, "failed to get prev revision for build %q", b.ID()).Err()
case prevRev == "":
logging.Warningf(c, "prev rev of build %q is unknown. Skipping blamelist computation", b.ID())
return nil
}
// Note that prev build may be coming from buildbot and having commit different
// from the true previous _LUCI_ build, which may cause blamelist to have
// extra or missing commits. This matters only for the first build after
// next build number bump.
// we don't really need a blamelist with a length > 50
commits, err := git.Get(c).Log(c, host, project, b.Sourcestamp.Revision, &git.LogOptions{Limit: 50})
switch status.Code(err) {
case codes.OK:
for _, commit := range commits {
if commit.Id == prevRev {
break
}
change := changeFromGitiles(b.Sourcestamp.Repository, "master", commit)
b.Sourcestamp.Changes = append(b.Sourcestamp.Changes, change)
}
return nil
case codes.NotFound:
logging.WithError(err).Warningf(
c,
"gitiles.log returned 404 %s/+/%s",
b.Sourcestamp.Repository, b.Sourcestamp.Revision)
b.Sourcestamp.Changes = nil
return nil
default:
return err
}
} | go | func fetchChanges(c context.Context, b *buildbot.Build) error {
memcache.Set(c, buildRevCache(c, b))
// initialize the slice so that when serialized to JSON, it is [], not null.
b.Sourcestamp.Changes = []buildbot.Change{}
host, project, err := gitiles.ParseRepoURL(b.Sourcestamp.Repository)
if err != nil {
logging.Warningf(
c,
"build %q does not have a valid Gitiles repository URL, %q. Skipping blamelist computation",
b.ID(), b.Sourcestamp.Repository)
return nil
}
if !commitHashRe.MatchString(b.Sourcestamp.Revision) {
logging.Warningf(
c,
"build %q revision %q is not a commit hash. Skipping blamelist computation",
b.Sourcestamp.Revision, b.ID())
return nil
}
prevRev, err := getPrevRev(c, b, 100)
switch {
case err != nil:
return errors.Annotate(err, "failed to get prev revision for build %q", b.ID()).Err()
case prevRev == "":
logging.Warningf(c, "prev rev of build %q is unknown. Skipping blamelist computation", b.ID())
return nil
}
// Note that prev build may be coming from buildbot and having commit different
// from the true previous _LUCI_ build, which may cause blamelist to have
// extra or missing commits. This matters only for the first build after
// next build number bump.
// we don't really need a blamelist with a length > 50
commits, err := git.Get(c).Log(c, host, project, b.Sourcestamp.Revision, &git.LogOptions{Limit: 50})
switch status.Code(err) {
case codes.OK:
for _, commit := range commits {
if commit.Id == prevRev {
break
}
change := changeFromGitiles(b.Sourcestamp.Repository, "master", commit)
b.Sourcestamp.Changes = append(b.Sourcestamp.Changes, change)
}
return nil
case codes.NotFound:
logging.WithError(err).Warningf(
c,
"gitiles.log returned 404 %s/+/%s",
b.Sourcestamp.Repository, b.Sourcestamp.Revision)
b.Sourcestamp.Changes = nil
return nil
default:
return err
}
} | [
"func",
"fetchChanges",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"*",
"buildbot",
".",
"Build",
")",
"error",
"{",
"memcache",
".",
"Set",
"(",
"c",
",",
"buildRevCache",
"(",
"c",
",",
"b",
")",
")",
"\n\n",
"// initialize the slice so that when ser... | // fetchChanges populates b.SourceStamp.Changes from Gitiles.
//
// Uses memcache to read the revision of the previous build.
// If not available, loads the previous build that has a commit hash revision. | [
"fetchChanges",
"populates",
"b",
".",
"SourceStamp",
".",
"Changes",
"from",
"Gitiles",
".",
"Uses",
"memcache",
"to",
"read",
"the",
"revision",
"of",
"the",
"previous",
"build",
".",
"If",
"not",
"available",
"loads",
"the",
"previous",
"build",
"that",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/blame.go#L104-L165 |
8,688 | luci/luci-go | milo/buildsource/buildbot/buildstore/blame.go | changeFromGitiles | func changeFromGitiles(repoURL, branch string, commit *gitpb.Commit) buildbot.Change {
ct, _ := ptypes.Timestamp(commit.Committer.Time)
return buildbot.Change{
At: ct.Format("Mon _2 Jan 2006 15:04:05"),
Branch: &branch,
Comments: commit.Message,
Repository: repoURL,
Rev: commit.Id,
Revision: commit.Id,
Revlink: fmt.Sprintf("%s/+/%s", strings.TrimSuffix(repoURL, "/"), commit.Id),
When: int(ct.Unix()),
Who: commit.Author.Email,
// TODO(nodir): add Files if someone needs them.
}
} | go | func changeFromGitiles(repoURL, branch string, commit *gitpb.Commit) buildbot.Change {
ct, _ := ptypes.Timestamp(commit.Committer.Time)
return buildbot.Change{
At: ct.Format("Mon _2 Jan 2006 15:04:05"),
Branch: &branch,
Comments: commit.Message,
Repository: repoURL,
Rev: commit.Id,
Revision: commit.Id,
Revlink: fmt.Sprintf("%s/+/%s", strings.TrimSuffix(repoURL, "/"), commit.Id),
When: int(ct.Unix()),
Who: commit.Author.Email,
// TODO(nodir): add Files if someone needs them.
}
} | [
"func",
"changeFromGitiles",
"(",
"repoURL",
",",
"branch",
"string",
",",
"commit",
"*",
"gitpb",
".",
"Commit",
")",
"buildbot",
".",
"Change",
"{",
"ct",
",",
"_",
":=",
"ptypes",
".",
"Timestamp",
"(",
"commit",
".",
"Committer",
".",
"Time",
")",
... | // changeFromGitiles converts a gitiles.Commit to a buildbot change. | [
"changeFromGitiles",
"converts",
"a",
"gitiles",
".",
"Commit",
"to",
"a",
"buildbot",
"change",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/blame.go#L168-L182 |
8,689 | luci/luci-go | milo/buildsource/buildbot/buildstore/blame.go | getPrevRev | func getPrevRev(c context.Context, b *buildbot.Build, maxRecursionDepth int) (string, error) {
// note: we cannot use exponential scan here because there may be build
// number gaps anywhere, for example given build numbers 10 20 30 40,
// if we check 25 while scanning [20, 40), we don't know if we should continue
// scanning in [20, 25) or (25, 40).
switch {
case b.Number == 0:
return "", nil
case maxRecursionDepth <= 0:
logging.Warningf(c, "reached maximum recursion depth; giving up")
return "", nil
}
prev := &buildbot.Build{
Master: b.Master,
Buildername: b.Buildername,
Number: b.Number - 1,
}
cache := buildRevCache(c, prev)
err := memcache.Get(c, cache)
if err == nil {
// fast path
return string(cache.Value()), nil
}
// slow path
if err != memcache.ErrCacheMiss {
logging.WithError(err).Warningf(c, "memcache.get failed for key %q", cache.Key())
}
fetched, err := getBuild(c, prev.ID(), false, false)
if err != nil {
return "", err
}
var prevRev string
if fetched != nil && commitHashRe.MatchString(fetched.Sourcestamp.Revision) {
prevRev = fetched.Sourcestamp.Revision
} else {
// slowest path
// May happen if there is a gap in build numbers or
// if someone scheduled a build manually with no or HEAD revision.
// Rare case.
// This is a recursive call of itself.
// The results are memcached along the stack though.
if prevRev, err = getPrevRev(c, b, maxRecursionDepth-1); err != nil {
return "", err
}
}
cache.SetValue([]byte(prevRev))
memcache.Set(c, cache)
return prevRev, nil
} | go | func getPrevRev(c context.Context, b *buildbot.Build, maxRecursionDepth int) (string, error) {
// note: we cannot use exponential scan here because there may be build
// number gaps anywhere, for example given build numbers 10 20 30 40,
// if we check 25 while scanning [20, 40), we don't know if we should continue
// scanning in [20, 25) or (25, 40).
switch {
case b.Number == 0:
return "", nil
case maxRecursionDepth <= 0:
logging.Warningf(c, "reached maximum recursion depth; giving up")
return "", nil
}
prev := &buildbot.Build{
Master: b.Master,
Buildername: b.Buildername,
Number: b.Number - 1,
}
cache := buildRevCache(c, prev)
err := memcache.Get(c, cache)
if err == nil {
// fast path
return string(cache.Value()), nil
}
// slow path
if err != memcache.ErrCacheMiss {
logging.WithError(err).Warningf(c, "memcache.get failed for key %q", cache.Key())
}
fetched, err := getBuild(c, prev.ID(), false, false)
if err != nil {
return "", err
}
var prevRev string
if fetched != nil && commitHashRe.MatchString(fetched.Sourcestamp.Revision) {
prevRev = fetched.Sourcestamp.Revision
} else {
// slowest path
// May happen if there is a gap in build numbers or
// if someone scheduled a build manually with no or HEAD revision.
// Rare case.
// This is a recursive call of itself.
// The results are memcached along the stack though.
if prevRev, err = getPrevRev(c, b, maxRecursionDepth-1); err != nil {
return "", err
}
}
cache.SetValue([]byte(prevRev))
memcache.Set(c, cache)
return prevRev, nil
} | [
"func",
"getPrevRev",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"*",
"buildbot",
".",
"Build",
",",
"maxRecursionDepth",
"int",
")",
"(",
"string",
",",
"error",
")",
"{",
"// note: we cannot use exponential scan here because there may be build",
"// number gaps ... | // getPrevRev returns revision of the closest previous build with a commit
// hash, or "" if not found.
// Memcaches results. | [
"getPrevRev",
"returns",
"revision",
"of",
"the",
"closest",
"previous",
"build",
"with",
"a",
"commit",
"hash",
"or",
"if",
"not",
"found",
".",
"Memcaches",
"results",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/blame.go#L187-L241 |
8,690 | luci/luci-go | milo/buildsource/buildbot/buildstore/blame.go | buildRevCache | func buildRevCache(c context.Context, b *buildbot.Build) memcache.Item {
item := memcache.NewItem(c, "buildbot_revision/"+b.ID().String())
if b.Sourcestamp != nil {
item.SetValue([]byte(b.Sourcestamp.Revision))
}
return item
} | go | func buildRevCache(c context.Context, b *buildbot.Build) memcache.Item {
item := memcache.NewItem(c, "buildbot_revision/"+b.ID().String())
if b.Sourcestamp != nil {
item.SetValue([]byte(b.Sourcestamp.Revision))
}
return item
} | [
"func",
"buildRevCache",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"*",
"buildbot",
".",
"Build",
")",
"memcache",
".",
"Item",
"{",
"item",
":=",
"memcache",
".",
"NewItem",
"(",
"c",
",",
"\"",
"\"",
"+",
"b",
".",
"ID",
"(",
")",
".",
"St... | // buildRevCache returns a memcache.Item for the build's revision.
// Initializes the value with current revision. | [
"buildRevCache",
"returns",
"a",
"memcache",
".",
"Item",
"for",
"the",
"build",
"s",
"revision",
".",
"Initializes",
"the",
"value",
"with",
"current",
"revision",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/blame.go#L245-L251 |
8,691 | luci/luci-go | common/tsmon/field/serialize.go | SerializeDescriptor | func SerializeDescriptor(fields []Field) []*pb.MetricsDataSet_MetricFieldDescriptor {
ret := make([]*pb.MetricsDataSet_MetricFieldDescriptor, len(fields))
for i, f := range fields {
d := &pb.MetricsDataSet_MetricFieldDescriptor{
Name: proto.String(f.Name),
}
switch f.Type {
case StringType:
d.FieldType = pb.MetricsDataSet_MetricFieldDescriptor_STRING.Enum()
case BoolType:
d.FieldType = pb.MetricsDataSet_MetricFieldDescriptor_BOOL.Enum()
case IntType:
d.FieldType = pb.MetricsDataSet_MetricFieldDescriptor_INT64.Enum()
}
ret[i] = d
}
return ret
} | go | func SerializeDescriptor(fields []Field) []*pb.MetricsDataSet_MetricFieldDescriptor {
ret := make([]*pb.MetricsDataSet_MetricFieldDescriptor, len(fields))
for i, f := range fields {
d := &pb.MetricsDataSet_MetricFieldDescriptor{
Name: proto.String(f.Name),
}
switch f.Type {
case StringType:
d.FieldType = pb.MetricsDataSet_MetricFieldDescriptor_STRING.Enum()
case BoolType:
d.FieldType = pb.MetricsDataSet_MetricFieldDescriptor_BOOL.Enum()
case IntType:
d.FieldType = pb.MetricsDataSet_MetricFieldDescriptor_INT64.Enum()
}
ret[i] = d
}
return ret
} | [
"func",
"SerializeDescriptor",
"(",
"fields",
"[",
"]",
"Field",
")",
"[",
"]",
"*",
"pb",
".",
"MetricsDataSet_MetricFieldDescriptor",
"{",
"ret",
":=",
"make",
"(",
"[",
"]",
"*",
"pb",
".",
"MetricsDataSet_MetricFieldDescriptor",
",",
"len",
"(",
"fields",
... | // SerializeDescriptor returns a slice of field descriptors, representing just
// the names and types of fields. | [
"SerializeDescriptor",
"returns",
"a",
"slice",
"of",
"field",
"descriptors",
"representing",
"just",
"the",
"names",
"and",
"types",
"of",
"fields",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/field/serialize.go#L25-L46 |
8,692 | luci/luci-go | common/tsmon/field/serialize.go | Serialize | func Serialize(fields []Field, values []interface{}) []*pb.MetricsData_MetricField {
ret := make([]*pb.MetricsData_MetricField, len(fields))
for i, f := range fields {
d := &pb.MetricsData_MetricField{
Name: proto.String(f.Name),
}
switch f.Type {
case StringType:
d.Value = &pb.MetricsData_MetricField_StringValue{values[i].(string)}
case BoolType:
d.Value = &pb.MetricsData_MetricField_BoolValue{values[i].(bool)}
case IntType:
d.Value = &pb.MetricsData_MetricField_Int64Value{values[i].(int64)}
}
ret[i] = d
}
return ret
} | go | func Serialize(fields []Field, values []interface{}) []*pb.MetricsData_MetricField {
ret := make([]*pb.MetricsData_MetricField, len(fields))
for i, f := range fields {
d := &pb.MetricsData_MetricField{
Name: proto.String(f.Name),
}
switch f.Type {
case StringType:
d.Value = &pb.MetricsData_MetricField_StringValue{values[i].(string)}
case BoolType:
d.Value = &pb.MetricsData_MetricField_BoolValue{values[i].(bool)}
case IntType:
d.Value = &pb.MetricsData_MetricField_Int64Value{values[i].(int64)}
}
ret[i] = d
}
return ret
} | [
"func",
"Serialize",
"(",
"fields",
"[",
"]",
"Field",
",",
"values",
"[",
"]",
"interface",
"{",
"}",
")",
"[",
"]",
"*",
"pb",
".",
"MetricsData_MetricField",
"{",
"ret",
":=",
"make",
"(",
"[",
"]",
"*",
"pb",
".",
"MetricsData_MetricField",
",",
... | // Serialize returns a slice of ts_mon_proto.MetricsData.MetricsField messages
// representing the field names and values. | [
"Serialize",
"returns",
"a",
"slice",
"of",
"ts_mon_proto",
".",
"MetricsData",
".",
"MetricsField",
"messages",
"representing",
"the",
"field",
"names",
"and",
"values",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/field/serialize.go#L50-L71 |
8,693 | luci/luci-go | cipd/appengine/ui/common.go | routeToPage | func routeToPage(c *router.Context) error {
path := c.Params.ByName("path")
switch chunks := strings.SplitN(path, "/+/", 2); {
case len(chunks) <= 1: // no '/+/' in path => prefix listing page
return prefixListingPage(c, path)
case len(chunks) == 2 && chunks[1] == "": // ends with '/+/' => package page
return packagePage(c, chunks[0])
case len(chunks) == 2: // has something after '/+/' => instance page
return instancePage(c, chunks[0], chunks[1])
default:
return status.Errorf(codes.InvalidArgument, "malformed page URL")
}
} | go | func routeToPage(c *router.Context) error {
path := c.Params.ByName("path")
switch chunks := strings.SplitN(path, "/+/", 2); {
case len(chunks) <= 1: // no '/+/' in path => prefix listing page
return prefixListingPage(c, path)
case len(chunks) == 2 && chunks[1] == "": // ends with '/+/' => package page
return packagePage(c, chunks[0])
case len(chunks) == 2: // has something after '/+/' => instance page
return instancePage(c, chunks[0], chunks[1])
default:
return status.Errorf(codes.InvalidArgument, "malformed page URL")
}
} | [
"func",
"routeToPage",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"error",
"{",
"path",
":=",
"c",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
"\n",
"switch",
"chunks",
":=",
"strings",
".",
"SplitN",
"(",
"path",
",",
"\"",
"\"",
",",
... | // routeToPage routes to an appropriate page depending on the request URL. | [
"routeToPage",
"routes",
"to",
"an",
"appropriate",
"page",
"depending",
"on",
"the",
"request",
"URL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/ui/common.go#L72-L84 |
8,694 | luci/luci-go | tumble/service.go | FireAllTasks | func (s *Service) FireAllTasks(c context.Context) error {
cfg := getConfig(c)
namespaces, err := s.getNamespaces(c, cfg)
if err != nil {
return err
}
// Probe each namespace in parallel. Each probe function reports its own
// errors, so the work pool will never return any non-nil error response.
var errCount, taskCount counter
_ = parallel.WorkPool(cfg.NumGoroutines, func(ch chan<- func() error) {
for _, ns := range namespaces {
ns := ns
ch <- func() error {
// Generate a list of all shards.
allShards := make([]taskShard, 0, cfg.TotalShardCount(ns))
for i := uint64(0); i < cfg.TotalShardCount(ns); i++ {
allShards = append(allShards, taskShard{i, minTS})
}
s.fireAllTasksForNamespace(c, cfg, ns, allShards, &errCount, &taskCount)
return nil
}
}
})
if errCount > 0 {
logging.Errorf(c, "Encountered %d error(s).", errCount)
return errors.New("errors were encountered while probing for tasks")
}
logging.Debugf(c, "Successfully probed %d namespace(s) and fired %d tasks(s).",
len(namespaces), taskCount)
return err
} | go | func (s *Service) FireAllTasks(c context.Context) error {
cfg := getConfig(c)
namespaces, err := s.getNamespaces(c, cfg)
if err != nil {
return err
}
// Probe each namespace in parallel. Each probe function reports its own
// errors, so the work pool will never return any non-nil error response.
var errCount, taskCount counter
_ = parallel.WorkPool(cfg.NumGoroutines, func(ch chan<- func() error) {
for _, ns := range namespaces {
ns := ns
ch <- func() error {
// Generate a list of all shards.
allShards := make([]taskShard, 0, cfg.TotalShardCount(ns))
for i := uint64(0); i < cfg.TotalShardCount(ns); i++ {
allShards = append(allShards, taskShard{i, minTS})
}
s.fireAllTasksForNamespace(c, cfg, ns, allShards, &errCount, &taskCount)
return nil
}
}
})
if errCount > 0 {
logging.Errorf(c, "Encountered %d error(s).", errCount)
return errors.New("errors were encountered while probing for tasks")
}
logging.Debugf(c, "Successfully probed %d namespace(s) and fired %d tasks(s).",
len(namespaces), taskCount)
return err
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"FireAllTasks",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"cfg",
":=",
"getConfig",
"(",
"c",
")",
"\n\n",
"namespaces",
",",
"err",
":=",
"s",
".",
"getNamespaces",
"(",
"c",
",",
"cfg",
")",
"\... | // FireAllTasks searches for work in all namespaces, and fires off a process
// task for any shards it finds that have at least one Mutation present to
// ensure that no work languishes forever. This may not be needed in
// a constantly-loaded system with good tumble key distribution. | [
"FireAllTasks",
"searches",
"for",
"work",
"in",
"all",
"namespaces",
"and",
"fires",
"off",
"a",
"process",
"task",
"for",
"any",
"shards",
"it",
"finds",
"that",
"have",
"at",
"least",
"one",
"Mutation",
"present",
"to",
"ensure",
"that",
"no",
"work",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/service.go#L89-L122 |
8,695 | luci/luci-go | tumble/service.go | processURL | func processURL(ts timestamp, shard uint64, ns string, loop bool) string {
v := strings.NewReplacer(
":shard_id", fmt.Sprint(shard),
":timestamp", strconv.FormatInt(int64(ts), 10),
).Replace(processShardPattern)
// Append our namespace query parameter. This is cosmetic, and the default
// namespace will have this query parameter omitted.
query := url.Values{}
if ns != "" {
query.Set("ns", ns)
}
if !loop {
query.Set("single", "1")
}
if len(query) > 0 {
v += "?" + query.Encode()
}
return v
} | go | func processURL(ts timestamp, shard uint64, ns string, loop bool) string {
v := strings.NewReplacer(
":shard_id", fmt.Sprint(shard),
":timestamp", strconv.FormatInt(int64(ts), 10),
).Replace(processShardPattern)
// Append our namespace query parameter. This is cosmetic, and the default
// namespace will have this query parameter omitted.
query := url.Values{}
if ns != "" {
query.Set("ns", ns)
}
if !loop {
query.Set("single", "1")
}
if len(query) > 0 {
v += "?" + query.Encode()
}
return v
} | [
"func",
"processURL",
"(",
"ts",
"timestamp",
",",
"shard",
"uint64",
",",
"ns",
"string",
",",
"loop",
"bool",
")",
"string",
"{",
"v",
":=",
"strings",
".",
"NewReplacer",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprint",
"(",
"shard",
")",
",",
"\"",
... | // processURL creates a new url for a process shard taskqueue task, including
// the given timestamp and shard number. | [
"processURL",
"creates",
"a",
"new",
"url",
"for",
"a",
"process",
"shard",
"taskqueue",
"task",
"including",
"the",
"given",
"timestamp",
"and",
"shard",
"number",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/service.go#L280-L299 |
8,696 | luci/luci-go | server/auth/authdb/snapshot.go | IsInternalService | func (db *SnapshotDB) IsInternalService(c context.Context, hostname string) (bool, error) {
if db.internalServices == nil {
return false, nil
}
return db.internalServices.MatchString(hostname), nil
} | go | func (db *SnapshotDB) IsInternalService(c context.Context, hostname string) (bool, error) {
if db.internalServices == nil {
return false, nil
}
return db.internalServices.MatchString(hostname), nil
} | [
"func",
"(",
"db",
"*",
"SnapshotDB",
")",
"IsInternalService",
"(",
"c",
"context",
".",
"Context",
",",
"hostname",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"db",
".",
"internalServices",
"==",
"nil",
"{",
"return",
"false",
",",
"ni... | // IsInternalService returns true if the given hostname belongs to a service
// that is a part of the current LUCI deployment.
//
// What hosts are internal is controlled by 'internal_service_regexp' setting
// in security.cfg in the Auth Service configs. | [
"IsInternalService",
"returns",
"true",
"if",
"the",
"given",
"hostname",
"belongs",
"to",
"a",
"service",
"that",
"is",
"a",
"part",
"of",
"the",
"current",
"LUCI",
"deployment",
".",
"What",
"hosts",
"are",
"internal",
"is",
"controlled",
"by",
"internal_ser... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/snapshot.go#L215-L220 |
8,697 | luci/luci-go | server/auth/authdb/snapshot.go | IsMember | func (db *SnapshotDB) IsMember(c context.Context, id identity.Identity, groups []string) (bool, error) {
// TODO(vadimsh): Optimize multi-group case.
for _, gr := range groups {
switch found, err := db.isMemberImpl(c, id, gr); {
case err != nil:
return false, err
case found:
return true, nil
}
}
return false, nil
} | go | func (db *SnapshotDB) IsMember(c context.Context, id identity.Identity, groups []string) (bool, error) {
// TODO(vadimsh): Optimize multi-group case.
for _, gr := range groups {
switch found, err := db.isMemberImpl(c, id, gr); {
case err != nil:
return false, err
case found:
return true, nil
}
}
return false, nil
} | [
"func",
"(",
"db",
"*",
"SnapshotDB",
")",
"IsMember",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"identity",
".",
"Identity",
",",
"groups",
"[",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// TODO(vadimsh): Optimize multi-group case.",
... | // IsMember returns true if the given identity belongs to any of the groups.
//
// Unknown groups are considered empty. May return errors if underlying
// datastore has issues. | [
"IsMember",
"returns",
"true",
"if",
"the",
"given",
"identity",
"belongs",
"to",
"any",
"of",
"the",
"groups",
".",
"Unknown",
"groups",
"are",
"considered",
"empty",
".",
"May",
"return",
"errors",
"if",
"underlying",
"datastore",
"has",
"issues",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/snapshot.go#L226-L237 |
8,698 | luci/luci-go | server/auth/authdb/snapshot.go | CheckMembership | func (db *SnapshotDB) CheckMembership(c context.Context, id identity.Identity, groups []string) (out []string, err error) {
// TODO(vadimsh): Optimize multi-group case.
for _, gr := range groups {
switch found, err := db.isMemberImpl(c, id, gr); {
case err != nil:
return nil, err
case found:
out = append(out, gr)
}
}
return
} | go | func (db *SnapshotDB) CheckMembership(c context.Context, id identity.Identity, groups []string) (out []string, err error) {
// TODO(vadimsh): Optimize multi-group case.
for _, gr := range groups {
switch found, err := db.isMemberImpl(c, id, gr); {
case err != nil:
return nil, err
case found:
out = append(out, gr)
}
}
return
} | [
"func",
"(",
"db",
"*",
"SnapshotDB",
")",
"CheckMembership",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"identity",
".",
"Identity",
",",
"groups",
"[",
"]",
"string",
")",
"(",
"out",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"// TODO... | // CheckMembership returns groups from the given list the identity belongs to.
//
// Unlike IsMember, it doesn't stop on the first hit but continues evaluating
// all groups.
//
// Unknown groups are considered empty. The order of groups in the result may
// be different from the order in 'groups'.
//
// May return errors if underlying datastore has issues. | [
"CheckMembership",
"returns",
"groups",
"from",
"the",
"given",
"list",
"the",
"identity",
"belongs",
"to",
".",
"Unlike",
"IsMember",
"it",
"doesn",
"t",
"stop",
"on",
"the",
"first",
"hit",
"but",
"continues",
"evaluating",
"all",
"groups",
".",
"Unknown",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/snapshot.go#L248-L259 |
8,699 | luci/luci-go | server/auth/authdb/snapshot.go | isMemberImpl | func (db *SnapshotDB) isMemberImpl(c context.Context, id identity.Identity, groupName string) (bool, error) {
// Cycle detection check uses a stack of groups currently being explored. Use
// stack allocated array as a backing store to avoid unnecessary dynamic
// allocation. If stack depth grows beyond 8, 'append' will reallocate it on
// the heap.
var backingStore [8]*group
current := backingStore[:0]
// Keep a set of all visited groups to avoid revisiting them in case of a
// diamond-like graph, e.g A -> B, A -> C, B -> D, C -> D (we don't need to
// visit D twice in this case).
visited := make(map[*group]struct{}, 10)
// isMember is used to recurse over nested groups.
var isMember func(*group) bool
isMember = func(gr *group) bool {
// 'id' is a direct member?
if _, ok := gr.members[id]; ok {
return true
}
// 'id' matches some glob?
for _, glob := range gr.globs {
if glob.Match(id) {
return true
}
}
if len(gr.nested) == 0 {
return false
}
current = append(current, gr) // popped before return
found := false
outer_loop:
for _, nested := range gr.nested {
// There should be no cycles, but do the check just in case there are,
// seg faulting with stack overflow is very bad. In case of a cycle, skip
// the offending group, but keep searching other groups.
for _, ancestor := range current {
if ancestor == nested {
logging.Errorf(c, "auth: unexpected group nesting cycle in group %q", groupName)
continue outer_loop
}
}
// Explored 'nested' already (and didn't find anything) while visiting
// some sibling branch? Skip.
if _, seen := visited[nested]; seen {
continue
}
if isMember(nested) {
found = true
break
}
}
// Note that we don't use defers here since they have non-negligible runtime
// cost. Using 'defer' here makes IsMember ~1.7x slower (1200 ns vs 700 ns),
// See BenchmarkIsMember.
current = current[:len(current)-1]
visited[gr] = struct{}{}
return found
}
if gr := db.groups[groupName]; gr != nil {
return isMember(gr), nil
}
return false, nil
} | go | func (db *SnapshotDB) isMemberImpl(c context.Context, id identity.Identity, groupName string) (bool, error) {
// Cycle detection check uses a stack of groups currently being explored. Use
// stack allocated array as a backing store to avoid unnecessary dynamic
// allocation. If stack depth grows beyond 8, 'append' will reallocate it on
// the heap.
var backingStore [8]*group
current := backingStore[:0]
// Keep a set of all visited groups to avoid revisiting them in case of a
// diamond-like graph, e.g A -> B, A -> C, B -> D, C -> D (we don't need to
// visit D twice in this case).
visited := make(map[*group]struct{}, 10)
// isMember is used to recurse over nested groups.
var isMember func(*group) bool
isMember = func(gr *group) bool {
// 'id' is a direct member?
if _, ok := gr.members[id]; ok {
return true
}
// 'id' matches some glob?
for _, glob := range gr.globs {
if glob.Match(id) {
return true
}
}
if len(gr.nested) == 0 {
return false
}
current = append(current, gr) // popped before return
found := false
outer_loop:
for _, nested := range gr.nested {
// There should be no cycles, but do the check just in case there are,
// seg faulting with stack overflow is very bad. In case of a cycle, skip
// the offending group, but keep searching other groups.
for _, ancestor := range current {
if ancestor == nested {
logging.Errorf(c, "auth: unexpected group nesting cycle in group %q", groupName)
continue outer_loop
}
}
// Explored 'nested' already (and didn't find anything) while visiting
// some sibling branch? Skip.
if _, seen := visited[nested]; seen {
continue
}
if isMember(nested) {
found = true
break
}
}
// Note that we don't use defers here since they have non-negligible runtime
// cost. Using 'defer' here makes IsMember ~1.7x slower (1200 ns vs 700 ns),
// See BenchmarkIsMember.
current = current[:len(current)-1]
visited[gr] = struct{}{}
return found
}
if gr := db.groups[groupName]; gr != nil {
return isMember(gr), nil
}
return false, nil
} | [
"func",
"(",
"db",
"*",
"SnapshotDB",
")",
"isMemberImpl",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"identity",
".",
"Identity",
",",
"groupName",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// Cycle detection check uses a stack of groups current... | // isMemberImpl implements IsMember check for a single group only. | [
"isMemberImpl",
"implements",
"IsMember",
"check",
"for",
"a",
"single",
"group",
"only",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/snapshot.go#L262-L336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.