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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7,300 | luci/luci-go | grpc/logging/grpc_logger.go | translateLevel | func translateLevel(l logging.Level) int {
switch l {
case Suppress:
return -1
case logging.Error:
return 0
case logging.Warning, logging.Info:
return 1
default:
return 2
}
} | go | func translateLevel(l logging.Level) int {
switch l {
case Suppress:
return -1
case logging.Error:
return 0
case logging.Warning, logging.Info:
return 1
default:
return 2
}
} | [
"func",
"translateLevel",
"(",
"l",
"logging",
".",
"Level",
")",
"int",
"{",
"switch",
"l",
"{",
"case",
"Suppress",
":",
"return",
"-",
"1",
"\n",
"case",
"logging",
".",
"Error",
":",
"return",
"0",
"\n",
"case",
"logging",
".",
"Warning",
",",
"l... | // translateLevel translates a "verbose level" to a logging level. | [
"translateLevel",
"translates",
"a",
"verbose",
"level",
"to",
"a",
"logging",
"level",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/logging/grpc_logger.go#L176-L187 |
7,301 | luci/luci-go | appengine/gaeauth/server/default.go | InstallHandlers | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
m := CookieAuth.(cookieAuthMethod)
if oid, ok := m.Method.(*openid.AuthMethod); ok {
oid.InstallHandlers(r, base)
}
auth.InstallHandlers(r, base)
authdbimpl.InstallHandlers(r, base)
} | go | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
m := CookieAuth.(cookieAuthMethod)
if oid, ok := m.Method.(*openid.AuthMethod); ok {
oid.InstallHandlers(r, base)
}
auth.InstallHandlers(r, base)
authdbimpl.InstallHandlers(r, base)
} | [
"func",
"InstallHandlers",
"(",
"r",
"*",
"router",
".",
"Router",
",",
"base",
"router",
".",
"MiddlewareChain",
")",
"{",
"m",
":=",
"CookieAuth",
".",
"(",
"cookieAuthMethod",
")",
"\n",
"if",
"oid",
",",
"ok",
":=",
"m",
".",
"Method",
".",
"(",
... | // InstallHandlers installs HTTP handlers for various default routes related
// to authentication system.
//
// Must be installed in server HTTP router for authentication to work. | [
"InstallHandlers",
"installs",
"HTTP",
"handlers",
"for",
"various",
"default",
"routes",
"related",
"to",
"authentication",
"system",
".",
"Must",
"be",
"installed",
"in",
"server",
"HTTP",
"router",
"for",
"authentication",
"to",
"work",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/default.go#L41-L48 |
7,302 | luci/luci-go | dm/api/distributor/swarming/v1/cipd.go | ToCipdPackage | func (c *CipdPackage) ToCipdPackage() *swarm.SwarmingRpcsCipdPackage {
if c == nil {
return nil
}
return &swarm.SwarmingRpcsCipdPackage{PackageName: c.Name, Version: c.Version}
} | go | func (c *CipdPackage) ToCipdPackage() *swarm.SwarmingRpcsCipdPackage {
if c == nil {
return nil
}
return &swarm.SwarmingRpcsCipdPackage{PackageName: c.Name, Version: c.Version}
} | [
"func",
"(",
"c",
"*",
"CipdPackage",
")",
"ToCipdPackage",
"(",
")",
"*",
"swarm",
".",
"SwarmingRpcsCipdPackage",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"swarm",
".",
"SwarmingRpcsCipdPackage",
"{",
"PackageNam... | // ToCipdPackage converts this to a swarming api SwarmingRpcsCipdPackage. | [
"ToCipdPackage",
"converts",
"this",
"to",
"a",
"swarming",
"api",
"SwarmingRpcsCipdPackage",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/swarming/v1/cipd.go#L24-L29 |
7,303 | luci/luci-go | dm/api/distributor/swarming/v1/cipd.go | ToCipdInput | func (c *CipdSpec) ToCipdInput() *swarm.SwarmingRpcsCipdInput {
if c == nil || c.Client == nil && len(c.ByPath) == 0 {
return nil
}
ret := &swarm.SwarmingRpcsCipdInput{
ClientPackage: c.Client.ToCipdPackage(),
}
if len(c.ByPath) > 0 {
count := 0
paths := make(sort.StringSlice, 0, len(c.ByPath))
for path, pkgs := range c.ByPath {
paths = append(paths, path)
count += len(pkgs.Pkg)
}
ret.Packages = make([]*swarm.SwarmingRpcsCipdPackage, 0, count)
for _, path := range paths {
for _, pkg := range c.ByPath[path].Pkg {
retPkg := pkg.ToCipdPackage()
retPkg.Path = path
ret.Packages = append(ret.Packages, retPkg)
}
}
}
return ret
} | go | func (c *CipdSpec) ToCipdInput() *swarm.SwarmingRpcsCipdInput {
if c == nil || c.Client == nil && len(c.ByPath) == 0 {
return nil
}
ret := &swarm.SwarmingRpcsCipdInput{
ClientPackage: c.Client.ToCipdPackage(),
}
if len(c.ByPath) > 0 {
count := 0
paths := make(sort.StringSlice, 0, len(c.ByPath))
for path, pkgs := range c.ByPath {
paths = append(paths, path)
count += len(pkgs.Pkg)
}
ret.Packages = make([]*swarm.SwarmingRpcsCipdPackage, 0, count)
for _, path := range paths {
for _, pkg := range c.ByPath[path].Pkg {
retPkg := pkg.ToCipdPackage()
retPkg.Path = path
ret.Packages = append(ret.Packages, retPkg)
}
}
}
return ret
} | [
"func",
"(",
"c",
"*",
"CipdSpec",
")",
"ToCipdInput",
"(",
")",
"*",
"swarm",
".",
"SwarmingRpcsCipdInput",
"{",
"if",
"c",
"==",
"nil",
"||",
"c",
".",
"Client",
"==",
"nil",
"&&",
"len",
"(",
"c",
".",
"ByPath",
")",
"==",
"0",
"{",
"return",
... | // ToCipdInput converts this to a swarming api SwarmingRpcsCipdInput. | [
"ToCipdInput",
"converts",
"this",
"to",
"a",
"swarming",
"api",
"SwarmingRpcsCipdInput",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/swarming/v1/cipd.go#L32-L56 |
7,304 | luci/luci-go | auth/identity/identity.go | MakeIdentity | func MakeIdentity(identity string) (Identity, error) {
id := Identity(identity)
if err := id.Validate(); err != nil {
return "", err
}
return id, nil
} | go | func MakeIdentity(identity string) (Identity, error) {
id := Identity(identity)
if err := id.Validate(); err != nil {
return "", err
}
return id, nil
} | [
"func",
"MakeIdentity",
"(",
"identity",
"string",
")",
"(",
"Identity",
",",
"error",
")",
"{",
"id",
":=",
"Identity",
"(",
"identity",
")",
"\n",
"if",
"err",
":=",
"id",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"... | // MakeIdentity ensures 'identity' string looks like a valid identity and
// returns it as Identity value. | [
"MakeIdentity",
"ensures",
"identity",
"string",
"looks",
"like",
"a",
"valid",
"identity",
"and",
"returns",
"it",
"as",
"Identity",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/identity.go#L68-L74 |
7,305 | luci/luci-go | auth/identity/identity.go | Validate | func (id Identity) Validate() error {
chunks := strings.SplitN(string(id), ":", 2)
if len(chunks) != 2 {
return fmt.Errorf("auth: bad identity string %q", id)
}
re := knownKinds[Kind(chunks[0])]
if re == nil {
return fmt.Errorf("auth: bad identity kind %q", chunks[0])
}
if !re.MatchString(chunks[1]) {
return fmt.Errorf("auth: bad value %q for identity kind %q", chunks[1], chunks[0])
}
return nil
} | go | func (id Identity) Validate() error {
chunks := strings.SplitN(string(id), ":", 2)
if len(chunks) != 2 {
return fmt.Errorf("auth: bad identity string %q", id)
}
re := knownKinds[Kind(chunks[0])]
if re == nil {
return fmt.Errorf("auth: bad identity kind %q", chunks[0])
}
if !re.MatchString(chunks[1]) {
return fmt.Errorf("auth: bad value %q for identity kind %q", chunks[1], chunks[0])
}
return nil
} | [
"func",
"(",
"id",
"Identity",
")",
"Validate",
"(",
")",
"error",
"{",
"chunks",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"id",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"chunks",
")",
"!=",
"2",
"{",
"return",
"f... | // Validate checks that the identity string is well-formed. | [
"Validate",
"checks",
"that",
"the",
"identity",
"string",
"is",
"well",
"-",
"formed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/identity.go#L77-L90 |
7,306 | luci/luci-go | auth/identity/identity.go | Kind | func (id Identity) Kind() Kind {
chunks := strings.SplitN(string(id), ":", 2)
if len(chunks) != 2 {
return Anonymous
}
return Kind(chunks[0])
} | go | func (id Identity) Kind() Kind {
chunks := strings.SplitN(string(id), ":", 2)
if len(chunks) != 2 {
return Anonymous
}
return Kind(chunks[0])
} | [
"func",
"(",
"id",
"Identity",
")",
"Kind",
"(",
")",
"Kind",
"{",
"chunks",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"id",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"chunks",
")",
"!=",
"2",
"{",
"return",
"Anonym... | // Kind returns identity kind. If identity string is invalid returns Anonymous. | [
"Kind",
"returns",
"identity",
"kind",
".",
"If",
"identity",
"string",
"is",
"invalid",
"returns",
"Anonymous",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/identity.go#L93-L99 |
7,307 | luci/luci-go | auth/identity/identity.go | Email | func (id Identity) Email() string {
chunks := strings.SplitN(string(id), ":", 2)
if len(chunks) != 2 {
return ""
}
if Kind(chunks[0]) == User {
return chunks[1]
}
return ""
} | go | func (id Identity) Email() string {
chunks := strings.SplitN(string(id), ":", 2)
if len(chunks) != 2 {
return ""
}
if Kind(chunks[0]) == User {
return chunks[1]
}
return ""
} | [
"func",
"(",
"id",
"Identity",
")",
"Email",
"(",
")",
"string",
"{",
"chunks",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"id",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"chunks",
")",
"!=",
"2",
"{",
"return",
"\""... | // Email returns user's email for identity with kind User or empty string for
// all other identity kinds. If identity string is undefined returns "". | [
"Email",
"returns",
"user",
"s",
"email",
"for",
"identity",
"with",
"kind",
"User",
"or",
"empty",
"string",
"for",
"all",
"other",
"identity",
"kinds",
".",
"If",
"identity",
"string",
"is",
"undefined",
"returns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/identity/identity.go#L113-L122 |
7,308 | luci/luci-go | common/errors/tags.go | TagValueIn | func TagValueIn(t TagKey, err error) (value interface{}, ok bool) {
Walk(err, func(err error) bool {
if sc, isSC := err.(stackContexter); isSC {
if value, ok = sc.stackContext().tags[t]; ok {
return false
}
}
return true
})
return
} | go | func TagValueIn(t TagKey, err error) (value interface{}, ok bool) {
Walk(err, func(err error) bool {
if sc, isSC := err.(stackContexter); isSC {
if value, ok = sc.stackContext().tags[t]; ok {
return false
}
}
return true
})
return
} | [
"func",
"TagValueIn",
"(",
"t",
"TagKey",
",",
"err",
"error",
")",
"(",
"value",
"interface",
"{",
"}",
",",
"ok",
"bool",
")",
"{",
"Walk",
"(",
"err",
",",
"func",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"sc",
",",
"isSC",
":=",
"err",
... | // TagValueIn will retrieve the tagged value from the error that's associated
// with this key, and a boolean indicating if the tag was present or not. | [
"TagValueIn",
"will",
"retrieve",
"the",
"tagged",
"value",
"from",
"the",
"error",
"that",
"s",
"associated",
"with",
"this",
"key",
"and",
"a",
"boolean",
"indicating",
"if",
"the",
"tag",
"was",
"present",
"or",
"not",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/tags.go#L56-L66 |
7,309 | luci/luci-go | common/errors/tags.go | In | func (b BoolTag) In(err error) bool {
v, ok := TagValueIn(b.Key, err)
if !ok {
return false
}
return v.(bool)
} | go | func (b BoolTag) In(err error) bool {
v, ok := TagValueIn(b.Key, err)
if !ok {
return false
}
return v.(bool)
} | [
"func",
"(",
"b",
"BoolTag",
")",
"In",
"(",
"err",
"error",
")",
"bool",
"{",
"v",
",",
"ok",
":=",
"TagValueIn",
"(",
"b",
".",
"Key",
",",
"err",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"v",
".",
"(",... | // In returns true iff this tag value has been set to true on this error. | [
"In",
"returns",
"true",
"iff",
"this",
"tag",
"value",
"has",
"been",
"set",
"to",
"true",
"on",
"this",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/tags.go#L106-L112 |
7,310 | luci/luci-go | common/errors/tags.go | GetTags | func GetTags(err error) map[TagKey]interface{} {
ret := map[TagKey]interface{}{}
Walk(err, func(err error) bool {
if sc, ok := err.(stackContexter); ok {
ctx := sc.stackContext()
for k, v := range ctx.tags {
if _, ok := ret[k]; !ok {
ret[k] = v
}
}
}
return true
})
return ret
} | go | func GetTags(err error) map[TagKey]interface{} {
ret := map[TagKey]interface{}{}
Walk(err, func(err error) bool {
if sc, ok := err.(stackContexter); ok {
ctx := sc.stackContext()
for k, v := range ctx.tags {
if _, ok := ret[k]; !ok {
ret[k] = v
}
}
}
return true
})
return ret
} | [
"func",
"GetTags",
"(",
"err",
"error",
")",
"map",
"[",
"TagKey",
"]",
"interface",
"{",
"}",
"{",
"ret",
":=",
"map",
"[",
"TagKey",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"Walk",
"(",
"err",
",",
"func",
"(",
"err",
"error",
")",
"bool",
... | // GetTags returns a map of all TagKeys set in this error to their value.
//
// A nil value means that the tag is present, but has a nil associated value.
//
// This is done in a depth-first traversal of the error stack, with the
// most-recently-set value of the tag taking precendence. | [
"GetTags",
"returns",
"a",
"map",
"of",
"all",
"TagKeys",
"set",
"in",
"this",
"error",
"to",
"their",
"value",
".",
"A",
"nil",
"value",
"means",
"that",
"the",
"tag",
"is",
"present",
"but",
"has",
"a",
"nil",
"associated",
"value",
".",
"This",
"is"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/tags.go#L156-L170 |
7,311 | luci/luci-go | tools/cmd/bqschemaupdater/main.go | schemaFromMessage | func schemaFromMessage(desc *descriptor.FileDescriptorSet, messageName string) (schema bigquery.Schema, description string, err error) {
conv := schemaConverter{
desc: desc,
sourceCodeInfo: make(map[*descriptor.FileDescriptorProto]sourceCodeInfoMap, len(desc.File)),
}
for _, f := range desc.File {
conv.sourceCodeInfo[f], err = descutil.IndexSourceCodeInfo(f)
if err != nil {
return nil, "", errors.Annotate(err, "failed to index source code info in file %q", f.GetName()).Err()
}
}
return conv.schema(messageName)
} | go | func schemaFromMessage(desc *descriptor.FileDescriptorSet, messageName string) (schema bigquery.Schema, description string, err error) {
conv := schemaConverter{
desc: desc,
sourceCodeInfo: make(map[*descriptor.FileDescriptorProto]sourceCodeInfoMap, len(desc.File)),
}
for _, f := range desc.File {
conv.sourceCodeInfo[f], err = descutil.IndexSourceCodeInfo(f)
if err != nil {
return nil, "", errors.Annotate(err, "failed to index source code info in file %q", f.GetName()).Err()
}
}
return conv.schema(messageName)
} | [
"func",
"schemaFromMessage",
"(",
"desc",
"*",
"descriptor",
".",
"FileDescriptorSet",
",",
"messageName",
"string",
")",
"(",
"schema",
"bigquery",
".",
"Schema",
",",
"description",
"string",
",",
"err",
"error",
")",
"{",
"conv",
":=",
"schemaConverter",
"{... | // schemaFromMessage loads a message by name from .proto files in dir
// and converts the message to a bigquery schema. | [
"schemaFromMessage",
"loads",
"a",
"message",
"by",
"name",
"from",
".",
"proto",
"files",
"in",
"dir",
"and",
"converts",
"the",
"message",
"to",
"a",
"bigquery",
"schema",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/bqschemaupdater/main.go#L235-L247 |
7,312 | luci/luci-go | tools/cmd/bqschemaupdater/main.go | loadProtoDescription | func loadProtoDescription(dir string, importPaths []string) (*descriptor.FileDescriptorSet, error) {
dir, err := filepath.Abs(dir)
if err != nil {
return nil, errors.Annotate(err, "could make path %q absolute", dir).Err()
}
tempDir, err := ioutil.TempDir("", "")
if err != nil {
return nil, err
}
defer os.RemoveAll(tempDir)
descFile := filepath.Join(tempDir, "desc")
importPaths, err = protoImportPaths(dir, importPaths)
if err != nil {
return nil, err
}
args := []string{
"--descriptor_set_out=" + descFile,
"--include_imports",
"--include_source_info",
}
for _, p := range importPaths {
args = append(args, "-I="+p)
}
protoFiles, err := filepath.Glob(filepath.Join(dir, "*.proto"))
if err != nil {
return nil, err
}
if len(protoFiles) == 0 {
return nil, fmt.Errorf("no .proto files found in directory %q", dir)
}
args = append(args, protoFiles...)
protoc := exec.Command("protoc", args...)
protoc.Stderr = os.Stderr
if err := protoc.Run(); err != nil {
return nil, errors.Annotate(err, "protoc run failed").Err()
}
descBytes, err := ioutil.ReadFile(descFile)
if err != nil {
return nil, err
}
var desc descriptor.FileDescriptorSet
err = proto.Unmarshal(descBytes, &desc)
return &desc, err
} | go | func loadProtoDescription(dir string, importPaths []string) (*descriptor.FileDescriptorSet, error) {
dir, err := filepath.Abs(dir)
if err != nil {
return nil, errors.Annotate(err, "could make path %q absolute", dir).Err()
}
tempDir, err := ioutil.TempDir("", "")
if err != nil {
return nil, err
}
defer os.RemoveAll(tempDir)
descFile := filepath.Join(tempDir, "desc")
importPaths, err = protoImportPaths(dir, importPaths)
if err != nil {
return nil, err
}
args := []string{
"--descriptor_set_out=" + descFile,
"--include_imports",
"--include_source_info",
}
for _, p := range importPaths {
args = append(args, "-I="+p)
}
protoFiles, err := filepath.Glob(filepath.Join(dir, "*.proto"))
if err != nil {
return nil, err
}
if len(protoFiles) == 0 {
return nil, fmt.Errorf("no .proto files found in directory %q", dir)
}
args = append(args, protoFiles...)
protoc := exec.Command("protoc", args...)
protoc.Stderr = os.Stderr
if err := protoc.Run(); err != nil {
return nil, errors.Annotate(err, "protoc run failed").Err()
}
descBytes, err := ioutil.ReadFile(descFile)
if err != nil {
return nil, err
}
var desc descriptor.FileDescriptorSet
err = proto.Unmarshal(descBytes, &desc)
return &desc, err
} | [
"func",
"loadProtoDescription",
"(",
"dir",
"string",
",",
"importPaths",
"[",
"]",
"string",
")",
"(",
"*",
"descriptor",
".",
"FileDescriptorSet",
",",
"error",
")",
"{",
"dir",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"dir",
")",
"\n",
"if",
"... | // loadProtoDescription compiles .proto files in the dir
// and returns their descriptor. | [
"loadProtoDescription",
"compiles",
".",
"proto",
"files",
"in",
"the",
"dir",
"and",
"returns",
"their",
"descriptor",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/bqschemaupdater/main.go#L306-L354 |
7,313 | luci/luci-go | tools/cmd/bqschemaupdater/main.go | confirm | func confirm(action string) (response bool) {
fmt.Printf("%s? [y/N] ", action)
var res string
fmt.Scanln(&res)
return res == "y" || res == "Y"
} | go | func confirm(action string) (response bool) {
fmt.Printf("%s? [y/N] ", action)
var res string
fmt.Scanln(&res)
return res == "y" || res == "Y"
} | [
"func",
"confirm",
"(",
"action",
"string",
")",
"(",
"response",
"bool",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\"",
",",
"action",
")",
"\n",
"var",
"res",
"string",
"\n",
"fmt",
".",
"Scanln",
"(",
"&",
"res",
")",
"\n",
"return",
"res",
... | // confirm asks for a user confirmation for an action, with No as default.
// Only "y" or "Y" responses is treated as yes. | [
"confirm",
"asks",
"for",
"a",
"user",
"confirmation",
"for",
"an",
"action",
"with",
"No",
"as",
"default",
".",
"Only",
"y",
"or",
"Y",
"responses",
"is",
"treated",
"as",
"yes",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/bqschemaupdater/main.go#L366-L371 |
7,314 | luci/luci-go | cipd/appengine/impl/model/ref.go | Proto | func (e *Ref) Proto() *api.Ref {
return &api.Ref{
Name: e.Name,
Package: e.Package.StringID(),
Instance: common.InstanceIDToObjectRef(e.InstanceID),
ModifiedBy: e.ModifiedBy,
ModifiedTs: google.NewTimestamp(e.ModifiedTs),
}
} | go | func (e *Ref) Proto() *api.Ref {
return &api.Ref{
Name: e.Name,
Package: e.Package.StringID(),
Instance: common.InstanceIDToObjectRef(e.InstanceID),
ModifiedBy: e.ModifiedBy,
ModifiedTs: google.NewTimestamp(e.ModifiedTs),
}
} | [
"func",
"(",
"e",
"*",
"Ref",
")",
"Proto",
"(",
")",
"*",
"api",
".",
"Ref",
"{",
"return",
"&",
"api",
".",
"Ref",
"{",
"Name",
":",
"e",
".",
"Name",
",",
"Package",
":",
"e",
".",
"Package",
".",
"StringID",
"(",
")",
",",
"Instance",
":"... | // Proto returns cipd.Ref proto with information from this entity. | [
"Proto",
"returns",
"cipd",
".",
"Ref",
"proto",
"with",
"information",
"from",
"this",
"entity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/ref.go#L53-L61 |
7,315 | luci/luci-go | cipd/appengine/impl/model/ref.go | GetRef | func GetRef(c context.Context, pkg, ref string) (*Ref, error) {
r := &Ref{Name: ref, Package: PackageKey(c, pkg)}
switch err := datastore.Get(c, r); {
case err == datastore.ErrNoSuchEntity:
return nil, errors.Reason("no such ref").Tag(grpcutil.NotFoundTag).Err()
case err != nil:
return nil, errors.Annotate(err, "failed to fetch the ref").Tag(transient.Tag).Err()
}
return r, nil
} | go | func GetRef(c context.Context, pkg, ref string) (*Ref, error) {
r := &Ref{Name: ref, Package: PackageKey(c, pkg)}
switch err := datastore.Get(c, r); {
case err == datastore.ErrNoSuchEntity:
return nil, errors.Reason("no such ref").Tag(grpcutil.NotFoundTag).Err()
case err != nil:
return nil, errors.Annotate(err, "failed to fetch the ref").Tag(transient.Tag).Err()
}
return r, nil
} | [
"func",
"GetRef",
"(",
"c",
"context",
".",
"Context",
",",
"pkg",
",",
"ref",
"string",
")",
"(",
"*",
"Ref",
",",
"error",
")",
"{",
"r",
":=",
"&",
"Ref",
"{",
"Name",
":",
"ref",
",",
"Package",
":",
"PackageKey",
"(",
"c",
",",
"pkg",
")",... | // GetRef fetches the given ref.
//
// Returns gRPC-tagged NotFound error if there's no such ref. | [
"GetRef",
"fetches",
"the",
"given",
"ref",
".",
"Returns",
"gRPC",
"-",
"tagged",
"NotFound",
"error",
"if",
"there",
"s",
"no",
"such",
"ref",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/ref.go#L124-L133 |
7,316 | luci/luci-go | cipd/appengine/impl/model/ref.go | DeleteRef | func DeleteRef(c context.Context, pkg, ref string) error {
return Txn(c, "DeleteRef", func(c context.Context) error {
r, err := GetRef(c, pkg, ref)
switch {
case grpcutil.Code(err) == codes.NotFound:
return nil
case err != nil:
return err // transient
}
err = datastore.Delete(c, &Ref{
Name: ref,
Package: PackageKey(c, pkg),
})
if err != nil {
return transient.Tag.Apply(err)
}
return EmitEvent(c, &api.Event{
Kind: api.EventKind_INSTANCE_REF_UNSET,
Package: pkg,
Instance: r.InstanceID,
Ref: ref,
})
})
} | go | func DeleteRef(c context.Context, pkg, ref string) error {
return Txn(c, "DeleteRef", func(c context.Context) error {
r, err := GetRef(c, pkg, ref)
switch {
case grpcutil.Code(err) == codes.NotFound:
return nil
case err != nil:
return err // transient
}
err = datastore.Delete(c, &Ref{
Name: ref,
Package: PackageKey(c, pkg),
})
if err != nil {
return transient.Tag.Apply(err)
}
return EmitEvent(c, &api.Event{
Kind: api.EventKind_INSTANCE_REF_UNSET,
Package: pkg,
Instance: r.InstanceID,
Ref: ref,
})
})
} | [
"func",
"DeleteRef",
"(",
"c",
"context",
".",
"Context",
",",
"pkg",
",",
"ref",
"string",
")",
"error",
"{",
"return",
"Txn",
"(",
"c",
",",
"\"",
"\"",
",",
"func",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"r",
",",
"err",
":=",... | // DeleteRef removes the ref if it exists.
//
// Does nothing if there's no such ref or package. | [
"DeleteRef",
"removes",
"the",
"ref",
"if",
"it",
"exists",
".",
"Does",
"nothing",
"if",
"there",
"s",
"no",
"such",
"ref",
"or",
"package",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/ref.go#L138-L163 |
7,317 | luci/luci-go | cipd/appengine/impl/model/ref.go | ListPackageRefs | func ListPackageRefs(c context.Context, pkg string) (out []*Ref, err error) {
q := datastore.NewQuery("PackageRef").
Ancestor(PackageKey(c, pkg)).
Order("-modified_ts")
if err := datastore.GetAll(c, q, &out); err != nil {
return nil, errors.Annotate(err, "datastore query failed").Tag(transient.Tag).Err()
}
return
} | go | func ListPackageRefs(c context.Context, pkg string) (out []*Ref, err error) {
q := datastore.NewQuery("PackageRef").
Ancestor(PackageKey(c, pkg)).
Order("-modified_ts")
if err := datastore.GetAll(c, q, &out); err != nil {
return nil, errors.Annotate(err, "datastore query failed").Tag(transient.Tag).Err()
}
return
} | [
"func",
"ListPackageRefs",
"(",
"c",
"context",
".",
"Context",
",",
"pkg",
"string",
")",
"(",
"out",
"[",
"]",
"*",
"Ref",
",",
"err",
"error",
")",
"{",
"q",
":=",
"datastore",
".",
"NewQuery",
"(",
"\"",
"\"",
")",
".",
"Ancestor",
"(",
"Packag... | // ListPackageRefs returns all refs in a package, most recently modified first.
//
// Returns an empty list if there's no such package at all. | [
"ListPackageRefs",
"returns",
"all",
"refs",
"in",
"a",
"package",
"most",
"recently",
"modified",
"first",
".",
"Returns",
"an",
"empty",
"list",
"if",
"there",
"s",
"no",
"such",
"package",
"at",
"all",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/ref.go#L168-L176 |
7,318 | luci/luci-go | cipd/appengine/impl/model/ref.go | ListInstanceRefs | func ListInstanceRefs(c context.Context, inst *Instance) (out []*Ref, err error) {
if inst.Package == nil {
panic("bad Instance")
}
q := datastore.NewQuery("PackageRef").
Ancestor(inst.Package).
Eq("instance_id", inst.InstanceID).
Order("-modified_ts")
if err := datastore.GetAll(c, q, &out); err != nil {
return nil, errors.Annotate(err, "datastore query failed").Tag(transient.Tag).Err()
}
return
} | go | func ListInstanceRefs(c context.Context, inst *Instance) (out []*Ref, err error) {
if inst.Package == nil {
panic("bad Instance")
}
q := datastore.NewQuery("PackageRef").
Ancestor(inst.Package).
Eq("instance_id", inst.InstanceID).
Order("-modified_ts")
if err := datastore.GetAll(c, q, &out); err != nil {
return nil, errors.Annotate(err, "datastore query failed").Tag(transient.Tag).Err()
}
return
} | [
"func",
"ListInstanceRefs",
"(",
"c",
"context",
".",
"Context",
",",
"inst",
"*",
"Instance",
")",
"(",
"out",
"[",
"]",
"*",
"Ref",
",",
"err",
"error",
")",
"{",
"if",
"inst",
".",
"Package",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\... | // ListInstanceRefs returns all refs that point to a particular instance, most
// recently modified first.
//
// This is a subset of the output of ListPackageRefs for the corresponding
// package.
//
// Assumes 'inst' is a valid Instance, panics otherwise.
//
// Returns an empty list if there's no such instance at all. | [
"ListInstanceRefs",
"returns",
"all",
"refs",
"that",
"point",
"to",
"a",
"particular",
"instance",
"most",
"recently",
"modified",
"first",
".",
"This",
"is",
"a",
"subset",
"of",
"the",
"output",
"of",
"ListPackageRefs",
"for",
"the",
"corresponding",
"package... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/ref.go#L187-L199 |
7,319 | luci/luci-go | scheduler/appengine/engine/triage.go | prepare | func (op *triageOp) prepare(c context.Context) error {
op.started = clock.Now(c).UTC() // used to derive relative time in the debug log
op.debugInfoLog(c, "Starting")
op.finishedSet = recentlyFinishedSet(c, op.jobID)
op.triggersSet = pendingTriggersSet(c, op.jobID)
wg := sync.WaitGroup{}
wg.Add(2)
// Grab all pending triggers to decided what to do with them.
var triggersErr error
go func() {
defer wg.Done()
op.triggersList, op.readyTriggers, triggersErr = op.triggersSet.Triggers(c)
if triggersErr != nil {
op.debugErrLog(c, triggersErr, "Failed to grab pending triggers")
} else {
sortTriggers(op.readyTriggers)
}
}()
// Grab a list of recently finished invocations to remove them from
// ActiveInvocations list.
var finishedErr error
go func() {
defer wg.Done()
op.finishedList, finishedErr = op.finishedSet.List(c)
if finishedErr != nil {
op.debugErrLog(c, finishedErr, "Failed to grab recently finished invocations")
}
}()
wg.Wait()
if triggersErr != nil || finishedErr != nil {
return errTriagePrepareFail // the original error is already logged
}
op.debugInfoLog(c, "Pending triggers set: %d items, %d garbage", len(op.triggersList.Items), len(op.triggersList.Garbage))
op.debugInfoLog(c, "Recently finished set: %d items, %d garbage", len(op.finishedList.Items), len(op.finishedList.Garbage))
// Remove old tombstones to keep the set tidy. We fail hard here on errors to
// make sure progress stops if garbage can't be cleaned up for some reason.
// It is better to fail early rather than silently accumulate tons of garbage
// until everything grinds to a halt.
if err := dsset.CleanupGarbage(c, op.triggersList.Garbage, op.finishedList.Garbage); err != nil {
op.debugErrLog(c, err, "Failed to cleanup dsset garbage")
return err
}
// Log something mostly to capture the timestamp.
op.debugInfoLog(c, "The preparation is finished")
return nil
} | go | func (op *triageOp) prepare(c context.Context) error {
op.started = clock.Now(c).UTC() // used to derive relative time in the debug log
op.debugInfoLog(c, "Starting")
op.finishedSet = recentlyFinishedSet(c, op.jobID)
op.triggersSet = pendingTriggersSet(c, op.jobID)
wg := sync.WaitGroup{}
wg.Add(2)
// Grab all pending triggers to decided what to do with them.
var triggersErr error
go func() {
defer wg.Done()
op.triggersList, op.readyTriggers, triggersErr = op.triggersSet.Triggers(c)
if triggersErr != nil {
op.debugErrLog(c, triggersErr, "Failed to grab pending triggers")
} else {
sortTriggers(op.readyTriggers)
}
}()
// Grab a list of recently finished invocations to remove them from
// ActiveInvocations list.
var finishedErr error
go func() {
defer wg.Done()
op.finishedList, finishedErr = op.finishedSet.List(c)
if finishedErr != nil {
op.debugErrLog(c, finishedErr, "Failed to grab recently finished invocations")
}
}()
wg.Wait()
if triggersErr != nil || finishedErr != nil {
return errTriagePrepareFail // the original error is already logged
}
op.debugInfoLog(c, "Pending triggers set: %d items, %d garbage", len(op.triggersList.Items), len(op.triggersList.Garbage))
op.debugInfoLog(c, "Recently finished set: %d items, %d garbage", len(op.finishedList.Items), len(op.finishedList.Garbage))
// Remove old tombstones to keep the set tidy. We fail hard here on errors to
// make sure progress stops if garbage can't be cleaned up for some reason.
// It is better to fail early rather than silently accumulate tons of garbage
// until everything grinds to a halt.
if err := dsset.CleanupGarbage(c, op.triggersList.Garbage, op.finishedList.Garbage); err != nil {
op.debugErrLog(c, err, "Failed to cleanup dsset garbage")
return err
}
// Log something mostly to capture the timestamp.
op.debugInfoLog(c, "The preparation is finished")
return nil
} | [
"func",
"(",
"op",
"*",
"triageOp",
")",
"prepare",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"op",
".",
"started",
"=",
"clock",
".",
"Now",
"(",
"c",
")",
".",
"UTC",
"(",
")",
"// used to derive relative time in the debug log",
"\n",
"op... | // prepare fetches all pending triggers and events from dsset structs. | [
"prepare",
"fetches",
"all",
"pending",
"triggers",
"and",
"events",
"from",
"dsset",
"structs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/triage.go#L101-L154 |
7,320 | luci/luci-go | scheduler/appengine/engine/triage.go | debugErrLog | func (op *triageOp) debugErrLog(c context.Context, err error, format string, args ...interface{}) {
if err == nil {
logging.Errorf(c, format, args...)
op.appendToLog(c, fmt.Sprintf("Error: "+format, args...))
} else {
logging.WithError(err).Errorf(c, format, args...)
op.appendToLog(c, fmt.Sprintf("Error: "+format+" - %s", append(args, err)...))
}
} | go | func (op *triageOp) debugErrLog(c context.Context, err error, format string, args ...interface{}) {
if err == nil {
logging.Errorf(c, format, args...)
op.appendToLog(c, fmt.Sprintf("Error: "+format, args...))
} else {
logging.WithError(err).Errorf(c, format, args...)
op.appendToLog(c, fmt.Sprintf("Error: "+format+" - %s", append(args, err)...))
}
} | [
"func",
"(",
"op",
"*",
"triageOp",
")",
"debugErrLog",
"(",
"c",
"context",
".",
"Context",
",",
"err",
"error",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"logging",
".",
"Errorf",
... | // debugErrLog adds a line to the triage debug log and Errorf log. | [
"debugErrLog",
"adds",
"a",
"line",
"to",
"the",
"triage",
"debug",
"log",
"and",
"Errorf",
"log",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/triage.go#L270-L278 |
7,321 | luci/luci-go | scheduler/appengine/engine/triage.go | appendToLog | func (op *triageOp) appendToLog(c context.Context, msg string) {
const maxMessageCount = 1000
ms := clock.Now(c).Sub(op.started).Nanoseconds() / 1e6
op.debugLogLock.Lock()
if op.debugLogMsgs <= maxMessageCount {
if op.debugLogMsgs < maxMessageCount {
fmt.Fprintf(&op.debugLog, "[%03d ms] %s\n", ms, msg)
} else {
fmt.Fprintf(&op.debugLog, "<the log is too long, truncated here>")
}
op.debugLogMsgs++
}
op.debugLogLock.Unlock()
} | go | func (op *triageOp) appendToLog(c context.Context, msg string) {
const maxMessageCount = 1000
ms := clock.Now(c).Sub(op.started).Nanoseconds() / 1e6
op.debugLogLock.Lock()
if op.debugLogMsgs <= maxMessageCount {
if op.debugLogMsgs < maxMessageCount {
fmt.Fprintf(&op.debugLog, "[%03d ms] %s\n", ms, msg)
} else {
fmt.Fprintf(&op.debugLog, "<the log is too long, truncated here>")
}
op.debugLogMsgs++
}
op.debugLogLock.Unlock()
} | [
"func",
"(",
"op",
"*",
"triageOp",
")",
"appendToLog",
"(",
"c",
"context",
".",
"Context",
",",
"msg",
"string",
")",
"{",
"const",
"maxMessageCount",
"=",
"1000",
"\n\n",
"ms",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
".",
"Sub",
"(",
"op",
"."... | // appendToLog adds a line to the debug log, prefixing it with current time. | [
"appendToLog",
"adds",
"a",
"line",
"to",
"the",
"debug",
"log",
"prefixing",
"it",
"with",
"current",
"time",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/triage.go#L281-L296 |
7,322 | luci/luci-go | scheduler/appengine/engine/triage.go | tidyActiveInvocations | func (op *triageOp) tidyActiveInvocations(c context.Context, job *Job) (*dsset.PopOp, error) {
now := clock.Now(c).UTC()
// Deserialize the list of recently finished invocations, as stored in the
// entity. Discard old items right away. If it is broken, log, but proceed.
// It is ~OK to loose it (this will temporary cause some API calls to return
// incomplete data).
finishedRecord, err := filteredFinishedInvs(
job.FinishedInvocationsRaw, now.Add(-FinishedInvocationsHorizon))
if err != nil {
op.debugErrLog(c, err, "Failed to unmarshal FinishedInvocationsRaw, skipping")
}
// Note that per dsset API we need to do BeginPop if there's some garbage,
// even if Items is empty. We can skip this if both lists are empty though.
var popOp *dsset.PopOp
if len(op.finishedList.Items) != 0 || len(op.finishedList.Garbage) != 0 {
popOp, err = op.finishedSet.BeginPop(c, op.finishedList)
if err != nil {
op.debugErrLog(c, err, "Failed to pop from finished invocations set")
return nil, err
}
// Items can have IDs popped by some other transaction already. Collect
// only ones consumed by us here.
reallyFinished := make(map[int64]struct{}, len(op.finishedList.Items))
for _, itm := range op.finishedList.Items {
if popOp.Pop(itm.ID) {
reallyFinished[op.finishedSet.ItemToInvID(&itm)] = struct{}{}
}
}
// Remove IDs of all finished invocations from ActiveInvocations list,
// preserving the order, and add them to the finished invocations list.
if len(reallyFinished) != 0 {
filtered := make([]int64, 0, len(job.ActiveInvocations))
for _, id := range job.ActiveInvocations {
if _, yep := reallyFinished[id]; !yep {
filtered = append(filtered, id) // still running
continue
}
op.debugInfoLog(c, "Invocation %d is acknowledged as finished", id)
finishedRecord = append(finishedRecord, &internal.FinishedInvocation{
InvocationId: id,
Finished: google.NewTimestamp(now),
})
}
job.ActiveInvocations = filtered
}
}
// Marshal back FinishedInvocationsRaw after it has been updated.
job.FinishedInvocationsRaw = marshalFinishedInvs(finishedRecord)
// Log summary.
op.debugInfoLog(c, "Number of active invocations: %d", len(job.ActiveInvocations))
op.debugInfoLog(c, "Number of recently finished: %d", len(finishedRecord))
return popOp, nil
} | go | func (op *triageOp) tidyActiveInvocations(c context.Context, job *Job) (*dsset.PopOp, error) {
now := clock.Now(c).UTC()
// Deserialize the list of recently finished invocations, as stored in the
// entity. Discard old items right away. If it is broken, log, but proceed.
// It is ~OK to loose it (this will temporary cause some API calls to return
// incomplete data).
finishedRecord, err := filteredFinishedInvs(
job.FinishedInvocationsRaw, now.Add(-FinishedInvocationsHorizon))
if err != nil {
op.debugErrLog(c, err, "Failed to unmarshal FinishedInvocationsRaw, skipping")
}
// Note that per dsset API we need to do BeginPop if there's some garbage,
// even if Items is empty. We can skip this if both lists are empty though.
var popOp *dsset.PopOp
if len(op.finishedList.Items) != 0 || len(op.finishedList.Garbage) != 0 {
popOp, err = op.finishedSet.BeginPop(c, op.finishedList)
if err != nil {
op.debugErrLog(c, err, "Failed to pop from finished invocations set")
return nil, err
}
// Items can have IDs popped by some other transaction already. Collect
// only ones consumed by us here.
reallyFinished := make(map[int64]struct{}, len(op.finishedList.Items))
for _, itm := range op.finishedList.Items {
if popOp.Pop(itm.ID) {
reallyFinished[op.finishedSet.ItemToInvID(&itm)] = struct{}{}
}
}
// Remove IDs of all finished invocations from ActiveInvocations list,
// preserving the order, and add them to the finished invocations list.
if len(reallyFinished) != 0 {
filtered := make([]int64, 0, len(job.ActiveInvocations))
for _, id := range job.ActiveInvocations {
if _, yep := reallyFinished[id]; !yep {
filtered = append(filtered, id) // still running
continue
}
op.debugInfoLog(c, "Invocation %d is acknowledged as finished", id)
finishedRecord = append(finishedRecord, &internal.FinishedInvocation{
InvocationId: id,
Finished: google.NewTimestamp(now),
})
}
job.ActiveInvocations = filtered
}
}
// Marshal back FinishedInvocationsRaw after it has been updated.
job.FinishedInvocationsRaw = marshalFinishedInvs(finishedRecord)
// Log summary.
op.debugInfoLog(c, "Number of active invocations: %d", len(job.ActiveInvocations))
op.debugInfoLog(c, "Number of recently finished: %d", len(finishedRecord))
return popOp, nil
} | [
"func",
"(",
"op",
"*",
"triageOp",
")",
"tidyActiveInvocations",
"(",
"c",
"context",
".",
"Context",
",",
"job",
"*",
"Job",
")",
"(",
"*",
"dsset",
".",
"PopOp",
",",
"error",
")",
"{",
"now",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
".",
"UT... | // tidyActiveInvocations removes finished invocations from ActiveInvocations,
// and adds them to FinishedInvocations.
//
// Called within a transaction. Mutates job. Returns an open dsset.PopOp that
// must be eventually submitted with dsset.FinishPop. | [
"tidyActiveInvocations",
"removes",
"finished",
"invocations",
"from",
"ActiveInvocations",
"and",
"adds",
"them",
"to",
"FinishedInvocations",
".",
"Called",
"within",
"a",
"transaction",
".",
"Mutates",
"job",
".",
"Returns",
"an",
"open",
"dsset",
".",
"PopOp",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/triage.go#L303-L362 |
7,323 | luci/luci-go | scheduler/appengine/engine/triage.go | processTriggers | func (op *triageOp) processTriggers(c context.Context, job *Job) (*dsset.PopOp, error) {
popOp, err := op.triggersSet.BeginPop(c, op.triggersList)
if err != nil {
op.debugErrLog(c, err, "Failed to pop from pending triggers set")
return nil, err
}
// Filter out all triggers already popped by some other transaction.
triggers := make([]*internal.Trigger, 0, len(op.readyTriggers))
for _, t := range op.readyTriggers {
if popOp.CanPop(t.Id) {
triggers = append(triggers, t)
}
}
op.debugInfoLog(c, "Triggers available in this txn: %d", len(triggers))
// If the job is paused or disabled, just pop all triggers without starting
// anything. Note: there's a best-effort shortcut for ignoring triggers
// for paused jobs in execEnqueueTriggersTask.
if len(triggers) != 0 {
if job.Paused || !job.Enabled {
op.debugInfoLog(c, "The job is inactive, clearing the pending triggers queue")
for _, t := range triggers {
popOp.Pop(t.Id)
}
return popOp, nil
}
}
// Keep the set of pending triggers bounded, to avoid total meltdown caused
// by slow triage transactions.
if len(triggers) > op.maxAllowedTriggers {
dropping := len(triggers) - op.maxAllowedTriggers
op.debugErrLog(c, nil, "Too many pending triggers (>%d), dropping %d oldest", op.maxAllowedTriggers, dropping)
for i := 0; i < dropping; i++ {
popOp.Pop(triggers[i].Id)
}
triggers = triggers[dropping:]
}
// Ask the policy to convert triggers into invocations. Note that triggers is
// not the only input to the triggering policy, so we call it on each triage,
// even if there's no pending triggers.
op.debugInfoLog(c, "Invoking the triggering policy function")
out := op.triggeringPolicy(c, job, triggers)
op.debugInfoLog(c, "The policy requested %d new invocations", len(out.Requests))
// Actually pop all consumed triggers and start the corresponding invocations.
// Note that this modifies job.ActiveInvocations list.
if len(out.Requests) != 0 {
consumed := 0
for _, r := range out.Requests {
for _, t := range r.IncomingTriggers {
popOp.Pop(t.Id)
}
consumed += len(r.IncomingTriggers)
}
if err := op.enqueueInvocations(c, job, out.Requests); err != nil {
op.debugErrLog(c, err, "Failed to enqueue some invocations")
return nil, err
}
op.debugInfoLog(c, "New invocations enqueued, consumed %d triggers", consumed)
}
return popOp, nil
} | go | func (op *triageOp) processTriggers(c context.Context, job *Job) (*dsset.PopOp, error) {
popOp, err := op.triggersSet.BeginPop(c, op.triggersList)
if err != nil {
op.debugErrLog(c, err, "Failed to pop from pending triggers set")
return nil, err
}
// Filter out all triggers already popped by some other transaction.
triggers := make([]*internal.Trigger, 0, len(op.readyTriggers))
for _, t := range op.readyTriggers {
if popOp.CanPop(t.Id) {
triggers = append(triggers, t)
}
}
op.debugInfoLog(c, "Triggers available in this txn: %d", len(triggers))
// If the job is paused or disabled, just pop all triggers without starting
// anything. Note: there's a best-effort shortcut for ignoring triggers
// for paused jobs in execEnqueueTriggersTask.
if len(triggers) != 0 {
if job.Paused || !job.Enabled {
op.debugInfoLog(c, "The job is inactive, clearing the pending triggers queue")
for _, t := range triggers {
popOp.Pop(t.Id)
}
return popOp, nil
}
}
// Keep the set of pending triggers bounded, to avoid total meltdown caused
// by slow triage transactions.
if len(triggers) > op.maxAllowedTriggers {
dropping := len(triggers) - op.maxAllowedTriggers
op.debugErrLog(c, nil, "Too many pending triggers (>%d), dropping %d oldest", op.maxAllowedTriggers, dropping)
for i := 0; i < dropping; i++ {
popOp.Pop(triggers[i].Id)
}
triggers = triggers[dropping:]
}
// Ask the policy to convert triggers into invocations. Note that triggers is
// not the only input to the triggering policy, so we call it on each triage,
// even if there's no pending triggers.
op.debugInfoLog(c, "Invoking the triggering policy function")
out := op.triggeringPolicy(c, job, triggers)
op.debugInfoLog(c, "The policy requested %d new invocations", len(out.Requests))
// Actually pop all consumed triggers and start the corresponding invocations.
// Note that this modifies job.ActiveInvocations list.
if len(out.Requests) != 0 {
consumed := 0
for _, r := range out.Requests {
for _, t := range r.IncomingTriggers {
popOp.Pop(t.Id)
}
consumed += len(r.IncomingTriggers)
}
if err := op.enqueueInvocations(c, job, out.Requests); err != nil {
op.debugErrLog(c, err, "Failed to enqueue some invocations")
return nil, err
}
op.debugInfoLog(c, "New invocations enqueued, consumed %d triggers", consumed)
}
return popOp, nil
} | [
"func",
"(",
"op",
"*",
"triageOp",
")",
"processTriggers",
"(",
"c",
"context",
".",
"Context",
",",
"job",
"*",
"Job",
")",
"(",
"*",
"dsset",
".",
"PopOp",
",",
"error",
")",
"{",
"popOp",
",",
"err",
":=",
"op",
".",
"triggersSet",
".",
"BeginP... | // processTriggers pops pending triggers, converting them into invocations. | [
"processTriggers",
"pops",
"pending",
"triggers",
"converting",
"them",
"into",
"invocations",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/triage.go#L365-L430 |
7,324 | luci/luci-go | scheduler/appengine/engine/triage.go | triggeringPolicy | func (op *triageOp) triggeringPolicy(c context.Context, job *Job, triggers []*internal.Trigger) policy.Out {
var policyFunc policy.Func
p, err := policy.UnmarshalDefinition(job.TriggeringPolicyRaw)
if err == nil {
policyFunc, err = op.policyFactory(p)
}
if err != nil {
op.debugErrLog(c, err, "Failed to instantiate the triggering policy function, using the default policy instead")
policyFunc = policy.Default()
}
return policyFunc(policyFuncEnv{c, op}, policy.In{
Now: clock.Now(c).UTC(),
ActiveInvocations: job.ActiveInvocations,
Triggers: triggers,
})
} | go | func (op *triageOp) triggeringPolicy(c context.Context, job *Job, triggers []*internal.Trigger) policy.Out {
var policyFunc policy.Func
p, err := policy.UnmarshalDefinition(job.TriggeringPolicyRaw)
if err == nil {
policyFunc, err = op.policyFactory(p)
}
if err != nil {
op.debugErrLog(c, err, "Failed to instantiate the triggering policy function, using the default policy instead")
policyFunc = policy.Default()
}
return policyFunc(policyFuncEnv{c, op}, policy.In{
Now: clock.Now(c).UTC(),
ActiveInvocations: job.ActiveInvocations,
Triggers: triggers,
})
} | [
"func",
"(",
"op",
"*",
"triageOp",
")",
"triggeringPolicy",
"(",
"c",
"context",
".",
"Context",
",",
"job",
"*",
"Job",
",",
"triggers",
"[",
"]",
"*",
"internal",
".",
"Trigger",
")",
"policy",
".",
"Out",
"{",
"var",
"policyFunc",
"policy",
".",
... | // triggeringPolicy decides how to convert a set of pending triggers into
// a bunch of new invocations.
//
// Called within a job transaction. Must not do any expensive calls. | [
"triggeringPolicy",
"decides",
"how",
"to",
"convert",
"a",
"set",
"of",
"pending",
"triggers",
"into",
"a",
"bunch",
"of",
"new",
"invocations",
".",
"Called",
"within",
"a",
"job",
"transaction",
".",
"Must",
"not",
"do",
"any",
"expensive",
"calls",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/triage.go#L436-L451 |
7,325 | luci/luci-go | common/sync/cancelcond/cancelCond.go | New | func New(l sync.Locker) *Cond {
return &Cond{
Cond: sync.NewCond(l),
}
} | go | func New(l sync.Locker) *Cond {
return &Cond{
Cond: sync.NewCond(l),
}
} | [
"func",
"New",
"(",
"l",
"sync",
".",
"Locker",
")",
"*",
"Cond",
"{",
"return",
"&",
"Cond",
"{",
"Cond",
":",
"sync",
".",
"NewCond",
"(",
"l",
")",
",",
"}",
"\n",
"}"
] | // New creates a new Context-cancellable Cond. | [
"New",
"creates",
"a",
"new",
"Context",
"-",
"cancellable",
"Cond",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/cancelcond/cancelCond.go#L31-L35 |
7,326 | luci/luci-go | config/appengine/gaeconfig/default.go | UseFlex | func UseFlex(c context.Context) context.Context {
// TODO: Install a path to load configurations from datastore cache. ATM,
// it can't be done because using datastore cache requires the ability to
// write to datastore.
ccfg := cacheConfig{
GlobalCache: func(c context.Context, be backend.B, s *Settings) backend.B {
return caching.LRUBackend(be, configProcCache.LRU(c), s.CacheExpiration())
},
}
return installConfigBackend(c, mustFetchCachedSettings(c), nil, ccfg)
} | go | func UseFlex(c context.Context) context.Context {
// TODO: Install a path to load configurations from datastore cache. ATM,
// it can't be done because using datastore cache requires the ability to
// write to datastore.
ccfg := cacheConfig{
GlobalCache: func(c context.Context, be backend.B, s *Settings) backend.B {
return caching.LRUBackend(be, configProcCache.LRU(c), s.CacheExpiration())
},
}
return installConfigBackend(c, mustFetchCachedSettings(c), nil, ccfg)
} | [
"func",
"UseFlex",
"(",
"c",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"// TODO: Install a path to load configurations from datastore cache. ATM,",
"// it can't be done because using datastore cache requires the ability to",
"// write to datastore.",
"ccfg",
":=... | // UseFlex installs the default luci-config client for an AppEngine Flex
// environment.
//
// UseFlex has the same effect as Use, except that the backing cache is
// a process-local cache instead of the AppEngine memcache service. | [
"UseFlex",
"installs",
"the",
"default",
"luci",
"-",
"config",
"client",
"for",
"an",
"AppEngine",
"Flex",
"environment",
".",
"UseFlex",
"has",
"the",
"same",
"effect",
"as",
"Use",
"except",
"that",
"the",
"backing",
"cache",
"is",
"a",
"process",
"-",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/gaeconfig/default.go#L162-L172 |
7,327 | luci/luci-go | config/appengine/gaeconfig/default.go | devServerBackend | func devServerBackend() backend.B {
pwd := os.Getenv("PWD") // os.Getwd works funny with symlinks, use PWD
candidates := []string{
filepath.Join(pwd, devCfgDir),
filepath.Join(filepath.Dir(pwd), devCfgDir),
}
for _, dir := range candidates {
if _, err := os.Stat(dir); err == nil {
fs, err := filesystem.New(dir)
if err != nil {
return erroring.New(err)
}
return &client.Backend{&testconfig.Provider{
Base: fs,
}}
}
}
return erroring.New(fmt.Errorf("luci-config: could not find local configs in any of %s", candidates))
} | go | func devServerBackend() backend.B {
pwd := os.Getenv("PWD") // os.Getwd works funny with symlinks, use PWD
candidates := []string{
filepath.Join(pwd, devCfgDir),
filepath.Join(filepath.Dir(pwd), devCfgDir),
}
for _, dir := range candidates {
if _, err := os.Stat(dir); err == nil {
fs, err := filesystem.New(dir)
if err != nil {
return erroring.New(err)
}
return &client.Backend{&testconfig.Provider{
Base: fs,
}}
}
}
return erroring.New(fmt.Errorf("luci-config: could not find local configs in any of %s", candidates))
} | [
"func",
"devServerBackend",
"(",
")",
"backend",
".",
"B",
"{",
"pwd",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"// os.Getwd works funny with symlinks, use PWD",
"\n",
"candidates",
":=",
"[",
"]",
"string",
"{",
"filepath",
".",
"Join",
"(",
"pwd",
... | // devServerConfig returns backend.B to use on a devserver.
//
// See New for details. | [
"devServerConfig",
"returns",
"backend",
".",
"B",
"to",
"use",
"on",
"a",
"devserver",
".",
"See",
"New",
"for",
"details",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/gaeconfig/default.go#L247-L265 |
7,328 | luci/luci-go | client/isolated/archive.go | Archive | func Archive(ctx context.Context, arch *archiver.Archiver, opts *ArchiveOptions) *archiver.PendingItem {
item, err := archive(ctx, arch, opts)
if err != nil {
i := &archiver.PendingItem{DisplayName: opts.Isolated}
i.SetErr(err)
return i
}
return item
} | go | func Archive(ctx context.Context, arch *archiver.Archiver, opts *ArchiveOptions) *archiver.PendingItem {
item, err := archive(ctx, arch, opts)
if err != nil {
i := &archiver.PendingItem{DisplayName: opts.Isolated}
i.SetErr(err)
return i
}
return item
} | [
"func",
"Archive",
"(",
"ctx",
"context",
".",
"Context",
",",
"arch",
"*",
"archiver",
".",
"Archiver",
",",
"opts",
"*",
"ArchiveOptions",
")",
"*",
"archiver",
".",
"PendingItem",
"{",
"item",
",",
"err",
":=",
"archive",
"(",
"ctx",
",",
"arch",
",... | // Archive uses the given archiver and options to constructed an isolated file, and
// uploads it and its dependencies.
//
// Archive returns the digest of the composite isolated file. | [
"Archive",
"uses",
"the",
"given",
"archiver",
"and",
"options",
"to",
"constructed",
"an",
"isolated",
"file",
"and",
"uploads",
"it",
"and",
"its",
"dependencies",
".",
"Archive",
"returns",
"the",
"digest",
"of",
"the",
"composite",
"isolated",
"file",
"."
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolated/archive.go#L65-L73 |
7,329 | luci/luci-go | logdog/appengine/coordinator/endpoints/services/service.go | maybeEnterProjectNamespace | func maybeEnterProjectNamespace(c context.Context, req proto.Message) (context.Context, error) {
if pbm, ok := req.(endpoints.ProjectBoundMessage); ok {
project := types.ProjectName(pbm.GetMessageProject())
log.Fields{
"project": project,
}.Debugf(c, "Request is entering project namespace.")
if err := coordinator.WithProjectNamespace(&c, project, coordinator.NamespaceAccessNoAuth); err != nil {
return c, err
}
}
return c, nil
} | go | func maybeEnterProjectNamespace(c context.Context, req proto.Message) (context.Context, error) {
if pbm, ok := req.(endpoints.ProjectBoundMessage); ok {
project := types.ProjectName(pbm.GetMessageProject())
log.Fields{
"project": project,
}.Debugf(c, "Request is entering project namespace.")
if err := coordinator.WithProjectNamespace(&c, project, coordinator.NamespaceAccessNoAuth); err != nil {
return c, err
}
}
return c, nil
} | [
"func",
"maybeEnterProjectNamespace",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"proto",
".",
"Message",
")",
"(",
"context",
".",
"Context",
",",
"error",
")",
"{",
"if",
"pbm",
",",
"ok",
":=",
"req",
".",
"(",
"endpoints",
".",
"ProjectBoundMes... | // maybeEnterProjectNamespace enters a datastore namespace based on the request
// message type. | [
"maybeEnterProjectNamespace",
"enters",
"a",
"datastore",
"namespace",
"based",
"on",
"the",
"request",
"message",
"type",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/service.go#L57-L68 |
7,330 | luci/luci-go | dm/appengine/model/backdep.go | Edge | func (b *BackDep) Edge() *FwdEdge {
ret := &FwdEdge{From: &b.Depender, To: &dm.Attempt_ID{}}
if err := ret.To.SetDMEncoded(b.DependeeGroup.StringID()); err != nil {
panic(err)
}
return ret
} | go | func (b *BackDep) Edge() *FwdEdge {
ret := &FwdEdge{From: &b.Depender, To: &dm.Attempt_ID{}}
if err := ret.To.SetDMEncoded(b.DependeeGroup.StringID()); err != nil {
panic(err)
}
return ret
} | [
"func",
"(",
"b",
"*",
"BackDep",
")",
"Edge",
"(",
")",
"*",
"FwdEdge",
"{",
"ret",
":=",
"&",
"FwdEdge",
"{",
"From",
":",
"&",
"b",
".",
"Depender",
",",
"To",
":",
"&",
"dm",
".",
"Attempt_ID",
"{",
"}",
"}",
"\n",
"if",
"err",
":=",
"ret... | // Edge produces a fwdedge object which points from the depending attempt to
// the depended-on attempt. | [
"Edge",
"produces",
"a",
"fwdedge",
"object",
"which",
"points",
"from",
"the",
"depending",
"attempt",
"to",
"the",
"depended",
"-",
"on",
"attempt",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/backdep.go#L67-L73 |
7,331 | luci/luci-go | lucicfg/cli/app.go | Main | func Main(params base.Parameters, args []string) int {
// Enable not-yet-standard Starlark features.
resolve.AllowLambda = true
resolve.AllowNestedDef = true
resolve.AllowFloat = true
resolve.AllowSet = true
// A hack to allow '#!/usr/bin/env lucicfg'. On Linux the shebang line can
// have at most two arguments, so we can't use '#!/usr/bin/env lucicfg gen'.
if len(args) == 1 {
if _, err := os.Stat(args[0]); err == nil {
args = []string{"generate", args[0]}
}
}
return subcommands.Run(GetApplication(params), fixflagpos.FixSubcommands(args))
} | go | func Main(params base.Parameters, args []string) int {
// Enable not-yet-standard Starlark features.
resolve.AllowLambda = true
resolve.AllowNestedDef = true
resolve.AllowFloat = true
resolve.AllowSet = true
// A hack to allow '#!/usr/bin/env lucicfg'. On Linux the shebang line can
// have at most two arguments, so we can't use '#!/usr/bin/env lucicfg gen'.
if len(args) == 1 {
if _, err := os.Stat(args[0]); err == nil {
args = []string{"generate", args[0]}
}
}
return subcommands.Run(GetApplication(params), fixflagpos.FixSubcommands(args))
} | [
"func",
"Main",
"(",
"params",
"base",
".",
"Parameters",
",",
"args",
"[",
"]",
"string",
")",
"int",
"{",
"// Enable not-yet-standard Starlark features.",
"resolve",
".",
"AllowLambda",
"=",
"true",
"\n",
"resolve",
".",
"AllowNestedDef",
"=",
"true",
"\n",
... | // Main runs the lucicfg CLI. | [
"Main",
"runs",
"the",
"lucicfg",
"CLI",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/cli/app.go#L39-L55 |
7,332 | luci/luci-go | lucicfg/cli/app.go | GetApplication | func GetApplication(params base.Parameters) *cli.Application {
return &cli.Application{
Name: "lucicfg",
Title: "LUCI config generator (" + lucicfg.UserAgent + ")",
Context: func(ctx context.Context) context.Context {
loggerConfig := gologger.LoggerConfig{
Format: `[P%{pid} %{time:15:04:05.000} %{shortfile} %{level:.1s}] %{message}`,
Out: os.Stderr,
}
return loggerConfig.Use(ctx)
},
Commands: []*subcommands.Command{
subcommands.Section("Config generation\n"),
generate.Cmd(params),
validate.Cmd(params),
subcommands.Section("Aiding in the migration\n"),
diff.Cmd(params),
subcommands.Section("Authentication for LUCI Config\n"),
authcli.SubcommandInfo(params.AuthOptions, "auth-info", true),
authcli.SubcommandLogin(params.AuthOptions, "auth-login", false),
authcli.SubcommandLogout(params.AuthOptions, "auth-logout", false),
subcommands.Section("Misc\n"),
subcommands.CmdHelp,
versioncli.CmdVersion(lucicfg.UserAgent),
},
}
} | go | func GetApplication(params base.Parameters) *cli.Application {
return &cli.Application{
Name: "lucicfg",
Title: "LUCI config generator (" + lucicfg.UserAgent + ")",
Context: func(ctx context.Context) context.Context {
loggerConfig := gologger.LoggerConfig{
Format: `[P%{pid} %{time:15:04:05.000} %{shortfile} %{level:.1s}] %{message}`,
Out: os.Stderr,
}
return loggerConfig.Use(ctx)
},
Commands: []*subcommands.Command{
subcommands.Section("Config generation\n"),
generate.Cmd(params),
validate.Cmd(params),
subcommands.Section("Aiding in the migration\n"),
diff.Cmd(params),
subcommands.Section("Authentication for LUCI Config\n"),
authcli.SubcommandInfo(params.AuthOptions, "auth-info", true),
authcli.SubcommandLogin(params.AuthOptions, "auth-login", false),
authcli.SubcommandLogout(params.AuthOptions, "auth-logout", false),
subcommands.Section("Misc\n"),
subcommands.CmdHelp,
versioncli.CmdVersion(lucicfg.UserAgent),
},
}
} | [
"func",
"GetApplication",
"(",
"params",
"base",
".",
"Parameters",
")",
"*",
"cli",
".",
"Application",
"{",
"return",
"&",
"cli",
".",
"Application",
"{",
"Name",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
"+",
"lucicfg",
".",
"UserAgent",
"+",
... | // GetApplication returns lucicfg cli.Application. | [
"GetApplication",
"returns",
"lucicfg",
"cli",
".",
"Application",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/cli/app.go#L58-L89 |
7,333 | luci/luci-go | server/auth/openid/cookie.go | makeSessionCookie | func makeSessionCookie(c context.Context, sid string, secure bool) (*http.Cookie, error) {
tok, err := sessionCookieToken.Generate(c, nil, map[string]string{"sid": sid}, 0)
if err != nil {
return nil, err
}
// Make cookie expire a bit earlier, to avoid weird "bad token" errors if
// clocks are out of sync.
exp := sessionCookieToken.Expiration - 15*time.Minute
return &http.Cookie{
Name: sessionCookieName,
Value: tok,
Path: "/",
Secure: secure,
HttpOnly: true, // no access from Javascript
Expires: clock.Now(c).Add(exp),
MaxAge: int(exp / time.Second),
}, nil
} | go | func makeSessionCookie(c context.Context, sid string, secure bool) (*http.Cookie, error) {
tok, err := sessionCookieToken.Generate(c, nil, map[string]string{"sid": sid}, 0)
if err != nil {
return nil, err
}
// Make cookie expire a bit earlier, to avoid weird "bad token" errors if
// clocks are out of sync.
exp := sessionCookieToken.Expiration - 15*time.Minute
return &http.Cookie{
Name: sessionCookieName,
Value: tok,
Path: "/",
Secure: secure,
HttpOnly: true, // no access from Javascript
Expires: clock.Now(c).Add(exp),
MaxAge: int(exp / time.Second),
}, nil
} | [
"func",
"makeSessionCookie",
"(",
"c",
"context",
".",
"Context",
",",
"sid",
"string",
",",
"secure",
"bool",
")",
"(",
"*",
"http",
".",
"Cookie",
",",
"error",
")",
"{",
"tok",
",",
"err",
":=",
"sessionCookieToken",
".",
"Generate",
"(",
"c",
",",
... | // makeSessionCookie takes a session ID and makes a signed cookie that can be
// put in a response. | [
"makeSessionCookie",
"takes",
"a",
"session",
"ID",
"and",
"makes",
"a",
"signed",
"cookie",
"that",
"can",
"be",
"put",
"in",
"a",
"response",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/cookie.go#L41-L58 |
7,334 | luci/luci-go | server/auth/openid/cookie.go | decodeSessionCookie | func decodeSessionCookie(c context.Context, r *http.Request) (string, error) {
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
return "", nil // no such cookie
}
payload, err := sessionCookieToken.Validate(c, cookie.Value, nil)
switch {
case transient.Tag.In(err):
return "", err
case err != nil:
logging.Warningf(c, "Failed to decode session cookie %q: %s", cookie.Value, err)
return "", nil
case payload["sid"] == "":
logging.Warningf(c, "No 'sid' key in cookie payload %v", payload)
return "", nil
}
return payload["sid"], nil
} | go | func decodeSessionCookie(c context.Context, r *http.Request) (string, error) {
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
return "", nil // no such cookie
}
payload, err := sessionCookieToken.Validate(c, cookie.Value, nil)
switch {
case transient.Tag.In(err):
return "", err
case err != nil:
logging.Warningf(c, "Failed to decode session cookie %q: %s", cookie.Value, err)
return "", nil
case payload["sid"] == "":
logging.Warningf(c, "No 'sid' key in cookie payload %v", payload)
return "", nil
}
return payload["sid"], nil
} | [
"func",
"decodeSessionCookie",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"sessionCookieName",
")",
"\n",
"if",
"err",
"... | // decodeSessionCookie takes an incoming request and returns a session ID stored
// in a session cookie, or "" if not there, invalid or expired. Returns errors
// on transient errors only. | [
"decodeSessionCookie",
"takes",
"an",
"incoming",
"request",
"and",
"returns",
"a",
"session",
"ID",
"stored",
"in",
"a",
"session",
"cookie",
"or",
"if",
"not",
"there",
"invalid",
"or",
"expired",
".",
"Returns",
"errors",
"on",
"transient",
"errors",
"only"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/cookie.go#L63-L80 |
7,335 | luci/luci-go | grpc/discovery/discovery.go | Enable | func Enable(server *prpc.Server) {
serviceNames := append(server.ServiceNames(), "discovery.Discovery")
service, err := New(serviceNames...)
if err != nil {
panic(err)
}
RegisterDiscoveryServer(server, service)
} | go | func Enable(server *prpc.Server) {
serviceNames := append(server.ServiceNames(), "discovery.Discovery")
service, err := New(serviceNames...)
if err != nil {
panic(err)
}
RegisterDiscoveryServer(server, service)
} | [
"func",
"Enable",
"(",
"server",
"*",
"prpc",
".",
"Server",
")",
"{",
"serviceNames",
":=",
"append",
"(",
"server",
".",
"ServiceNames",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"service",
",",
"err",
":=",
"New",
"(",
"serviceNames",
"...",
")",
"\n"... | // Enable registers a discovery service on the server.
// It makes all currently registered services and the discovery service
// discoverable. | [
"Enable",
"registers",
"a",
"discovery",
"service",
"on",
"the",
"server",
".",
"It",
"makes",
"all",
"currently",
"registered",
"services",
"and",
"the",
"discovery",
"service",
"discoverable",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/discovery/discovery.go#L48-L55 |
7,336 | luci/luci-go | grpc/discovery/discovery.go | combineDescriptors | func combineDescriptors(serviceNames []string) (*descriptor.FileDescriptorSet, error) {
result := &descriptor.FileDescriptorSet{}
// seenFiles is a set of descriptor files keyed by SHA256 of their contents.
seenFiles := map[[sha256.Size]byte]bool{}
for _, s := range serviceNames {
desc, err := GetDescriptorSet(s)
if err != nil {
return nil, fmt.Errorf("service %s: %s", s, err)
}
if desc == nil {
return nil, fmt.Errorf(
"descriptor for service %q is not found. "+
"Did you compile it with go.chromium.org/luci/grpc/cmd/cproto?",
s)
}
for _, f := range desc.GetFile() {
binary, err := proto.Marshal(f)
if err != nil {
return nil, fmt.Errorf("could not marshal description of %s", f.GetName())
}
hash := sha256.Sum256(binary)
if !seenFiles[hash] {
result.File = append(result.File, f)
seenFiles[hash] = true
}
}
}
return result, nil
} | go | func combineDescriptors(serviceNames []string) (*descriptor.FileDescriptorSet, error) {
result := &descriptor.FileDescriptorSet{}
// seenFiles is a set of descriptor files keyed by SHA256 of their contents.
seenFiles := map[[sha256.Size]byte]bool{}
for _, s := range serviceNames {
desc, err := GetDescriptorSet(s)
if err != nil {
return nil, fmt.Errorf("service %s: %s", s, err)
}
if desc == nil {
return nil, fmt.Errorf(
"descriptor for service %q is not found. "+
"Did you compile it with go.chromium.org/luci/grpc/cmd/cproto?",
s)
}
for _, f := range desc.GetFile() {
binary, err := proto.Marshal(f)
if err != nil {
return nil, fmt.Errorf("could not marshal description of %s", f.GetName())
}
hash := sha256.Sum256(binary)
if !seenFiles[hash] {
result.File = append(result.File, f)
seenFiles[hash] = true
}
}
}
return result, nil
} | [
"func",
"combineDescriptors",
"(",
"serviceNames",
"[",
"]",
"string",
")",
"(",
"*",
"descriptor",
".",
"FileDescriptorSet",
",",
"error",
")",
"{",
"result",
":=",
"&",
"descriptor",
".",
"FileDescriptorSet",
"{",
"}",
"\n",
"// seenFiles is a set of descriptor ... | // combineDescriptors creates one FileDescriptorSet that covers all services
// and their dependencies. | [
"combineDescriptors",
"creates",
"one",
"FileDescriptorSet",
"that",
"covers",
"all",
"services",
"and",
"their",
"dependencies",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/discovery/discovery.go#L71-L101 |
7,337 | luci/luci-go | common/logging/fields.go | NewFields | func NewFields(v map[string]interface{}) Fields {
fields := make(Fields)
for k, v := range v {
fields[k] = v
}
return fields
} | go | func NewFields(v map[string]interface{}) Fields {
fields := make(Fields)
for k, v := range v {
fields[k] = v
}
return fields
} | [
"func",
"NewFields",
"(",
"v",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"Fields",
"{",
"fields",
":=",
"make",
"(",
"Fields",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"v",
"{",
"fields",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
... | // NewFields instantiates a new Fields instance by duplicating the supplied map. | [
"NewFields",
"instantiates",
"a",
"new",
"Fields",
"instance",
"by",
"duplicating",
"the",
"supplied",
"map",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/fields.go#L41-L47 |
7,338 | luci/luci-go | common/logging/fields.go | Copy | func (f Fields) Copy(other Fields) Fields {
if len(f) == 0 && len(other) == 0 {
return nil
}
ret := make(Fields, len(f)+len(other))
for k, v := range f {
ret[k] = v
}
for k, v := range other {
ret[k] = v
}
return ret
} | go | func (f Fields) Copy(other Fields) Fields {
if len(f) == 0 && len(other) == 0 {
return nil
}
ret := make(Fields, len(f)+len(other))
for k, v := range f {
ret[k] = v
}
for k, v := range other {
ret[k] = v
}
return ret
} | [
"func",
"(",
"f",
"Fields",
")",
"Copy",
"(",
"other",
"Fields",
")",
"Fields",
"{",
"if",
"len",
"(",
"f",
")",
"==",
"0",
"&&",
"len",
"(",
"other",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"ret",
":=",
"make",
"(",
"Fields",
... | // Copy returns a copy of this Fields with the keys from other overlaid on top
// of this one's. | [
"Copy",
"returns",
"a",
"copy",
"of",
"this",
"Fields",
"with",
"the",
"keys",
"from",
"other",
"overlaid",
"on",
"top",
"of",
"this",
"one",
"s",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/fields.go#L58-L71 |
7,339 | luci/luci-go | common/logging/fields.go | SortedEntries | func (f Fields) SortedEntries() (s []*FieldEntry) {
if len(f) == 0 {
return nil
}
s = make([]*FieldEntry, 0, len(f))
for k, v := range f {
s = append(s, &FieldEntry{k, v})
}
sort.Sort(fieldEntrySlice(s))
return
} | go | func (f Fields) SortedEntries() (s []*FieldEntry) {
if len(f) == 0 {
return nil
}
s = make([]*FieldEntry, 0, len(f))
for k, v := range f {
s = append(s, &FieldEntry{k, v})
}
sort.Sort(fieldEntrySlice(s))
return
} | [
"func",
"(",
"f",
"Fields",
")",
"SortedEntries",
"(",
")",
"(",
"s",
"[",
"]",
"*",
"FieldEntry",
")",
"{",
"if",
"len",
"(",
"f",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"s",
"=",
"make",
"(",
"[",
"]",
"*",
"FieldEntry",
","... | // SortedEntries processes a Fields object, pruning invisible fields, placing
// the ErrorKey field first, and then sorting the remaining fields by key. | [
"SortedEntries",
"processes",
"a",
"Fields",
"object",
"pruning",
"invisible",
"fields",
"placing",
"the",
"ErrorKey",
"field",
"first",
"and",
"then",
"sorting",
"the",
"remaining",
"fields",
"by",
"key",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/fields.go#L75-L85 |
7,340 | luci/luci-go | common/logging/fields.go | String | func (f Fields) String() string {
b := bytes.Buffer{}
b.WriteRune('{')
for idx, e := range f.SortedEntries() {
if idx > 0 {
b.WriteString(", ")
}
b.WriteString(e.String())
}
b.WriteRune('}')
return b.String()
} | go | func (f Fields) String() string {
b := bytes.Buffer{}
b.WriteRune('{')
for idx, e := range f.SortedEntries() {
if idx > 0 {
b.WriteString(", ")
}
b.WriteString(e.String())
}
b.WriteRune('}')
return b.String()
} | [
"func",
"(",
"f",
"Fields",
")",
"String",
"(",
")",
"string",
"{",
"b",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"b",
".",
"WriteRune",
"(",
"'{'",
")",
"\n",
"for",
"idx",
",",
"e",
":=",
"range",
"f",
".",
"SortedEntries",
"(",
")",
"{"... | // String returns a string describing the contents of f in a sorted,
// dictionary-like format. | [
"String",
"returns",
"a",
"string",
"describing",
"the",
"contents",
"of",
"f",
"in",
"a",
"sorted",
"dictionary",
"-",
"like",
"format",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/fields.go#L89-L100 |
7,341 | luci/luci-go | common/logging/fields.go | GetFields | func GetFields(c context.Context) Fields {
if ret, ok := c.Value(fieldsKey).(Fields); ok {
return ret
}
return nil
} | go | func GetFields(c context.Context) Fields {
if ret, ok := c.Value(fieldsKey).(Fields); ok {
return ret
}
return nil
} | [
"func",
"GetFields",
"(",
"c",
"context",
".",
"Context",
")",
"Fields",
"{",
"if",
"ret",
",",
"ok",
":=",
"c",
".",
"Value",
"(",
"fieldsKey",
")",
".",
"(",
"Fields",
")",
";",
"ok",
"{",
"return",
"ret",
"\n",
"}",
"\n",
"return",
"nil",
"\n"... | // GetFields returns the current Fields.
//
// This method is used for logger implementations with the understanding that
// the returned fields must not be mutated. | [
"GetFields",
"returns",
"the",
"current",
"Fields",
".",
"This",
"method",
"is",
"used",
"for",
"logger",
"implementations",
"with",
"the",
"understanding",
"that",
"the",
"returned",
"fields",
"must",
"not",
"be",
"mutated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/fields.go#L193-L198 |
7,342 | luci/luci-go | milo/git/context.go | WithProject | func WithProject(ctx context.Context, project string) context.Context {
return context.WithValue(ctx, &luciProjectKey, project)
} | go | func WithProject(ctx context.Context, project string) context.Context {
return context.WithValue(ctx, &luciProjectKey, project)
} | [
"func",
"WithProject",
"(",
"ctx",
"context",
".",
"Context",
",",
"project",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"&",
"luciProjectKey",
",",
"project",
")",
"\n",
"}"
] | // WithProject annotates the context object with the LUCI project that
// a request is handled for. | [
"WithProject",
"annotates",
"the",
"context",
"object",
"with",
"the",
"LUCI",
"project",
"that",
"a",
"request",
"is",
"handled",
"for",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/context.go#L27-L29 |
7,343 | luci/luci-go | milo/git/context.go | ProjectFromContext | func ProjectFromContext(ctx context.Context) (string, error) {
project, ok := ctx.Value(&luciProjectKey).(string)
if !ok {
return "", errors.Reason("LUCI project not available in context").Err()
}
if project == "" {
return "", errors.Reason("LUCI project is empty string").Err()
}
return project, nil
} | go | func ProjectFromContext(ctx context.Context) (string, error) {
project, ok := ctx.Value(&luciProjectKey).(string)
if !ok {
return "", errors.Reason("LUCI project not available in context").Err()
}
if project == "" {
return "", errors.Reason("LUCI project is empty string").Err()
}
return project, nil
} | [
"func",
"ProjectFromContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"string",
",",
"error",
")",
"{",
"project",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"&",
"luciProjectKey",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
... | // ProjectFromContext is the opposite of WithProject, is extracts the
// LUCI project which the current call stack is handling a request for. | [
"ProjectFromContext",
"is",
"the",
"opposite",
"of",
"WithProject",
"is",
"extracts",
"the",
"LUCI",
"project",
"which",
"the",
"current",
"call",
"stack",
"is",
"handling",
"a",
"request",
"for",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/context.go#L33-L42 |
7,344 | luci/luci-go | logdog/appengine/coordinator/logStreamEncoding.go | decodeKey | func decodeKey(k string) (string, error) {
if !strings.HasPrefix(k, encodedKeyPrefix) {
return "", fmt.Errorf("encoded key missing prefix (%s)", encodedKeyPrefix)
}
data, err := keyEncoding.DecodeString(k[len(encodedKeyPrefix):])
if err != nil {
return "", fmt.Errorf("failed to decode key: %v", err)
}
return string(data), nil
} | go | func decodeKey(k string) (string, error) {
if !strings.HasPrefix(k, encodedKeyPrefix) {
return "", fmt.Errorf("encoded key missing prefix (%s)", encodedKeyPrefix)
}
data, err := keyEncoding.DecodeString(k[len(encodedKeyPrefix):])
if err != nil {
return "", fmt.Errorf("failed to decode key: %v", err)
}
return string(data), nil
} | [
"func",
"decodeKey",
"(",
"k",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"k",
",",
"encodedKeyPrefix",
")",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"encode... | // decodeKey converts an encoded key into its original key string. | [
"decodeKey",
"converts",
"an",
"encoded",
"key",
"into",
"its",
"original",
"key",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logStreamEncoding.go#L40-L50 |
7,345 | luci/luci-go | logdog/appengine/coordinator/hashID.go | Normalize | func (id *HashID) Normalize() error {
// encoding/hex encodes using lower-case hexadecimal. Note that this is a
// no-op if the ID is already lowercase.
idv := strings.ToLower(string(*id))
if decodeSize := hex.DecodedLen(len(idv)); decodeSize != sha256.Size {
return fmt.Errorf("invalid SHA256 hash size (%d != %d)", decodeSize, sha256.Size)
}
for i, r := range idv {
if !strings.ContainsRune(validHashIDChars, r) {
return fmt.Errorf("invalid character '%c' at %d", r, i)
}
}
*id = HashID(idv)
return nil
} | go | func (id *HashID) Normalize() error {
// encoding/hex encodes using lower-case hexadecimal. Note that this is a
// no-op if the ID is already lowercase.
idv := strings.ToLower(string(*id))
if decodeSize := hex.DecodedLen(len(idv)); decodeSize != sha256.Size {
return fmt.Errorf("invalid SHA256 hash size (%d != %d)", decodeSize, sha256.Size)
}
for i, r := range idv {
if !strings.ContainsRune(validHashIDChars, r) {
return fmt.Errorf("invalid character '%c' at %d", r, i)
}
}
*id = HashID(idv)
return nil
} | [
"func",
"(",
"id",
"*",
"HashID",
")",
"Normalize",
"(",
")",
"error",
"{",
"// encoding/hex encodes using lower-case hexadecimal. Note that this is a",
"// no-op if the ID is already lowercase.",
"idv",
":=",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"*",
"id",
")... | // Normalize normalizes the hash ID and verifies its integrity. | [
"Normalize",
"normalizes",
"the",
"hash",
"ID",
"and",
"verifies",
"its",
"integrity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/hashID.go#L35-L50 |
7,346 | luci/luci-go | appengine/bqlog/bqlog.go | projID | func (l *Log) projID(ctx context.Context) string {
if l.ProjectID == "" {
return info.TrimmedAppID(ctx)
}
return l.ProjectID
} | go | func (l *Log) projID(ctx context.Context) string {
if l.ProjectID == "" {
return info.TrimmedAppID(ctx)
}
return l.ProjectID
} | [
"func",
"(",
"l",
"*",
"Log",
")",
"projID",
"(",
"ctx",
"context",
".",
"Context",
")",
"string",
"{",
"if",
"l",
".",
"ProjectID",
"==",
"\"",
"\"",
"{",
"return",
"info",
".",
"TrimmedAppID",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"return",
"l",
".... | // projID returns ProjectID or a GAE app ID if ProjectID is "". | [
"projID",
"returns",
"ProjectID",
"or",
"a",
"GAE",
"app",
"ID",
"if",
"ProjectID",
"is",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L443-L448 |
7,347 | luci/luci-go | appengine/bqlog/bqlog.go | tableRef | func (l *Log) tableRef(ctx context.Context) (string, error) {
projID := l.projID(ctx)
if projID == "" || strings.ContainsRune(projID, '/') {
return "", fmt.Errorf("invalid project ID %q", projID)
}
if l.DatasetID == "" || strings.ContainsRune(l.DatasetID, '/') {
return "", fmt.Errorf("invalid dataset ID %q", l.DatasetID)
}
if l.TableID == "" || strings.ContainsRune(l.TableID, '/') {
return "", fmt.Errorf("invalid table ID %q", l.TableID)
}
return fmt.Sprintf("%s/%s/%s", projID, l.DatasetID, l.TableID), nil
} | go | func (l *Log) tableRef(ctx context.Context) (string, error) {
projID := l.projID(ctx)
if projID == "" || strings.ContainsRune(projID, '/') {
return "", fmt.Errorf("invalid project ID %q", projID)
}
if l.DatasetID == "" || strings.ContainsRune(l.DatasetID, '/') {
return "", fmt.Errorf("invalid dataset ID %q", l.DatasetID)
}
if l.TableID == "" || strings.ContainsRune(l.TableID, '/') {
return "", fmt.Errorf("invalid table ID %q", l.TableID)
}
return fmt.Sprintf("%s/%s/%s", projID, l.DatasetID, l.TableID), nil
} | [
"func",
"(",
"l",
"*",
"Log",
")",
"tableRef",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"string",
",",
"error",
")",
"{",
"projID",
":=",
"l",
".",
"projID",
"(",
"ctx",
")",
"\n",
"if",
"projID",
"==",
"\"",
"\"",
"||",
"strings",
".",
... | // tableRef returns an identifier of the table in BigQuery.
//
// Returns an error if Log is misconfigred. | [
"tableRef",
"returns",
"an",
"identifier",
"of",
"the",
"table",
"in",
"BigQuery",
".",
"Returns",
"an",
"error",
"if",
"Log",
"is",
"misconfigred",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L453-L465 |
7,348 | luci/luci-go | appengine/bqlog/bqlog.go | bigQuery | func (l *Log) bigQuery(ctx context.Context) (*bqapi.Service, error) {
tr, err := auth.GetRPCTransport(ctx, auth.AsSelf, auth.WithScopes(bqapi.BigqueryScope))
if err != nil {
return nil, err
}
return bqapi.New(&http.Client{Transport: tr})
} | go | func (l *Log) bigQuery(ctx context.Context) (*bqapi.Service, error) {
tr, err := auth.GetRPCTransport(ctx, auth.AsSelf, auth.WithScopes(bqapi.BigqueryScope))
if err != nil {
return nil, err
}
return bqapi.New(&http.Client{Transport: tr})
} | [
"func",
"(",
"l",
"*",
"Log",
")",
"bigQuery",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"bqapi",
".",
"Service",
",",
"error",
")",
"{",
"tr",
",",
"err",
":=",
"auth",
".",
"GetRPCTransport",
"(",
"ctx",
",",
"auth",
".",
"AsSelf",
... | // bigQuery constructs an instance of BigQuery API client with proper auth. | [
"bigQuery",
"constructs",
"an",
"instance",
"of",
"BigQuery",
"API",
"client",
"with",
"proper",
"auth",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L468-L474 |
7,349 | luci/luci-go | appengine/bqlog/bqlog.go | doInsert | func (l *Log) doInsert(ctx context.Context, req *bqapi.TableDataInsertAllRequest) (*bqapi.TableDataInsertAllResponse, error) {
ctx, _ = clock.WithTimeout(ctx, 30*time.Second)
logging.Infof(ctx, "Sending %d rows to BigQuery", len(req.Rows))
bq, err := l.bigQuery(ctx)
if err != nil {
return nil, err
}
call := bq.Tabledata.InsertAll(l.projID(ctx), l.DatasetID, l.TableID, req)
return call.Context(ctx).Do()
} | go | func (l *Log) doInsert(ctx context.Context, req *bqapi.TableDataInsertAllRequest) (*bqapi.TableDataInsertAllResponse, error) {
ctx, _ = clock.WithTimeout(ctx, 30*time.Second)
logging.Infof(ctx, "Sending %d rows to BigQuery", len(req.Rows))
bq, err := l.bigQuery(ctx)
if err != nil {
return nil, err
}
call := bq.Tabledata.InsertAll(l.projID(ctx), l.DatasetID, l.TableID, req)
return call.Context(ctx).Do()
} | [
"func",
"(",
"l",
"*",
"Log",
")",
"doInsert",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"bqapi",
".",
"TableDataInsertAllRequest",
")",
"(",
"*",
"bqapi",
".",
"TableDataInsertAllResponse",
",",
"error",
")",
"{",
"ctx",
",",
"_",
"=",
"... | // doInsert does the actual BigQuery call.
//
// It is mocked in tests. | [
"doInsert",
"does",
"the",
"actual",
"BigQuery",
"call",
".",
"It",
"is",
"mocked",
"in",
"tests",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L479-L488 |
7,350 | luci/luci-go | appengine/bqlog/bqlog.go | start | func (f *asyncFlusher) start(numParallel int) {
f.chunks = make(chan chunk)
for i := 0; i < numParallel; i++ {
f.wg.Add(1)
go func() {
defer f.wg.Done()
f.uploaderLoop()
}()
}
} | go | func (f *asyncFlusher) start(numParallel int) {
f.chunks = make(chan chunk)
for i := 0; i < numParallel; i++ {
f.wg.Add(1)
go func() {
defer f.wg.Done()
f.uploaderLoop()
}()
}
} | [
"func",
"(",
"f",
"*",
"asyncFlusher",
")",
"start",
"(",
"numParallel",
"int",
")",
"{",
"f",
".",
"chunks",
"=",
"make",
"(",
"chan",
"chunk",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numParallel",
";",
"i",
"++",
"{",
"f",
".",
"wg"... | // start launches internal goroutines that upload data. | [
"start",
"launches",
"internal",
"goroutines",
"that",
"upload",
"data",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L515-L524 |
7,351 | luci/luci-go | appengine/bqlog/bqlog.go | waitAll | func (f *asyncFlusher) waitAll() (int, error) {
close(f.chunks)
f.wg.Wait()
if len(f.errs) == 0 {
return f.rowsSent, nil
}
return f.rowsSent, f.errs
} | go | func (f *asyncFlusher) waitAll() (int, error) {
close(f.chunks)
f.wg.Wait()
if len(f.errs) == 0 {
return f.rowsSent, nil
}
return f.rowsSent, f.errs
} | [
"func",
"(",
"f",
"*",
"asyncFlusher",
")",
"waitAll",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"close",
"(",
"f",
".",
"chunks",
")",
"\n",
"f",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"if",
"len",
"(",
"f",
".",
"errs",
")",
"==",
"0... | // waitAll waits for completion of all pending 'sendChunk' calls and stops all
// internal goroutines.
//
// Returns total number of rows sent and all the errors. | [
"waitAll",
"waits",
"for",
"completion",
"of",
"all",
"pending",
"sendChunk",
"calls",
"and",
"stops",
"all",
"internal",
"goroutines",
".",
"Returns",
"total",
"number",
"of",
"rows",
"sent",
"and",
"all",
"the",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L530-L537 |
7,352 | luci/luci-go | appengine/bqlog/bqlog.go | ctx | func (f *asyncFlusher) ctx(chunkIndex int32) context.Context {
return logging.SetField(f.Context, "chunk", chunkIndex)
} | go | func (f *asyncFlusher) ctx(chunkIndex int32) context.Context {
return logging.SetField(f.Context, "chunk", chunkIndex)
} | [
"func",
"(",
"f",
"*",
"asyncFlusher",
")",
"ctx",
"(",
"chunkIndex",
"int32",
")",
"context",
".",
"Context",
"{",
"return",
"logging",
".",
"SetField",
"(",
"f",
".",
"Context",
",",
"\"",
"\"",
",",
"chunkIndex",
")",
"\n",
"}"
] | // ctx returns a context to use for logging operations happening to some chunk. | [
"ctx",
"returns",
"a",
"context",
"to",
"use",
"for",
"logging",
"operations",
"happening",
"to",
"some",
"chunk",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L540-L542 |
7,353 | luci/luci-go | appengine/bqlog/bqlog.go | sendChunk | func (f *asyncFlusher) sendChunk(c chunk) {
c.index = atomic.AddInt32(&f.index, 1)
logging.Infof(f.ctx(c.index), "Chunk with %d batches queued", len(c.Tasks))
f.chunks <- c
} | go | func (f *asyncFlusher) sendChunk(c chunk) {
c.index = atomic.AddInt32(&f.index, 1)
logging.Infof(f.ctx(c.index), "Chunk with %d batches queued", len(c.Tasks))
f.chunks <- c
} | [
"func",
"(",
"f",
"*",
"asyncFlusher",
")",
"sendChunk",
"(",
"c",
"chunk",
")",
"{",
"c",
".",
"index",
"=",
"atomic",
".",
"AddInt32",
"(",
"&",
"f",
".",
"index",
",",
"1",
")",
"\n",
"logging",
".",
"Infof",
"(",
"f",
".",
"ctx",
"(",
"c",
... | // sendChunk starts an asynchronous operation to upload data to BigQuery.
//
// Can block if too many parallel uploads are already underway. Panics if called
// before 'start' or after 'waitAll'.
//
// On successful upload it deletes the tasks from Pull Queue. | [
"sendChunk",
"starts",
"an",
"asynchronous",
"operation",
"to",
"upload",
"data",
"to",
"BigQuery",
".",
"Can",
"block",
"if",
"too",
"many",
"parallel",
"uploads",
"are",
"already",
"underway",
".",
"Panics",
"if",
"called",
"before",
"start",
"or",
"after",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L550-L554 |
7,354 | luci/luci-go | appengine/bqlog/bqlog.go | uploaderLoop | func (f *asyncFlusher) uploaderLoop() {
for chunk := range f.chunks {
ctx := f.ctx(chunk.index)
logging.Infof(ctx, "Chunk flush starting")
sent, err := f.upload(ctx, chunk)
f.mu.Lock()
if err == nil {
f.rowsSent += sent
} else {
f.errs = append(f.errs, err)
}
f.mu.Unlock()
logging.Infof(ctx, "Chunk flush finished")
}
} | go | func (f *asyncFlusher) uploaderLoop() {
for chunk := range f.chunks {
ctx := f.ctx(chunk.index)
logging.Infof(ctx, "Chunk flush starting")
sent, err := f.upload(ctx, chunk)
f.mu.Lock()
if err == nil {
f.rowsSent += sent
} else {
f.errs = append(f.errs, err)
}
f.mu.Unlock()
logging.Infof(ctx, "Chunk flush finished")
}
} | [
"func",
"(",
"f",
"*",
"asyncFlusher",
")",
"uploaderLoop",
"(",
")",
"{",
"for",
"chunk",
":=",
"range",
"f",
".",
"chunks",
"{",
"ctx",
":=",
"f",
".",
"ctx",
"(",
"chunk",
".",
"index",
")",
"\n",
"logging",
".",
"Infof",
"(",
"ctx",
",",
"\""... | // uploaderLoop runs in a separate goroutine. | [
"uploaderLoop",
"runs",
"in",
"a",
"separate",
"goroutine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/bqlog/bqlog.go#L557-L571 |
7,355 | luci/luci-go | server/secrets/secrets.go | Clone | func (b NamedBlob) Clone() NamedBlob {
return NamedBlob{
ID: b.ID,
Blob: append([]byte(nil), b.Blob...),
}
} | go | func (b NamedBlob) Clone() NamedBlob {
return NamedBlob{
ID: b.ID,
Blob: append([]byte(nil), b.Blob...),
}
} | [
"func",
"(",
"b",
"NamedBlob",
")",
"Clone",
"(",
")",
"NamedBlob",
"{",
"return",
"NamedBlob",
"{",
"ID",
":",
"b",
".",
"ID",
",",
"Blob",
":",
"append",
"(",
"[",
"]",
"byte",
"(",
"nil",
")",
",",
"b",
".",
"Blob",
"...",
")",
",",
"}",
"... | // Clone makes a deep copy of the NamedBlob. | [
"Clone",
"makes",
"a",
"deep",
"copy",
"of",
"the",
"NamedBlob",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/secrets/secrets.go#L37-L42 |
7,356 | luci/luci-go | server/secrets/secrets.go | Blobs | func (s Secret) Blobs() []NamedBlob {
out := make([]NamedBlob, 0, 1+len(s.Previous))
out = append(out, s.Current)
out = append(out, s.Previous...)
return out
} | go | func (s Secret) Blobs() []NamedBlob {
out := make([]NamedBlob, 0, 1+len(s.Previous))
out = append(out, s.Current)
out = append(out, s.Previous...)
return out
} | [
"func",
"(",
"s",
"Secret",
")",
"Blobs",
"(",
")",
"[",
"]",
"NamedBlob",
"{",
"out",
":=",
"make",
"(",
"[",
"]",
"NamedBlob",
",",
"0",
",",
"1",
"+",
"len",
"(",
"s",
".",
"Previous",
")",
")",
"\n",
"out",
"=",
"append",
"(",
"out",
",",... | // Blobs returns current blob and all previous blobs as one array. | [
"Blobs",
"returns",
"current",
"blob",
"and",
"all",
"previous",
"blobs",
"as",
"one",
"array",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/secrets/secrets.go#L56-L61 |
7,357 | luci/luci-go | server/secrets/secrets.go | Clone | func (s Secret) Clone() Secret {
out := Secret{Current: s.Current.Clone()}
if s.Previous != nil {
out.Previous = make([]NamedBlob, len(s.Previous))
for i := range out.Previous {
out.Previous[i] = s.Previous[i].Clone()
}
}
return out
} | go | func (s Secret) Clone() Secret {
out := Secret{Current: s.Current.Clone()}
if s.Previous != nil {
out.Previous = make([]NamedBlob, len(s.Previous))
for i := range out.Previous {
out.Previous[i] = s.Previous[i].Clone()
}
}
return out
} | [
"func",
"(",
"s",
"Secret",
")",
"Clone",
"(",
")",
"Secret",
"{",
"out",
":=",
"Secret",
"{",
"Current",
":",
"s",
".",
"Current",
".",
"Clone",
"(",
")",
"}",
"\n",
"if",
"s",
".",
"Previous",
"!=",
"nil",
"{",
"out",
".",
"Previous",
"=",
"m... | // Clone makes a deep copy of the Secret. | [
"Clone",
"makes",
"a",
"deep",
"copy",
"of",
"the",
"Secret",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/secrets/secrets.go#L64-L73 |
7,358 | luci/luci-go | server/secrets/secrets.go | GetSecret | func (s StaticStore) GetSecret(k Key) (Secret, error) {
if secret, ok := s[k]; ok {
return secret.Clone(), nil
}
return Secret{}, ErrNoSuchSecret
} | go | func (s StaticStore) GetSecret(k Key) (Secret, error) {
if secret, ok := s[k]; ok {
return secret.Clone(), nil
}
return Secret{}, ErrNoSuchSecret
} | [
"func",
"(",
"s",
"StaticStore",
")",
"GetSecret",
"(",
"k",
"Key",
")",
"(",
"Secret",
",",
"error",
")",
"{",
"if",
"secret",
",",
"ok",
":=",
"s",
"[",
"k",
"]",
";",
"ok",
"{",
"return",
"secret",
".",
"Clone",
"(",
")",
",",
"nil",
"\n",
... | // GetSecret returns a copy of a secret given its key or ErrNoSuchSecret if no
// such secret. | [
"GetSecret",
"returns",
"a",
"copy",
"of",
"a",
"secret",
"given",
"its",
"key",
"or",
"ErrNoSuchSecret",
"if",
"no",
"such",
"secret",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/secrets/secrets.go#L90-L95 |
7,359 | luci/luci-go | milo/common/time.go | HumanDuration | func HumanDuration(d time.Duration) string {
t := int64(d.Seconds())
day := t / 86400
hr := (t % 86400) / 3600
if day > 0 {
if hr != 0 {
return fmt.Sprintf("%d days %d hrs", day, hr)
}
return fmt.Sprintf("%d days", day)
}
min := (t % 3600) / 60
if hr > 0 {
if min != 0 {
return fmt.Sprintf("%d hrs %d mins", hr, min)
}
return fmt.Sprintf("%d hrs", hr)
}
sec := t % 60
if min > 0 {
if sec != 0 {
return fmt.Sprintf("%d mins %d secs", min, sec)
}
return fmt.Sprintf("%d mins", min)
}
if sec != 0 {
return fmt.Sprintf("%d secs", sec)
}
if d > time.Millisecond {
return fmt.Sprintf("%d ms", d/time.Millisecond)
}
return "0"
} | go | func HumanDuration(d time.Duration) string {
t := int64(d.Seconds())
day := t / 86400
hr := (t % 86400) / 3600
if day > 0 {
if hr != 0 {
return fmt.Sprintf("%d days %d hrs", day, hr)
}
return fmt.Sprintf("%d days", day)
}
min := (t % 3600) / 60
if hr > 0 {
if min != 0 {
return fmt.Sprintf("%d hrs %d mins", hr, min)
}
return fmt.Sprintf("%d hrs", hr)
}
sec := t % 60
if min > 0 {
if sec != 0 {
return fmt.Sprintf("%d mins %d secs", min, sec)
}
return fmt.Sprintf("%d mins", min)
}
if sec != 0 {
return fmt.Sprintf("%d secs", sec)
}
if d > time.Millisecond {
return fmt.Sprintf("%d ms", d/time.Millisecond)
}
return "0"
} | [
"func",
"HumanDuration",
"(",
"d",
"time",
".",
"Duration",
")",
"string",
"{",
"t",
":=",
"int64",
"(",
"d",
".",
"Seconds",
"(",
")",
")",
"\n",
"day",
":=",
"t",
"/",
"86400",
"\n",
"hr",
":=",
"(",
"t",
"%",
"86400",
")",
"/",
"3600",
"\n\n... | // humanDuration translates d into a human readable string of x units y units,
// where x and y could be in days, hours, minutes, or seconds, whichever is the
// largest. | [
"humanDuration",
"translates",
"d",
"into",
"a",
"human",
"readable",
"string",
"of",
"x",
"units",
"y",
"units",
"where",
"x",
"and",
"y",
"could",
"be",
"in",
"days",
"hours",
"minutes",
"or",
"seconds",
"whichever",
"is",
"the",
"largest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/time.go#L80-L117 |
7,360 | luci/luci-go | logdog/appengine/coordinator/config/settings.go | Load | func (s *Settings) Load(c context.Context) error {
var loadMe Settings
// Load additional global config from settings. If it's missing, that's fine,
// since its fields are all optional.
if err := settings.Get(c, globalConfigSettingsKey, &loadMe); err != nil {
// The settings are missing, so let's install the empty settings.
if err != settings.ErrNoSettings {
log.WithError(err).Errorf(c, "Failed to load global config from settings.")
return err
}
if err := settings.Set(c, globalConfigSettingsKey, &loadMe, "application", "initial empty config"); err != nil {
log.WithError(err).Warningf(c, "Failed to initialize empty config.")
}
}
*s = loadMe
return nil
} | go | func (s *Settings) Load(c context.Context) error {
var loadMe Settings
// Load additional global config from settings. If it's missing, that's fine,
// since its fields are all optional.
if err := settings.Get(c, globalConfigSettingsKey, &loadMe); err != nil {
// The settings are missing, so let's install the empty settings.
if err != settings.ErrNoSettings {
log.WithError(err).Errorf(c, "Failed to load global config from settings.")
return err
}
if err := settings.Set(c, globalConfigSettingsKey, &loadMe, "application", "initial empty config"); err != nil {
log.WithError(err).Warningf(c, "Failed to initialize empty config.")
}
}
*s = loadMe
return nil
} | [
"func",
"(",
"s",
"*",
"Settings",
")",
"Load",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"var",
"loadMe",
"Settings",
"\n\n",
"// Load additional global config from settings. If it's missing, that's fine,",
"// since its fields are all optional.",
"if",
"er... | // Load populates the settings instance from the stored settings.
//
// If no settings are stored, an empty Settings instance will be loaded and
// this will return nil.
//
// An error will be returned if an operation that is expected to succeed fails. | [
"Load",
"populates",
"the",
"settings",
"instance",
"from",
"the",
"stored",
"settings",
".",
"If",
"no",
"settings",
"are",
"stored",
"an",
"empty",
"Settings",
"instance",
"will",
"be",
"loaded",
"and",
"this",
"will",
"return",
"nil",
".",
"An",
"error",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/settings.go#L46-L65 |
7,361 | luci/luci-go | logdog/appengine/coordinator/config/settings.go | Store | func (s *Settings) Store(c context.Context, why string) error {
id := auth.CurrentIdentity(c)
log.Fields{
"identity": id,
"reason": why,
}.Infof(c, "Updating global configuration.")
return settings.Set(c, globalConfigSettingsKey, s, string(id), why)
} | go | func (s *Settings) Store(c context.Context, why string) error {
id := auth.CurrentIdentity(c)
log.Fields{
"identity": id,
"reason": why,
}.Infof(c, "Updating global configuration.")
return settings.Set(c, globalConfigSettingsKey, s, string(id), why)
} | [
"func",
"(",
"s",
"*",
"Settings",
")",
"Store",
"(",
"c",
"context",
".",
"Context",
",",
"why",
"string",
")",
"error",
"{",
"id",
":=",
"auth",
".",
"CurrentIdentity",
"(",
"c",
")",
"\n",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"id",
",",... | // Store stores the new global configuration. | [
"Store",
"stores",
"the",
"new",
"global",
"configuration",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/config/settings.go#L68-L75 |
7,362 | luci/luci-go | machine-db/appengine/model/datacenters.go | fetch | func (t *DatacentersTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, description, state
FROM datacenters
`)
if err != nil {
return errors.Annotate(err, "failed to select datacenters").Err()
}
defer rows.Close()
for rows.Next() {
dc := &Datacenter{}
if err := rows.Scan(&dc.Id, &dc.Name, &dc.Description, &dc.State); err != nil {
return errors.Annotate(err, "failed to scan datacenter").Err()
}
t.current = append(t.current, dc)
}
return nil
} | go | func (t *DatacentersTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, description, state
FROM datacenters
`)
if err != nil {
return errors.Annotate(err, "failed to select datacenters").Err()
}
defer rows.Close()
for rows.Next() {
dc := &Datacenter{}
if err := rows.Scan(&dc.Id, &dc.Name, &dc.Description, &dc.State); err != nil {
return errors.Annotate(err, "failed to scan datacenter").Err()
}
t.current = append(t.current, dc)
}
return nil
} | [
"func",
"(",
"t",
"*",
"DatacentersTable",
")",
"fetch",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"db",
":=",
"database",
".",
"Get",
"(",
"c",
")",
"\n",
"rows",
",",
"err",
":=",
"db",
".",
"QueryContext",
"(",
"c",
",",
"`\n\t\tSE... | // fetch fetches the datacenters from the database. | [
"fetch",
"fetches",
"the",
"datacenters",
"from",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/datacenters.go#L47-L65 |
7,363 | luci/luci-go | machine-db/appengine/model/datacenters.go | computeChanges | func (t *DatacentersTable) computeChanges(c context.Context, datacenters []*config.Datacenter) {
cfgs := make(map[string]*Datacenter, len(datacenters))
for _, cfg := range datacenters {
cfgs[cfg.Name] = &Datacenter{
Datacenter: config.Datacenter{
Name: cfg.Name,
Description: cfg.Description,
State: cfg.State,
},
}
}
for _, dc := range t.current {
if cfg, ok := cfgs[dc.Name]; ok {
// Datacenter found in the config.
if t.needsUpdate(dc, cfg) {
// Datacenter doesn't match the config.
cfg.Id = dc.Id
t.updates = append(t.updates, cfg)
}
// Record that the datacenter config has been seen.
delete(cfgs, cfg.Name)
} else {
// Datacenter not found in the config.
t.removals = append(t.removals, dc)
}
}
// Datacenters remaining in the map are present in the config but not the database.
// Iterate deterministically over the slice to determine which datacenters need to be added.
for _, cfg := range datacenters {
if dc, ok := cfgs[cfg.Name]; ok {
t.additions = append(t.additions, dc)
}
}
} | go | func (t *DatacentersTable) computeChanges(c context.Context, datacenters []*config.Datacenter) {
cfgs := make(map[string]*Datacenter, len(datacenters))
for _, cfg := range datacenters {
cfgs[cfg.Name] = &Datacenter{
Datacenter: config.Datacenter{
Name: cfg.Name,
Description: cfg.Description,
State: cfg.State,
},
}
}
for _, dc := range t.current {
if cfg, ok := cfgs[dc.Name]; ok {
// Datacenter found in the config.
if t.needsUpdate(dc, cfg) {
// Datacenter doesn't match the config.
cfg.Id = dc.Id
t.updates = append(t.updates, cfg)
}
// Record that the datacenter config has been seen.
delete(cfgs, cfg.Name)
} else {
// Datacenter not found in the config.
t.removals = append(t.removals, dc)
}
}
// Datacenters remaining in the map are present in the config but not the database.
// Iterate deterministically over the slice to determine which datacenters need to be added.
for _, cfg := range datacenters {
if dc, ok := cfgs[cfg.Name]; ok {
t.additions = append(t.additions, dc)
}
}
} | [
"func",
"(",
"t",
"*",
"DatacentersTable",
")",
"computeChanges",
"(",
"c",
"context",
".",
"Context",
",",
"datacenters",
"[",
"]",
"*",
"config",
".",
"Datacenter",
")",
"{",
"cfgs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Datacenter",
",... | // computeChanges computes the changes that need to be made to the datacenters in the database. | [
"computeChanges",
"computes",
"the",
"changes",
"that",
"need",
"to",
"be",
"made",
"to",
"the",
"datacenters",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/datacenters.go#L73-L108 |
7,364 | luci/luci-go | machine-db/appengine/model/datacenters.go | remove | func (t *DatacentersTable) remove(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.removals) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
DELETE FROM datacenters
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Remove each datacenter from the table. It's more efficient to update the slice of
// datacenters once at the end rather than for each removal, so use a defer.
removed := make(map[int64]struct{}, len(t.removals))
defer func() {
var dcs []*Datacenter
for _, dc := range t.current {
if _, ok := removed[dc.Id]; !ok {
dcs = append(dcs, dc)
}
}
t.current = dcs
}()
for len(t.removals) > 0 {
dc := t.removals[0]
if _, err := stmt.ExecContext(c, dc.Id); err != nil {
// Defer ensures the slice of datacenters is updated even if we exit early.
return errors.Annotate(err, "failed to remove datacenter %q", dc.Name).Err()
}
removed[dc.Id] = struct{}{}
t.removals = t.removals[1:]
logging.Infof(c, "Removed datacenter %q", dc.Name)
}
return nil
} | go | func (t *DatacentersTable) remove(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.removals) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
DELETE FROM datacenters
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Remove each datacenter from the table. It's more efficient to update the slice of
// datacenters once at the end rather than for each removal, so use a defer.
removed := make(map[int64]struct{}, len(t.removals))
defer func() {
var dcs []*Datacenter
for _, dc := range t.current {
if _, ok := removed[dc.Id]; !ok {
dcs = append(dcs, dc)
}
}
t.current = dcs
}()
for len(t.removals) > 0 {
dc := t.removals[0]
if _, err := stmt.ExecContext(c, dc.Id); err != nil {
// Defer ensures the slice of datacenters is updated even if we exit early.
return errors.Annotate(err, "failed to remove datacenter %q", dc.Name).Err()
}
removed[dc.Id] = struct{}{}
t.removals = t.removals[1:]
logging.Infof(c, "Removed datacenter %q", dc.Name)
}
return nil
} | [
"func",
"(",
"t",
"*",
"DatacentersTable",
")",
"remove",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"// Avoid using the database connection to prepare unnecessary statements.",
"if",
"len",
"(",
"t",
".",
"removals",
")",
"==",
"0",
"{",
"return",
... | // remove removes all datacenters pending removal from the database, clearing pending removals.
// No-op unless computeChanges was called first. Idempotent until computeChanges is called again. | [
"remove",
"removes",
"all",
"datacenters",
"pending",
"removal",
"from",
"the",
"database",
"clearing",
"pending",
"removals",
".",
"No",
"-",
"op",
"unless",
"computeChanges",
"was",
"called",
"first",
".",
"Idempotent",
"until",
"computeChanges",
"is",
"called",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/datacenters.go#L148-L187 |
7,365 | luci/luci-go | machine-db/appengine/model/datacenters.go | update | func (t *DatacentersTable) update(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.updates) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
UPDATE datacenters
SET description = ?, state = ?
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Update each datacenter in the table. It's more efficient to update the slice of
// datacenters once at the end rather than for each update, so use a defer.
updated := make(map[int64]*Datacenter, len(t.updates))
defer func() {
for _, dc := range t.current {
if u, ok := updated[dc.Id]; ok {
dc.Description = u.Description
dc.State = u.State
}
}
}()
for len(t.updates) > 0 {
dc := t.updates[0]
if _, err := stmt.ExecContext(c, dc.Description, dc.State, dc.Id); err != nil {
return errors.Annotate(err, "failed to update datacenter %q", dc.Name).Err()
}
updated[dc.Id] = dc
t.updates = t.updates[1:]
logging.Infof(c, "Updated datacenter %q", dc.Name)
}
return nil
} | go | func (t *DatacentersTable) update(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.updates) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
UPDATE datacenters
SET description = ?, state = ?
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Update each datacenter in the table. It's more efficient to update the slice of
// datacenters once at the end rather than for each update, so use a defer.
updated := make(map[int64]*Datacenter, len(t.updates))
defer func() {
for _, dc := range t.current {
if u, ok := updated[dc.Id]; ok {
dc.Description = u.Description
dc.State = u.State
}
}
}()
for len(t.updates) > 0 {
dc := t.updates[0]
if _, err := stmt.ExecContext(c, dc.Description, dc.State, dc.Id); err != nil {
return errors.Annotate(err, "failed to update datacenter %q", dc.Name).Err()
}
updated[dc.Id] = dc
t.updates = t.updates[1:]
logging.Infof(c, "Updated datacenter %q", dc.Name)
}
return nil
} | [
"func",
"(",
"t",
"*",
"DatacentersTable",
")",
"update",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"// Avoid using the database connection to prepare unnecessary statements.",
"if",
"len",
"(",
"t",
".",
"updates",
")",
"==",
"0",
"{",
"return",
"... | // update updates all datacenters pending update in the database, clearing pending updates.
// No-op unless computeChanges was called first. Idempotent until computeChanges is called again. | [
"update",
"updates",
"all",
"datacenters",
"pending",
"update",
"in",
"the",
"database",
"clearing",
"pending",
"updates",
".",
"No",
"-",
"op",
"unless",
"computeChanges",
"was",
"called",
"first",
".",
"Idempotent",
"until",
"computeChanges",
"is",
"called",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/datacenters.go#L191-L229 |
7,366 | luci/luci-go | machine-db/appengine/model/datacenters.go | ids | func (t *DatacentersTable) ids(c context.Context) map[string]int64 {
dcs := make(map[string]int64, len(t.current))
for _, dc := range t.current {
dcs[dc.Name] = dc.Id
}
return dcs
} | go | func (t *DatacentersTable) ids(c context.Context) map[string]int64 {
dcs := make(map[string]int64, len(t.current))
for _, dc := range t.current {
dcs[dc.Name] = dc.Id
}
return dcs
} | [
"func",
"(",
"t",
"*",
"DatacentersTable",
")",
"ids",
"(",
"c",
"context",
".",
"Context",
")",
"map",
"[",
"string",
"]",
"int64",
"{",
"dcs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int64",
",",
"len",
"(",
"t",
".",
"current",
")",
")"... | // ids returns a map of datacenter names to IDs. | [
"ids",
"returns",
"a",
"map",
"of",
"datacenter",
"names",
"to",
"IDs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/datacenters.go#L232-L238 |
7,367 | luci/luci-go | machine-db/appengine/model/datacenters.go | EnsureDatacenters | func EnsureDatacenters(c context.Context, cfgs []*config.Datacenter) (map[string]int64, error) {
t := &DatacentersTable{}
if err := t.fetch(c); err != nil {
return nil, errors.Annotate(err, "failed to fetch datacenters").Err()
}
t.computeChanges(c, cfgs)
if err := t.add(c); err != nil {
return nil, errors.Annotate(err, "failed to add datacenters").Err()
}
if err := t.remove(c); err != nil {
return nil, errors.Annotate(err, "failed to remove datacenters").Err()
}
if err := t.update(c); err != nil {
return nil, errors.Annotate(err, "failed to update datacenters").Err()
}
return t.ids(c), nil
} | go | func EnsureDatacenters(c context.Context, cfgs []*config.Datacenter) (map[string]int64, error) {
t := &DatacentersTable{}
if err := t.fetch(c); err != nil {
return nil, errors.Annotate(err, "failed to fetch datacenters").Err()
}
t.computeChanges(c, cfgs)
if err := t.add(c); err != nil {
return nil, errors.Annotate(err, "failed to add datacenters").Err()
}
if err := t.remove(c); err != nil {
return nil, errors.Annotate(err, "failed to remove datacenters").Err()
}
if err := t.update(c); err != nil {
return nil, errors.Annotate(err, "failed to update datacenters").Err()
}
return t.ids(c), nil
} | [
"func",
"EnsureDatacenters",
"(",
"c",
"context",
".",
"Context",
",",
"cfgs",
"[",
"]",
"*",
"config",
".",
"Datacenter",
")",
"(",
"map",
"[",
"string",
"]",
"int64",
",",
"error",
")",
"{",
"t",
":=",
"&",
"DatacentersTable",
"{",
"}",
"\n",
"if",... | // EnsureDatacenters ensures the database contains exactly the given datacenters.
// Returns a map of datacenter names to IDs in the database. | [
"EnsureDatacenters",
"ensures",
"the",
"database",
"contains",
"exactly",
"the",
"given",
"datacenters",
".",
"Returns",
"a",
"map",
"of",
"datacenter",
"names",
"to",
"IDs",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/datacenters.go#L242-L258 |
7,368 | luci/luci-go | grpc/cmd/prpc/show.go | show | func show(c context.Context, client *prpc.Client, name string) error {
desc, err := loadDescription(c, client)
if err != nil {
return fmt.Errorf("could not load server description: %s", err)
}
if name == "" {
for _, s := range desc.Services {
fmt.Println(s)
}
return nil
}
file, obj, path := descutil.Resolve(desc.Description, name)
if obj == nil {
return fmt.Errorf("name %q could not resolved", name)
}
print := newPrinter(os.Stdout)
if err := print.SetFile(file); err != nil {
return err
}
switch obj := obj.(type) {
case *descriptor.ServiceDescriptorProto:
print.Service(obj, -1)
case *descriptor.MethodDescriptorProto:
serviceIndex, methodIndex := path[1], path[3]
print.Service(file.Service[serviceIndex], methodIndex)
printMsg := func(name string) error {
name = strings.TrimPrefix(name, ".")
file, msg, _ := descutil.Resolve(desc.Description, name)
if msg == nil {
print.Printf("// Message %q is not found\n", name)
return nil
}
if err := print.SetFile(file); err != nil {
return err
}
print.Message(msg.(*descriptor.DescriptorProto))
return nil
}
print.Printf("\n")
if err := printMsg(obj.GetInputType()); err != nil {
return err
}
print.Printf("\n")
if err := printMsg(obj.GetOutputType()); err != nil {
return err
}
case *descriptor.DescriptorProto:
print.Message(obj)
case *descriptor.FieldDescriptorProto:
print.Field(obj)
case *descriptor.EnumDescriptorProto:
print.Enum(obj)
case *descriptor.EnumValueDescriptorProto:
print.EnumValue(obj)
default:
return fmt.Errorf("object of type %T is not supported", obj)
}
return print.Err
} | go | func show(c context.Context, client *prpc.Client, name string) error {
desc, err := loadDescription(c, client)
if err != nil {
return fmt.Errorf("could not load server description: %s", err)
}
if name == "" {
for _, s := range desc.Services {
fmt.Println(s)
}
return nil
}
file, obj, path := descutil.Resolve(desc.Description, name)
if obj == nil {
return fmt.Errorf("name %q could not resolved", name)
}
print := newPrinter(os.Stdout)
if err := print.SetFile(file); err != nil {
return err
}
switch obj := obj.(type) {
case *descriptor.ServiceDescriptorProto:
print.Service(obj, -1)
case *descriptor.MethodDescriptorProto:
serviceIndex, methodIndex := path[1], path[3]
print.Service(file.Service[serviceIndex], methodIndex)
printMsg := func(name string) error {
name = strings.TrimPrefix(name, ".")
file, msg, _ := descutil.Resolve(desc.Description, name)
if msg == nil {
print.Printf("// Message %q is not found\n", name)
return nil
}
if err := print.SetFile(file); err != nil {
return err
}
print.Message(msg.(*descriptor.DescriptorProto))
return nil
}
print.Printf("\n")
if err := printMsg(obj.GetInputType()); err != nil {
return err
}
print.Printf("\n")
if err := printMsg(obj.GetOutputType()); err != nil {
return err
}
case *descriptor.DescriptorProto:
print.Message(obj)
case *descriptor.FieldDescriptorProto:
print.Field(obj)
case *descriptor.EnumDescriptorProto:
print.Enum(obj)
case *descriptor.EnumValueDescriptorProto:
print.EnumValue(obj)
default:
return fmt.Errorf("object of type %T is not supported", obj)
}
return print.Err
} | [
"func",
"show",
"(",
"c",
"context",
".",
"Context",
",",
"client",
"*",
"prpc",
".",
"Client",
",",
"name",
"string",
")",
"error",
"{",
"desc",
",",
"err",
":=",
"loadDescription",
"(",
"c",
",",
"client",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{"... | // show prints a definition of an object referenced by name in proto3 style. | [
"show",
"prints",
"a",
"definition",
"of",
"an",
"object",
"referenced",
"by",
"name",
"in",
"proto3",
"style",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/show.go#L82-L154 |
7,369 | luci/luci-go | tokenserver/appengine/impl/certchecker/rpc_is_revoked_cert.go | IsRevokedCert | func (r *IsRevokedCertRPC) IsRevokedCert(c context.Context, req *admin.IsRevokedCertRequest) (*admin.IsRevokedCertResponse, error) {
sn := big.Int{}
if _, ok := sn.SetString(req.Sn, 0); !ok {
return nil, status.Errorf(codes.InvalidArgument, "can't parse 'sn'")
}
checker, err := GetCertChecker(c, req.Ca)
if err != nil {
if details, ok := err.(Error); ok && details.Reason == NoSuchCA {
return nil, status.Errorf(codes.NotFound, "no such CA: %q", req.Ca)
}
return nil, status.Errorf(codes.Internal, "failed to check %q CRL - %s", req.Ca, err)
}
revoked, err := checker.CRL.IsRevokedSN(c, &sn)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check %q CRL - %s", req.Ca, err)
}
return &admin.IsRevokedCertResponse{Revoked: revoked}, nil
} | go | func (r *IsRevokedCertRPC) IsRevokedCert(c context.Context, req *admin.IsRevokedCertRequest) (*admin.IsRevokedCertResponse, error) {
sn := big.Int{}
if _, ok := sn.SetString(req.Sn, 0); !ok {
return nil, status.Errorf(codes.InvalidArgument, "can't parse 'sn'")
}
checker, err := GetCertChecker(c, req.Ca)
if err != nil {
if details, ok := err.(Error); ok && details.Reason == NoSuchCA {
return nil, status.Errorf(codes.NotFound, "no such CA: %q", req.Ca)
}
return nil, status.Errorf(codes.Internal, "failed to check %q CRL - %s", req.Ca, err)
}
revoked, err := checker.CRL.IsRevokedSN(c, &sn)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check %q CRL - %s", req.Ca, err)
}
return &admin.IsRevokedCertResponse{Revoked: revoked}, nil
} | [
"func",
"(",
"r",
"*",
"IsRevokedCertRPC",
")",
"IsRevokedCert",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"admin",
".",
"IsRevokedCertRequest",
")",
"(",
"*",
"admin",
".",
"IsRevokedCertResponse",
",",
"error",
")",
"{",
"sn",
":=",
"big",
... | // IsRevokedCert says whether a certificate serial number is in the CRL. | [
"IsRevokedCert",
"says",
"whether",
"a",
"certificate",
"serial",
"number",
"is",
"in",
"the",
"CRL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certchecker/rpc_is_revoked_cert.go#L32-L52 |
7,370 | luci/luci-go | luci_notify/notify/srcman.go | srcmanCheckout | func srcmanCheckout(c context.Context, build *Build) (Checkout, error) {
transport, err := auth.GetRPCTransport(c, auth.AsSelf)
if err != nil {
return nil, errors.Annotate(err, "getting RPC Transport").Err()
}
client := coordinator.NewClient(&prpc.Client{
C: &http.Client{Transport: transport},
Host: build.Infra.Logdog.Hostname,
Options: prpc.DefaultOptions(),
})
qo := coordinator.QueryOptions{
ContentType: srcman.ContentTypeSourceManifest,
}
logProject := types.ProjectName(build.Infra.Logdog.Project)
logPath := path.Join(build.Infra.Logdog.Prefix, "**")
// Perform the query, capturing exactly one log stream and erroring otherwise.
var log *coordinator.LogStream
err = client.Query(c, logProject, logPath, qo, func(s *coordinator.LogStream) bool {
log = s
return false
})
switch {
case err != nil:
return nil, grpcutil.WrapIfTransient(err)
case log == nil:
logging.Infof(c, "unable to find source manifest in project %s at path %s",
build.Infra.Logdog.Project, logPath)
return nil, nil
}
// Read the source manifest from the log stream.
var buf bytes.Buffer
_, err = buf.ReadFrom(&renderer.Renderer{
Source: client.Stream(logProject, log.Path).Fetcher(c, nil),
Raw: true,
})
if err != nil {
return nil, errors.Annotate(err, "failed to read stream").Tag(transient.Tag).Err()
}
// Unmarshal the source manifest from the bytes.
var manifest srcman.Manifest
if err := proto.Unmarshal(buf.Bytes(), &manifest); err != nil {
return nil, err
}
results := make(Checkout)
for dirname, dir := range manifest.Directories {
gitCheckout := dir.GetGitCheckout()
if gitCheckout == nil {
continue
}
url, err := gitiles.NormalizeRepoURL(gitCheckout.RepoUrl, false)
if err != nil {
logging.WithError(err).Warningf(c, "could not parse RepoURL %q for dir %q", gitCheckout.RepoUrl, dirname)
continue
}
if !strings.HasSuffix(url.Host, ".googlesource.com") {
logging.WithError(err).Warningf(c, "unsupported git host %q for dir %q", gitCheckout.RepoUrl, dirname)
continue
}
results[url.String()] = gitCheckout.Revision
}
return results, nil
} | go | func srcmanCheckout(c context.Context, build *Build) (Checkout, error) {
transport, err := auth.GetRPCTransport(c, auth.AsSelf)
if err != nil {
return nil, errors.Annotate(err, "getting RPC Transport").Err()
}
client := coordinator.NewClient(&prpc.Client{
C: &http.Client{Transport: transport},
Host: build.Infra.Logdog.Hostname,
Options: prpc.DefaultOptions(),
})
qo := coordinator.QueryOptions{
ContentType: srcman.ContentTypeSourceManifest,
}
logProject := types.ProjectName(build.Infra.Logdog.Project)
logPath := path.Join(build.Infra.Logdog.Prefix, "**")
// Perform the query, capturing exactly one log stream and erroring otherwise.
var log *coordinator.LogStream
err = client.Query(c, logProject, logPath, qo, func(s *coordinator.LogStream) bool {
log = s
return false
})
switch {
case err != nil:
return nil, grpcutil.WrapIfTransient(err)
case log == nil:
logging.Infof(c, "unable to find source manifest in project %s at path %s",
build.Infra.Logdog.Project, logPath)
return nil, nil
}
// Read the source manifest from the log stream.
var buf bytes.Buffer
_, err = buf.ReadFrom(&renderer.Renderer{
Source: client.Stream(logProject, log.Path).Fetcher(c, nil),
Raw: true,
})
if err != nil {
return nil, errors.Annotate(err, "failed to read stream").Tag(transient.Tag).Err()
}
// Unmarshal the source manifest from the bytes.
var manifest srcman.Manifest
if err := proto.Unmarshal(buf.Bytes(), &manifest); err != nil {
return nil, err
}
results := make(Checkout)
for dirname, dir := range manifest.Directories {
gitCheckout := dir.GetGitCheckout()
if gitCheckout == nil {
continue
}
url, err := gitiles.NormalizeRepoURL(gitCheckout.RepoUrl, false)
if err != nil {
logging.WithError(err).Warningf(c, "could not parse RepoURL %q for dir %q", gitCheckout.RepoUrl, dirname)
continue
}
if !strings.HasSuffix(url.Host, ".googlesource.com") {
logging.WithError(err).Warningf(c, "unsupported git host %q for dir %q", gitCheckout.RepoUrl, dirname)
continue
}
results[url.String()] = gitCheckout.Revision
}
return results, nil
} | [
"func",
"srcmanCheckout",
"(",
"c",
"context",
".",
"Context",
",",
"build",
"*",
"Build",
")",
"(",
"Checkout",
",",
"error",
")",
"{",
"transport",
",",
"err",
":=",
"auth",
".",
"GetRPCTransport",
"(",
"c",
",",
"auth",
".",
"AsSelf",
")",
"\n",
"... | // srcmanCheckout is a CheckoutFunc which retrieves a source checkout related
// to a build by querying LogDog for a source manifest stream associated with
// that build. It assumes that the build has exactly one source manifest. | [
"srcmanCheckout",
"is",
"a",
"CheckoutFunc",
"which",
"retrieves",
"a",
"source",
"checkout",
"related",
"to",
"a",
"build",
"by",
"querying",
"LogDog",
"for",
"a",
"source",
"manifest",
"stream",
"associated",
"with",
"that",
"build",
".",
"It",
"assumes",
"t... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/srcman.go#L46-L113 |
7,371 | luci/luci-go | client/internal/common/concurrent.go | NewGoroutinePool | func NewGoroutinePool(ctx context.Context, maxConcurrentJobs int) *GoroutinePool {
return &GoroutinePool{
ctx: ctx,
sema: newSemaphore(maxConcurrentJobs),
}
} | go | func NewGoroutinePool(ctx context.Context, maxConcurrentJobs int) *GoroutinePool {
return &GoroutinePool{
ctx: ctx,
sema: newSemaphore(maxConcurrentJobs),
}
} | [
"func",
"NewGoroutinePool",
"(",
"ctx",
"context",
".",
"Context",
",",
"maxConcurrentJobs",
"int",
")",
"*",
"GoroutinePool",
"{",
"return",
"&",
"GoroutinePool",
"{",
"ctx",
":",
"ctx",
",",
"sema",
":",
"newSemaphore",
"(",
"maxConcurrentJobs",
")",
",",
... | // NewGoroutinePool creates a new GoroutinePool running at most
// maxConcurrentJobs concurrent operations. | [
"NewGoroutinePool",
"creates",
"a",
"new",
"GoroutinePool",
"running",
"at",
"most",
"maxConcurrentJobs",
"concurrent",
"operations",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/concurrent.go#L86-L91 |
7,372 | luci/luci-go | client/internal/common/concurrent.go | Schedule | func (g *GoroutinePool) Schedule(job, onCanceled func()) {
g.wg.Add(1)
// Note: We could save a bit of memory by preallocating maxConcurrentJobs
// goroutines instead of one goroutine per item.
go func() {
defer g.wg.Done()
if g.sema.wait(g.ctx) == nil {
defer g.sema.signal()
job()
} else if onCanceled != nil {
onCanceled()
}
}()
} | go | func (g *GoroutinePool) Schedule(job, onCanceled func()) {
g.wg.Add(1)
// Note: We could save a bit of memory by preallocating maxConcurrentJobs
// goroutines instead of one goroutine per item.
go func() {
defer g.wg.Done()
if g.sema.wait(g.ctx) == nil {
defer g.sema.signal()
job()
} else if onCanceled != nil {
onCanceled()
}
}()
} | [
"func",
"(",
"g",
"*",
"GoroutinePool",
")",
"Schedule",
"(",
"job",
",",
"onCanceled",
"func",
"(",
")",
")",
"{",
"g",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"// Note: We could save a bit of memory by preallocating maxConcurrentJobs",
"// goroutines instead... | // Schedule adds a new job for execution as a separate goroutine.
//
// If the GoroutinePool context is canceled, onCanceled is called instead. It
// is fine to pass nil as onCanceled. | [
"Schedule",
"adds",
"a",
"new",
"job",
"for",
"execution",
"as",
"a",
"separate",
"goroutine",
".",
"If",
"the",
"GoroutinePool",
"context",
"is",
"canceled",
"onCanceled",
"is",
"called",
"instead",
".",
"It",
"is",
"fine",
"to",
"pass",
"nil",
"as",
"onC... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/concurrent.go#L114-L127 |
7,373 | luci/luci-go | client/internal/common/concurrent.go | NewGoroutinePriorityPool | func NewGoroutinePriorityPool(ctx context.Context, maxConcurrentJobs int) *GoroutinePriorityPool {
pool := &GoroutinePriorityPool{
ctx: ctx,
sema: newSemaphore(maxConcurrentJobs),
tasks: priorityQueue{},
}
return pool
} | go | func NewGoroutinePriorityPool(ctx context.Context, maxConcurrentJobs int) *GoroutinePriorityPool {
pool := &GoroutinePriorityPool{
ctx: ctx,
sema: newSemaphore(maxConcurrentJobs),
tasks: priorityQueue{},
}
return pool
} | [
"func",
"NewGoroutinePriorityPool",
"(",
"ctx",
"context",
".",
"Context",
",",
"maxConcurrentJobs",
"int",
")",
"*",
"GoroutinePriorityPool",
"{",
"pool",
":=",
"&",
"GoroutinePriorityPool",
"{",
"ctx",
":",
"ctx",
",",
"sema",
":",
"newSemaphore",
"(",
"maxCon... | // NewGoroutinePriorityPool creates a new goroutine pool with at most
// maxConcurrentJobs.
//
// Each task is run according to the priority of each item. | [
"NewGoroutinePriorityPool",
"creates",
"a",
"new",
"goroutine",
"pool",
"with",
"at",
"most",
"maxConcurrentJobs",
".",
"Each",
"task",
"is",
"run",
"according",
"to",
"the",
"priority",
"of",
"each",
"item",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/concurrent.go#L133-L140 |
7,374 | luci/luci-go | client/internal/common/concurrent.go | Schedule | func (g *GoroutinePriorityPool) Schedule(priority int64, job, onCanceled func()) {
g.wg.Add(1)
t := &task{priority, job, onCanceled}
g.mu.Lock()
heap.Push(&g.tasks, t)
g.mu.Unlock()
go g.executeOne()
} | go | func (g *GoroutinePriorityPool) Schedule(priority int64, job, onCanceled func()) {
g.wg.Add(1)
t := &task{priority, job, onCanceled}
g.mu.Lock()
heap.Push(&g.tasks, t)
g.mu.Unlock()
go g.executeOne()
} | [
"func",
"(",
"g",
"*",
"GoroutinePriorityPool",
")",
"Schedule",
"(",
"priority",
"int64",
",",
"job",
",",
"onCanceled",
"func",
"(",
")",
")",
"{",
"g",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"t",
":=",
"&",
"task",
"{",
"priority",
",",
"... | // Schedule adds a new job for execution as a separate goroutine.
//
// If the GoroutinePriorityPool is canceled, onCanceled is called instead. It
// is fine to pass nil as onCanceled. Smaller values of priority imply earlier
// execution.
//
// The lower the priority value, the higher the priority of the item. | [
"Schedule",
"adds",
"a",
"new",
"job",
"for",
"execution",
"as",
"a",
"separate",
"goroutine",
".",
"If",
"the",
"GoroutinePriorityPool",
"is",
"canceled",
"onCanceled",
"is",
"called",
"instead",
".",
"It",
"is",
"fine",
"to",
"pass",
"nil",
"as",
"onCancel... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/concurrent.go#L168-L175 |
7,375 | luci/luci-go | starlark/starlarkproto/message.go | NewMessage | func NewMessage(typ *MessageType) *Message {
return &Message{
typ: typ,
fields: starlark.StringDict{},
}
} | go | func NewMessage(typ *MessageType) *Message {
return &Message{
typ: typ,
fields: starlark.StringDict{},
}
} | [
"func",
"NewMessage",
"(",
"typ",
"*",
"MessageType",
")",
"*",
"Message",
"{",
"return",
"&",
"Message",
"{",
"typ",
":",
"typ",
",",
"fields",
":",
"starlark",
".",
"StringDict",
"{",
"}",
",",
"}",
"\n",
"}"
] | // NewMessage instantiates a new empty message of the given type. | [
"NewMessage",
"instantiates",
"a",
"new",
"empty",
"message",
"of",
"the",
"given",
"type",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L41-L46 |
7,376 | luci/luci-go | starlark/starlarkproto/message.go | ToProto | func (m *Message) ToProto() (proto.Message, error) {
ptr := m.typ.NewProtoMessage() // ~ ptr := &ProtoMessage{}
msg := ptr.Elem() // ~ msg := *ptr (a reference)
for name, val := range m.fields {
fd, ok := m.typ.fields[name]
if !ok {
panic("should not happen, SetField and Attr checks the structure already")
}
if err := assign(fd.onProtoReflection(msg, reflectToProto), val); err != nil {
return nil, fmt.Errorf("bad value for field %q of %q - %s", name, m.Type(), err)
}
}
return ptr.Interface().(proto.Message), nil
} | go | func (m *Message) ToProto() (proto.Message, error) {
ptr := m.typ.NewProtoMessage() // ~ ptr := &ProtoMessage{}
msg := ptr.Elem() // ~ msg := *ptr (a reference)
for name, val := range m.fields {
fd, ok := m.typ.fields[name]
if !ok {
panic("should not happen, SetField and Attr checks the structure already")
}
if err := assign(fd.onProtoReflection(msg, reflectToProto), val); err != nil {
return nil, fmt.Errorf("bad value for field %q of %q - %s", name, m.Type(), err)
}
}
return ptr.Interface().(proto.Message), nil
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"ToProto",
"(",
")",
"(",
"proto",
".",
"Message",
",",
"error",
")",
"{",
"ptr",
":=",
"m",
".",
"typ",
".",
"NewProtoMessage",
"(",
")",
"// ~ ptr := &ProtoMessage{}",
"\n",
"msg",
":=",
"ptr",
".",
"Elem",
"(... | // ToProto returns a new populated proto message of an appropriate type.
//
// Returns an error if the data inside the Starlark representation of
// the message has a wrong type. | [
"ToProto",
"returns",
"a",
"new",
"populated",
"proto",
"message",
"of",
"an",
"appropriate",
"type",
".",
"Returns",
"an",
"error",
"if",
"the",
"data",
"inside",
"the",
"Starlark",
"representation",
"of",
"the",
"message",
"has",
"a",
"wrong",
"type",
"."
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L57-L72 |
7,377 | luci/luci-go | starlark/starlarkproto/message.go | FromProto | func (m *Message) FromProto(p proto.Message) error {
ptr := reflect.ValueOf(p)
if ptr.Type() != m.typ.Type() {
return fmt.Errorf("bad message type: got %s, expect %s", ptr.Type(), m.typ.Type())
}
msg := ptr.Elem()
for name, fd := range m.typ.fields {
// Get the field's value from the proto message as reflect.Value. For unused
// oneof alternatives this is an invalid zero value, we skip them right
// away. For other fields it is reflect.Value (of fd.typ type) that MAY be
// nil inside (for unset fields). toStarlarkValue converts such values to
// starlark.None.
val := fd.onProtoReflection(msg, reflectFromProto)
if !val.IsValid() {
continue
}
// Convert the Go value to the corresponding Starlark value and assign it to
// the field in 'm'.
sv, err := toStarlarkValue(val)
if err != nil {
return fmt.Errorf("cannot recognize value of field %s: %s", name, err)
}
if err := m.SetField(name, sv); err != nil {
return err
}
}
return nil
} | go | func (m *Message) FromProto(p proto.Message) error {
ptr := reflect.ValueOf(p)
if ptr.Type() != m.typ.Type() {
return fmt.Errorf("bad message type: got %s, expect %s", ptr.Type(), m.typ.Type())
}
msg := ptr.Elem()
for name, fd := range m.typ.fields {
// Get the field's value from the proto message as reflect.Value. For unused
// oneof alternatives this is an invalid zero value, we skip them right
// away. For other fields it is reflect.Value (of fd.typ type) that MAY be
// nil inside (for unset fields). toStarlarkValue converts such values to
// starlark.None.
val := fd.onProtoReflection(msg, reflectFromProto)
if !val.IsValid() {
continue
}
// Convert the Go value to the corresponding Starlark value and assign it to
// the field in 'm'.
sv, err := toStarlarkValue(val)
if err != nil {
return fmt.Errorf("cannot recognize value of field %s: %s", name, err)
}
if err := m.SetField(name, sv); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"FromProto",
"(",
"p",
"proto",
".",
"Message",
")",
"error",
"{",
"ptr",
":=",
"reflect",
".",
"ValueOf",
"(",
"p",
")",
"\n",
"if",
"ptr",
".",
"Type",
"(",
")",
"!=",
"m",
".",
"typ",
".",
"Type",
"(",
... | // FromProto populates fields of this message based on values in proto.Message.
//
// Returns an error on type mismatch. | [
"FromProto",
"populates",
"fields",
"of",
"this",
"message",
"based",
"on",
"values",
"in",
"proto",
".",
"Message",
".",
"Returns",
"an",
"error",
"on",
"type",
"mismatch",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L77-L106 |
7,378 | luci/luci-go | starlark/starlarkproto/message.go | String | func (m *Message) String() string {
msg, err := m.ToProto()
if err != nil {
return fmt.Sprintf("<!Bad %s: %s!>", m.Type(), err)
}
return msg.String()
} | go | func (m *Message) String() string {
msg, err := m.ToProto()
if err != nil {
return fmt.Sprintf("<!Bad %s: %s!>", m.Type(), err)
}
return msg.String()
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"String",
"(",
")",
"string",
"{",
"msg",
",",
"err",
":=",
"m",
".",
"ToProto",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"m",
".",
"Type",
"(... | // Basic starlark.Value interface.
// String implements starlark.Value. | [
"Basic",
"starlark",
".",
"Value",
"interface",
".",
"String",
"implements",
"starlark",
".",
"Value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L138-L144 |
7,379 | luci/luci-go | starlark/starlarkproto/message.go | Freeze | func (m *Message) Freeze() {
if !m.frozen {
m.fields.Freeze()
m.frozen = true
}
} | go | func (m *Message) Freeze() {
if !m.frozen {
m.fields.Freeze()
m.frozen = true
}
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"Freeze",
"(",
")",
"{",
"if",
"!",
"m",
".",
"frozen",
"{",
"m",
".",
"fields",
".",
"Freeze",
"(",
")",
"\n",
"m",
".",
"frozen",
"=",
"true",
"\n",
"}",
"\n",
"}"
] | // Freeze implements starlark.Value. | [
"Freeze",
"implements",
"starlark",
".",
"Value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L157-L162 |
7,380 | luci/luci-go | starlark/starlarkproto/message.go | Attr | func (m *Message) Attr(name string) (starlark.Value, error) {
// The field was already set?
val, ok := m.fields[name]
if ok {
return val, nil
}
// The field wasn't set, but it is defined by the proto schema? Need to
// generate and return the default value then, except for oneof alternatives
// that do not have defaults. This is needed to make sure callers are
// explicitly picking a oneof alternative by assigning a value to it, rather
// than have it picked implicitly be reading an attribute (which is weird).
if fd, ok := m.typ.fields[name]; ok {
if !fd.defaultable {
return starlark.None, nil
}
def, err := newDefaultValue(fd.typ)
if err != nil {
return nil, err
}
// Lazy initialization of fields is an implementation detail. From the
// caller's point of view, all fields had their default values even before
// the object was frozen. Lazy-initialize the field, even if we are frozen,
// but make sure it is frozen itself too.
//
// TODO(vadimsh): This is not thread safe and should be improved if a frozen
// *Message is shared between goroutines. Generally frozen values are
// assumed to be safe for cross-goroutine use, which is not the case here.
// If this becomes important, we can force-initialize and freeze all default
// fields in Freeze().
if m.frozen {
def.Freeze()
}
m.fields[name] = def
return def, nil
}
return nil, fmt.Errorf("proto message %q has no field %q", m.Type(), name)
} | go | func (m *Message) Attr(name string) (starlark.Value, error) {
// The field was already set?
val, ok := m.fields[name]
if ok {
return val, nil
}
// The field wasn't set, but it is defined by the proto schema? Need to
// generate and return the default value then, except for oneof alternatives
// that do not have defaults. This is needed to make sure callers are
// explicitly picking a oneof alternative by assigning a value to it, rather
// than have it picked implicitly be reading an attribute (which is weird).
if fd, ok := m.typ.fields[name]; ok {
if !fd.defaultable {
return starlark.None, nil
}
def, err := newDefaultValue(fd.typ)
if err != nil {
return nil, err
}
// Lazy initialization of fields is an implementation detail. From the
// caller's point of view, all fields had their default values even before
// the object was frozen. Lazy-initialize the field, even if we are frozen,
// but make sure it is frozen itself too.
//
// TODO(vadimsh): This is not thread safe and should be improved if a frozen
// *Message is shared between goroutines. Generally frozen values are
// assumed to be safe for cross-goroutine use, which is not the case here.
// If this becomes important, we can force-initialize and freeze all default
// fields in Freeze().
if m.frozen {
def.Freeze()
}
m.fields[name] = def
return def, nil
}
return nil, fmt.Errorf("proto message %q has no field %q", m.Type(), name)
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"Attr",
"(",
"name",
"string",
")",
"(",
"starlark",
".",
"Value",
",",
"error",
")",
"{",
"// The field was already set?",
"val",
",",
"ok",
":=",
"m",
".",
"fields",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
... | // HasAttrs and HasSetField interfaces that make the message look like a struct.
// Attr implements starlark.HasAttrs. | [
"HasAttrs",
"and",
"HasSetField",
"interfaces",
"that",
"make",
"the",
"message",
"look",
"like",
"a",
"struct",
".",
"Attr",
"implements",
"starlark",
".",
"HasAttrs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L175-L213 |
7,381 | luci/luci-go | starlark/starlarkproto/message.go | SetField | func (m *Message) SetField(name string, val starlark.Value) error {
fd, ok := m.typ.fields[name]
if !ok {
return fmt.Errorf("proto message %q has no field %q", m.Type(), name)
}
// Setting a field to None removes it completely.
if val == starlark.None {
if err := m.checkMutable(); err != nil {
return err
}
delete(m.fields, name)
return nil
}
// If assigning to a messaged-valued field (singular or repeated), recognize
// dicts and Nones and use them to instantiate values (perhaps empty) of the
// corresponding proto type. This allows to construct deeply nested protobuf
// messages just by using lists, dicts and primitive values. Python does this
// too.
val, err := maybeMakeMessages(fd.typ, val)
if err != nil {
return fmt.Errorf("when constructing %q in proto %q - %s", name, m.Type(), err)
}
// Do a light type check. It doesn't "recurse" into lists or tuples. So it is
// still possible to assign e.g. a list of strings to a "repeated int64"
// field. This will be discovered later in ToProto when trying to construct
// a proto message from Starlark values.
if err := checkAssignable(fd.typ, val); err != nil {
return fmt.Errorf("can't assign value of type %q to field %q in proto %q - %s", val.Type(), name, m.Type(), err)
}
if err := m.checkMutable(); err != nil {
return err
}
m.fields[name] = val
// onChanged hooks is used by oneof's to clear alternatives that weren't
// picked.
if fd.onChanged != nil {
fd.onChanged(m.fields)
}
return nil
} | go | func (m *Message) SetField(name string, val starlark.Value) error {
fd, ok := m.typ.fields[name]
if !ok {
return fmt.Errorf("proto message %q has no field %q", m.Type(), name)
}
// Setting a field to None removes it completely.
if val == starlark.None {
if err := m.checkMutable(); err != nil {
return err
}
delete(m.fields, name)
return nil
}
// If assigning to a messaged-valued field (singular or repeated), recognize
// dicts and Nones and use them to instantiate values (perhaps empty) of the
// corresponding proto type. This allows to construct deeply nested protobuf
// messages just by using lists, dicts and primitive values. Python does this
// too.
val, err := maybeMakeMessages(fd.typ, val)
if err != nil {
return fmt.Errorf("when constructing %q in proto %q - %s", name, m.Type(), err)
}
// Do a light type check. It doesn't "recurse" into lists or tuples. So it is
// still possible to assign e.g. a list of strings to a "repeated int64"
// field. This will be discovered later in ToProto when trying to construct
// a proto message from Starlark values.
if err := checkAssignable(fd.typ, val); err != nil {
return fmt.Errorf("can't assign value of type %q to field %q in proto %q - %s", val.Type(), name, m.Type(), err)
}
if err := m.checkMutable(); err != nil {
return err
}
m.fields[name] = val
// onChanged hooks is used by oneof's to clear alternatives that weren't
// picked.
if fd.onChanged != nil {
fd.onChanged(m.fields)
}
return nil
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"SetField",
"(",
"name",
"string",
",",
"val",
"starlark",
".",
"Value",
")",
"error",
"{",
"fd",
",",
"ok",
":=",
"m",
".",
"typ",
".",
"fields",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"f... | // SetField implements starlark.HasSetField. | [
"SetField",
"implements",
"starlark",
".",
"HasSetField",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L221-L265 |
7,382 | luci/luci-go | starlark/starlarkproto/message.go | checkMutable | func (m *Message) checkMutable() error {
if m.frozen {
return fmt.Errorf("cannot modify frozen proto message %q", m.Type())
}
return nil
} | go | func (m *Message) checkMutable() error {
if m.frozen {
return fmt.Errorf("cannot modify frozen proto message %q", m.Type())
}
return nil
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"checkMutable",
"(",
")",
"error",
"{",
"if",
"m",
".",
"frozen",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"m",
".",
"Type",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkMutable returns an error if the message is frozen. | [
"checkMutable",
"returns",
"an",
"error",
"if",
"the",
"message",
"is",
"frozen",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L268-L273 |
7,383 | luci/luci-go | starlark/starlarkproto/message.go | shouldMakeMessages | func shouldMakeMessages(seq starlark.Sequence) bool {
iter := seq.Iterate()
defer iter.Done()
var v starlark.Value
for iter.Next(&v) {
if v == starlark.None {
return true
}
if _, ok := v.(*starlark.Dict); ok {
return true
}
}
return false
} | go | func shouldMakeMessages(seq starlark.Sequence) bool {
iter := seq.Iterate()
defer iter.Done()
var v starlark.Value
for iter.Next(&v) {
if v == starlark.None {
return true
}
if _, ok := v.(*starlark.Dict); ok {
return true
}
}
return false
} | [
"func",
"shouldMakeMessages",
"(",
"seq",
"starlark",
".",
"Sequence",
")",
"bool",
"{",
"iter",
":=",
"seq",
".",
"Iterate",
"(",
")",
"\n",
"defer",
"iter",
".",
"Done",
"(",
")",
"\n",
"var",
"v",
"starlark",
".",
"Value",
"\n",
"for",
"iter",
"."... | // shouldMakeMessages returns true if seq has at least one dict or None that
// should be converted to a proto message. | [
"shouldMakeMessages",
"returns",
"true",
"if",
"seq",
"has",
"at",
"least",
"one",
"dict",
"or",
"None",
"that",
"should",
"be",
"converted",
"to",
"a",
"proto",
"message",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/message.go#L337-L350 |
7,384 | luci/luci-go | logdog/server/service/service.go | Run | func (s *Service) Run(c context.Context, f func(context.Context) error) {
// Log to Stdout using JSON log lines.
c = teelogger.Use(c, gkelogger.GetFactory(os.Stdout))
// If a service name isn't specified, default to the base of the current
// executable.
if s.Name == "" {
s.Name = filepath.Base(os.Args[0])
}
s.useDatastoreConfig = true // If available, use datastore config.
rc := 0
if err := s.runImpl(c, f); err != nil {
log.WithError(err).Errorf(c, "Application exiting with error.")
rc = 1
}
os.Exit(rc)
} | go | func (s *Service) Run(c context.Context, f func(context.Context) error) {
// Log to Stdout using JSON log lines.
c = teelogger.Use(c, gkelogger.GetFactory(os.Stdout))
// If a service name isn't specified, default to the base of the current
// executable.
if s.Name == "" {
s.Name = filepath.Base(os.Args[0])
}
s.useDatastoreConfig = true // If available, use datastore config.
rc := 0
if err := s.runImpl(c, f); err != nil {
log.WithError(err).Errorf(c, "Application exiting with error.")
rc = 1
}
os.Exit(rc)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"Run",
"(",
"c",
"context",
".",
"Context",
",",
"f",
"func",
"(",
"context",
".",
"Context",
")",
"error",
")",
"{",
"// Log to Stdout using JSON log lines.",
"c",
"=",
"teelogger",
".",
"Use",
"(",
"c",
",",
"gk... | // Run performs service-wide initialization and invokes the specified run
// function. | [
"Run",
"performs",
"service",
"-",
"wide",
"initialization",
"and",
"invokes",
"the",
"specified",
"run",
"function",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/service.go#L157-L174 |
7,385 | luci/luci-go | logdog/server/service/service.go | probeGCEEnvironment | func (s *Service) probeGCEEnvironment(c context.Context) {
s.onGCE = metadata.OnGCE()
if !s.onGCE {
log.Infof(c, "Not on GCE.")
return
}
// Determine our service ID from metadata. The service ID will equal the cloud
// project ID.
if s.serviceID == "" {
var err error
if s.serviceID, err = metadata.ProjectID(); err != nil {
log.WithError(err).Warningf(c, "Failed to probe GCE project ID.")
}
log.Fields{
"serviceID": s.serviceID,
}.Infof(c, "Probed GCE service ID.")
}
} | go | func (s *Service) probeGCEEnvironment(c context.Context) {
s.onGCE = metadata.OnGCE()
if !s.onGCE {
log.Infof(c, "Not on GCE.")
return
}
// Determine our service ID from metadata. The service ID will equal the cloud
// project ID.
if s.serviceID == "" {
var err error
if s.serviceID, err = metadata.ProjectID(); err != nil {
log.WithError(err).Warningf(c, "Failed to probe GCE project ID.")
}
log.Fields{
"serviceID": s.serviceID,
}.Infof(c, "Probed GCE service ID.")
}
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"probeGCEEnvironment",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"s",
".",
"onGCE",
"=",
"metadata",
".",
"OnGCE",
"(",
")",
"\n",
"if",
"!",
"s",
".",
"onGCE",
"{",
"log",
".",
"Infof",
"(",
"c",
",",
... | // probeGCEEnvironment fills in any parameters that can be probed from Google
// Compute Engine metadata.
//
// If we're not running on GCE, this will do nothing. It is non-fatal if any
// given GCE field fails to be probed. | [
"probeGCEEnvironment",
"fills",
"in",
"any",
"parameters",
"that",
"can",
"be",
"probed",
"from",
"Google",
"Compute",
"Engine",
"metadata",
".",
"If",
"we",
"re",
"not",
"running",
"on",
"GCE",
"this",
"will",
"do",
"nothing",
".",
"It",
"is",
"non",
"-",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/service.go#L326-L345 |
7,386 | luci/luci-go | logdog/server/service/service.go | ServiceConfigPath | func (s *Service) ServiceConfigPath() (cfglib.Set, string) {
return cfglib.ServiceSet(s.serviceID), svcconfig.ServiceConfigPath
} | go | func (s *Service) ServiceConfigPath() (cfglib.Set, string) {
return cfglib.ServiceSet(s.serviceID), svcconfig.ServiceConfigPath
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"ServiceConfigPath",
"(",
")",
"(",
"cfglib",
".",
"Set",
",",
"string",
")",
"{",
"return",
"cfglib",
".",
"ServiceSet",
"(",
"s",
".",
"serviceID",
")",
",",
"svcconfig",
".",
"ServiceConfigPath",
"\n",
"}"
] | // ServiceConfigPath returns the ConfigSet and path to the current service's
// configuration. | [
"ServiceConfigPath",
"returns",
"the",
"ConfigSet",
"and",
"path",
"to",
"the",
"current",
"service",
"s",
"configuration",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/service.go#L475-L477 |
7,387 | luci/luci-go | logdog/server/service/service.go | ProjectConfigPath | func (s *Service) ProjectConfigPath(proj types.ProjectName) (cfglib.Set, string) {
return cfglib.ProjectSet(string(proj)), svcconfig.ProjectConfigPath(s.serviceID)
} | go | func (s *Service) ProjectConfigPath(proj types.ProjectName) (cfglib.Set, string) {
return cfglib.ProjectSet(string(proj)), svcconfig.ProjectConfigPath(s.serviceID)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"ProjectConfigPath",
"(",
"proj",
"types",
".",
"ProjectName",
")",
"(",
"cfglib",
".",
"Set",
",",
"string",
")",
"{",
"return",
"cfglib",
".",
"ProjectSet",
"(",
"string",
"(",
"proj",
")",
")",
",",
"svcconfig"... | // ProjectConfigPath returns the ConfigSet and path to the current service's
// project configuration for proj. | [
"ProjectConfigPath",
"returns",
"the",
"ConfigSet",
"and",
"path",
"to",
"the",
"current",
"service",
"s",
"project",
"configuration",
"for",
"proj",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/service.go#L484-L486 |
7,388 | luci/luci-go | logdog/server/service/service.go | ProjectConfig | func (s *Service) ProjectConfig(c context.Context, proj types.ProjectName) (*svcconfig.ProjectConfig, error) {
cset, path := s.ProjectConfigPath(proj)
var pcfg svcconfig.ProjectConfig
msg, err := s.configCache.Get(c, cset, path, &pcfg)
if err != nil {
return nil, errors.Annotate(err, "failed to load project config from %s.%s", cset, path).Err()
}
return msg.(*svcconfig.ProjectConfig), nil
} | go | func (s *Service) ProjectConfig(c context.Context, proj types.ProjectName) (*svcconfig.ProjectConfig, error) {
cset, path := s.ProjectConfigPath(proj)
var pcfg svcconfig.ProjectConfig
msg, err := s.configCache.Get(c, cset, path, &pcfg)
if err != nil {
return nil, errors.Annotate(err, "failed to load project config from %s.%s", cset, path).Err()
}
return msg.(*svcconfig.ProjectConfig), nil
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"ProjectConfig",
"(",
"c",
"context",
".",
"Context",
",",
"proj",
"types",
".",
"ProjectName",
")",
"(",
"*",
"svcconfig",
".",
"ProjectConfig",
",",
"error",
")",
"{",
"cset",
",",
"path",
":=",
"s",
".",
"Pro... | // ProjectConfig returns the current service's project configuration for proj. | [
"ProjectConfig",
"returns",
"the",
"current",
"service",
"s",
"project",
"configuration",
"for",
"proj",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/service.go#L489-L498 |
7,389 | luci/luci-go | logdog/server/service/service.go | GSClient | func (s *Service) GSClient(c context.Context, proj types.ProjectName) (gs.Client, error) {
// Get an Authenticator bound to the token scopes that we need for
// authenticated Cloud Storage access.
transport, err := serverAuth.GetRPCTransport(c, serverAuth.AsProject, serverAuth.WithProject(string(proj)), serverAuth.WithScopes(gs.ReadWriteScopes...))
if err != nil {
log.WithError(err).Errorf(c, "Failed to create authenticated transport for Google Storage client.")
return nil, err
}
client, err := gs.NewProdClient(c, transport)
if err != nil {
log.WithError(err).Errorf(c, "Failed to create Google Storage client.")
return nil, err
}
return client, nil
} | go | func (s *Service) GSClient(c context.Context, proj types.ProjectName) (gs.Client, error) {
// Get an Authenticator bound to the token scopes that we need for
// authenticated Cloud Storage access.
transport, err := serverAuth.GetRPCTransport(c, serverAuth.AsProject, serverAuth.WithProject(string(proj)), serverAuth.WithScopes(gs.ReadWriteScopes...))
if err != nil {
log.WithError(err).Errorf(c, "Failed to create authenticated transport for Google Storage client.")
return nil, err
}
client, err := gs.NewProdClient(c, transport)
if err != nil {
log.WithError(err).Errorf(c, "Failed to create Google Storage client.")
return nil, err
}
return client, nil
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"GSClient",
"(",
"c",
"context",
".",
"Context",
",",
"proj",
"types",
".",
"ProjectName",
")",
"(",
"gs",
".",
"Client",
",",
"error",
")",
"{",
"// Get an Authenticator bound to the token scopes that we need for",
"// aut... | // GSClient returns an authenticated Google Storage client instance. | [
"GSClient",
"returns",
"an",
"authenticated",
"Google",
"Storage",
"client",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/service.go#L571-L586 |
7,390 | luci/luci-go | logdog/server/service/service.go | withAuthService | func (s *Service) withAuthService(c context.Context) context.Context {
return serverAuth.Initialize(c, &serverAuth.Config{
DBProvider: nil, // We don't need to store an auth DB.
Signer: nil, // We don't need to sign anything.
AccessTokenProvider: func(ic context.Context, scopes []string) (*oauth2.Token, error) {
// Create a new Authenticator for the supplied scopes.
//
// Pass our outer Context, since we don't want the cached Authenticator
// instance to be permanently bound to the inner Context.
a, err := s.authenticatorForScopes(c, scopes)
scopesStr := strings.Join(scopes, " ")
if err != nil {
log.Fields{
"scopes": scopesStr,
log.ErrorKey: err,
}.Errorf(c, "Failed to create authenticator.")
return nil, err
}
tok, err := a.GetAccessToken(minAuthTokenLifetime)
if err != nil {
log.Fields{
"scopes": scopesStr,
log.ErrorKey: err,
}.Errorf(c, "Failed to mint access token.")
}
return tok, err
},
AnonymousTransport: func(ic context.Context) http.RoundTripper {
return s.unauthenticatedTransport()
},
})
} | go | func (s *Service) withAuthService(c context.Context) context.Context {
return serverAuth.Initialize(c, &serverAuth.Config{
DBProvider: nil, // We don't need to store an auth DB.
Signer: nil, // We don't need to sign anything.
AccessTokenProvider: func(ic context.Context, scopes []string) (*oauth2.Token, error) {
// Create a new Authenticator for the supplied scopes.
//
// Pass our outer Context, since we don't want the cached Authenticator
// instance to be permanently bound to the inner Context.
a, err := s.authenticatorForScopes(c, scopes)
scopesStr := strings.Join(scopes, " ")
if err != nil {
log.Fields{
"scopes": scopesStr,
log.ErrorKey: err,
}.Errorf(c, "Failed to create authenticator.")
return nil, err
}
tok, err := a.GetAccessToken(minAuthTokenLifetime)
if err != nil {
log.Fields{
"scopes": scopesStr,
log.ErrorKey: err,
}.Errorf(c, "Failed to mint access token.")
}
return tok, err
},
AnonymousTransport: func(ic context.Context) http.RoundTripper {
return s.unauthenticatedTransport()
},
})
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"withAuthService",
"(",
"c",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"return",
"serverAuth",
".",
"Initialize",
"(",
"c",
",",
"&",
"serverAuth",
".",
"Config",
"{",
"DBProvider",
":",
"nil",... | // withAuthService configures service-wide authentication and installs it into
// the supplied Context. | [
"withAuthService",
"configures",
"service",
"-",
"wide",
"authentication",
"and",
"installs",
"it",
"into",
"the",
"supplied",
"Context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/service.go#L613-L644 |
7,391 | luci/luci-go | common/runtime/profiling/profiler.go | AddFlags | func (p *Profiler) AddFlags(fs *flag.FlagSet) {
fs.StringVar(&p.BindHTTP, "profile-bind-http", "",
"If specified, run a runtime profiler HTTP server bound to this [address][:port].")
fs.StringVar(&p.Dir, "profile-output-dir", "",
"If specified, allow generation of profiling artifacts, which will be written here.")
fs.BoolVar(&p.ProfileCPU, "profile-cpu", false, "If specified, enables CPU profiling.")
fs.BoolVar(&p.ProfileHeap, "profile-heap", false, "If specified, enables heap profiling.")
} | go | func (p *Profiler) AddFlags(fs *flag.FlagSet) {
fs.StringVar(&p.BindHTTP, "profile-bind-http", "",
"If specified, run a runtime profiler HTTP server bound to this [address][:port].")
fs.StringVar(&p.Dir, "profile-output-dir", "",
"If specified, allow generation of profiling artifacts, which will be written here.")
fs.BoolVar(&p.ProfileCPU, "profile-cpu", false, "If specified, enables CPU profiling.")
fs.BoolVar(&p.ProfileHeap, "profile-heap", false, "If specified, enables heap profiling.")
} | [
"func",
"(",
"p",
"*",
"Profiler",
")",
"AddFlags",
"(",
"fs",
"*",
"flag",
".",
"FlagSet",
")",
"{",
"fs",
".",
"StringVar",
"(",
"&",
"p",
".",
"BindHTTP",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"fs",
".",
"StringVar",
... | // AddFlags adds command line flags to common Profiler fields. | [
"AddFlags",
"adds",
"command",
"line",
"flags",
"to",
"common",
"Profiler",
"fields",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/profiling/profiler.go#L80-L88 |
7,392 | luci/luci-go | common/runtime/profiling/profiler.go | Start | func (p *Profiler) Start() error {
if p.Dir == "" {
if p.ProfileCPU {
return errors.New("-profile-cpu requires -profile-output-dir to be set")
}
if p.ProfileHeap {
return errors.New("-profile-heap requires -profile-output-dir to be set")
}
}
if p.ProfileCPU {
out, err := os.Create(p.generateOutPath("cpu"))
if err != nil {
return errors.Annotate(err, "failed to create CPU profile output file").Err()
}
pprof.StartCPUProfile(out)
p.profilingCPU = true
}
if p.BindHTTP != "" {
if err := p.startHTTP(); err != nil {
return errors.Annotate(err, "failed to start HTTP server").Err()
}
}
return nil
} | go | func (p *Profiler) Start() error {
if p.Dir == "" {
if p.ProfileCPU {
return errors.New("-profile-cpu requires -profile-output-dir to be set")
}
if p.ProfileHeap {
return errors.New("-profile-heap requires -profile-output-dir to be set")
}
}
if p.ProfileCPU {
out, err := os.Create(p.generateOutPath("cpu"))
if err != nil {
return errors.Annotate(err, "failed to create CPU profile output file").Err()
}
pprof.StartCPUProfile(out)
p.profilingCPU = true
}
if p.BindHTTP != "" {
if err := p.startHTTP(); err != nil {
return errors.Annotate(err, "failed to start HTTP server").Err()
}
}
return nil
} | [
"func",
"(",
"p",
"*",
"Profiler",
")",
"Start",
"(",
")",
"error",
"{",
"if",
"p",
".",
"Dir",
"==",
"\"",
"\"",
"{",
"if",
"p",
".",
"ProfileCPU",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
".",
... | // Start starts the Profiler's configured operations. On success, returns a
// function that can be called to shutdown the profiling server.
//
// Calling Stop is not necessary, but will enable end-of-operation profiling
// to be gathered. | [
"Start",
"starts",
"the",
"Profiler",
"s",
"configured",
"operations",
".",
"On",
"success",
"returns",
"a",
"function",
"that",
"can",
"be",
"called",
"to",
"shutdown",
"the",
"profiling",
"server",
".",
"Calling",
"Stop",
"is",
"not",
"necessary",
"but",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/profiling/profiler.go#L95-L121 |
7,393 | luci/luci-go | common/runtime/profiling/profiler.go | Stop | func (p *Profiler) Stop() {
if p.profilingCPU {
pprof.StopCPUProfile()
p.profilingCPU = false
}
if p.listener != nil {
if err := p.listener.Close(); err != nil {
p.getLogger().Warningf("Failed to stop profile HTTP server: %s", err)
}
p.listener = nil
}
// Take one final snapshot.
p.DumpSnapshot()
} | go | func (p *Profiler) Stop() {
if p.profilingCPU {
pprof.StopCPUProfile()
p.profilingCPU = false
}
if p.listener != nil {
if err := p.listener.Close(); err != nil {
p.getLogger().Warningf("Failed to stop profile HTTP server: %s", err)
}
p.listener = nil
}
// Take one final snapshot.
p.DumpSnapshot()
} | [
"func",
"(",
"p",
"*",
"Profiler",
")",
"Stop",
"(",
")",
"{",
"if",
"p",
".",
"profilingCPU",
"{",
"pprof",
".",
"StopCPUProfile",
"(",
")",
"\n",
"p",
".",
"profilingCPU",
"=",
"false",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"listener",
"!=",
"nil",
... | // Stop stops the Profiler's operations. | [
"Stop",
"stops",
"the",
"Profiler",
"s",
"operations",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/profiling/profiler.go#L154-L169 |
7,394 | luci/luci-go | common/runtime/profiling/profiler.go | DumpSnapshot | func (p *Profiler) DumpSnapshot() error {
if p.Dir == "" {
return nil
}
if p.ProfileHeap {
if err := p.dumpHeapProfile(); err != nil {
return errors.Annotate(err, "failed to dump heap profile").Err()
}
}
return nil
} | go | func (p *Profiler) DumpSnapshot() error {
if p.Dir == "" {
return nil
}
if p.ProfileHeap {
if err := p.dumpHeapProfile(); err != nil {
return errors.Annotate(err, "failed to dump heap profile").Err()
}
}
return nil
} | [
"func",
"(",
"p",
"*",
"Profiler",
")",
"DumpSnapshot",
"(",
")",
"error",
"{",
"if",
"p",
".",
"Dir",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"ProfileHeap",
"{",
"if",
"err",
":=",
"p",
".",
"dumpHeapProfile",
... | // DumpSnapshot dumps a profile snapshot to the configured output directory. If
// no output directory is configured, nothing will happen. | [
"DumpSnapshot",
"dumps",
"a",
"profile",
"snapshot",
"to",
"the",
"configured",
"output",
"directory",
".",
"If",
"no",
"output",
"directory",
"is",
"configured",
"nothing",
"will",
"happen",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/profiling/profiler.go#L173-L185 |
7,395 | luci/luci-go | tokenserver/appengine/impl/utils/service_info.go | ServiceVersion | func ServiceVersion(c context.Context, s signing.Signer) (string, error) {
inf, err := s.ServiceInfo(c) // cached
if err != nil {
return "", err
}
return fmt.Sprintf("%s/%s", inf.AppID, inf.AppVersion), nil
} | go | func ServiceVersion(c context.Context, s signing.Signer) (string, error) {
inf, err := s.ServiceInfo(c) // cached
if err != nil {
return "", err
}
return fmt.Sprintf("%s/%s", inf.AppID, inf.AppVersion), nil
} | [
"func",
"ServiceVersion",
"(",
"c",
"context",
".",
"Context",
",",
"s",
"signing",
".",
"Signer",
")",
"(",
"string",
",",
"error",
")",
"{",
"inf",
",",
"err",
":=",
"s",
".",
"ServiceInfo",
"(",
"c",
")",
"// cached",
"\n",
"if",
"err",
"!=",
"n... | // ServiceVersion returns a string that identifies the app and the version.
//
// It is put in some server responses. The function extracts this information
// from the given signer.
//
// This function almost never returns errors. It can return an error only when
// called for the first time during the process lifetime. It gets cached after
// first successful return. | [
"ServiceVersion",
"returns",
"a",
"string",
"that",
"identifies",
"the",
"app",
"and",
"the",
"version",
".",
"It",
"is",
"put",
"in",
"some",
"server",
"responses",
".",
"The",
"function",
"extracts",
"this",
"information",
"from",
"the",
"given",
"signer",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/service_info.go#L32-L38 |
7,396 | luci/luci-go | auth/integration/localauth/rpcs/getoauthtoken.go | Validate | func (r *GetOAuthTokenRequest) Validate() error {
switch {
case len(r.Scopes) == 0:
return errors.New(`field "scopes" is required`)
case len(r.Secret) == 0:
return errors.New(`field "secret" is required`)
case r.AccountID == "":
return errors.New(`field "account_id" is required`)
}
return nil
} | go | func (r *GetOAuthTokenRequest) Validate() error {
switch {
case len(r.Scopes) == 0:
return errors.New(`field "scopes" is required`)
case len(r.Secret) == 0:
return errors.New(`field "secret" is required`)
case r.AccountID == "":
return errors.New(`field "account_id" is required`)
}
return nil
} | [
"func",
"(",
"r",
"*",
"GetOAuthTokenRequest",
")",
"Validate",
"(",
")",
"error",
"{",
"switch",
"{",
"case",
"len",
"(",
"r",
".",
"Scopes",
")",
"==",
"0",
":",
"return",
"errors",
".",
"New",
"(",
"`field \"scopes\" is required`",
")",
"\n",
"case",
... | // Validate checks that the request is structurally valid. | [
"Validate",
"checks",
"that",
"the",
"request",
"is",
"structurally",
"valid",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/integration/localauth/rpcs/getoauthtoken.go#L29-L39 |
7,397 | luci/luci-go | common/sync/promise/map.go | Get | func (pm *Map) Get(c context.Context, key interface{}, gen Generator) *Promise {
pm.mu.RLock()
p := pm.m[key]
pm.mu.RUnlock()
if p != nil {
return p
}
pm.mu.Lock()
defer pm.mu.Unlock()
if p = pm.m[key]; p == nil {
p = New(c, gen)
if pm.m == nil {
pm.m = make(map[interface{}]*Promise, 1)
}
pm.m[key] = p
}
return p
} | go | func (pm *Map) Get(c context.Context, key interface{}, gen Generator) *Promise {
pm.mu.RLock()
p := pm.m[key]
pm.mu.RUnlock()
if p != nil {
return p
}
pm.mu.Lock()
defer pm.mu.Unlock()
if p = pm.m[key]; p == nil {
p = New(c, gen)
if pm.m == nil {
pm.m = make(map[interface{}]*Promise, 1)
}
pm.m[key] = p
}
return p
} | [
"func",
"(",
"pm",
"*",
"Map",
")",
"Get",
"(",
"c",
"context",
".",
"Context",
",",
"key",
"interface",
"{",
"}",
",",
"gen",
"Generator",
")",
"*",
"Promise",
"{",
"pm",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"p",
":=",
"pm",
".",
"m",
"[... | // Get either returns an existing promise for the given key or creates and
// immediately launches a new promise. | [
"Get",
"either",
"returns",
"an",
"existing",
"promise",
"for",
"the",
"given",
"key",
"or",
"creates",
"and",
"immediately",
"launches",
"a",
"new",
"promise",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/promise/map.go#L34-L54 |
7,398 | luci/luci-go | milo/buildsource/buildbucket/feedback_links.go | MakeBuildBugLink | func MakeBuildBugLink(bt *config.BugTemplate, data interface{}) (string, error) {
summary, err := summary(bt, data)
if err != nil {
return "", errors.Annotate(err, "Unable to make summary for build bug link.").Err()
}
description, err := description(bt, data)
if err != nil {
return "", errors.Annotate(err, "Unable to make description for build bug link.").Err()
}
query := url.Values{
"summary": {summary},
"description": {description},
}
if len(bt.Components) > 0 {
query.Add("components", strings.Join(bt.Components, ","))
}
link := url.URL{
Scheme: "https",
Host: "bugs.chromium.org",
Path: fmt.Sprintf("/p/%s/issues/entry", bt.MonorailProject),
RawQuery: query.Encode(),
}
return link.String(), nil
} | go | func MakeBuildBugLink(bt *config.BugTemplate, data interface{}) (string, error) {
summary, err := summary(bt, data)
if err != nil {
return "", errors.Annotate(err, "Unable to make summary for build bug link.").Err()
}
description, err := description(bt, data)
if err != nil {
return "", errors.Annotate(err, "Unable to make description for build bug link.").Err()
}
query := url.Values{
"summary": {summary},
"description": {description},
}
if len(bt.Components) > 0 {
query.Add("components", strings.Join(bt.Components, ","))
}
link := url.URL{
Scheme: "https",
Host: "bugs.chromium.org",
Path: fmt.Sprintf("/p/%s/issues/entry", bt.MonorailProject),
RawQuery: query.Encode(),
}
return link.String(), nil
} | [
"func",
"MakeBuildBugLink",
"(",
"bt",
"*",
"config",
".",
"BugTemplate",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"summary",
",",
"err",
":=",
"summary",
"(",
"bt",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
... | // makeBuildBugLink attempts to create the feedback link for the build page. If the
// project is not configured for a custom build bug link or an interpolation placeholder
// cannot be satisfied an empty string is returned. | [
"makeBuildBugLink",
"attempts",
"to",
"create",
"the",
"feedback",
"link",
"for",
"the",
"build",
"page",
".",
"If",
"the",
"project",
"is",
"not",
"configured",
"for",
"a",
"custom",
"build",
"bug",
"link",
"or",
"an",
"interpolation",
"placeholder",
"cannot"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/feedback_links.go#L45-L72 |
7,399 | luci/luci-go | appengine/datastorecache/cache.go | pruneInterval | func (cache *Cache) pruneInterval() time.Duration {
if cache.AccessUpdateInterval > 0 && cache.PruneFactor > 0 {
return cache.AccessUpdateInterval * time.Duration(1+cache.PruneFactor)
}
return 0
} | go | func (cache *Cache) pruneInterval() time.Duration {
if cache.AccessUpdateInterval > 0 && cache.PruneFactor > 0 {
return cache.AccessUpdateInterval * time.Duration(1+cache.PruneFactor)
}
return 0
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"pruneInterval",
"(",
")",
"time",
".",
"Duration",
"{",
"if",
"cache",
".",
"AccessUpdateInterval",
">",
"0",
"&&",
"cache",
".",
"PruneFactor",
">",
"0",
"{",
"return",
"cache",
".",
"AccessUpdateInterval",
"*",
... | // pruneInterval calculates the prune interval. This is a function of the
// cache's AccessUpdateInterval and PruneFactor.
//
// If either AccessUpdateInterval or PruneFactor is <= 0, this will return 0,
// indicating no prune interval. | [
"pruneInterval",
"calculates",
"the",
"prune",
"interval",
".",
"This",
"is",
"a",
"function",
"of",
"the",
"cache",
"s",
"AccessUpdateInterval",
"and",
"PruneFactor",
".",
"If",
"either",
"AccessUpdateInterval",
"or",
"PruneFactor",
"is",
"<",
"=",
"0",
"this",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/datastorecache/cache.go#L171-L176 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.