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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6,900 | luci/luci-go | grpc/cmd/cproto/transform.go | generateClients | func (t *transformer) generateClients(file *ast.File, s *service) error {
switch newDecls, err := t.generateClient(s.protoPackageName, s.name, s.clientIface); {
case err != nil:
return err
case len(newDecls) > 0:
insertAST(file, s.clientIfaceDecl, newDecls)
return nil
default:
return nil
}
} | go | func (t *transformer) generateClients(file *ast.File, s *service) error {
switch newDecls, err := t.generateClient(s.protoPackageName, s.name, s.clientIface); {
case err != nil:
return err
case len(newDecls) > 0:
insertAST(file, s.clientIfaceDecl, newDecls)
return nil
default:
return nil
}
} | [
"func",
"(",
"t",
"*",
"transformer",
")",
"generateClients",
"(",
"file",
"*",
"ast",
".",
"File",
",",
"s",
"*",
"service",
")",
"error",
"{",
"switch",
"newDecls",
",",
"err",
":=",
"t",
".",
"generateClient",
"(",
"s",
".",
"protoPackageName",
",",... | // generateClients finds client interface declarations
// and inserts pRPC implementations after them. | [
"generateClients",
"finds",
"client",
"interface",
"declarations",
"and",
"inserts",
"pRPC",
"implementations",
"after",
"them",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/transform.go#L123-L133 |
6,901 | luci/luci-go | grpc/cmd/cproto/transform.go | generateClient | func (t *transformer) generateClient(protoPackage, serviceName string, iface *ast.InterfaceType) ([]ast.Decl, error) {
// This function used to construct an AST. It was a lot of code.
// Now it generates code via a template and parses back to AST.
// Slower, but saner and easier to make changes.
type Method struct {
Name string
InputMessage string
OutputMessage string
}
methods := make([]Method, 0, len(iface.Methods.List))
var buf bytes.Buffer
toGoCode := func(n ast.Node) (string, error) {
defer buf.Reset()
err := format.Node(&buf, t.fset, n)
if err != nil {
return "", err
}
return buf.String(), nil
}
for _, m := range iface.Methods.List {
signature, ok := m.Type.(*ast.FuncType)
if !ok {
return nil, fmt.Errorf("unexpected embedded interface in %sClient", serviceName)
}
inStructPtr := signature.Params.List[1].Type.(*ast.StarExpr)
inStruct, err := toGoCode(inStructPtr.X)
if err != nil {
return nil, err
}
outStructPtr := signature.Results.List[0].Type.(*ast.StarExpr)
outStruct, err := toGoCode(outStructPtr.X)
if err != nil {
return nil, err
}
methods = append(methods, Method{
Name: m.Names[0].Name,
InputMessage: inStruct,
OutputMessage: outStruct,
})
}
prpcSymbolPrefix := "prpc."
if t.inPRPCPackage {
prpcSymbolPrefix = ""
}
err := clientCodeTemplate.Execute(&buf, map[string]interface{}{
"Service": serviceName,
"ProtoPkg": protoPackage,
"StructName": firstLower(serviceName) + "PRPCClient",
"Methods": methods,
"PRPCSymbolPrefix": prpcSymbolPrefix,
})
if err != nil {
return nil, fmt.Errorf("client template execution: %s", err)
}
f, err := parser.ParseFile(t.fset, "", buf.String(), 0)
if err != nil {
return nil, fmt.Errorf("client template result parsing: %s. Code: %#v", err, buf.String())
}
return f.Decls, nil
} | go | func (t *transformer) generateClient(protoPackage, serviceName string, iface *ast.InterfaceType) ([]ast.Decl, error) {
// This function used to construct an AST. It was a lot of code.
// Now it generates code via a template and parses back to AST.
// Slower, but saner and easier to make changes.
type Method struct {
Name string
InputMessage string
OutputMessage string
}
methods := make([]Method, 0, len(iface.Methods.List))
var buf bytes.Buffer
toGoCode := func(n ast.Node) (string, error) {
defer buf.Reset()
err := format.Node(&buf, t.fset, n)
if err != nil {
return "", err
}
return buf.String(), nil
}
for _, m := range iface.Methods.List {
signature, ok := m.Type.(*ast.FuncType)
if !ok {
return nil, fmt.Errorf("unexpected embedded interface in %sClient", serviceName)
}
inStructPtr := signature.Params.List[1].Type.(*ast.StarExpr)
inStruct, err := toGoCode(inStructPtr.X)
if err != nil {
return nil, err
}
outStructPtr := signature.Results.List[0].Type.(*ast.StarExpr)
outStruct, err := toGoCode(outStructPtr.X)
if err != nil {
return nil, err
}
methods = append(methods, Method{
Name: m.Names[0].Name,
InputMessage: inStruct,
OutputMessage: outStruct,
})
}
prpcSymbolPrefix := "prpc."
if t.inPRPCPackage {
prpcSymbolPrefix = ""
}
err := clientCodeTemplate.Execute(&buf, map[string]interface{}{
"Service": serviceName,
"ProtoPkg": protoPackage,
"StructName": firstLower(serviceName) + "PRPCClient",
"Methods": methods,
"PRPCSymbolPrefix": prpcSymbolPrefix,
})
if err != nil {
return nil, fmt.Errorf("client template execution: %s", err)
}
f, err := parser.ParseFile(t.fset, "", buf.String(), 0)
if err != nil {
return nil, fmt.Errorf("client template result parsing: %s. Code: %#v", err, buf.String())
}
return f.Decls, nil
} | [
"func",
"(",
"t",
"*",
"transformer",
")",
"generateClient",
"(",
"protoPackage",
",",
"serviceName",
"string",
",",
"iface",
"*",
"ast",
".",
"InterfaceType",
")",
"(",
"[",
"]",
"ast",
".",
"Decl",
",",
"error",
")",
"{",
"// This function used to construc... | // generateClient generates pRPC implementation of a client interface. | [
"generateClient",
"generates",
"pRPC",
"implementation",
"of",
"a",
"client",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/transform.go#L169-L236 |
6,902 | luci/luci-go | mp/cmd/mpagent/utils.go | getClient | func getClient(ctx context.Context, client *http.Client, server string) (*MachineProvider, error) {
mp, err := machine.New(client)
if err != nil {
return nil, err
}
mp.BasePath = server + "/_ah/api/machine/v1/"
return &MachineProvider{client: mp}, nil
} | go | func getClient(ctx context.Context, client *http.Client, server string) (*MachineProvider, error) {
mp, err := machine.New(client)
if err != nil {
return nil, err
}
mp.BasePath = server + "/_ah/api/machine/v1/"
return &MachineProvider{client: mp}, nil
} | [
"func",
"getClient",
"(",
"ctx",
"context",
".",
"Context",
",",
"client",
"*",
"http",
".",
"Client",
",",
"server",
"string",
")",
"(",
"*",
"MachineProvider",
",",
"error",
")",
"{",
"mp",
",",
"err",
":=",
"machine",
".",
"New",
"(",
"client",
")... | // getClient returns a new instance of the MachineProvider client. | [
"getClient",
"returns",
"a",
"new",
"instance",
"of",
"the",
"MachineProvider",
"client",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/utils.go#L32-L39 |
6,903 | luci/luci-go | mp/cmd/mpagent/utils.go | ack | func (mp *MachineProvider) ack(ctx context.Context, hostname, backend string) error {
return mp.client.Ack(&machine.ComponentsMachineProviderRpcMessagesAckRequest{
Backend: backend,
Hostname: hostname,
}).Context(ctx).Do()
} | go | func (mp *MachineProvider) ack(ctx context.Context, hostname, backend string) error {
return mp.client.Ack(&machine.ComponentsMachineProviderRpcMessagesAckRequest{
Backend: backend,
Hostname: hostname,
}).Context(ctx).Do()
} | [
"func",
"(",
"mp",
"*",
"MachineProvider",
")",
"ack",
"(",
"ctx",
"context",
".",
"Context",
",",
"hostname",
",",
"backend",
"string",
")",
"error",
"{",
"return",
"mp",
".",
"client",
".",
"Ack",
"(",
"&",
"machine",
".",
"ComponentsMachineProviderRpcMe... | // ack acknowledges receipt and execution of a Machine Provider instruction. | [
"ack",
"acknowledges",
"receipt",
"and",
"execution",
"of",
"a",
"Machine",
"Provider",
"instruction",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/utils.go#L42-L47 |
6,904 | luci/luci-go | mp/cmd/mpagent/utils.go | poll | func (mp *MachineProvider) poll(ctx context.Context, hostname, backend string) (*machine.ComponentsMachineProviderRpcMessagesPollResponse, error) {
return mp.client.Poll(&machine.ComponentsMachineProviderRpcMessagesPollRequest{
Backend: backend,
Hostname: hostname,
}).Context(ctx).Do()
} | go | func (mp *MachineProvider) poll(ctx context.Context, hostname, backend string) (*machine.ComponentsMachineProviderRpcMessagesPollResponse, error) {
return mp.client.Poll(&machine.ComponentsMachineProviderRpcMessagesPollRequest{
Backend: backend,
Hostname: hostname,
}).Context(ctx).Do()
} | [
"func",
"(",
"mp",
"*",
"MachineProvider",
")",
"poll",
"(",
"ctx",
"context",
".",
"Context",
",",
"hostname",
",",
"backend",
"string",
")",
"(",
"*",
"machine",
".",
"ComponentsMachineProviderRpcMessagesPollResponse",
",",
"error",
")",
"{",
"return",
"mp",... | // poll polls Machine Provider for instructions.
//
// Returns an Instruction. | [
"poll",
"polls",
"Machine",
"Provider",
"for",
"instructions",
".",
"Returns",
"an",
"Instruction",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/utils.go#L52-L57 |
6,905 | luci/luci-go | mp/cmd/mpagent/utils.go | substitute | func substitute(ctx context.Context, templateString string, substitutions interface{}) (string, error) {
template, err := template.New(templateString).Parse(templateString)
if err != nil {
return "", err
}
buffer := bytes.Buffer{}
if err = template.Execute(&buffer, substitutions); err != nil {
return "", nil
}
return buffer.String(), nil
} | go | func substitute(ctx context.Context, templateString string, substitutions interface{}) (string, error) {
template, err := template.New(templateString).Parse(templateString)
if err != nil {
return "", err
}
buffer := bytes.Buffer{}
if err = template.Execute(&buffer, substitutions); err != nil {
return "", nil
}
return buffer.String(), nil
} | [
"func",
"substitute",
"(",
"ctx",
"context",
".",
"Context",
",",
"templateString",
"string",
",",
"substitutions",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"template",
",",
"err",
":=",
"template",
".",
"New",
"(",
"templateStrin... | // substitute reads a template string and performs substitutions.
//
// Returns a string. | [
"substitute",
"reads",
"a",
"template",
"string",
"and",
"performs",
"substitutions",
".",
"Returns",
"a",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/utils.go#L62-L72 |
6,906 | luci/luci-go | mp/cmd/mpagent/utils.go | substituteAsset | func substituteAsset(ctx context.Context, asset string, substitutions interface{}) (string, error) {
return substitute(ctx, string(GetAsset(asset)), substitutions)
} | go | func substituteAsset(ctx context.Context, asset string, substitutions interface{}) (string, error) {
return substitute(ctx, string(GetAsset(asset)), substitutions)
} | [
"func",
"substituteAsset",
"(",
"ctx",
"context",
".",
"Context",
",",
"asset",
"string",
",",
"substitutions",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"substitute",
"(",
"ctx",
",",
"string",
"(",
"GetAsset",
"(",
"a... | // substitute asset reads an asset string and performs substitutions.
//
// Returns a string. | [
"substitute",
"asset",
"reads",
"an",
"asset",
"string",
"and",
"performs",
"substitutions",
".",
"Returns",
"a",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/mpagent/utils.go#L77-L79 |
6,907 | luci/luci-go | common/cli/cli.go | Getenv | func Getenv(ctx context.Context, key string) string {
return LookupEnv(ctx, key).Value
} | go | func Getenv(ctx context.Context, key string) string {
return LookupEnv(ctx, key).Value
} | [
"func",
"Getenv",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"string",
"{",
"return",
"LookupEnv",
"(",
"ctx",
",",
"key",
")",
".",
"Value",
"\n",
"}"
] | // Getenv returns the given value from the embedded subcommands.Env, or "" if
// the value was unset and had no default. | [
"Getenv",
"returns",
"the",
"given",
"value",
"from",
"the",
"embedded",
"subcommands",
".",
"Env",
"or",
"if",
"the",
"value",
"was",
"unset",
"and",
"had",
"no",
"default",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/cli/cli.go#L41-L43 |
6,908 | luci/luci-go | common/cli/cli.go | LookupEnv | func LookupEnv(ctx context.Context, key string) subcommands.EnvVar {
e, _ := ctx.Value(&envKey).(subcommands.Env)
return e[key]
} | go | func LookupEnv(ctx context.Context, key string) subcommands.EnvVar {
e, _ := ctx.Value(&envKey).(subcommands.Env)
return e[key]
} | [
"func",
"LookupEnv",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"subcommands",
".",
"EnvVar",
"{",
"e",
",",
"_",
":=",
"ctx",
".",
"Value",
"(",
"&",
"envKey",
")",
".",
"(",
"subcommands",
".",
"Env",
")",
"\n",
"return",
"... | // LookupEnv returns the given value from the embedded subcommands.Env as-is. | [
"LookupEnv",
"returns",
"the",
"given",
"value",
"from",
"the",
"embedded",
"subcommands",
".",
"Env",
"as",
"-",
"is",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/cli/cli.go#L46-L49 |
6,909 | luci/luci-go | common/cli/cli.go | MakeGetEnv | func MakeGetEnv(ctx context.Context) func(string) string {
return func(key string) string {
if v := LookupEnv(ctx, key); v.Exists {
return v.Value
}
return ""
}
} | go | func MakeGetEnv(ctx context.Context) func(string) string {
return func(key string) string {
if v := LookupEnv(ctx, key); v.Exists {
return v.Value
}
return ""
}
} | [
"func",
"MakeGetEnv",
"(",
"ctx",
"context",
".",
"Context",
")",
"func",
"(",
"string",
")",
"string",
"{",
"return",
"func",
"(",
"key",
"string",
")",
"string",
"{",
"if",
"v",
":=",
"LookupEnv",
"(",
"ctx",
",",
"key",
")",
";",
"v",
".",
"Exis... | // MakeGetEnv returns a function bound to the supplied Context that has the
// same semantics as os.Getenv. This can be used to simplify environment
// compatibility. | [
"MakeGetEnv",
"returns",
"a",
"function",
"bound",
"to",
"the",
"supplied",
"Context",
"that",
"has",
"the",
"same",
"semantics",
"as",
"os",
".",
"Getenv",
".",
"This",
"can",
"be",
"used",
"to",
"simplify",
"environment",
"compatibility",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/cli/cli.go#L54-L61 |
6,910 | luci/luci-go | common/cli/cli.go | GetCommands | func (a *Application) GetCommands() []*subcommands.Command {
a.profiling.addProfiling(a.Commands)
return a.Commands
} | go | func (a *Application) GetCommands() []*subcommands.Command {
a.profiling.addProfiling(a.Commands)
return a.Commands
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"GetCommands",
"(",
")",
"[",
"]",
"*",
"subcommands",
".",
"Command",
"{",
"a",
".",
"profiling",
".",
"addProfiling",
"(",
"a",
".",
"Commands",
")",
"\n",
"return",
"a",
".",
"Commands",
"\n",
"}"
] | // GetCommands implements interface subcommands.Application. | [
"GetCommands",
"implements",
"interface",
"subcommands",
".",
"Application",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/cli/cli.go#L114-L117 |
6,911 | luci/luci-go | buildbucket/access/action.go | ParseAction | func ParseAction(action string) (Action, error) {
if action, ok := nameToAction[action]; ok {
return action, nil
}
return 0, fmt.Errorf("unexpected action %q", action)
} | go | func ParseAction(action string) (Action, error) {
if action, ok := nameToAction[action]; ok {
return action, nil
}
return 0, fmt.Errorf("unexpected action %q", action)
} | [
"func",
"ParseAction",
"(",
"action",
"string",
")",
"(",
"Action",
",",
"error",
")",
"{",
"if",
"action",
",",
"ok",
":=",
"nameToAction",
"[",
"action",
"]",
";",
"ok",
"{",
"return",
"action",
",",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"f... | // ParseAction parses the action name into an. | [
"ParseAction",
"parses",
"the",
"action",
"name",
"into",
"an",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/action.go#L89-L94 |
6,912 | luci/luci-go | buildbucket/access/action.go | String | func (a Action) String() string {
// Fast path for only one action.
if name, ok := actionToName[a]; ok {
return name
}
// Slow path for many actions.
var values []string
for action, name := range actionToName {
if action&a == action {
values = append(values, name)
}
}
return strings.Join(values, ", ")
} | go | func (a Action) String() string {
// Fast path for only one action.
if name, ok := actionToName[a]; ok {
return name
}
// Slow path for many actions.
var values []string
for action, name := range actionToName {
if action&a == action {
values = append(values, name)
}
}
return strings.Join(values, ", ")
} | [
"func",
"(",
"a",
"Action",
")",
"String",
"(",
")",
"string",
"{",
"// Fast path for only one action.",
"if",
"name",
",",
"ok",
":=",
"actionToName",
"[",
"a",
"]",
";",
"ok",
"{",
"return",
"name",
"\n",
"}",
"\n",
"// Slow path for many actions.",
"var",... | // String returns the action name as a string. | [
"String",
"returns",
"the",
"action",
"name",
"as",
"a",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/action.go#L97-L110 |
6,913 | luci/luci-go | buildbucket/access/action.go | MarshalBinary | func (a *Action) MarshalBinary() ([]byte, error) {
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, uint32(*a))
return bytes, nil
} | go | func (a *Action) MarshalBinary() ([]byte, error) {
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, uint32(*a))
return bytes, nil
} | [
"func",
"(",
"a",
"*",
"Action",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"bytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"bytes",
",",... | // MarshalBinary encodes the Action as bytes. | [
"MarshalBinary",
"encodes",
"the",
"Action",
"as",
"bytes",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/action.go#L113-L117 |
6,914 | luci/luci-go | buildbucket/access/action.go | UnmarshalBinary | func (a *Action) UnmarshalBinary(blob []byte) error {
if len(blob) != 4 {
return errors.New("expected length of 4")
}
*a = Action(binary.LittleEndian.Uint32(blob))
return nil
} | go | func (a *Action) UnmarshalBinary(blob []byte) error {
if len(blob) != 4 {
return errors.New("expected length of 4")
}
*a = Action(binary.LittleEndian.Uint32(blob))
return nil
} | [
"func",
"(",
"a",
"*",
"Action",
")",
"UnmarshalBinary",
"(",
"blob",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"len",
"(",
"blob",
")",
"!=",
"4",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"*",
"a",
"=",
"A... | // UnmarshalBinary decodes an Action from bytes. | [
"UnmarshalBinary",
"decodes",
"an",
"Action",
"from",
"bytes",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/action.go#L120-L126 |
6,915 | luci/luci-go | common/api/gitiles/refset.go | Has | func (w RefSet) Has(ref string) bool {
for prefix, wrp := range w.byPrefix {
nsPrefix := prefix + "/"
if strings.HasPrefix(ref, nsPrefix) && wrp.hasRef(ref) {
return true
}
}
return false
} | go | func (w RefSet) Has(ref string) bool {
for prefix, wrp := range w.byPrefix {
nsPrefix := prefix + "/"
if strings.HasPrefix(ref, nsPrefix) && wrp.hasRef(ref) {
return true
}
}
return false
} | [
"func",
"(",
"w",
"RefSet",
")",
"Has",
"(",
"ref",
"string",
")",
"bool",
"{",
"for",
"prefix",
",",
"wrp",
":=",
"range",
"w",
".",
"byPrefix",
"{",
"nsPrefix",
":=",
"prefix",
"+",
"\"",
"\"",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"ref",... | // Has checks if a specific ref is in this set. | [
"Has",
"checks",
"if",
"a",
"specific",
"ref",
"is",
"in",
"this",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/refset.go#L95-L104 |
6,916 | luci/luci-go | common/api/gitiles/refset.go | Resolve | func (w RefSet) Resolve(c context.Context, client gitiles.GitilesClient, project string) (refTips map[string]string, missingRefs []string, err error) {
lock := sync.Mutex{} // for concurrent writes to the map
refTips = map[string]string{}
err = parallel.FanOutIn(func(work chan<- func() error) {
for prefix := range w.byPrefix {
prefix := prefix
work <- func() error {
resp, err := client.Refs(c, &gitiles.RefsRequest{Project: project, RefsPath: prefix})
if err != nil {
return err
}
lock.Lock()
defer lock.Unlock()
for ref, tip := range resp.Revisions {
if w.Has(ref) {
refTips[ref] = tip
}
}
return nil
}
}
})
if err != nil {
return
}
// Compute missingRefs as those for which no actual ref was found.
for _, ref := range w.literalRefs {
if _, ok := refTips[ref]; !ok {
missingRefs = append(missingRefs, ref)
}
}
for _, r := range w.regexpRefs {
found := false
// This loop isn't the most efficient way to perform this search, and may
// result in executing MatchString O(refTips) times. If necessary to
// optimize, store individual regexps inside relevant refSetPrefix,
// and then mark corresponding regexps as "found" on the fly inside a
// goroutine working with the refSetPrefix.
for resolvedRef := range refTips {
if r.re.MatchString(resolvedRef) {
found = true
break
}
}
if !found {
missingRefs = append(missingRefs, r.ref)
}
}
return
} | go | func (w RefSet) Resolve(c context.Context, client gitiles.GitilesClient, project string) (refTips map[string]string, missingRefs []string, err error) {
lock := sync.Mutex{} // for concurrent writes to the map
refTips = map[string]string{}
err = parallel.FanOutIn(func(work chan<- func() error) {
for prefix := range w.byPrefix {
prefix := prefix
work <- func() error {
resp, err := client.Refs(c, &gitiles.RefsRequest{Project: project, RefsPath: prefix})
if err != nil {
return err
}
lock.Lock()
defer lock.Unlock()
for ref, tip := range resp.Revisions {
if w.Has(ref) {
refTips[ref] = tip
}
}
return nil
}
}
})
if err != nil {
return
}
// Compute missingRefs as those for which no actual ref was found.
for _, ref := range w.literalRefs {
if _, ok := refTips[ref]; !ok {
missingRefs = append(missingRefs, ref)
}
}
for _, r := range w.regexpRefs {
found := false
// This loop isn't the most efficient way to perform this search, and may
// result in executing MatchString O(refTips) times. If necessary to
// optimize, store individual regexps inside relevant refSetPrefix,
// and then mark corresponding regexps as "found" on the fly inside a
// goroutine working with the refSetPrefix.
for resolvedRef := range refTips {
if r.re.MatchString(resolvedRef) {
found = true
break
}
}
if !found {
missingRefs = append(missingRefs, r.ref)
}
}
return
} | [
"func",
"(",
"w",
"RefSet",
")",
"Resolve",
"(",
"c",
"context",
".",
"Context",
",",
"client",
"gitiles",
".",
"GitilesClient",
",",
"project",
"string",
")",
"(",
"refTips",
"map",
"[",
"string",
"]",
"string",
",",
"missingRefs",
"[",
"]",
"string",
... | // Resolve queries gitiles to resolve watched refs to git SHA1 hash of their
// current tips.
//
// Returns map from individual ref to its SHA1 hash and a list of original refs,
// incl. regular expressions, which either don't exist or are not visible to the
// requester. | [
"Resolve",
"queries",
"gitiles",
"to",
"resolve",
"watched",
"refs",
"to",
"git",
"SHA1",
"hash",
"of",
"their",
"current",
"tips",
".",
"Returns",
"map",
"from",
"individual",
"ref",
"to",
"its",
"SHA1",
"hash",
"and",
"a",
"list",
"of",
"original",
"refs... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/refset.go#L112-L161 |
6,917 | luci/luci-go | common/api/gitiles/refset.go | ValidateRefSet | func ValidateRefSet(c *validation.Context, refs []string) {
for _, ref := range refs {
if strings.HasPrefix(ref, "regexp:") {
validateRegexpRef(c, ref)
continue
}
if !strings.HasPrefix(ref, "refs/") {
c.Errorf("ref must start with 'refs/' not %q", ref)
}
if strings.Count(ref, "/") < 2 {
c.Errorf(`fewer than 2 slashes in ref %q`, ref)
}
}
} | go | func ValidateRefSet(c *validation.Context, refs []string) {
for _, ref := range refs {
if strings.HasPrefix(ref, "regexp:") {
validateRegexpRef(c, ref)
continue
}
if !strings.HasPrefix(ref, "refs/") {
c.Errorf("ref must start with 'refs/' not %q", ref)
}
if strings.Count(ref, "/") < 2 {
c.Errorf(`fewer than 2 slashes in ref %q`, ref)
}
}
} | [
"func",
"ValidateRefSet",
"(",
"c",
"*",
"validation",
".",
"Context",
",",
"refs",
"[",
"]",
"string",
")",
"{",
"for",
"_",
",",
"ref",
":=",
"range",
"refs",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"ref",
",",
"\"",
"\"",
")",
"{",
"validat... | // ValidateRefSet validates strings representing a set of refs.
//
// It ensures that passed strings match the requirements as described in the
// documentation for the NewRefSet function. It is designed to work with config
// validation logic, hence one needs to pass in the validation.Context as well. | [
"ValidateRefSet",
"validates",
"strings",
"representing",
"a",
"set",
"of",
"refs",
".",
"It",
"ensures",
"that",
"passed",
"strings",
"match",
"the",
"requirements",
"as",
"described",
"in",
"the",
"documentation",
"for",
"the",
"NewRefSet",
"function",
".",
"I... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/refset.go#L168-L183 |
6,918 | luci/luci-go | logdog/client/butler/bootstrap/env.go | Augment | func (e *Environment) Augment(base environ.Env) {
exportIf := func(envKey, v string) {
if v != "" {
base.Set(envKey, v)
}
}
exportIf(bootstrap.EnvCoordinatorHost, e.CoordinatorHost)
exportIf(bootstrap.EnvStreamPrefix, string(e.Prefix))
exportIf(bootstrap.EnvStreamProject, string(e.Project))
exportIf(bootstrap.EnvStreamServerPath, e.StreamServerURI)
} | go | func (e *Environment) Augment(base environ.Env) {
exportIf := func(envKey, v string) {
if v != "" {
base.Set(envKey, v)
}
}
exportIf(bootstrap.EnvCoordinatorHost, e.CoordinatorHost)
exportIf(bootstrap.EnvStreamPrefix, string(e.Prefix))
exportIf(bootstrap.EnvStreamProject, string(e.Project))
exportIf(bootstrap.EnvStreamServerPath, e.StreamServerURI)
} | [
"func",
"(",
"e",
"*",
"Environment",
")",
"Augment",
"(",
"base",
"environ",
".",
"Env",
")",
"{",
"exportIf",
":=",
"func",
"(",
"envKey",
",",
"v",
"string",
")",
"{",
"if",
"v",
"!=",
"\"",
"\"",
"{",
"base",
".",
"Set",
"(",
"envKey",
",",
... | // Augment augments the supplied base environment with LogDog Butler bootstrap
// parameters. | [
"Augment",
"augments",
"the",
"supplied",
"base",
"environment",
"with",
"LogDog",
"Butler",
"bootstrap",
"parameters",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/bootstrap/env.go#L43-L54 |
6,919 | luci/luci-go | gce/appengine/backend/cron.go | newHTTPHandler | func newHTTPHandler(f func(c context.Context) error) router.Handler {
return func(c *router.Context) {
c.Writer.Header().Set("Content-Type", "text/plain")
if err := f(c.Context); err != nil {
errors.Log(c.Context, err)
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
c.Writer.WriteHeader(http.StatusOK)
}
} | go | func newHTTPHandler(f func(c context.Context) error) router.Handler {
return func(c *router.Context) {
c.Writer.Header().Set("Content-Type", "text/plain")
if err := f(c.Context); err != nil {
errors.Log(c.Context, err)
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
c.Writer.WriteHeader(http.StatusOK)
}
} | [
"func",
"newHTTPHandler",
"(",
"f",
"func",
"(",
"c",
"context",
".",
"Context",
")",
"error",
")",
"router",
".",
"Handler",
"{",
"return",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"c",
".",
"Writer",
".",
"Header",
"(",
")",
"."... | // newHTTPHandler returns a router.Handler which invokes the given function. | [
"newHTTPHandler",
"returns",
"a",
"router",
".",
"Handler",
"which",
"invokes",
"the",
"given",
"function",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L35-L47 |
6,920 | luci/luci-go | gce/appengine/backend/cron.go | trigger | func trigger(c context.Context, t tasks.Task, q *datastore.Query) error {
tasks := make([]*tq.Task, 0)
newPayload := payloadFactory(t)
addTask := func(k *datastore.Key) {
tasks = append(tasks, &tq.Task{
Payload: newPayload(k.StringID()),
})
}
if err := datastore.Run(c, q, addTask); err != nil {
return errors.Annotate(err, "failed to fetch keys").Err()
}
logging.Debugf(c, "scheduling %d tasks", len(tasks))
if err := getDispatcher(c).AddTask(c, tasks...); err != nil {
return errors.Annotate(err, "failed to schedule tasks").Err()
}
return nil
} | go | func trigger(c context.Context, t tasks.Task, q *datastore.Query) error {
tasks := make([]*tq.Task, 0)
newPayload := payloadFactory(t)
addTask := func(k *datastore.Key) {
tasks = append(tasks, &tq.Task{
Payload: newPayload(k.StringID()),
})
}
if err := datastore.Run(c, q, addTask); err != nil {
return errors.Annotate(err, "failed to fetch keys").Err()
}
logging.Debugf(c, "scheduling %d tasks", len(tasks))
if err := getDispatcher(c).AddTask(c, tasks...); err != nil {
return errors.Annotate(err, "failed to schedule tasks").Err()
}
return nil
} | [
"func",
"trigger",
"(",
"c",
"context",
".",
"Context",
",",
"t",
"tasks",
".",
"Task",
",",
"q",
"*",
"datastore",
".",
"Query",
")",
"error",
"{",
"tasks",
":=",
"make",
"(",
"[",
"]",
"*",
"tq",
".",
"Task",
",",
"0",
")",
"\n",
"newPayload",
... | // trigger triggers a task queue task for each key returned by the given query. | [
"trigger",
"triggers",
"a",
"task",
"queue",
"task",
"for",
"each",
"key",
"returned",
"by",
"the",
"given",
"query",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L65-L81 |
6,921 | luci/luci-go | gce/appengine/backend/cron.go | countVMsAsync | func countVMsAsync(c context.Context) error {
return trigger(c, &tasks.CountVMs{}, datastore.NewQuery(model.ConfigKind))
} | go | func countVMsAsync(c context.Context) error {
return trigger(c, &tasks.CountVMs{}, datastore.NewQuery(model.ConfigKind))
} | [
"func",
"countVMsAsync",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"trigger",
"(",
"c",
",",
"&",
"tasks",
".",
"CountVMs",
"{",
"}",
",",
"datastore",
".",
"NewQuery",
"(",
"model",
".",
"ConfigKind",
")",
")",
"\n",
"}"
] | // countVMsAsync schedules task queue tasks to count VMs for each config. | [
"countVMsAsync",
"schedules",
"task",
"queue",
"tasks",
"to",
"count",
"VMs",
"for",
"each",
"config",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L84-L86 |
6,922 | luci/luci-go | gce/appengine/backend/cron.go | createInstancesAsync | func createInstancesAsync(c context.Context) error {
return trigger(c, &tasks.CreateInstance{}, datastore.NewQuery(model.VMKind).Eq("url", ""))
} | go | func createInstancesAsync(c context.Context) error {
return trigger(c, &tasks.CreateInstance{}, datastore.NewQuery(model.VMKind).Eq("url", ""))
} | [
"func",
"createInstancesAsync",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"trigger",
"(",
"c",
",",
"&",
"tasks",
".",
"CreateInstance",
"{",
"}",
",",
"datastore",
".",
"NewQuery",
"(",
"model",
".",
"VMKind",
")",
".",
"Eq",
"... | // createInstancesAsync schedules task queue tasks to create each GCE instance. | [
"createInstancesAsync",
"schedules",
"task",
"queue",
"tasks",
"to",
"create",
"each",
"GCE",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L89-L91 |
6,923 | luci/luci-go | gce/appengine/backend/cron.go | drainVMsAsync | func drainVMsAsync(c context.Context) error {
return trigger(c, &tasks.DrainVM{}, datastore.NewQuery(model.VMKind))
} | go | func drainVMsAsync(c context.Context) error {
return trigger(c, &tasks.DrainVM{}, datastore.NewQuery(model.VMKind))
} | [
"func",
"drainVMsAsync",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"trigger",
"(",
"c",
",",
"&",
"tasks",
".",
"DrainVM",
"{",
"}",
",",
"datastore",
".",
"NewQuery",
"(",
"model",
".",
"VMKind",
")",
")",
"\n",
"}"
] | // drainVMsAsync schedules task queue tasks to drain each VM. | [
"drainVMsAsync",
"schedules",
"task",
"queue",
"tasks",
"to",
"drain",
"each",
"VM",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L94-L96 |
6,924 | luci/luci-go | gce/appengine/backend/cron.go | expandConfigsAsync | func expandConfigsAsync(c context.Context) error {
return trigger(c, &tasks.ExpandConfig{}, datastore.NewQuery(model.ConfigKind))
} | go | func expandConfigsAsync(c context.Context) error {
return trigger(c, &tasks.ExpandConfig{}, datastore.NewQuery(model.ConfigKind))
} | [
"func",
"expandConfigsAsync",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"trigger",
"(",
"c",
",",
"&",
"tasks",
".",
"ExpandConfig",
"{",
"}",
",",
"datastore",
".",
"NewQuery",
"(",
"model",
".",
"ConfigKind",
")",
")",
"\n",
"... | // expandConfigsAsync schedules task queue tasks to expand each config. | [
"expandConfigsAsync",
"schedules",
"task",
"queue",
"tasks",
"to",
"expand",
"each",
"config",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L99-L101 |
6,925 | luci/luci-go | gce/appengine/backend/cron.go | manageBotsAsync | func manageBotsAsync(c context.Context) error {
return trigger(c, &tasks.ManageBot{}, datastore.NewQuery(model.VMKind).Gt("url", ""))
} | go | func manageBotsAsync(c context.Context) error {
return trigger(c, &tasks.ManageBot{}, datastore.NewQuery(model.VMKind).Gt("url", ""))
} | [
"func",
"manageBotsAsync",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"trigger",
"(",
"c",
",",
"&",
"tasks",
".",
"ManageBot",
"{",
"}",
",",
"datastore",
".",
"NewQuery",
"(",
"model",
".",
"VMKind",
")",
".",
"Gt",
"(",
"\""... | // manageBotsAsync schedules task queue tasks to manage each Swarming bot. | [
"manageBotsAsync",
"schedules",
"task",
"queue",
"tasks",
"to",
"manage",
"each",
"Swarming",
"bot",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L104-L106 |
6,926 | luci/luci-go | gce/appengine/backend/cron.go | reportQuotasAsync | func reportQuotasAsync(c context.Context) error {
return trigger(c, &tasks.ReportQuota{}, datastore.NewQuery(model.ProjectKind))
} | go | func reportQuotasAsync(c context.Context) error {
return trigger(c, &tasks.ReportQuota{}, datastore.NewQuery(model.ProjectKind))
} | [
"func",
"reportQuotasAsync",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"trigger",
"(",
"c",
",",
"&",
"tasks",
".",
"ReportQuota",
"{",
"}",
",",
"datastore",
".",
"NewQuery",
"(",
"model",
".",
"ProjectKind",
")",
")",
"\n",
"}... | // reportQuotasAsync schedules task queue tasks to report quota in each project. | [
"reportQuotasAsync",
"schedules",
"task",
"queue",
"tasks",
"to",
"report",
"quota",
"in",
"each",
"project",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/cron.go#L109-L111 |
6,927 | luci/luci-go | machine-db/appengine/rpc/oses.go | ListOSes | func (*Service) ListOSes(c context.Context, req *crimson.ListOSesRequest) (*crimson.ListOSesResponse, error) {
oses, err := listOSes(c, stringset.NewFromSlice(req.Names...))
if err != nil {
return nil, err
}
return &crimson.ListOSesResponse{
Oses: oses,
}, nil
} | go | func (*Service) ListOSes(c context.Context, req *crimson.ListOSesRequest) (*crimson.ListOSesResponse, error) {
oses, err := listOSes(c, stringset.NewFromSlice(req.Names...))
if err != nil {
return nil, err
}
return &crimson.ListOSesResponse{
Oses: oses,
}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"ListOSes",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"ListOSesRequest",
")",
"(",
"*",
"crimson",
".",
"ListOSesResponse",
",",
"error",
")",
"{",
"oses",
",",
"err",
":=",
"listOSes",
"(",... | // ListOSes handles a request to retrieve operating systems. | [
"ListOSes",
"handles",
"a",
"request",
"to",
"retrieve",
"operating",
"systems",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/oses.go#L28-L36 |
6,928 | luci/luci-go | machine-db/appengine/rpc/oses.go | listOSes | func listOSes(c context.Context, names stringset.Set) ([]*crimson.OS, error) {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT name, description
FROM oses
`)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch operating systems").Err()
}
defer rows.Close()
var oses []*crimson.OS
for rows.Next() {
os := &crimson.OS{}
if err = rows.Scan(&os.Name, &os.Description); err != nil {
return nil, errors.Annotate(err, "failed to fetch operating system").Err()
}
if matches(os.Name, names) {
oses = append(oses, os)
}
}
return oses, nil
} | go | func listOSes(c context.Context, names stringset.Set) ([]*crimson.OS, error) {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT name, description
FROM oses
`)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch operating systems").Err()
}
defer rows.Close()
var oses []*crimson.OS
for rows.Next() {
os := &crimson.OS{}
if err = rows.Scan(&os.Name, &os.Description); err != nil {
return nil, errors.Annotate(err, "failed to fetch operating system").Err()
}
if matches(os.Name, names) {
oses = append(oses, os)
}
}
return oses, nil
} | [
"func",
"listOSes",
"(",
"c",
"context",
".",
"Context",
",",
"names",
"stringset",
".",
"Set",
")",
"(",
"[",
"]",
"*",
"crimson",
".",
"OS",
",",
"error",
")",
"{",
"db",
":=",
"database",
".",
"Get",
"(",
"c",
")",
"\n",
"rows",
",",
"err",
... | // listOSes returns a slice of operating systems in the database. | [
"listOSes",
"returns",
"a",
"slice",
"of",
"operating",
"systems",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/oses.go#L39-L61 |
6,929 | luci/luci-go | lucicfg/graph/node.go | declare | func (n *Node) declare(idx int, props *starlarkstruct.Struct, idempotent bool, trace *builtins.CapturedStacktrace) {
props.Freeze()
n.Index = idx
n.Props = props
n.Idempotent = idempotent
n.Trace = trace
} | go | func (n *Node) declare(idx int, props *starlarkstruct.Struct, idempotent bool, trace *builtins.CapturedStacktrace) {
props.Freeze()
n.Index = idx
n.Props = props
n.Idempotent = idempotent
n.Trace = trace
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"declare",
"(",
"idx",
"int",
",",
"props",
"*",
"starlarkstruct",
".",
"Struct",
",",
"idempotent",
"bool",
",",
"trace",
"*",
"builtins",
".",
"CapturedStacktrace",
")",
"{",
"props",
".",
"Freeze",
"(",
")",
"\n",... | // declare marks the node as declared.
//
// Freezes properties as a side effect. | [
"declare",
"marks",
"the",
"node",
"as",
"declared",
".",
"Freezes",
"properties",
"as",
"a",
"side",
"effect",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/node.go#L53-L59 |
6,930 | luci/luci-go | lucicfg/graph/node.go | BelongsTo | func (n *Node) BelongsTo(g *Graph) bool {
return n.Key.set == &g.KeySet
} | go | func (n *Node) BelongsTo(g *Graph) bool {
return n.Key.set == &g.KeySet
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"BelongsTo",
"(",
"g",
"*",
"Graph",
")",
"bool",
"{",
"return",
"n",
".",
"Key",
".",
"set",
"==",
"&",
"g",
".",
"KeySet",
"\n",
"}"
] | // BelongsTo returns true if the node was declared in the given graph. | [
"BelongsTo",
"returns",
"true",
"if",
"the",
"node",
"was",
"declared",
"in",
"the",
"given",
"graph",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/node.go#L62-L64 |
6,931 | luci/luci-go | lucicfg/graph/node.go | listChildren | func (n *Node) listChildren() []*Node {
if n.childrenList == nil {
// Note: we want to allocate a new slice even if it is empty, so that
// n.childrenList is not nil anymore (to indicate we did the calculation
// already).
n.childrenList = make([]*Node, 0, len(n.children))
seen := make(map[*Key]struct{}, len(n.children))
for _, edge := range n.children {
if _, ok := seen[edge.Child.Key]; !ok {
seen[edge.Child.Key] = struct{}{}
n.childrenList = append(n.childrenList, edge.Child)
}
}
}
return append([]*Node(nil), n.childrenList...)
} | go | func (n *Node) listChildren() []*Node {
if n.childrenList == nil {
// Note: we want to allocate a new slice even if it is empty, so that
// n.childrenList is not nil anymore (to indicate we did the calculation
// already).
n.childrenList = make([]*Node, 0, len(n.children))
seen := make(map[*Key]struct{}, len(n.children))
for _, edge := range n.children {
if _, ok := seen[edge.Child.Key]; !ok {
seen[edge.Child.Key] = struct{}{}
n.childrenList = append(n.childrenList, edge.Child)
}
}
}
return append([]*Node(nil), n.childrenList...)
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"listChildren",
"(",
")",
"[",
"]",
"*",
"Node",
"{",
"if",
"n",
".",
"childrenList",
"==",
"nil",
"{",
"// Note: we want to allocate a new slice even if it is empty, so that",
"// n.childrenList is not nil anymore (to indicate we did t... | // listChildren returns a slice with a set of direct children of the node, in
// order corresponding edges were declared.
//
// Must be used only with finalized graphs, since the function caches its result
// internally on a first call. Returns a copy of the cached result. | [
"listChildren",
"returns",
"a",
"slice",
"with",
"a",
"set",
"of",
"direct",
"children",
"of",
"the",
"node",
"in",
"order",
"corresponding",
"edges",
"were",
"declared",
".",
"Must",
"be",
"used",
"only",
"with",
"finalized",
"graphs",
"since",
"the",
"func... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/node.go#L103-L118 |
6,932 | luci/luci-go | lucicfg/graph/node.go | listParents | func (n *Node) listParents() []*Node {
if n.parentsList == nil {
// Note: we want to allocate a new slice even if it is empty, so that
// n.parentsList is not nil anymore (to indicate we did the calculation
// already).
n.parentsList = make([]*Node, 0, len(n.parents))
seen := make(map[*Key]struct{}, len(n.parents))
for _, edge := range n.parents {
if _, ok := seen[edge.Parent.Key]; !ok {
seen[edge.Parent.Key] = struct{}{}
n.parentsList = append(n.parentsList, edge.Parent)
}
}
}
return append([]*Node(nil), n.parentsList...)
} | go | func (n *Node) listParents() []*Node {
if n.parentsList == nil {
// Note: we want to allocate a new slice even if it is empty, so that
// n.parentsList is not nil anymore (to indicate we did the calculation
// already).
n.parentsList = make([]*Node, 0, len(n.parents))
seen := make(map[*Key]struct{}, len(n.parents))
for _, edge := range n.parents {
if _, ok := seen[edge.Parent.Key]; !ok {
seen[edge.Parent.Key] = struct{}{}
n.parentsList = append(n.parentsList, edge.Parent)
}
}
}
return append([]*Node(nil), n.parentsList...)
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"listParents",
"(",
")",
"[",
"]",
"*",
"Node",
"{",
"if",
"n",
".",
"parentsList",
"==",
"nil",
"{",
"// Note: we want to allocate a new slice even if it is empty, so that",
"// n.parentsList is not nil anymore (to indicate we did the ... | // listParents returns a slice with a set of direct parents of the node, in
// order corresponding edges were declared.
//
// Must be used only with finalized graphs, since the function caches its result
// internally on a first call. Returns a copy of the cached result. | [
"listParents",
"returns",
"a",
"slice",
"with",
"a",
"set",
"of",
"direct",
"parents",
"of",
"the",
"node",
"in",
"order",
"corresponding",
"edges",
"were",
"declared",
".",
"Must",
"be",
"used",
"only",
"with",
"finalized",
"graphs",
"since",
"the",
"functi... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/node.go#L125-L140 |
6,933 | luci/luci-go | lucicfg/graph/node.go | String | func (n *Node) String() string {
ids := make([]string, 0, 5) // overestimate
p := n.Key
for p != nil {
if !strings.HasPrefix(p.Kind(), "_") {
ids = append(ids, p.ID())
}
p = p.Container()
}
for l, r := 0, len(ids)-1; l < r; l, r = l+1, r-1 {
ids[l], ids[r] = ids[r], ids[l]
}
return fmt.Sprintf("%s(%q)", n.Key.Kind(), strings.Join(ids, "/"))
} | go | func (n *Node) String() string {
ids := make([]string, 0, 5) // overestimate
p := n.Key
for p != nil {
if !strings.HasPrefix(p.Kind(), "_") {
ids = append(ids, p.ID())
}
p = p.Container()
}
for l, r := 0, len(ids)-1; l < r; l, r = l+1, r-1 {
ids[l], ids[r] = ids[r], ids[l]
}
return fmt.Sprintf("%s(%q)", n.Key.Kind(), strings.Join(ids, "/"))
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"String",
"(",
")",
"string",
"{",
"ids",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"5",
")",
"// overestimate",
"\n",
"p",
":=",
"n",
".",
"Key",
"\n",
"for",
"p",
"!=",
"nil",
"{",
"if",
"!",
... | // String is a part of starlark.Value interface.
//
// Returns a node title as derived from the kind of last component of its key
// and IDs of all key components whose kind doesn't start with '_'. It's not
// 1-to-1 mapping to the full information in the key, but usually good enough to
// identify the node in error messages. | [
"String",
"is",
"a",
"part",
"of",
"starlark",
".",
"Value",
"interface",
".",
"Returns",
"a",
"node",
"title",
"as",
"derived",
"from",
"the",
"kind",
"of",
"last",
"component",
"of",
"its",
"key",
"and",
"IDs",
"of",
"all",
"key",
"components",
"whose"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/node.go#L148-L161 |
6,934 | luci/luci-go | cipd/client/cipd/action_plan.go | Empty | func (a *Actions) Empty() bool {
return len(a.ToInstall) == 0 &&
len(a.ToUpdate) == 0 &&
len(a.ToRemove) == 0 &&
len(a.ToRepair) == 0
} | go | func (a *Actions) Empty() bool {
return len(a.ToInstall) == 0 &&
len(a.ToUpdate) == 0 &&
len(a.ToRemove) == 0 &&
len(a.ToRepair) == 0
} | [
"func",
"(",
"a",
"*",
"Actions",
")",
"Empty",
"(",
")",
"bool",
"{",
"return",
"len",
"(",
"a",
".",
"ToInstall",
")",
"==",
"0",
"&&",
"len",
"(",
"a",
".",
"ToUpdate",
")",
"==",
"0",
"&&",
"len",
"(",
"a",
".",
"ToRemove",
")",
"==",
"0"... | // Empty is true if there are no actions specified. | [
"Empty",
"is",
"true",
"if",
"there",
"are",
"no",
"actions",
"specified",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/action_plan.go#L44-L49 |
6,935 | luci/luci-go | cipd/client/cipd/action_plan.go | NumBrokenFiles | func (p *RepairPlan) NumBrokenFiles() int {
return len(p.ToRedeploy) + len(p.ToRelink)
} | go | func (p *RepairPlan) NumBrokenFiles() int {
return len(p.ToRedeploy) + len(p.ToRelink)
} | [
"func",
"(",
"p",
"*",
"RepairPlan",
")",
"NumBrokenFiles",
"(",
")",
"int",
"{",
"return",
"len",
"(",
"p",
".",
"ToRedeploy",
")",
"+",
"len",
"(",
"p",
".",
"ToRelink",
")",
"\n",
"}"
] | // NumBrokenFiles returns number of files that will be repaired. | [
"NumBrokenFiles",
"returns",
"number",
"of",
"files",
"that",
"will",
"be",
"repaired",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/action_plan.go#L100-L102 |
6,936 | luci/luci-go | cipd/client/cipd/action_plan.go | Log | func (am ActionMap) Log(ctx context.Context, verbose bool) {
keys := make([]string, 0, len(am))
for key := range am {
keys = append(keys, key)
}
sort.Strings(keys)
for _, subdir := range keys {
actions := am[subdir]
if subdir == "" {
logging.Infof(ctx, "In root:")
} else {
logging.Infof(ctx, "In subdir %q:", subdir)
}
if len(actions.ToInstall) != 0 {
logging.Infof(ctx, " to install:")
for _, pin := range actions.ToInstall {
logging.Infof(ctx, " %s", pin)
}
}
if len(actions.ToUpdate) != 0 {
logging.Infof(ctx, " to update:")
for _, pair := range actions.ToUpdate {
logging.Infof(ctx, " %s (%s -> %s)",
pair.From.PackageName, pair.From.InstanceID, pair.To.InstanceID)
}
}
if len(actions.ToRemove) != 0 {
logging.Infof(ctx, " to remove:")
for _, pin := range actions.ToRemove {
logging.Infof(ctx, " %s", pin)
}
}
if len(actions.ToRepair) != 0 {
logging.Infof(ctx, " to repair:")
for _, broken := range actions.ToRepair {
more := broken.RepairPlan.ReinstallReason
if more == "" {
more = fmt.Sprintf("%d file(s) to repair", broken.RepairPlan.NumBrokenFiles())
}
logging.Infof(ctx, " %s (%s)", broken.Pin, more)
if verbose && len(broken.RepairPlan.ToRedeploy) != 0 {
logging.Infof(ctx, " to redeploy:")
for _, f := range broken.RepairPlan.ToRedeploy {
logging.Infof(ctx, " %s", f)
}
}
if verbose && len(broken.RepairPlan.ToRelink) != 0 {
logging.Infof(ctx, " to relink:")
for _, f := range broken.RepairPlan.ToRelink {
logging.Infof(ctx, " %s", f)
}
}
}
}
}
} | go | func (am ActionMap) Log(ctx context.Context, verbose bool) {
keys := make([]string, 0, len(am))
for key := range am {
keys = append(keys, key)
}
sort.Strings(keys)
for _, subdir := range keys {
actions := am[subdir]
if subdir == "" {
logging.Infof(ctx, "In root:")
} else {
logging.Infof(ctx, "In subdir %q:", subdir)
}
if len(actions.ToInstall) != 0 {
logging.Infof(ctx, " to install:")
for _, pin := range actions.ToInstall {
logging.Infof(ctx, " %s", pin)
}
}
if len(actions.ToUpdate) != 0 {
logging.Infof(ctx, " to update:")
for _, pair := range actions.ToUpdate {
logging.Infof(ctx, " %s (%s -> %s)",
pair.From.PackageName, pair.From.InstanceID, pair.To.InstanceID)
}
}
if len(actions.ToRemove) != 0 {
logging.Infof(ctx, " to remove:")
for _, pin := range actions.ToRemove {
logging.Infof(ctx, " %s", pin)
}
}
if len(actions.ToRepair) != 0 {
logging.Infof(ctx, " to repair:")
for _, broken := range actions.ToRepair {
more := broken.RepairPlan.ReinstallReason
if more == "" {
more = fmt.Sprintf("%d file(s) to repair", broken.RepairPlan.NumBrokenFiles())
}
logging.Infof(ctx, " %s (%s)", broken.Pin, more)
if verbose && len(broken.RepairPlan.ToRedeploy) != 0 {
logging.Infof(ctx, " to redeploy:")
for _, f := range broken.RepairPlan.ToRedeploy {
logging.Infof(ctx, " %s", f)
}
}
if verbose && len(broken.RepairPlan.ToRelink) != 0 {
logging.Infof(ctx, " to relink:")
for _, f := range broken.RepairPlan.ToRelink {
logging.Infof(ctx, " %s", f)
}
}
}
}
}
} | [
"func",
"(",
"am",
"ActionMap",
")",
"Log",
"(",
"ctx",
"context",
".",
"Context",
",",
"verbose",
"bool",
")",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"am",
")",
")",
"\n",
"for",
"key",
":=",
"range",
"a... | // Log prints the pending action to the logger installed in ctx.
//
// If verbose is true, prints filenames of files that need a repair. | [
"Log",
"prints",
"the",
"pending",
"action",
"to",
"the",
"logger",
"installed",
"in",
"ctx",
".",
"If",
"verbose",
"is",
"true",
"prints",
"filenames",
"of",
"files",
"that",
"need",
"a",
"repair",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/action_plan.go#L129-L187 |
6,937 | luci/luci-go | cipd/client/cipd/action_plan.go | buildActionPlan | func buildActionPlan(desired, existing common.PinSliceBySubdir, needsRepair repairCB) (aMap ActionMap) {
desiredSubdirs := stringset.New(len(desired))
for desiredSubdir := range desired {
desiredSubdirs.Add(desiredSubdir)
}
existingSubdirs := stringset.New(len(existing))
for existingSubdir := range existing {
existingSubdirs.Add(existingSubdir)
}
aMap = ActionMap{}
// all newly added subdirs
desiredSubdirs.Difference(existingSubdirs).Iter(func(subdir string) bool {
if want := desired[subdir]; len(want) > 0 {
aMap[subdir] = &Actions{ToInstall: want}
}
return true
})
// all removed subdirs
existingSubdirs.Difference(desiredSubdirs).Iter(func(subdir string) bool {
if have := existing[subdir]; len(have) > 0 {
aMap[subdir] = &Actions{ToRemove: have}
}
return true
})
// all common subdirs
desiredSubdirs.Intersect(existingSubdirs).Iter(func(subdir string) bool {
a := Actions{}
// Figure out what needs to be installed, updated or repaired.
haveMap := existing[subdir].ToMap()
for _, want := range desired[subdir] {
if haveID, exists := haveMap[want.PackageName]; !exists {
a.ToInstall = append(a.ToInstall, want)
} else if haveID != want.InstanceID {
a.ToUpdate = append(a.ToUpdate, UpdatedPin{
From: common.Pin{PackageName: want.PackageName, InstanceID: haveID},
To: want,
})
} else if repairPlan := needsRepair(subdir, want); repairPlan != nil {
a.ToRepair = append(a.ToRepair, BrokenPin{
Pin: want,
RepairPlan: *repairPlan,
})
}
}
// Figure out what needs to be removed.
wantMap := desired[subdir].ToMap()
for _, have := range existing[subdir] {
if wantMap[have.PackageName] == "" {
a.ToRemove = append(a.ToRemove, have)
}
}
if !a.Empty() {
aMap[subdir] = &a
}
return true
})
if len(aMap) == 0 {
return nil
}
return
} | go | func buildActionPlan(desired, existing common.PinSliceBySubdir, needsRepair repairCB) (aMap ActionMap) {
desiredSubdirs := stringset.New(len(desired))
for desiredSubdir := range desired {
desiredSubdirs.Add(desiredSubdir)
}
existingSubdirs := stringset.New(len(existing))
for existingSubdir := range existing {
existingSubdirs.Add(existingSubdir)
}
aMap = ActionMap{}
// all newly added subdirs
desiredSubdirs.Difference(existingSubdirs).Iter(func(subdir string) bool {
if want := desired[subdir]; len(want) > 0 {
aMap[subdir] = &Actions{ToInstall: want}
}
return true
})
// all removed subdirs
existingSubdirs.Difference(desiredSubdirs).Iter(func(subdir string) bool {
if have := existing[subdir]; len(have) > 0 {
aMap[subdir] = &Actions{ToRemove: have}
}
return true
})
// all common subdirs
desiredSubdirs.Intersect(existingSubdirs).Iter(func(subdir string) bool {
a := Actions{}
// Figure out what needs to be installed, updated or repaired.
haveMap := existing[subdir].ToMap()
for _, want := range desired[subdir] {
if haveID, exists := haveMap[want.PackageName]; !exists {
a.ToInstall = append(a.ToInstall, want)
} else if haveID != want.InstanceID {
a.ToUpdate = append(a.ToUpdate, UpdatedPin{
From: common.Pin{PackageName: want.PackageName, InstanceID: haveID},
To: want,
})
} else if repairPlan := needsRepair(subdir, want); repairPlan != nil {
a.ToRepair = append(a.ToRepair, BrokenPin{
Pin: want,
RepairPlan: *repairPlan,
})
}
}
// Figure out what needs to be removed.
wantMap := desired[subdir].ToMap()
for _, have := range existing[subdir] {
if wantMap[have.PackageName] == "" {
a.ToRemove = append(a.ToRemove, have)
}
}
if !a.Empty() {
aMap[subdir] = &a
}
return true
})
if len(aMap) == 0 {
return nil
}
return
} | [
"func",
"buildActionPlan",
"(",
"desired",
",",
"existing",
"common",
".",
"PinSliceBySubdir",
",",
"needsRepair",
"repairCB",
")",
"(",
"aMap",
"ActionMap",
")",
"{",
"desiredSubdirs",
":=",
"stringset",
".",
"New",
"(",
"len",
"(",
"desired",
")",
")",
"\n... | // buildActionPlan is used by EnsurePackages to figure out what to install,
// remove, update or repair.
//
// The given 'needsRepair' callback is called for each installed pin to decide
// whether it should be repaired and how. | [
"buildActionPlan",
"is",
"used",
"by",
"EnsurePackages",
"to",
"figure",
"out",
"what",
"to",
"install",
"remove",
"update",
"or",
"repair",
".",
"The",
"given",
"needsRepair",
"callback",
"is",
"called",
"for",
"each",
"installed",
"pin",
"to",
"decide",
"whe... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/action_plan.go#L198-L267 |
6,938 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_via_grant.go | validateRequest | func (r *MintOAuthTokenViaGrantRPC) validateRequest(c context.Context, req *minter.MintOAuthTokenViaGrantRequest, caller identity.Identity) (*tokenserver.OAuthTokenGrantBody, *Rule, error) {
// Grab the token body, if it is valid.
grantBody, err := r.decodeAndValidateToken(c, req.GrantToken)
if err != nil {
return nil, nil, err
}
// The token is usable only by whoever requested it in the first place.
if grantBody.Proxy != string(caller) {
// Note: grantBody.Proxy is part of the token already, caller knows it, so
// we aren't exposing any new information by returning it in the message.
logging.Errorf(c, "Unauthorized caller (expecting %q)", grantBody.Proxy)
return nil, nil, status.Errorf(codes.PermissionDenied, "unauthorized caller (expecting %s)", grantBody.Proxy)
}
// Check that rules still allow this token (rules could have changed since
// the grant was generated).
rule, err := r.recheckRules(c, grantBody)
if err != nil {
return nil, nil, err
}
// OAuth scopes check is specific to this RPC, it's not done by recheckRules.
if err := rule.CheckScopes(req.OauthScope); err != nil {
logging.WithError(err).Errorf(c, "Bad scopes")
return nil, nil, status.Errorf(codes.PermissionDenied, "bad scopes - %s", err)
}
return grantBody, rule, nil
} | go | func (r *MintOAuthTokenViaGrantRPC) validateRequest(c context.Context, req *minter.MintOAuthTokenViaGrantRequest, caller identity.Identity) (*tokenserver.OAuthTokenGrantBody, *Rule, error) {
// Grab the token body, if it is valid.
grantBody, err := r.decodeAndValidateToken(c, req.GrantToken)
if err != nil {
return nil, nil, err
}
// The token is usable only by whoever requested it in the first place.
if grantBody.Proxy != string(caller) {
// Note: grantBody.Proxy is part of the token already, caller knows it, so
// we aren't exposing any new information by returning it in the message.
logging.Errorf(c, "Unauthorized caller (expecting %q)", grantBody.Proxy)
return nil, nil, status.Errorf(codes.PermissionDenied, "unauthorized caller (expecting %s)", grantBody.Proxy)
}
// Check that rules still allow this token (rules could have changed since
// the grant was generated).
rule, err := r.recheckRules(c, grantBody)
if err != nil {
return nil, nil, err
}
// OAuth scopes check is specific to this RPC, it's not done by recheckRules.
if err := rule.CheckScopes(req.OauthScope); err != nil {
logging.WithError(err).Errorf(c, "Bad scopes")
return nil, nil, status.Errorf(codes.PermissionDenied, "bad scopes - %s", err)
}
return grantBody, rule, nil
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenViaGrantRPC",
")",
"validateRequest",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"minter",
".",
"MintOAuthTokenViaGrantRequest",
",",
"caller",
"identity",
".",
"Identity",
")",
"(",
"*",
"tokenserver",
".",
"OA... | // validateRequest decodes the request and checks that it is allowed.
//
// Logs and returns verified deserialized token body and corresponding rule on
// success or a grpc error on error. | [
"validateRequest",
"decodes",
"the",
"request",
"and",
"checks",
"that",
"it",
"is",
"allowed",
".",
"Logs",
"and",
"returns",
"verified",
"deserialized",
"token",
"body",
"and",
"corresponding",
"rule",
"on",
"success",
"or",
"a",
"grpc",
"error",
"on",
"erro... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_via_grant.go#L155-L184 |
6,939 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_via_grant.go | decodeAndValidateToken | func (r *MintOAuthTokenViaGrantRPC) decodeAndValidateToken(c context.Context, grantToken string) (*tokenserver.OAuthTokenGrantBody, error) {
// Attempt to decode the grant and log all information we can get (even if the
// token is no longer technically valid). This information helps to debug
// invalid tokens. InspectGrant returns an error only if the inspection
// operation itself fails. If the token is invalid, it returns an inspection
// with non-empty InvalidityReason.
inspection, err := InspectGrant(c, r.Signer, grantToken)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
// This is non-nil for tokens with a valid body, even if they aren't properly
// signed or they have already expired. These additional checks are handled
// below after we log the body.
grantBody, _ := inspection.Body.(*tokenserver.OAuthTokenGrantBody)
if grantBody == nil {
logging.Errorf(c, "Malformed grant token - %s", inspection.InvalidityReason)
return nil, status.Errorf(codes.InvalidArgument, "malformed grant token - %s", inspection.InvalidityReason)
}
if logging.IsLogging(c, logging.Debug) {
m := jsonpb.Marshaler{Indent: " "}
dump, _ := m.MarshalToString(grantBody)
logging.Debugf(c, "OAuthTokenGrantBody:\n%s", dump)
}
if inspection.InvalidityReason != "" {
logging.Errorf(c, "Invalid grant token - %s", inspection.InvalidityReason)
return nil, status.Errorf(codes.InvalidArgument, "invalid grant token - %s", inspection.InvalidityReason)
}
// At this point we've verified 'grantToken' was issued by us (it is signed)
// and it hasn't expired yet. Assert this.
if !inspection.Signed || !inspection.NonExpired {
panic(fmt.Sprintf("assertion failure Signed=%v, NonExpired=%v", inspection.Signed, inspection.NonExpired))
}
return grantBody, nil
} | go | func (r *MintOAuthTokenViaGrantRPC) decodeAndValidateToken(c context.Context, grantToken string) (*tokenserver.OAuthTokenGrantBody, error) {
// Attempt to decode the grant and log all information we can get (even if the
// token is no longer technically valid). This information helps to debug
// invalid tokens. InspectGrant returns an error only if the inspection
// operation itself fails. If the token is invalid, it returns an inspection
// with non-empty InvalidityReason.
inspection, err := InspectGrant(c, r.Signer, grantToken)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
// This is non-nil for tokens with a valid body, even if they aren't properly
// signed or they have already expired. These additional checks are handled
// below after we log the body.
grantBody, _ := inspection.Body.(*tokenserver.OAuthTokenGrantBody)
if grantBody == nil {
logging.Errorf(c, "Malformed grant token - %s", inspection.InvalidityReason)
return nil, status.Errorf(codes.InvalidArgument, "malformed grant token - %s", inspection.InvalidityReason)
}
if logging.IsLogging(c, logging.Debug) {
m := jsonpb.Marshaler{Indent: " "}
dump, _ := m.MarshalToString(grantBody)
logging.Debugf(c, "OAuthTokenGrantBody:\n%s", dump)
}
if inspection.InvalidityReason != "" {
logging.Errorf(c, "Invalid grant token - %s", inspection.InvalidityReason)
return nil, status.Errorf(codes.InvalidArgument, "invalid grant token - %s", inspection.InvalidityReason)
}
// At this point we've verified 'grantToken' was issued by us (it is signed)
// and it hasn't expired yet. Assert this.
if !inspection.Signed || !inspection.NonExpired {
panic(fmt.Sprintf("assertion failure Signed=%v, NonExpired=%v", inspection.Signed, inspection.NonExpired))
}
return grantBody, nil
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenViaGrantRPC",
")",
"decodeAndValidateToken",
"(",
"c",
"context",
".",
"Context",
",",
"grantToken",
"string",
")",
"(",
"*",
"tokenserver",
".",
"OAuthTokenGrantBody",
",",
"error",
")",
"{",
"// Attempt to decode the grant and... | // decodeAndValidateToken checks the token signature, expiration time and
// unmarshals it.
//
// Logs and returns deserialized token body on success or a grpc error on error. | [
"decodeAndValidateToken",
"checks",
"the",
"token",
"signature",
"expiration",
"time",
"and",
"unmarshals",
"it",
".",
"Logs",
"and",
"returns",
"deserialized",
"token",
"body",
"on",
"success",
"or",
"a",
"grpc",
"error",
"on",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_via_grant.go#L190-L227 |
6,940 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_via_grant.go | recheckRules | func (r *MintOAuthTokenViaGrantRPC) recheckRules(c context.Context, grantBody *tokenserver.OAuthTokenGrantBody) (*Rule, error) {
// Check that rules still allow this token (rules could have changed since
// the grant was generated).
rules, err := r.Rules(c)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to load service accounts rules")
return nil, status.Errorf(codes.Internal, "failed to load service accounts rules")
}
return rules.Check(c, &RulesQuery{
ServiceAccount: grantBody.ServiceAccount,
Proxy: identity.Identity(grantBody.Proxy),
EndUser: identity.Identity(grantBody.EndUser),
})
} | go | func (r *MintOAuthTokenViaGrantRPC) recheckRules(c context.Context, grantBody *tokenserver.OAuthTokenGrantBody) (*Rule, error) {
// Check that rules still allow this token (rules could have changed since
// the grant was generated).
rules, err := r.Rules(c)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to load service accounts rules")
return nil, status.Errorf(codes.Internal, "failed to load service accounts rules")
}
return rules.Check(c, &RulesQuery{
ServiceAccount: grantBody.ServiceAccount,
Proxy: identity.Identity(grantBody.Proxy),
EndUser: identity.Identity(grantBody.EndUser),
})
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenViaGrantRPC",
")",
"recheckRules",
"(",
"c",
"context",
".",
"Context",
",",
"grantBody",
"*",
"tokenserver",
".",
"OAuthTokenGrantBody",
")",
"(",
"*",
"Rule",
",",
"error",
")",
"{",
"// Check that rules still allow this tok... | // recheckRules verifies the token is still allowed by the rules.
//
// Returns a grpc error if the token no longer matches the rules. | [
"recheckRules",
"verifies",
"the",
"token",
"is",
"still",
"allowed",
"by",
"the",
"rules",
".",
"Returns",
"a",
"grpc",
"error",
"if",
"the",
"token",
"no",
"longer",
"matches",
"the",
"rules",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_via_grant.go#L232-L245 |
6,941 | luci/luci-go | lucicfg/tracked.go | FindTrackedFiles | func FindTrackedFiles(dir string, patterns []string) ([]string, error) {
// Avoid scanning the directory if the tracked set is known to be empty.
if len(patterns) == 0 {
return nil, nil
}
// Missing directory is considered empty.
if _, err := os.Stat(dir); os.IsNotExist(err) {
return nil, nil
}
isTracked := TrackedSet(patterns)
var tracked []string
err := filepath.Walk(dir, func(p string, info os.FileInfo, err error) error {
if err != nil || !info.Mode().IsRegular() {
return err
}
rel, err := filepath.Rel(dir, p)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
yes, err := isTracked(rel)
if yes {
tracked = append(tracked, rel)
}
return err
})
if err != nil {
return nil, errors.Annotate(err, "failed to scan the directory for tracked files").Err()
}
sort.Strings(tracked)
return tracked, nil
} | go | func FindTrackedFiles(dir string, patterns []string) ([]string, error) {
// Avoid scanning the directory if the tracked set is known to be empty.
if len(patterns) == 0 {
return nil, nil
}
// Missing directory is considered empty.
if _, err := os.Stat(dir); os.IsNotExist(err) {
return nil, nil
}
isTracked := TrackedSet(patterns)
var tracked []string
err := filepath.Walk(dir, func(p string, info os.FileInfo, err error) error {
if err != nil || !info.Mode().IsRegular() {
return err
}
rel, err := filepath.Rel(dir, p)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
yes, err := isTracked(rel)
if yes {
tracked = append(tracked, rel)
}
return err
})
if err != nil {
return nil, errors.Annotate(err, "failed to scan the directory for tracked files").Err()
}
sort.Strings(tracked)
return tracked, nil
} | [
"func",
"FindTrackedFiles",
"(",
"dir",
"string",
",",
"patterns",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"// Avoid scanning the directory if the tracked set is known to be empty.",
"if",
"len",
"(",
"patterns",
")",
"==",
"0",
... | // FindTrackedFiles recursively discovers all regular files in the given
// directory whose names match given patterns.
//
// See TrackedSet for the format of `patterns`. If the directory doesn't exist,
// returns empty slice.
//
// Returned file names are sorted, slash-separated and relative to `dir`. | [
"FindTrackedFiles",
"recursively",
"discovers",
"all",
"regular",
"files",
"in",
"the",
"given",
"directory",
"whose",
"names",
"match",
"given",
"patterns",
".",
"See",
"TrackedSet",
"for",
"the",
"format",
"of",
"patterns",
".",
"If",
"the",
"directory",
"does... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/tracked.go#L73-L108 |
6,942 | luci/luci-go | logdog/appengine/coordinator/endpoints/admin/service.go | New | func New() logdog.AdminServer {
return &logdog.DecoratedAdmin{
Service: &server{},
Prelude: func(c context.Context, methodName string, req proto.Message) (context.Context, error) {
if err := coordinator.IsAdminUser(c); err != nil {
log.WithError(err).Warningf(c, "User is not an administrator.")
// If we're on development server, any user can access this endpoint.
if info.IsDevAppServer(c) {
log.Infof(c, "On development server, allowing admin access.")
return c, nil
}
u := auth.CurrentUser(c)
if u == nil || !u.Superuser {
return nil, grpcutil.PermissionDenied
}
log.Fields{
"email": u.Email,
"clientID": u.ClientID,
"name": u.Name,
}.Infof(c, "User is an AppEngine superuser. Granting access.")
}
return c, nil
},
}
} | go | func New() logdog.AdminServer {
return &logdog.DecoratedAdmin{
Service: &server{},
Prelude: func(c context.Context, methodName string, req proto.Message) (context.Context, error) {
if err := coordinator.IsAdminUser(c); err != nil {
log.WithError(err).Warningf(c, "User is not an administrator.")
// If we're on development server, any user can access this endpoint.
if info.IsDevAppServer(c) {
log.Infof(c, "On development server, allowing admin access.")
return c, nil
}
u := auth.CurrentUser(c)
if u == nil || !u.Superuser {
return nil, grpcutil.PermissionDenied
}
log.Fields{
"email": u.Email,
"clientID": u.ClientID,
"name": u.Name,
}.Infof(c, "User is an AppEngine superuser. Granting access.")
}
return c, nil
},
}
} | [
"func",
"New",
"(",
")",
"logdog",
".",
"AdminServer",
"{",
"return",
"&",
"logdog",
".",
"DecoratedAdmin",
"{",
"Service",
":",
"&",
"server",
"{",
"}",
",",
"Prelude",
":",
"func",
"(",
"c",
"context",
".",
"Context",
",",
"methodName",
"string",
","... | // New instantiates a new AdminServer instance. | [
"New",
"instantiates",
"a",
"new",
"AdminServer",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/admin/service.go#L33-L61 |
6,943 | luci/luci-go | dm/api/template/normalize.go | Normalize | func (t *File_Template) Normalize() error {
if t.DistributorConfigName == "" {
return fmt.Errorf("missing distributor_config_name")
}
if err := t.Parameters.Normalize(); err != nil {
return err
}
if err := t.DistributorParameters.Normalize(); err != nil {
return err
}
return nil
} | go | func (t *File_Template) Normalize() error {
if t.DistributorConfigName == "" {
return fmt.Errorf("missing distributor_config_name")
}
if err := t.Parameters.Normalize(); err != nil {
return err
}
if err := t.DistributorParameters.Normalize(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"t",
"*",
"File_Template",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"t",
".",
"DistributorConfigName",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"t",
".",
... | // Normalize will normalize this Template, returning an error if it is invalid. | [
"Normalize",
"will",
"normalize",
"this",
"Template",
"returning",
"an",
"error",
"if",
"it",
"is",
"invalid",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/template/normalize.go#L31-L42 |
6,944 | luci/luci-go | common/tsmon/versions/versions.go | Register | func Register(component, version string) {
registry.m.Lock()
defer registry.m.Unlock()
if registry.r == nil {
registry.r = make(map[string]string, 1)
}
registry.r[component] = version
} | go | func Register(component, version string) {
registry.m.Lock()
defer registry.m.Unlock()
if registry.r == nil {
registry.r = make(map[string]string, 1)
}
registry.r[component] = version
} | [
"func",
"Register",
"(",
"component",
",",
"version",
"string",
")",
"{",
"registry",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"registry",
".",
"m",
".",
"Unlock",
"(",
")",
"\n",
"if",
"registry",
".",
"r",
"==",
"nil",
"{",
"registry",
"."... | // Register tells the library to start reporting a version for given component.
//
// This should usually called during 'init' time.
//
// The component name will be used as a value of 'component' metric field, and
// the given version will become the actual reported metric value. It is a good
// idea to use a fully qualified go package name as 'component'. | [
"Register",
"tells",
"the",
"library",
"to",
"start",
"reporting",
"a",
"version",
"for",
"given",
"component",
".",
"This",
"should",
"usually",
"called",
"during",
"init",
"time",
".",
"The",
"component",
"name",
"will",
"be",
"used",
"as",
"a",
"value",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/versions/versions.go#L58-L65 |
6,945 | luci/luci-go | server/secrets/context.go | Get | func Get(c context.Context) Store {
if f, ok := c.Value(contextKey(0)).(Factory); ok && f != nil {
return f(c)
}
return nil
} | go | func Get(c context.Context) Store {
if f, ok := c.Value(contextKey(0)).(Factory); ok && f != nil {
return f(c)
}
return nil
} | [
"func",
"Get",
"(",
"c",
"context",
".",
"Context",
")",
"Store",
"{",
"if",
"f",
",",
"ok",
":=",
"c",
".",
"Value",
"(",
"contextKey",
"(",
"0",
")",
")",
".",
"(",
"Factory",
")",
";",
"ok",
"&&",
"f",
"!=",
"nil",
"{",
"return",
"f",
"(",... | // Get grabs a Store by calling Factory stored in the context. If one hasn't
// been set, it returns nil. | [
"Get",
"grabs",
"a",
"Store",
"by",
"calling",
"Factory",
"stored",
"in",
"the",
"context",
".",
"If",
"one",
"hasn",
"t",
"been",
"set",
"it",
"returns",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/secrets/context.go#L35-L40 |
6,946 | luci/luci-go | server/secrets/context.go | Set | func Set(c context.Context, s Store) context.Context {
if s == nil {
return SetFactory(c, nil)
}
return SetFactory(c, func(context.Context) Store { return s })
} | go | func Set(c context.Context, s Store) context.Context {
if s == nil {
return SetFactory(c, nil)
}
return SetFactory(c, func(context.Context) Store { return s })
} | [
"func",
"Set",
"(",
"c",
"context",
".",
"Context",
",",
"s",
"Store",
")",
"context",
".",
"Context",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"SetFactory",
"(",
"c",
",",
"nil",
")",
"\n",
"}",
"\n",
"return",
"SetFactory",
"(",
"c",
",",
"f... | // Set injects the Store object in the context to be returned by Get as is. | [
"Set",
"injects",
"the",
"Store",
"object",
"in",
"the",
"context",
"to",
"be",
"returned",
"by",
"Get",
"as",
"is",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/secrets/context.go#L48-L53 |
6,947 | luci/luci-go | server/secrets/context.go | GetSecret | func GetSecret(c context.Context, k Key) (Secret, error) {
if s := Get(c); s != nil {
return s.GetSecret(k)
}
return Secret{}, ErrNoStoreConfigured
} | go | func GetSecret(c context.Context, k Key) (Secret, error) {
if s := Get(c); s != nil {
return s.GetSecret(k)
}
return Secret{}, ErrNoStoreConfigured
} | [
"func",
"GetSecret",
"(",
"c",
"context",
".",
"Context",
",",
"k",
"Key",
")",
"(",
"Secret",
",",
"error",
")",
"{",
"if",
"s",
":=",
"Get",
"(",
"c",
")",
";",
"s",
"!=",
"nil",
"{",
"return",
"s",
".",
"GetSecret",
"(",
"k",
")",
"\n",
"}... | // GetSecret is shortcut for grabbing a Store from the context and using its
// GetSecret method. If the context doesn't have Store set,
// returns ErrNoStoreConfigured. | [
"GetSecret",
"is",
"shortcut",
"for",
"grabbing",
"a",
"Store",
"from",
"the",
"context",
"and",
"using",
"its",
"GetSecret",
"method",
".",
"If",
"the",
"context",
"doesn",
"t",
"have",
"Store",
"set",
"returns",
"ErrNoStoreConfigured",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/secrets/context.go#L58-L63 |
6,948 | luci/luci-go | scheduler/appengine/task/buildbucket/buildbucket.go | defaultTags | func defaultTags(c context.Context, ctl task.Controller, cfg *messages.BuildbucketTask) map[string]string {
if c != nil {
return map[string]string{
"builder": cfg.Builder,
"scheduler_invocation_id": fmt.Sprintf("%d", ctl.InvocationID()),
"scheduler_job_id": ctl.JobID(),
"user_agent": info.AppID(c),
}
}
return map[string]string{
"builder": "",
"scheduler_invocation_id": "",
"scheduler_job_id": "",
"user_agent": "",
}
} | go | func defaultTags(c context.Context, ctl task.Controller, cfg *messages.BuildbucketTask) map[string]string {
if c != nil {
return map[string]string{
"builder": cfg.Builder,
"scheduler_invocation_id": fmt.Sprintf("%d", ctl.InvocationID()),
"scheduler_job_id": ctl.JobID(),
"user_agent": info.AppID(c),
}
}
return map[string]string{
"builder": "",
"scheduler_invocation_id": "",
"scheduler_job_id": "",
"user_agent": "",
}
} | [
"func",
"defaultTags",
"(",
"c",
"context",
".",
"Context",
",",
"ctl",
"task",
".",
"Controller",
",",
"cfg",
"*",
"messages",
".",
"BuildbucketTask",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"if",
"c",
"!=",
"nil",
"{",
"return",
"map",
"[",
... | // defaultTags returns map with default set of tags.
//
// If context is nil, only keys are set. | [
"defaultTags",
"returns",
"map",
"with",
"default",
"set",
"of",
"tags",
".",
"If",
"context",
"is",
"nil",
"only",
"keys",
"are",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/buildbucket/buildbucket.go#L133-L148 |
6,949 | luci/luci-go | scheduler/appengine/task/buildbucket/buildbucket.go | writeTaskData | func writeTaskData(ctl task.Controller, td *taskData) (err error) {
if ctl.State().TaskData, err = json.Marshal(td); err != nil {
return errors.Annotate(err, "could not serialize TaskData").Err()
}
return nil
} | go | func writeTaskData(ctl task.Controller, td *taskData) (err error) {
if ctl.State().TaskData, err = json.Marshal(td); err != nil {
return errors.Annotate(err, "could not serialize TaskData").Err()
}
return nil
} | [
"func",
"writeTaskData",
"(",
"ctl",
"task",
".",
"Controller",
",",
"td",
"*",
"taskData",
")",
"(",
"err",
"error",
")",
"{",
"if",
"ctl",
".",
"State",
"(",
")",
".",
"TaskData",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"td",
")",
";",
"e... | // writeTaskData puts information about the task into invocation's TaskData. | [
"writeTaskData",
"puts",
"information",
"about",
"the",
"task",
"into",
"invocation",
"s",
"TaskData",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/buildbucket/buildbucket.go#L156-L161 |
6,950 | luci/luci-go | scheduler/appengine/task/buildbucket/buildbucket.go | readTaskData | func readTaskData(ctl task.Controller) (*taskData, error) {
td := &taskData{}
if err := json.Unmarshal(ctl.State().TaskData, td); err != nil {
return nil, errors.Annotate(err, "could not parse TaskData").Err()
}
return td, nil
} | go | func readTaskData(ctl task.Controller) (*taskData, error) {
td := &taskData{}
if err := json.Unmarshal(ctl.State().TaskData, td); err != nil {
return nil, errors.Annotate(err, "could not parse TaskData").Err()
}
return td, nil
} | [
"func",
"readTaskData",
"(",
"ctl",
"task",
".",
"Controller",
")",
"(",
"*",
"taskData",
",",
"error",
")",
"{",
"td",
":=",
"&",
"taskData",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"ctl",
".",
"State",
"(",
")",
".",
"... | // readTaskData parses task data blob as prepared by writeTaskData. | [
"readTaskData",
"parses",
"task",
"data",
"blob",
"as",
"prepared",
"by",
"writeTaskData",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/buildbucket/buildbucket.go#L164-L170 |
6,951 | luci/luci-go | scheduler/appengine/task/buildbucket/buildbucket.go | checkBuildStatusLater | func (m TaskManager) checkBuildStatusLater(c context.Context, ctl task.Controller) {
// TODO(vadimsh): Make the check interval configurable?
if !ctl.State().Status.Final() {
ctl.AddTimer(c, statusCheckTimerInterval, statusCheckTimerName, nil)
}
} | go | func (m TaskManager) checkBuildStatusLater(c context.Context, ctl task.Controller) {
// TODO(vadimsh): Make the check interval configurable?
if !ctl.State().Status.Final() {
ctl.AddTimer(c, statusCheckTimerInterval, statusCheckTimerName, nil)
}
} | [
"func",
"(",
"m",
"TaskManager",
")",
"checkBuildStatusLater",
"(",
"c",
"context",
".",
"Context",
",",
"ctl",
"task",
".",
"Controller",
")",
"{",
"// TODO(vadimsh): Make the check interval configurable?",
"if",
"!",
"ctl",
".",
"State",
"(",
")",
".",
"Status... | // checkBuildStatusLater schedules a delayed call to checkBuildStatus if the
// invocation is still running.
//
// This is a fallback mechanism in case PubSub notifications are delayed or
// lost for some reason. | [
"checkBuildStatusLater",
"schedules",
"a",
"delayed",
"call",
"to",
"checkBuildStatus",
"if",
"the",
"invocation",
"is",
"still",
"running",
".",
"This",
"is",
"a",
"fallback",
"mechanism",
"in",
"case",
"PubSub",
"notifications",
"are",
"delayed",
"or",
"lost",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/buildbucket/buildbucket.go#L390-L395 |
6,952 | luci/luci-go | scheduler/appengine/task/buildbucket/buildbucket.go | handleBuildResult | func (m TaskManager) handleBuildResult(c context.Context, ctl task.Controller, r *bbv1.ApiCommonBuildMessage) {
ctl.DebugLog(
"Build %d: status %q, result %q, failure_reason %q, cancelation_reason %q",
r.Id, r.Status, r.Result, r.FailureReason, r.CancelationReason)
switch {
case r.Status == "SCHEDULED" || r.Status == "STARTED":
return // do nothing
case r.Status == "COMPLETED" && r.Result == "SUCCESS":
ctl.State().Status = task.StatusSucceeded
default:
ctl.State().Status = task.StatusFailed
}
} | go | func (m TaskManager) handleBuildResult(c context.Context, ctl task.Controller, r *bbv1.ApiCommonBuildMessage) {
ctl.DebugLog(
"Build %d: status %q, result %q, failure_reason %q, cancelation_reason %q",
r.Id, r.Status, r.Result, r.FailureReason, r.CancelationReason)
switch {
case r.Status == "SCHEDULED" || r.Status == "STARTED":
return // do nothing
case r.Status == "COMPLETED" && r.Result == "SUCCESS":
ctl.State().Status = task.StatusSucceeded
default:
ctl.State().Status = task.StatusFailed
}
} | [
"func",
"(",
"m",
"TaskManager",
")",
"handleBuildResult",
"(",
"c",
"context",
".",
"Context",
",",
"ctl",
"task",
".",
"Controller",
",",
"r",
"*",
"bbv1",
".",
"ApiCommonBuildMessage",
")",
"{",
"ctl",
".",
"DebugLog",
"(",
"\"",
"\"",
",",
"r",
"."... | // handleBuildResult processes buildbucket results message updating the state
// of the invocation. | [
"handleBuildResult",
"processes",
"buildbucket",
"results",
"message",
"updating",
"the",
"state",
"of",
"the",
"invocation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/buildbucket/buildbucket.go#L461-L473 |
6,953 | luci/luci-go | logdog/client/butler/output/record.go | Record | func (o *EntryTracker) Record() *EntryRecord {
o.mu.Lock()
defer o.mu.Unlock()
var r EntryRecord
if len(o.streams) > 0 {
r.Streams = make(map[types.StreamPath]*StreamEntryRecord, len(o.streams))
for k, v := range o.streams {
r.Streams[k] = v.record()
}
}
return &r
} | go | func (o *EntryTracker) Record() *EntryRecord {
o.mu.Lock()
defer o.mu.Unlock()
var r EntryRecord
if len(o.streams) > 0 {
r.Streams = make(map[types.StreamPath]*StreamEntryRecord, len(o.streams))
for k, v := range o.streams {
r.Streams[k] = v.record()
}
}
return &r
} | [
"func",
"(",
"o",
"*",
"EntryTracker",
")",
"Record",
"(",
")",
"*",
"EntryRecord",
"{",
"o",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"r",
"EntryRecord",
"\n",
"if",
"len",
"(",
"... | // Record exports a snapshot of the current tracking state. | [
"Record",
"exports",
"a",
"snapshot",
"of",
"the",
"current",
"tracking",
"state",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/record.go#L159-L171 |
6,954 | luci/luci-go | logdog/client/butler/output/record.go | Track | func (o *EntryTracker) Track(b *logpb.ButlerLogBundle) {
entries := b.GetEntries()
if len(entries) == 0 {
return
}
st := make([]*streamEntryTracker, len(entries))
func() {
o.mu.Lock()
defer o.mu.Unlock()
for i, e := range entries {
st[i] = o.getOrCreateStreamLocked(e.GetDesc().Path())
}
}()
for i, e := range entries {
st[i].track(e.GetLogs())
}
} | go | func (o *EntryTracker) Track(b *logpb.ButlerLogBundle) {
entries := b.GetEntries()
if len(entries) == 0 {
return
}
st := make([]*streamEntryTracker, len(entries))
func() {
o.mu.Lock()
defer o.mu.Unlock()
for i, e := range entries {
st[i] = o.getOrCreateStreamLocked(e.GetDesc().Path())
}
}()
for i, e := range entries {
st[i].track(e.GetLogs())
}
} | [
"func",
"(",
"o",
"*",
"EntryTracker",
")",
"Track",
"(",
"b",
"*",
"logpb",
".",
"ButlerLogBundle",
")",
"{",
"entries",
":=",
"b",
".",
"GetEntries",
"(",
")",
"\n",
"if",
"len",
"(",
"entries",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
... | // Track adds the log entries contained in the supplied bundle to the record. | [
"Track",
"adds",
"the",
"log",
"entries",
"contained",
"in",
"the",
"supplied",
"bundle",
"to",
"the",
"record",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/record.go#L174-L193 |
6,955 | luci/luci-go | cipd/client/cipd/fs/fs_windows.go | longFileName | func longFileName(path string) string {
const MAGIC = `\\?\`
if !strings.HasPrefix(path, MAGIC) {
path = MAGIC + path
}
return path
} | go | func longFileName(path string) string {
const MAGIC = `\\?\`
if !strings.HasPrefix(path, MAGIC) {
path = MAGIC + path
}
return path
} | [
"func",
"longFileName",
"(",
"path",
"string",
")",
"string",
"{",
"const",
"MAGIC",
"=",
"`\\\\?\\`",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"MAGIC",
")",
"{",
"path",
"=",
"MAGIC",
"+",
"path",
"\n",
"}",
"\n",
"return",
"p... | // longFileName converts a non-UNC path to a \?\\ style long path. | [
"longFileName",
"converts",
"a",
"non",
"-",
"UNC",
"path",
"to",
"a",
"\\",
"?",
"\\\\",
"style",
"long",
"path",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/fs_windows.go#L39-L45 |
6,956 | luci/luci-go | vpython/application/application.go | Main | func (cfg *Config) Main(c context.Context, argv []string, env environ.Env) int {
if len(argv) == 0 {
panic("zero-length argument slice")
}
// Implementation of "checkWrapper": if CheckWrapperENV is set, we immediately
// exit with a non-zero value.
if wrapperCheck(env) {
return 1
}
defaultLogLevel := logging.Error
if env.GetEmpty(LogTraceENV) != "" {
defaultLogLevel = logging.Debug
}
c = gologger.StdConfig.Use(c)
c = logging.SetLevel(c, defaultLogLevel)
a := application{
Config: cfg,
opts: vpython.Options{
EnvConfig: venv.Config{
BaseDir: "", // (Determined below).
MaxHashLen: 6,
SetupEnv: env,
Package: cfg.VENVPackage,
PruneThreshold: cfg.PruneThreshold,
MaxPrunesPerSweep: cfg.MaxPrunesPerSweep,
Loader: cfg.PackageLoader,
},
BaseWheels: cfg.BaseWheels,
WaitForEnv: true,
SpecLoader: cfg.SpecLoader,
Environ: env,
},
logConfig: logging.Config{
Level: defaultLogLevel,
},
}
return run(c, func(c context.Context) error {
return a.mainImpl(c, argv[0], argv[1:])
})
} | go | func (cfg *Config) Main(c context.Context, argv []string, env environ.Env) int {
if len(argv) == 0 {
panic("zero-length argument slice")
}
// Implementation of "checkWrapper": if CheckWrapperENV is set, we immediately
// exit with a non-zero value.
if wrapperCheck(env) {
return 1
}
defaultLogLevel := logging.Error
if env.GetEmpty(LogTraceENV) != "" {
defaultLogLevel = logging.Debug
}
c = gologger.StdConfig.Use(c)
c = logging.SetLevel(c, defaultLogLevel)
a := application{
Config: cfg,
opts: vpython.Options{
EnvConfig: venv.Config{
BaseDir: "", // (Determined below).
MaxHashLen: 6,
SetupEnv: env,
Package: cfg.VENVPackage,
PruneThreshold: cfg.PruneThreshold,
MaxPrunesPerSweep: cfg.MaxPrunesPerSweep,
Loader: cfg.PackageLoader,
},
BaseWheels: cfg.BaseWheels,
WaitForEnv: true,
SpecLoader: cfg.SpecLoader,
Environ: env,
},
logConfig: logging.Config{
Level: defaultLogLevel,
},
}
return run(c, func(c context.Context) error {
return a.mainImpl(c, argv[0], argv[1:])
})
} | [
"func",
"(",
"cfg",
"*",
"Config",
")",
"Main",
"(",
"c",
"context",
".",
"Context",
",",
"argv",
"[",
"]",
"string",
",",
"env",
"environ",
".",
"Env",
")",
"int",
"{",
"if",
"len",
"(",
"argv",
")",
"==",
"0",
"{",
"panic",
"(",
"\"",
"\"",
... | // Main is the main application entry point. | [
"Main",
"is",
"the",
"main",
"application",
"entry",
"point",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/application/application.go#L360-L404 |
6,957 | luci/luci-go | appengine/gaemiddleware/standard/urlfetch.go | RoundTrip | func (c *contextAwareUrlFetch) RoundTrip(r *http.Request) (*http.Response, error) {
ctx := r.Context()
// We assume context.Background() always returns exact same object.
if ctx == background {
ctx = c.c
}
return urlfetch.Get(ctx).RoundTrip(r)
} | go | func (c *contextAwareUrlFetch) RoundTrip(r *http.Request) (*http.Response, error) {
ctx := r.Context()
// We assume context.Background() always returns exact same object.
if ctx == background {
ctx = c.c
}
return urlfetch.Get(ctx).RoundTrip(r)
} | [
"func",
"(",
"c",
"*",
"contextAwareUrlFetch",
")",
"RoundTrip",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"// We assume context.Background() a... | // RoundTrip is part of http.RoundTripper interface. | [
"RoundTrip",
"is",
"part",
"of",
"http",
".",
"RoundTripper",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaemiddleware/standard/urlfetch.go#L42-L49 |
6,958 | luci/luci-go | appengine/mapper/splitter/split.go | IsEmpty | func (r Range) IsEmpty() bool {
if r.Start == nil || r.End == nil {
return false
}
return !r.Start.Less(r.End)
} | go | func (r Range) IsEmpty() bool {
if r.Start == nil || r.End == nil {
return false
}
return !r.Start.Less(r.End)
} | [
"func",
"(",
"r",
"Range",
")",
"IsEmpty",
"(",
")",
"bool",
"{",
"if",
"r",
".",
"Start",
"==",
"nil",
"||",
"r",
".",
"End",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"!",
"r",
".",
"Start",
".",
"Less",
"(",
"r",
".",... | // IsEmpty is true if the range represents an empty set. | [
"IsEmpty",
"is",
"true",
"if",
"the",
"range",
"represents",
"an",
"empty",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/mapper/splitter/split.go#L74-L79 |
6,959 | luci/luci-go | lucicfg/docgen/symbols/symbols.go | newTerm | func newTerm(name string, def ast.Node) *Term {
return &Term{
symbol: symbol{
name: name,
def: def,
},
}
} | go | func newTerm(name string, def ast.Node) *Term {
return &Term{
symbol: symbol{
name: name,
def: def,
},
}
} | [
"func",
"newTerm",
"(",
"name",
"string",
",",
"def",
"ast",
".",
"Node",
")",
"*",
"Term",
"{",
"return",
"&",
"Term",
"{",
"symbol",
":",
"symbol",
"{",
"name",
":",
"name",
",",
"def",
":",
"def",
",",
"}",
",",
"}",
"\n",
"}"
] | // newTerm returns a new Term symbol. | [
"newTerm",
"returns",
"a",
"new",
"Term",
"symbol",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/symbols/symbols.go#L103-L110 |
6,960 | luci/luci-go | lucicfg/docgen/symbols/symbols.go | newInvocation | func newInvocation(name string, def ast.Node, fn Symbol, args []Symbol) *Invocation {
return &Invocation{
symbol: symbol{
name: name,
def: def,
},
fn: fn,
args: args,
}
} | go | func newInvocation(name string, def ast.Node, fn Symbol, args []Symbol) *Invocation {
return &Invocation{
symbol: symbol{
name: name,
def: def,
},
fn: fn,
args: args,
}
} | [
"func",
"newInvocation",
"(",
"name",
"string",
",",
"def",
"ast",
".",
"Node",
",",
"fn",
"Symbol",
",",
"args",
"[",
"]",
"Symbol",
")",
"*",
"Invocation",
"{",
"return",
"&",
"Invocation",
"{",
"symbol",
":",
"symbol",
"{",
"name",
":",
"name",
",... | // newInvocation returns a new Invocation symbol. | [
"newInvocation",
"returns",
"a",
"new",
"Invocation",
"symbol",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/symbols/symbols.go#L124-L133 |
6,961 | luci/luci-go | lucicfg/docgen/symbols/symbols.go | newStruct | func newStruct(name string, def ast.Node) *Struct {
return &Struct{
symbol: symbol{
name: name,
def: def,
},
}
} | go | func newStruct(name string, def ast.Node) *Struct {
return &Struct{
symbol: symbol{
name: name,
def: def,
},
}
} | [
"func",
"newStruct",
"(",
"name",
"string",
",",
"def",
"ast",
".",
"Node",
")",
"*",
"Struct",
"{",
"return",
"&",
"Struct",
"{",
"symbol",
":",
"symbol",
"{",
"name",
":",
"name",
",",
"def",
":",
"def",
",",
"}",
",",
"}",
"\n",
"}"
] | // newStruct returns a new struct with empty list of symbols inside.
//
// The caller then can populate it via AddSymbol and finalize with Freeze when
// done. | [
"newStruct",
"returns",
"a",
"new",
"struct",
"with",
"empty",
"list",
"of",
"symbols",
"inside",
".",
"The",
"caller",
"then",
"can",
"populate",
"it",
"via",
"AddSymbol",
"and",
"finalize",
"with",
"Freeze",
"when",
"done",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/symbols/symbols.go#L159-L166 |
6,962 | luci/luci-go | lucicfg/docgen/symbols/symbols.go | addSymbol | func (s *Struct) addSymbol(sym Symbol) {
if s.frozen {
panic("frozen")
}
s.symbols = append(s.symbols, sym)
} | go | func (s *Struct) addSymbol(sym Symbol) {
if s.frozen {
panic("frozen")
}
s.symbols = append(s.symbols, sym)
} | [
"func",
"(",
"s",
"*",
"Struct",
")",
"addSymbol",
"(",
"sym",
"Symbol",
")",
"{",
"if",
"s",
".",
"frozen",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"s",
".",
"symbols",
"=",
"append",
"(",
"s",
".",
"symbols",
",",
"sym",
")",
"... | // addSymbol appends a symbol to the symbols list in the struct.
//
// Note that starlark forbids reassigning variables in the module scope, so we
// don't check that 'sym' wasn't added before.
//
// Panics if the struct is frozen. | [
"addSymbol",
"appends",
"a",
"symbol",
"to",
"the",
"symbols",
"list",
"in",
"the",
"struct",
".",
"Note",
"that",
"starlark",
"forbids",
"reassigning",
"variables",
"in",
"the",
"module",
"scope",
"so",
"we",
"don",
"t",
"check",
"that",
"sym",
"wasn",
"t... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/symbols/symbols.go#L174-L179 |
6,963 | luci/luci-go | lucicfg/docgen/symbols/symbols.go | Transform | func (s *Struct) Transform(tr func(Symbol) (Symbol, error)) (*Struct, error) {
out := &Struct{
symbol: s.symbol,
symbols: make([]Symbol, 0, len(s.symbols)),
}
for _, sym := range s.symbols {
// Recursive branch.
if strct, ok := sym.(*Struct); ok {
t, err := strct.Transform(tr)
if err != nil {
return nil, err
}
out.symbols = append(out.symbols, t)
continue
}
// Leafs.
switch t, err := tr(sym); {
case err != nil:
return nil, err
case t != nil:
out.symbols = append(out.symbols, t)
}
}
out.frozen = true
return out, nil
} | go | func (s *Struct) Transform(tr func(Symbol) (Symbol, error)) (*Struct, error) {
out := &Struct{
symbol: s.symbol,
symbols: make([]Symbol, 0, len(s.symbols)),
}
for _, sym := range s.symbols {
// Recursive branch.
if strct, ok := sym.(*Struct); ok {
t, err := strct.Transform(tr)
if err != nil {
return nil, err
}
out.symbols = append(out.symbols, t)
continue
}
// Leafs.
switch t, err := tr(sym); {
case err != nil:
return nil, err
case t != nil:
out.symbols = append(out.symbols, t)
}
}
out.frozen = true
return out, nil
} | [
"func",
"(",
"s",
"*",
"Struct",
")",
"Transform",
"(",
"tr",
"func",
"(",
"Symbol",
")",
"(",
"Symbol",
",",
"error",
")",
")",
"(",
"*",
"Struct",
",",
"error",
")",
"{",
"out",
":=",
"&",
"Struct",
"{",
"symbol",
":",
"s",
".",
"symbol",
","... | // Transform returns a new struct made by applying a transformation to the
// receiver struct, recursively. | [
"Transform",
"returns",
"a",
"new",
"struct",
"made",
"by",
"applying",
"a",
"transformation",
"to",
"the",
"receiver",
"struct",
"recursively",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/symbols/symbols.go#L195-L220 |
6,964 | luci/luci-go | logdog/common/fetcher/fetcher.go | New | func New(c context.Context, o Options) *Fetcher {
if o.Delay <= 0 {
o.Delay = DefaultDelay
}
if o.BufferBytes <= 0 && o.BufferCount <= 0 {
o.BufferBytes = DefaultBufferBytes
}
if o.PrefetchFactor <= 1 {
o.PrefetchFactor = 1
}
f := Fetcher{
o: &o,
logC: make(chan *logResponse, o.Count),
}
go f.fetch(c)
return &f
} | go | func New(c context.Context, o Options) *Fetcher {
if o.Delay <= 0 {
o.Delay = DefaultDelay
}
if o.BufferBytes <= 0 && o.BufferCount <= 0 {
o.BufferBytes = DefaultBufferBytes
}
if o.PrefetchFactor <= 1 {
o.PrefetchFactor = 1
}
f := Fetcher{
o: &o,
logC: make(chan *logResponse, o.Count),
}
go f.fetch(c)
return &f
} | [
"func",
"New",
"(",
"c",
"context",
".",
"Context",
",",
"o",
"Options",
")",
"*",
"Fetcher",
"{",
"if",
"o",
".",
"Delay",
"<=",
"0",
"{",
"o",
".",
"Delay",
"=",
"DefaultDelay",
"\n",
"}",
"\n",
"if",
"o",
".",
"BufferBytes",
"<=",
"0",
"&&",
... | // New instantiates a new Fetcher instance.
//
// The Fetcher can be cancelled by cancelling the supplied context. | [
"New",
"instantiates",
"a",
"new",
"Fetcher",
"instance",
".",
"The",
"Fetcher",
"can",
"be",
"cancelled",
"by",
"cancelling",
"the",
"supplied",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/fetcher/fetcher.go#L144-L161 |
6,965 | luci/luci-go | logdog/common/fetcher/fetcher.go | NextLogEntry | func (f *Fetcher) NextLogEntry() (*logpb.LogEntry, error) {
var le *logpb.LogEntry
if f.fetchErr == nil {
resp := <-f.logC
if resp.err != nil {
f.fetchErr = resp.err
}
if resp.log != nil {
le = resp.log
}
}
return le, f.fetchErr
} | go | func (f *Fetcher) NextLogEntry() (*logpb.LogEntry, error) {
var le *logpb.LogEntry
if f.fetchErr == nil {
resp := <-f.logC
if resp.err != nil {
f.fetchErr = resp.err
}
if resp.log != nil {
le = resp.log
}
}
return le, f.fetchErr
} | [
"func",
"(",
"f",
"*",
"Fetcher",
")",
"NextLogEntry",
"(",
")",
"(",
"*",
"logpb",
".",
"LogEntry",
",",
"error",
")",
"{",
"var",
"le",
"*",
"logpb",
".",
"LogEntry",
"\n",
"if",
"f",
".",
"fetchErr",
"==",
"nil",
"{",
"resp",
":=",
"<-",
"f",
... | // NextLogEntry returns the next buffered LogEntry, blocking until it becomes
// available.
//
// If the end of the log stream is encountered, NextLogEntry will return
// io.EOF.
//
// If the Fetcher is cancelled, a context.Canceled error will be returned. | [
"NextLogEntry",
"returns",
"the",
"next",
"buffered",
"LogEntry",
"blocking",
"until",
"it",
"becomes",
"available",
".",
"If",
"the",
"end",
"of",
"the",
"log",
"stream",
"is",
"encountered",
"NextLogEntry",
"will",
"return",
"io",
".",
"EOF",
".",
"If",
"t... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/fetcher/fetcher.go#L177-L189 |
6,966 | luci/luci-go | auth/integration/localauth/server.go | initLocalAuth | func (s *Server) initLocalAuth(ctx context.Context) (*lucictx.LocalAuth, error) {
// Build a sorted list of LocalAuthAccount to put into the context, grab
// emails from the generators.
ids := make([]string, 0, len(s.TokenGenerators))
for id := range s.TokenGenerators {
ids = append(ids, id)
}
sort.Strings(ids)
accounts := make([]lucictx.LocalAuthAccount, len(ids))
for i, id := range ids {
email, err := s.TokenGenerators[id].GetEmail()
switch {
case err == auth.ErrNoEmail:
email = "-"
case err != nil:
return nil, errors.Annotate(err, "could not grab email of account %q", id).Err()
}
accounts[i] = lucictx.LocalAuthAccount{ID: id, Email: email}
}
secret := make([]byte, 48)
if _, err := cryptorand.Read(ctx, secret); err != nil {
return nil, err
}
return &lucictx.LocalAuth{
Secret: secret,
Accounts: accounts,
DefaultAccountID: s.DefaultAccountID,
}, nil
} | go | func (s *Server) initLocalAuth(ctx context.Context) (*lucictx.LocalAuth, error) {
// Build a sorted list of LocalAuthAccount to put into the context, grab
// emails from the generators.
ids := make([]string, 0, len(s.TokenGenerators))
for id := range s.TokenGenerators {
ids = append(ids, id)
}
sort.Strings(ids)
accounts := make([]lucictx.LocalAuthAccount, len(ids))
for i, id := range ids {
email, err := s.TokenGenerators[id].GetEmail()
switch {
case err == auth.ErrNoEmail:
email = "-"
case err != nil:
return nil, errors.Annotate(err, "could not grab email of account %q", id).Err()
}
accounts[i] = lucictx.LocalAuthAccount{ID: id, Email: email}
}
secret := make([]byte, 48)
if _, err := cryptorand.Read(ctx, secret); err != nil {
return nil, err
}
return &lucictx.LocalAuth{
Secret: secret,
Accounts: accounts,
DefaultAccountID: s.DefaultAccountID,
}, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"initLocalAuth",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"lucictx",
".",
"LocalAuth",
",",
"error",
")",
"{",
"// Build a sorted list of LocalAuthAccount to put into the context, grab",
"// emails from the generators."... | // initLocalAuth generates new LocalAuth struct with RPC port blank. | [
"initLocalAuth",
"generates",
"new",
"LocalAuth",
"struct",
"with",
"RPC",
"port",
"blank",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/integration/localauth/server.go#L153-L183 |
6,967 | luci/luci-go | auth/integration/localauth/server.go | routeToImpl | func (h *protocolHandler) routeToImpl(method string, request []byte) (interface{}, error) {
switch method {
case "GetOAuthToken":
req := &rpcs.GetOAuthTokenRequest{}
if err := json.Unmarshal(request, req); err != nil {
return nil, &protocolError{
Status: http.StatusBadRequest,
Message: fmt.Sprintf("Not JSON body - %s", err),
}
}
return h.handleGetOAuthToken(req)
default:
return nil, &protocolError{
Status: http.StatusNotFound,
Message: fmt.Sprintf("Unknown RPC method %q", method),
}
}
} | go | func (h *protocolHandler) routeToImpl(method string, request []byte) (interface{}, error) {
switch method {
case "GetOAuthToken":
req := &rpcs.GetOAuthTokenRequest{}
if err := json.Unmarshal(request, req); err != nil {
return nil, &protocolError{
Status: http.StatusBadRequest,
Message: fmt.Sprintf("Not JSON body - %s", err),
}
}
return h.handleGetOAuthToken(req)
default:
return nil, &protocolError{
Status: http.StatusNotFound,
Message: fmt.Sprintf("Unknown RPC method %q", method),
}
}
} | [
"func",
"(",
"h",
"*",
"protocolHandler",
")",
"routeToImpl",
"(",
"method",
"string",
",",
"request",
"[",
"]",
"byte",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"switch",
"method",
"{",
"case",
"\"",
"\"",
":",
"req",
":=",
"&",
"r... | // routeToImpl calls appropriate RPC method implementation. | [
"routeToImpl",
"calls",
"appropriate",
"RPC",
"method",
"implementation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/integration/localauth/server.go#L361-L378 |
6,968 | luci/luci-go | machine-db/appengine/model/platforms.go | fetch | func (t *PlatformsTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, description, manufacturer
FROM platforms
`)
if err != nil {
return errors.Annotate(err, "failed to select platforms").Err()
}
defer rows.Close()
for rows.Next() {
p := &Platform{}
if err := rows.Scan(&p.Id, &p.Name, &p.Description, &p.Manufacturer); err != nil {
return errors.Annotate(err, "failed to scan platform").Err()
}
t.current = append(t.current, p)
}
return nil
} | go | func (t *PlatformsTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, description, manufacturer
FROM platforms
`)
if err != nil {
return errors.Annotate(err, "failed to select platforms").Err()
}
defer rows.Close()
for rows.Next() {
p := &Platform{}
if err := rows.Scan(&p.Id, &p.Name, &p.Description, &p.Manufacturer); err != nil {
return errors.Annotate(err, "failed to scan platform").Err()
}
t.current = append(t.current, p)
}
return nil
} | [
"func",
"(",
"t",
"*",
"PlatformsTable",
")",
"fetch",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"db",
":=",
"database",
".",
"Get",
"(",
"c",
")",
"\n",
"rows",
",",
"err",
":=",
"db",
".",
"QueryContext",
"(",
"c",
",",
"`\n\t\tSELE... | // fetch fetches the platforms from the database. | [
"fetch",
"fetches",
"the",
"platforms",
"from",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/platforms.go#L47-L65 |
6,969 | luci/luci-go | machine-db/appengine/model/platforms.go | computeChanges | func (t *PlatformsTable) computeChanges(c context.Context, platforms []*config.Platform) {
cfgs := make(map[string]*Platform, len(platforms))
for _, cfg := range platforms {
cfgs[cfg.Name] = &Platform{
Platform: config.Platform{
Name: cfg.Name,
Description: cfg.Description,
Manufacturer: cfg.Manufacturer,
},
}
}
for _, p := range t.current {
if cfg, ok := cfgs[p.Name]; ok {
// Platform found in the config.
if t.needsUpdate(p, cfg) {
// Platform doesn't match the config.
cfg.Id = p.Id
t.updates = append(t.updates, cfg)
}
// Record that the platform config has been seen.
delete(cfgs, cfg.Name)
} else {
// Platform not found in the config.
t.removals = append(t.removals, p)
}
}
// Platforms remaining in the map are present in the config but not the database.
// Iterate deterministically over the slice to determine which platforms need to be added.
for _, cfg := range platforms {
if p, ok := cfgs[cfg.Name]; ok {
t.additions = append(t.additions, p)
}
}
} | go | func (t *PlatformsTable) computeChanges(c context.Context, platforms []*config.Platform) {
cfgs := make(map[string]*Platform, len(platforms))
for _, cfg := range platforms {
cfgs[cfg.Name] = &Platform{
Platform: config.Platform{
Name: cfg.Name,
Description: cfg.Description,
Manufacturer: cfg.Manufacturer,
},
}
}
for _, p := range t.current {
if cfg, ok := cfgs[p.Name]; ok {
// Platform found in the config.
if t.needsUpdate(p, cfg) {
// Platform doesn't match the config.
cfg.Id = p.Id
t.updates = append(t.updates, cfg)
}
// Record that the platform config has been seen.
delete(cfgs, cfg.Name)
} else {
// Platform not found in the config.
t.removals = append(t.removals, p)
}
}
// Platforms remaining in the map are present in the config but not the database.
// Iterate deterministically over the slice to determine which platforms need to be added.
for _, cfg := range platforms {
if p, ok := cfgs[cfg.Name]; ok {
t.additions = append(t.additions, p)
}
}
} | [
"func",
"(",
"t",
"*",
"PlatformsTable",
")",
"computeChanges",
"(",
"c",
"context",
".",
"Context",
",",
"platforms",
"[",
"]",
"*",
"config",
".",
"Platform",
")",
"{",
"cfgs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Platform",
",",
"le... | // computeChanges computes the changes that need to be made to the platforms in the database. | [
"computeChanges",
"computes",
"the",
"changes",
"that",
"need",
"to",
"be",
"made",
"to",
"the",
"platforms",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/platforms.go#L73-L108 |
6,970 | luci/luci-go | machine-db/appengine/model/platforms.go | remove | func (t *PlatformsTable) 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 platforms
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Remove each platform from the table. It's more efficient to update the slice of
// platforms once at the end rather than for each removal, so use a defer.
removed := make(map[int64]struct{}, len(t.removals))
defer func() {
var platforms []*Platform
for _, p := range t.current {
if _, ok := removed[p.Id]; !ok {
platforms = append(platforms, p)
}
}
t.current = platforms
}()
for len(t.removals) > 0 {
p := t.removals[0]
if _, err := stmt.ExecContext(c, p.Id); err != nil {
// Defer ensures the slice of platforms is updated even if we exit early.
return errors.Annotate(err, "failed to remove platform %q", p.Name).Err()
}
removed[p.Id] = struct{}{}
t.removals = t.removals[1:]
logging.Infof(c, "Removed platform %q", p.Name)
}
return nil
} | go | func (t *PlatformsTable) 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 platforms
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Remove each platform from the table. It's more efficient to update the slice of
// platforms once at the end rather than for each removal, so use a defer.
removed := make(map[int64]struct{}, len(t.removals))
defer func() {
var platforms []*Platform
for _, p := range t.current {
if _, ok := removed[p.Id]; !ok {
platforms = append(platforms, p)
}
}
t.current = platforms
}()
for len(t.removals) > 0 {
p := t.removals[0]
if _, err := stmt.ExecContext(c, p.Id); err != nil {
// Defer ensures the slice of platforms is updated even if we exit early.
return errors.Annotate(err, "failed to remove platform %q", p.Name).Err()
}
removed[p.Id] = struct{}{}
t.removals = t.removals[1:]
logging.Infof(c, "Removed platform %q", p.Name)
}
return nil
} | [
"func",
"(",
"t",
"*",
"PlatformsTable",
")",
"remove",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"// Avoid using the database connection to prepare unnecessary statements.",
"if",
"len",
"(",
"t",
".",
"removals",
")",
"==",
"0",
"{",
"return",
"n... | // remove removes all platforms pending removal from the database, clearing pending removals.
// No-op unless computeChanges was called first. Idempotent until computeChanges is called again. | [
"remove",
"removes",
"all",
"platforms",
"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/platforms.go#L148-L187 |
6,971 | luci/luci-go | machine-db/appengine/model/platforms.go | ids | func (t *PlatformsTable) ids(c context.Context) map[string]int64 {
platforms := make(map[string]int64, len(t.current))
for _, p := range t.current {
platforms[p.Name] = p.Id
}
return platforms
} | go | func (t *PlatformsTable) ids(c context.Context) map[string]int64 {
platforms := make(map[string]int64, len(t.current))
for _, p := range t.current {
platforms[p.Name] = p.Id
}
return platforms
} | [
"func",
"(",
"t",
"*",
"PlatformsTable",
")",
"ids",
"(",
"c",
"context",
".",
"Context",
")",
"map",
"[",
"string",
"]",
"int64",
"{",
"platforms",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int64",
",",
"len",
"(",
"t",
".",
"current",
")",
... | // ids returns a map of platform names to IDs. | [
"ids",
"returns",
"a",
"map",
"of",
"platform",
"names",
"to",
"IDs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/platforms.go#L232-L238 |
6,972 | luci/luci-go | machine-db/appengine/model/platforms.go | EnsurePlatforms | func EnsurePlatforms(c context.Context, cfgs []*config.Platform) (map[string]int64, error) {
t := &PlatformsTable{}
if err := t.fetch(c); err != nil {
return nil, errors.Annotate(err, "failed to fetch platforms").Err()
}
t.computeChanges(c, cfgs)
if err := t.add(c); err != nil {
return nil, errors.Annotate(err, "failed to add platforms").Err()
}
if err := t.remove(c); err != nil {
return nil, errors.Annotate(err, "failed to remove platforms").Err()
}
if err := t.update(c); err != nil {
return nil, errors.Annotate(err, "failed to update platforms").Err()
}
return t.ids(c), nil
} | go | func EnsurePlatforms(c context.Context, cfgs []*config.Platform) (map[string]int64, error) {
t := &PlatformsTable{}
if err := t.fetch(c); err != nil {
return nil, errors.Annotate(err, "failed to fetch platforms").Err()
}
t.computeChanges(c, cfgs)
if err := t.add(c); err != nil {
return nil, errors.Annotate(err, "failed to add platforms").Err()
}
if err := t.remove(c); err != nil {
return nil, errors.Annotate(err, "failed to remove platforms").Err()
}
if err := t.update(c); err != nil {
return nil, errors.Annotate(err, "failed to update platforms").Err()
}
return t.ids(c), nil
} | [
"func",
"EnsurePlatforms",
"(",
"c",
"context",
".",
"Context",
",",
"cfgs",
"[",
"]",
"*",
"config",
".",
"Platform",
")",
"(",
"map",
"[",
"string",
"]",
"int64",
",",
"error",
")",
"{",
"t",
":=",
"&",
"PlatformsTable",
"{",
"}",
"\n",
"if",
"er... | // EnsurePlatforms ensures the database contains exactly the given platforms.
// Returns a map of platform names to IDs. | [
"EnsurePlatforms",
"ensures",
"the",
"database",
"contains",
"exactly",
"the",
"given",
"platforms",
".",
"Returns",
"a",
"map",
"of",
"platform",
"names",
"to",
"IDs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/platforms.go#L242-L258 |
6,973 | luci/luci-go | grpc/prpc/client.go | renderOptions | func (c *Client) renderOptions(opts []grpc.CallOption) (*Options, error) {
var options *Options
if c.Options != nil {
cpy := *c.Options
options = &cpy
} else {
options = DefaultOptions()
}
if err := options.apply(opts); err != nil {
return nil, err
}
return options, nil
} | go | func (c *Client) renderOptions(opts []grpc.CallOption) (*Options, error) {
var options *Options
if c.Options != nil {
cpy := *c.Options
options = &cpy
} else {
options = DefaultOptions()
}
if err := options.apply(opts); err != nil {
return nil, err
}
return options, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"renderOptions",
"(",
"opts",
"[",
"]",
"grpc",
".",
"CallOption",
")",
"(",
"*",
"Options",
",",
"error",
")",
"{",
"var",
"options",
"*",
"Options",
"\n",
"if",
"c",
".",
"Options",
"!=",
"nil",
"{",
"cpy",
... | // renderOptions copies client options and applies opts. | [
"renderOptions",
"copies",
"client",
"options",
"and",
"applies",
"opts",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/client.go#L93-L105 |
6,974 | luci/luci-go | grpc/prpc/client.go | Call | func (c *Client) Call(ctx context.Context, serviceName, methodName string, in, out proto.Message, opts ...grpc.CallOption) error {
reqBody, err := proto.Marshal(in)
if err != nil {
return err
}
resp, err := c.CallRaw(ctx, serviceName, methodName, reqBody, FormatBinary, FormatBinary, opts...)
if err != nil {
return err
}
return proto.Unmarshal(resp, out)
} | go | func (c *Client) Call(ctx context.Context, serviceName, methodName string, in, out proto.Message, opts ...grpc.CallOption) error {
reqBody, err := proto.Marshal(in)
if err != nil {
return err
}
resp, err := c.CallRaw(ctx, serviceName, methodName, reqBody, FormatBinary, FormatBinary, opts...)
if err != nil {
return err
}
return proto.Unmarshal(resp, out)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Call",
"(",
"ctx",
"context",
".",
"Context",
",",
"serviceName",
",",
"methodName",
"string",
",",
"in",
",",
"out",
"proto",
".",
"Message",
",",
"opts",
"...",
"grpc",
".",
"CallOption",
")",
"error",
"{",
"r... | // Call makes an RPC.
// Retries on transient errors according to retry options.
// Logs HTTP errors.
//
// opts must be created by this package.
// Calling from multiple goroutines concurrently is safe, unless Client is mutated.
// Called from generated code.
//
// If there is a Deadline applied to the Context, it will be forwarded to the
// server using the HeaderTimeout header. | [
"Call",
"makes",
"an",
"RPC",
".",
"Retries",
"on",
"transient",
"errors",
"according",
"to",
"retry",
"options",
".",
"Logs",
"HTTP",
"errors",
".",
"opts",
"must",
"be",
"created",
"by",
"this",
"package",
".",
"Calling",
"from",
"multiple",
"goroutines",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/client.go#L124-L135 |
6,975 | luci/luci-go | grpc/prpc/client.go | prepareRequest | func prepareRequest(host, serviceName, methodName string, md metadata.MD, contentLength int, inf, outf Format, options *Options) *http.Request {
if host == "" {
panic("Host is not set")
}
req := &http.Request{
Method: "POST",
URL: &url.URL{
Scheme: "https",
Host: host,
Path: fmt.Sprintf("/prpc/%s/%s", serviceName, methodName),
},
Header: http.Header(md.Copy()),
}
if options.Insecure {
req.URL.Scheme = "http"
}
// Set headers.
req.Header.Set("Content-Type", inf.MediaType())
req.Header.Set("Accept", outf.MediaType())
userAgent := options.UserAgent
if userAgent == "" {
userAgent = DefaultUserAgent
}
req.Header.Set("User-Agent", userAgent)
req.ContentLength = int64(contentLength)
req.Header.Set("Content-Length", strconv.Itoa(contentLength))
// TODO(nodir): add "Accept-Encoding: gzip" when pRPC server supports it.
return req
} | go | func prepareRequest(host, serviceName, methodName string, md metadata.MD, contentLength int, inf, outf Format, options *Options) *http.Request {
if host == "" {
panic("Host is not set")
}
req := &http.Request{
Method: "POST",
URL: &url.URL{
Scheme: "https",
Host: host,
Path: fmt.Sprintf("/prpc/%s/%s", serviceName, methodName),
},
Header: http.Header(md.Copy()),
}
if options.Insecure {
req.URL.Scheme = "http"
}
// Set headers.
req.Header.Set("Content-Type", inf.MediaType())
req.Header.Set("Accept", outf.MediaType())
userAgent := options.UserAgent
if userAgent == "" {
userAgent = DefaultUserAgent
}
req.Header.Set("User-Agent", userAgent)
req.ContentLength = int64(contentLength)
req.Header.Set("Content-Length", strconv.Itoa(contentLength))
// TODO(nodir): add "Accept-Encoding: gzip" when pRPC server supports it.
return req
} | [
"func",
"prepareRequest",
"(",
"host",
",",
"serviceName",
",",
"methodName",
"string",
",",
"md",
"metadata",
".",
"MD",
",",
"contentLength",
"int",
",",
"inf",
",",
"outf",
"Format",
",",
"options",
"*",
"Options",
")",
"*",
"http",
".",
"Request",
"{... | // prepareRequest creates an HTTP request for an RPC,
// except it does not set the request body. | [
"prepareRequest",
"creates",
"an",
"HTTP",
"request",
"for",
"an",
"RPC",
"except",
"it",
"does",
"not",
"set",
"the",
"request",
"body",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/client.go#L353-L382 |
6,976 | luci/luci-go | logdog/server/collector/coordinator/cache.go | NewCache | func NewCache(c Coordinator, size int, expiration time.Duration) Coordinator {
if size <= 0 {
size = DefaultSize
}
if expiration <= 0 {
expiration = DefaultExpiration
}
return &cache{
Coordinator: c,
expiration: expiration,
lru: lru.New(size),
}
} | go | func NewCache(c Coordinator, size int, expiration time.Duration) Coordinator {
if size <= 0 {
size = DefaultSize
}
if expiration <= 0 {
expiration = DefaultExpiration
}
return &cache{
Coordinator: c,
expiration: expiration,
lru: lru.New(size),
}
} | [
"func",
"NewCache",
"(",
"c",
"Coordinator",
",",
"size",
"int",
",",
"expiration",
"time",
".",
"Duration",
")",
"Coordinator",
"{",
"if",
"size",
"<=",
"0",
"{",
"size",
"=",
"DefaultSize",
"\n",
"}",
"\n",
"if",
"expiration",
"<=",
"0",
"{",
"expira... | // NewCache creates a new Coordinator instance that wraps another Coordinator
// instance with a cache that retains the latest remote Coordinator state in a
// client-side LRU cache.
//
// If size is <= 0, DefaultSize will be used.
// If expiration is <= 0, DefaultExpiration will be used. | [
"NewCache",
"creates",
"a",
"new",
"Coordinator",
"instance",
"that",
"wraps",
"another",
"Coordinator",
"instance",
"with",
"a",
"cache",
"that",
"retains",
"the",
"latest",
"remote",
"Coordinator",
"state",
"in",
"a",
"client",
"-",
"side",
"LRU",
"cache",
"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/collector/coordinator/cache.go#L68-L81 |
6,977 | luci/luci-go | logdog/server/collector/coordinator/cache.go | RegisterStream | func (c *cache) RegisterStream(ctx context.Context, st *LogStreamState, desc []byte) (*LogStreamState, error) {
entry, created := c.getCacheEntry(ctx, cacheEntryKey{
project: st.Project,
path: st.Path,
})
tsCache.Add(ctx, 1, !created)
st, err := entry.registerStream(ctx, c.Coordinator, *st, desc)
if err != nil {
log.WithError(err).Errorf(ctx, "Error retrieving stream state.")
return nil, err
}
return st, nil
} | go | func (c *cache) RegisterStream(ctx context.Context, st *LogStreamState, desc []byte) (*LogStreamState, error) {
entry, created := c.getCacheEntry(ctx, cacheEntryKey{
project: st.Project,
path: st.Path,
})
tsCache.Add(ctx, 1, !created)
st, err := entry.registerStream(ctx, c.Coordinator, *st, desc)
if err != nil {
log.WithError(err).Errorf(ctx, "Error retrieving stream state.")
return nil, err
}
return st, nil
} | [
"func",
"(",
"c",
"*",
"cache",
")",
"RegisterStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"st",
"*",
"LogStreamState",
",",
"desc",
"[",
"]",
"byte",
")",
"(",
"*",
"LogStreamState",
",",
"error",
")",
"{",
"entry",
",",
"created",
":=",
"c"... | // RegisterStream invokes the wrapped Coordinator's RegisterStream method and
// caches the result. It uses a Promise to cause all simultaneous identical
// RegisterStream requests to block on a single RPC. | [
"RegisterStream",
"invokes",
"the",
"wrapped",
"Coordinator",
"s",
"RegisterStream",
"method",
"and",
"caches",
"the",
"result",
".",
"It",
"uses",
"a",
"Promise",
"to",
"cause",
"all",
"simultaneous",
"identical",
"RegisterStream",
"requests",
"to",
"block",
"on"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/collector/coordinator/cache.go#L108-L122 |
6,978 | luci/luci-go | logdog/server/collector/coordinator/cache.go | registerStream | func (ce *cacheEntry) registerStream(ctx context.Context, coord Coordinator, st LogStreamState, desc []byte) (*LogStreamState, error) {
// Initialize the registration Promise, if one is not defined.
//
// While locked, load the current registration promise and the local
// terminal index value.
var (
p *promise.Promise
tidx types.MessageIndex
)
ce.withLock(func() {
if ce.registerP == nil {
ce.registerP = promise.NewDeferred(func(ctx context.Context) (interface{}, error) {
st, err := coord.RegisterStream(ctx, &st, desc)
if err == nil {
// If the remote state has a terminal index, retain it locally.
ce.loadRemoteTerminalIndex(st.TerminalIndex)
return st, nil
}
return nil, err
})
}
p, tidx = ce.registerP, ce.terminalIndex
})
// Resolve our registration Promise.
remoteStateIface, err := p.Get(ctx)
if err != nil {
// If the promise failed transiently, clear it so that subsequent callers
// will regenerate a new promise. ONLY clear it if it it is the same
// promise, as different callers may have already cleared/rengerated it.
if transient.Tag.In(err) {
ce.withLock(func() {
if ce.registerP == p {
ce.registerP = nil
}
})
}
return nil, err
}
remoteState := remoteStateIface.(*LogStreamState)
// If our remote state doesn't include a terminal index and our local state
// has recorded a successful remote terminal index, return a copy of the
// remote state with the remote terminal index added.
if remoteState.TerminalIndex < 0 && tidx >= 0 {
remoteStateCopy := *remoteState
remoteStateCopy.TerminalIndex = tidx
remoteState = &remoteStateCopy
}
return remoteState, nil
} | go | func (ce *cacheEntry) registerStream(ctx context.Context, coord Coordinator, st LogStreamState, desc []byte) (*LogStreamState, error) {
// Initialize the registration Promise, if one is not defined.
//
// While locked, load the current registration promise and the local
// terminal index value.
var (
p *promise.Promise
tidx types.MessageIndex
)
ce.withLock(func() {
if ce.registerP == nil {
ce.registerP = promise.NewDeferred(func(ctx context.Context) (interface{}, error) {
st, err := coord.RegisterStream(ctx, &st, desc)
if err == nil {
// If the remote state has a terminal index, retain it locally.
ce.loadRemoteTerminalIndex(st.TerminalIndex)
return st, nil
}
return nil, err
})
}
p, tidx = ce.registerP, ce.terminalIndex
})
// Resolve our registration Promise.
remoteStateIface, err := p.Get(ctx)
if err != nil {
// If the promise failed transiently, clear it so that subsequent callers
// will regenerate a new promise. ONLY clear it if it it is the same
// promise, as different callers may have already cleared/rengerated it.
if transient.Tag.In(err) {
ce.withLock(func() {
if ce.registerP == p {
ce.registerP = nil
}
})
}
return nil, err
}
remoteState := remoteStateIface.(*LogStreamState)
// If our remote state doesn't include a terminal index and our local state
// has recorded a successful remote terminal index, return a copy of the
// remote state with the remote terminal index added.
if remoteState.TerminalIndex < 0 && tidx >= 0 {
remoteStateCopy := *remoteState
remoteStateCopy.TerminalIndex = tidx
remoteState = &remoteStateCopy
}
return remoteState, nil
} | [
"func",
"(",
"ce",
"*",
"cacheEntry",
")",
"registerStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"coord",
"Coordinator",
",",
"st",
"LogStreamState",
",",
"desc",
"[",
"]",
"byte",
")",
"(",
"*",
"LogStreamState",
",",
"error",
")",
"{",
"// Init... | // registerStream performs a RegisterStream Coordinator RPC. | [
"registerStream",
"performs",
"a",
"RegisterStream",
"Coordinator",
"RPC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/collector/coordinator/cache.go#L171-L223 |
6,979 | luci/luci-go | logdog/server/collector/coordinator/cache.go | terminateStream | func (ce *cacheEntry) terminateStream(ctx context.Context, coord Coordinator, tr TerminateRequest) error {
// Initialize the termination Promise if one is not defined. Also, grab our
// cached remote terminal index.
var (
p *promise.Promise
tidx types.MessageIndex = -1
)
ce.withLock(func() {
if ce.terminateP == nil {
// We're creating a new promise, so our tr's TerminalIndex will be set.
ce.terminateP = promise.NewDeferred(func(ctx context.Context) (interface{}, error) {
// Execute our TerminateStream RPC. If successful, retain the successful
// terminal index locally.
err := coord.TerminateStream(ctx, &tr)
if err == nil {
// Note that this happens within the Promise body, so this will not
// conflict with our outer lock.
ce.loadRemoteTerminalIndex(tr.TerminalIndex)
}
return nil, err
})
}
p, tidx = ce.terminateP, ce.terminalIndex
})
// If the stream is known to be terminated on the Coordinator side, we don't
// need to issue another request.
if tidx >= 0 {
if tr.TerminalIndex != tidx {
// Not much we can do here, and this probably will never happen, but let's
// log it if it does.
log.Fields{
"requestIndex": tr.TerminalIndex,
"cachedIndex": tidx,
}.Warningf(ctx, "Request terminal index doesn't match cached value.")
}
return nil
}
// Resolve our termination Promise.
if _, err := p.Get(ctx); err != nil {
// If this is a transient error, delete this Promise so future termination
// attempts will retry for this stream.
if transient.Tag.In(err) {
ce.withLock(func() {
if ce.terminateP == p {
ce.terminateP = nil
}
})
}
return err
}
return nil
} | go | func (ce *cacheEntry) terminateStream(ctx context.Context, coord Coordinator, tr TerminateRequest) error {
// Initialize the termination Promise if one is not defined. Also, grab our
// cached remote terminal index.
var (
p *promise.Promise
tidx types.MessageIndex = -1
)
ce.withLock(func() {
if ce.terminateP == nil {
// We're creating a new promise, so our tr's TerminalIndex will be set.
ce.terminateP = promise.NewDeferred(func(ctx context.Context) (interface{}, error) {
// Execute our TerminateStream RPC. If successful, retain the successful
// terminal index locally.
err := coord.TerminateStream(ctx, &tr)
if err == nil {
// Note that this happens within the Promise body, so this will not
// conflict with our outer lock.
ce.loadRemoteTerminalIndex(tr.TerminalIndex)
}
return nil, err
})
}
p, tidx = ce.terminateP, ce.terminalIndex
})
// If the stream is known to be terminated on the Coordinator side, we don't
// need to issue another request.
if tidx >= 0 {
if tr.TerminalIndex != tidx {
// Not much we can do here, and this probably will never happen, but let's
// log it if it does.
log.Fields{
"requestIndex": tr.TerminalIndex,
"cachedIndex": tidx,
}.Warningf(ctx, "Request terminal index doesn't match cached value.")
}
return nil
}
// Resolve our termination Promise.
if _, err := p.Get(ctx); err != nil {
// If this is a transient error, delete this Promise so future termination
// attempts will retry for this stream.
if transient.Tag.In(err) {
ce.withLock(func() {
if ce.terminateP == p {
ce.terminateP = nil
}
})
}
return err
}
return nil
} | [
"func",
"(",
"ce",
"*",
"cacheEntry",
")",
"terminateStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"coord",
"Coordinator",
",",
"tr",
"TerminateRequest",
")",
"error",
"{",
"// Initialize the termination Promise if one is not defined. Also, grab our",
"// cached re... | // terminateStream performs a TerminateStream Coordinator RPC. | [
"terminateStream",
"performs",
"a",
"TerminateStream",
"Coordinator",
"RPC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/collector/coordinator/cache.go#L226-L280 |
6,980 | luci/luci-go | logdog/server/collector/coordinator/cache.go | loadRemoteTerminalIndex | func (ce *cacheEntry) loadRemoteTerminalIndex(tidx types.MessageIndex) {
// Never load an invalid remote terminal index.
if tidx < 0 {
return
}
// Load the remote terminal index if one isn't already loaded.
ce.withLock(func() {
if ce.terminalIndex < 0 {
ce.terminalIndex = tidx
}
})
} | go | func (ce *cacheEntry) loadRemoteTerminalIndex(tidx types.MessageIndex) {
// Never load an invalid remote terminal index.
if tidx < 0 {
return
}
// Load the remote terminal index if one isn't already loaded.
ce.withLock(func() {
if ce.terminalIndex < 0 {
ce.terminalIndex = tidx
}
})
} | [
"func",
"(",
"ce",
"*",
"cacheEntry",
")",
"loadRemoteTerminalIndex",
"(",
"tidx",
"types",
".",
"MessageIndex",
")",
"{",
"// Never load an invalid remote terminal index.",
"if",
"tidx",
"<",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"// Load the remote terminal index i... | // loadRemoteTerminalIndex updates our cached remote terminal index with tidx,
// if tidx >= 0 and a remote terminal index is not already cached.
//
// This is executed in the bodies of the register and terminate Promises if they
// receive a terminal index remotely. | [
"loadRemoteTerminalIndex",
"updates",
"our",
"cached",
"remote",
"terminal",
"index",
"with",
"tidx",
"if",
"tidx",
">",
"=",
"0",
"and",
"a",
"remote",
"terminal",
"index",
"is",
"not",
"already",
"cached",
".",
"This",
"is",
"executed",
"in",
"the",
"bodie... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/collector/coordinator/cache.go#L287-L299 |
6,981 | luci/luci-go | common/data/treapstore/store.go | Snapshot | func (s *Store) Snapshot() *Store {
if s.IsReadOnly() {
return s
}
s.collLock.RLock()
defer s.collLock.RUnlock()
// Return a read-only Store with the new Collection set.
snap := &Store{
collLock: nil,
colls: make(map[string]*Collection, len(s.colls)),
collNames: s.collNames,
}
// Create a read-only Collection for each coll.
for k, coll := range s.colls {
newColl := &Collection{
name: coll.name,
}
newColl.setRoot(coll.currentRoot())
snap.colls[k] = newColl
}
return snap
} | go | func (s *Store) Snapshot() *Store {
if s.IsReadOnly() {
return s
}
s.collLock.RLock()
defer s.collLock.RUnlock()
// Return a read-only Store with the new Collection set.
snap := &Store{
collLock: nil,
colls: make(map[string]*Collection, len(s.colls)),
collNames: s.collNames,
}
// Create a read-only Collection for each coll.
for k, coll := range s.colls {
newColl := &Collection{
name: coll.name,
}
newColl.setRoot(coll.currentRoot())
snap.colls[k] = newColl
}
return snap
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Snapshot",
"(",
")",
"*",
"Store",
"{",
"if",
"s",
".",
"IsReadOnly",
"(",
")",
"{",
"return",
"s",
"\n",
"}",
"\n\n",
"s",
".",
"collLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"collLock",
".",... | // Snapshot creates a read-only copy of the Store and all of its Collection
// instances. Because a Store is copy-on-write, this is a cheap operation. | [
"Snapshot",
"creates",
"a",
"read",
"-",
"only",
"copy",
"of",
"the",
"Store",
"and",
"all",
"of",
"its",
"Collection",
"instances",
".",
"Because",
"a",
"Store",
"is",
"copy",
"-",
"on",
"-",
"write",
"this",
"is",
"a",
"cheap",
"operation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L71-L95 |
6,982 | luci/luci-go | common/data/treapstore/store.go | GetCollectionNames | func (s *Store) GetCollectionNames() []string {
if s.collLock != nil {
s.collLock.RLock()
defer s.collLock.RUnlock()
}
// Clone our collection names slice.
if len(s.collNames) == 0 {
return nil
}
return append([]string(nil), s.collNames...)
} | go | func (s *Store) GetCollectionNames() []string {
if s.collLock != nil {
s.collLock.RLock()
defer s.collLock.RUnlock()
}
// Clone our collection names slice.
if len(s.collNames) == 0 {
return nil
}
return append([]string(nil), s.collNames...)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"GetCollectionNames",
"(",
")",
"[",
"]",
"string",
"{",
"if",
"s",
".",
"collLock",
"!=",
"nil",
"{",
"s",
".",
"collLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"collLock",
".",
"RUnlock",
"(",
")... | // GetCollectionNames returns the names of the Collections in this Store, sorted
// alphabetically. | [
"GetCollectionNames",
"returns",
"the",
"names",
"of",
"the",
"Collections",
"in",
"this",
"Store",
"sorted",
"alphabetically",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L99-L110 |
6,983 | luci/luci-go | common/data/treapstore/store.go | GetCollection | func (s *Store) GetCollection(name string) *Collection {
if s.collLock != nil {
s.collLock.RLock()
defer s.collLock.RUnlock()
}
return s.colls[name]
} | go | func (s *Store) GetCollection(name string) *Collection {
if s.collLock != nil {
s.collLock.RLock()
defer s.collLock.RUnlock()
}
return s.colls[name]
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"GetCollection",
"(",
"name",
"string",
")",
"*",
"Collection",
"{",
"if",
"s",
".",
"collLock",
"!=",
"nil",
"{",
"s",
".",
"collLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"collLock",
".",
"RUnlock... | // GetCollection returns the Collection with the specified name. If no such
// Collection exists, GetCollection will return nil. | [
"GetCollection",
"returns",
"the",
"Collection",
"with",
"the",
"specified",
"name",
".",
"If",
"no",
"such",
"Collection",
"exists",
"GetCollection",
"will",
"return",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L114-L120 |
6,984 | luci/luci-go | common/data/treapstore/store.go | CreateCollection | func (s *Store) CreateCollection(name string, compare gtreap.Compare) *Collection {
s.assertNotReadOnly()
s.collLock.Lock()
defer s.collLock.Unlock()
// Try to get the existing Collection again now that we hold the write lock.
if _, ok := s.colls[name]; ok {
panic(fmt.Errorf("collection %q already exists", name))
}
// Create a new read/write Collection.
coll := &Collection{
name: name,
rootLock: &sync.RWMutex{},
}
coll.setRoot(gtreap.NewTreap(compare))
if s.colls == nil {
s.colls = make(map[string]*Collection)
}
s.colls[name] = coll
s.collNames = s.insertCollectionName(name)
return coll
} | go | func (s *Store) CreateCollection(name string, compare gtreap.Compare) *Collection {
s.assertNotReadOnly()
s.collLock.Lock()
defer s.collLock.Unlock()
// Try to get the existing Collection again now that we hold the write lock.
if _, ok := s.colls[name]; ok {
panic(fmt.Errorf("collection %q already exists", name))
}
// Create a new read/write Collection.
coll := &Collection{
name: name,
rootLock: &sync.RWMutex{},
}
coll.setRoot(gtreap.NewTreap(compare))
if s.colls == nil {
s.colls = make(map[string]*Collection)
}
s.colls[name] = coll
s.collNames = s.insertCollectionName(name)
return coll
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"CreateCollection",
"(",
"name",
"string",
",",
"compare",
"gtreap",
".",
"Compare",
")",
"*",
"Collection",
"{",
"s",
".",
"assertNotReadOnly",
"(",
")",
"\n\n",
"s",
".",
"collLock",
".",
"Lock",
"(",
")",
"\n",
... | // CreateCollection returns a Collection with the specified name. If the
// collection already exists, or if s is read-only, CreateCollection will panic. | [
"CreateCollection",
"returns",
"a",
"Collection",
"with",
"the",
"specified",
"name",
".",
"If",
"the",
"collection",
"already",
"exists",
"or",
"if",
"s",
"is",
"read",
"-",
"only",
"CreateCollection",
"will",
"panic",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L124-L148 |
6,985 | luci/luci-go | common/data/treapstore/store.go | insertCollectionName | func (s *Store) insertCollectionName(name string) []string {
sidx := sort.SearchStrings(s.collNames, name)
r := make([]string, 0, len(s.collNames)+1)
return append(append(append(r, s.collNames[:sidx]...), name), s.collNames[sidx:]...)
} | go | func (s *Store) insertCollectionName(name string) []string {
sidx := sort.SearchStrings(s.collNames, name)
r := make([]string, 0, len(s.collNames)+1)
return append(append(append(r, s.collNames[:sidx]...), name), s.collNames[sidx:]...)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"insertCollectionName",
"(",
"name",
"string",
")",
"[",
"]",
"string",
"{",
"sidx",
":=",
"sort",
".",
"SearchStrings",
"(",
"s",
".",
"collNames",
",",
"name",
")",
"\n",
"r",
":=",
"make",
"(",
"[",
"]",
"str... | // insertCollectionName returns a copy of s.collNames with name inserted
// in its appropriate sorted position. | [
"insertCollectionName",
"returns",
"a",
"copy",
"of",
"s",
".",
"collNames",
"with",
"name",
"inserted",
"in",
"its",
"appropriate",
"sorted",
"position",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L152-L156 |
6,986 | luci/luci-go | common/data/treapstore/store.go | Min | func (c *Collection) Min() gtreap.Item {
root := c.currentRoot()
if root == nil {
return nil
}
return root.Min()
} | go | func (c *Collection) Min() gtreap.Item {
root := c.currentRoot()
if root == nil {
return nil
}
return root.Min()
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Min",
"(",
")",
"gtreap",
".",
"Item",
"{",
"root",
":=",
"c",
".",
"currentRoot",
"(",
")",
"\n",
"if",
"root",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"root",
".",
"Min",
"(",
"... | // Min returns the smallest item in the collection. | [
"Min",
"returns",
"the",
"smallest",
"item",
"in",
"the",
"collection",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L185-L191 |
6,987 | luci/luci-go | common/data/treapstore/store.go | Max | func (c *Collection) Max() gtreap.Item {
root := c.currentRoot()
if root == nil {
return nil
}
return root.Max()
} | go | func (c *Collection) Max() gtreap.Item {
root := c.currentRoot()
if root == nil {
return nil
}
return root.Max()
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Max",
"(",
")",
"gtreap",
".",
"Item",
"{",
"root",
":=",
"c",
".",
"currentRoot",
"(",
")",
"\n",
"if",
"root",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"root",
".",
"Max",
"(",
"... | // Max returns the largest item in the collection. | [
"Max",
"returns",
"the",
"largest",
"item",
"in",
"the",
"collection",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L194-L200 |
6,988 | luci/luci-go | common/data/treapstore/store.go | Get | func (c *Collection) Get(i gtreap.Item) gtreap.Item {
root := c.currentRoot()
if root == nil {
return nil
}
return root.Get(i)
} | go | func (c *Collection) Get(i gtreap.Item) gtreap.Item {
root := c.currentRoot()
if root == nil {
return nil
}
return root.Get(i)
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Get",
"(",
"i",
"gtreap",
".",
"Item",
")",
"gtreap",
".",
"Item",
"{",
"root",
":=",
"c",
".",
"currentRoot",
"(",
")",
"\n",
"if",
"root",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
... | // Get returns the item in the Store that matches i, or nil if no such item
// exists. | [
"Get",
"returns",
"the",
"item",
"in",
"the",
"Store",
"that",
"matches",
"i",
"or",
"nil",
"if",
"no",
"such",
"item",
"exists",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L204-L210 |
6,989 | luci/luci-go | common/data/treapstore/store.go | Put | func (c *Collection) Put(i gtreap.Item) {
c.assertNotReadOnly()
// Lock around the entire Upsert operation to serialize Puts.
priority := rand.Int()
c.rootLock.Lock()
c.root = c.root.Upsert(i, priority)
c.rootLock.Unlock()
} | go | func (c *Collection) Put(i gtreap.Item) {
c.assertNotReadOnly()
// Lock around the entire Upsert operation to serialize Puts.
priority := rand.Int()
c.rootLock.Lock()
c.root = c.root.Upsert(i, priority)
c.rootLock.Unlock()
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Put",
"(",
"i",
"gtreap",
".",
"Item",
")",
"{",
"c",
".",
"assertNotReadOnly",
"(",
")",
"\n\n",
"// Lock around the entire Upsert operation to serialize Puts.",
"priority",
":=",
"rand",
".",
"Int",
"(",
")",
"\n",
... | // Put adds an item to the Store.
//
// If the Store is read-only, Put will panic. | [
"Put",
"adds",
"an",
"item",
"to",
"the",
"Store",
".",
"If",
"the",
"Store",
"is",
"read",
"-",
"only",
"Put",
"will",
"panic",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L215-L223 |
6,990 | luci/luci-go | common/data/treapstore/store.go | Delete | func (c *Collection) Delete(i gtreap.Item) {
c.assertNotReadOnly()
c.rootLock.Lock()
c.root = c.root.Delete(i)
c.rootLock.Unlock()
} | go | func (c *Collection) Delete(i gtreap.Item) {
c.assertNotReadOnly()
c.rootLock.Lock()
c.root = c.root.Delete(i)
c.rootLock.Unlock()
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Delete",
"(",
"i",
"gtreap",
".",
"Item",
")",
"{",
"c",
".",
"assertNotReadOnly",
"(",
")",
"\n\n",
"c",
".",
"rootLock",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"root",
"=",
"c",
".",
"root",
".",
"De... | // Delete deletes an item from the Collection, if such an item exists. | [
"Delete",
"deletes",
"an",
"item",
"from",
"the",
"Collection",
"if",
"such",
"an",
"item",
"exists",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L226-L232 |
6,991 | luci/luci-go | common/data/treapstore/store.go | VisitAscend | func (c *Collection) VisitAscend(pivot gtreap.Item, visitor gtreap.ItemVisitor) {
c.currentRoot().VisitAscend(pivot, visitor)
} | go | func (c *Collection) VisitAscend(pivot gtreap.Item, visitor gtreap.ItemVisitor) {
c.currentRoot().VisitAscend(pivot, visitor)
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"VisitAscend",
"(",
"pivot",
"gtreap",
".",
"Item",
",",
"visitor",
"gtreap",
".",
"ItemVisitor",
")",
"{",
"c",
".",
"currentRoot",
"(",
")",
".",
"VisitAscend",
"(",
"pivot",
",",
"visitor",
")",
"\n",
"}"
] | // VisitAscend traverses the Collection ascendingly, invoking visitor for each
// visited item.
//
// If visitor returns false, iteration will stop prematurely.
//
// VisitAscend is a more efficient traversal than using an Iterator, and is
// useful in times when entry-by-entry iteration is not required. | [
"VisitAscend",
"traverses",
"the",
"Collection",
"ascendingly",
"invoking",
"visitor",
"for",
"each",
"visited",
"item",
".",
"If",
"visitor",
"returns",
"false",
"iteration",
"will",
"stop",
"prematurely",
".",
"VisitAscend",
"is",
"a",
"more",
"efficient",
"trav... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L257-L259 |
6,992 | luci/luci-go | common/data/treapstore/store.go | Iterator | func (c *Collection) Iterator(pivot gtreap.Item) *gtreap.Iterator {
root := c.currentRoot()
if root == nil {
root = emptyTreap
}
return root.Iterator(pivot)
} | go | func (c *Collection) Iterator(pivot gtreap.Item) *gtreap.Iterator {
root := c.currentRoot()
if root == nil {
root = emptyTreap
}
return root.Iterator(pivot)
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Iterator",
"(",
"pivot",
"gtreap",
".",
"Item",
")",
"*",
"gtreap",
".",
"Iterator",
"{",
"root",
":=",
"c",
".",
"currentRoot",
"(",
")",
"\n",
"if",
"root",
"==",
"nil",
"{",
"root",
"=",
"emptyTreap",
"... | // Iterator returns an iterator over the Collection, starting at the supplied
// pivot item. | [
"Iterator",
"returns",
"an",
"iterator",
"over",
"the",
"Collection",
"starting",
"at",
"the",
"supplied",
"pivot",
"item",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/treapstore/store.go#L263-L269 |
6,993 | luci/luci-go | lucicfg/docgen/symbols/loader.go | init | func (l *Loader) init() {
if l.loading == nil {
l.loading = stringset.New(1)
l.sources = make(map[string]string, 1)
l.symbols = make(map[string]*Struct, 1)
}
} | go | func (l *Loader) init() {
if l.loading == nil {
l.loading = stringset.New(1)
l.sources = make(map[string]string, 1)
l.symbols = make(map[string]*Struct, 1)
}
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"init",
"(",
")",
"{",
"if",
"l",
".",
"loading",
"==",
"nil",
"{",
"l",
".",
"loading",
"=",
"stringset",
".",
"New",
"(",
"1",
")",
"\n",
"l",
".",
"sources",
"=",
"make",
"(",
"map",
"[",
"string",
"]"... | // init lazily initializes loader's guts. | [
"init",
"lazily",
"initializes",
"loader",
"s",
"guts",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/symbols/loader.go#L64-L70 |
6,994 | luci/luci-go | lucicfg/docgen/symbols/loader.go | Load | func (l *Loader) Load(module string) (syms *Struct, err error) {
defer func() {
err = errors.Annotate(err, "in %s", module).Err()
}()
l.init()
if !l.loading.Add(module) {
return nil, errors.New("recursive dependency")
}
defer l.loading.Del(module)
// Already processed it?
if syms, ok := l.symbols[module]; ok {
return syms, nil
}
// Load and parse the source code into a distilled AST.
src, err := l.Source(module)
if err != nil {
return nil, err
}
l.sources[module] = src
mod, err := ast.ParseModule(module, src)
if err != nil {
return nil, err
}
// Recursively resolve all references in 'mod' to their concrete definitions
// (perhaps in other modules). This returns a struct with a list of all
// symbols defined in the module.
var top *Struct
if top, err = l.resolveRefs(&mod.Namespace, nil); err != nil {
return nil, err
}
l.symbols[module] = top
return top, nil
} | go | func (l *Loader) Load(module string) (syms *Struct, err error) {
defer func() {
err = errors.Annotate(err, "in %s", module).Err()
}()
l.init()
if !l.loading.Add(module) {
return nil, errors.New("recursive dependency")
}
defer l.loading.Del(module)
// Already processed it?
if syms, ok := l.symbols[module]; ok {
return syms, nil
}
// Load and parse the source code into a distilled AST.
src, err := l.Source(module)
if err != nil {
return nil, err
}
l.sources[module] = src
mod, err := ast.ParseModule(module, src)
if err != nil {
return nil, err
}
// Recursively resolve all references in 'mod' to their concrete definitions
// (perhaps in other modules). This returns a struct with a list of all
// symbols defined in the module.
var top *Struct
if top, err = l.resolveRefs(&mod.Namespace, nil); err != nil {
return nil, err
}
l.symbols[module] = top
return top, nil
} | [
"func",
"(",
"l",
"*",
"Loader",
")",
"Load",
"(",
"module",
"string",
")",
"(",
"syms",
"*",
"Struct",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"err",
"=",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"mod... | // Loads loads the module and all modules it references, populating the
// loader's state with information about exported symbols.
//
// Returns a struct with a list of symbols defined in the module.
//
// Can be called multiple times with different modules. | [
"Loads",
"loads",
"the",
"module",
"and",
"all",
"modules",
"it",
"references",
"populating",
"the",
"loader",
"s",
"state",
"with",
"information",
"about",
"exported",
"symbols",
".",
"Returns",
"a",
"struct",
"with",
"a",
"list",
"of",
"symbols",
"defined",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/symbols/loader.go#L78-L114 |
6,995 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/config_validation.go | validateServiceAccountsCfg | func validateServiceAccountsCfg(ctx *validation.Context, cfg *admin.ServiceAccountsPermissions) {
if cfg.Defaults != nil {
validateDefaults(ctx, "defaults", cfg.Defaults)
}
names := stringset.New(0)
accounts := map[string]string{} // service account -> rule name where its defined
groups := map[string]string{} // group with accounts -> rule name where its defined
for i, rule := range cfg.Rules {
// Rule name must be unique. Missing name will be handled by 'validateRule'.
if rule.Name != "" {
if names.Has(rule.Name) {
ctx.Errorf("two rules with identical name %q", rule.Name)
} else {
names.Add(rule.Name)
}
}
// There should be no overlap between service account sets covered by each
// rule. Unfortunately we can't reliably dive into groups, since they may
// change after the config validation step. So compare only top level group
// names, Rules.Rule() method relies on this.
for _, account := range rule.ServiceAccount {
if name, ok := accounts[account]; ok {
ctx.Errorf("service account %q is mentioned by more than one rule (%q and %q)", account, name, rule.Name)
} else {
accounts[account] = rule.Name
}
}
for _, group := range rule.ServiceAccountGroup {
if name, ok := groups[group]; ok {
ctx.Errorf("service account group %q is mentioned by more than one rule (%q and %q)", group, name, rule.Name)
} else {
groups[group] = rule.Name
}
}
validateRule(ctx, fmt.Sprintf("rule #%d: %q", i+1, rule.Name), rule)
}
} | go | func validateServiceAccountsCfg(ctx *validation.Context, cfg *admin.ServiceAccountsPermissions) {
if cfg.Defaults != nil {
validateDefaults(ctx, "defaults", cfg.Defaults)
}
names := stringset.New(0)
accounts := map[string]string{} // service account -> rule name where its defined
groups := map[string]string{} // group with accounts -> rule name where its defined
for i, rule := range cfg.Rules {
// Rule name must be unique. Missing name will be handled by 'validateRule'.
if rule.Name != "" {
if names.Has(rule.Name) {
ctx.Errorf("two rules with identical name %q", rule.Name)
} else {
names.Add(rule.Name)
}
}
// There should be no overlap between service account sets covered by each
// rule. Unfortunately we can't reliably dive into groups, since they may
// change after the config validation step. So compare only top level group
// names, Rules.Rule() method relies on this.
for _, account := range rule.ServiceAccount {
if name, ok := accounts[account]; ok {
ctx.Errorf("service account %q is mentioned by more than one rule (%q and %q)", account, name, rule.Name)
} else {
accounts[account] = rule.Name
}
}
for _, group := range rule.ServiceAccountGroup {
if name, ok := groups[group]; ok {
ctx.Errorf("service account group %q is mentioned by more than one rule (%q and %q)", group, name, rule.Name)
} else {
groups[group] = rule.Name
}
}
validateRule(ctx, fmt.Sprintf("rule #%d: %q", i+1, rule.Name), rule)
}
} | [
"func",
"validateServiceAccountsCfg",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"cfg",
"*",
"admin",
".",
"ServiceAccountsPermissions",
")",
"{",
"if",
"cfg",
".",
"Defaults",
"!=",
"nil",
"{",
"validateDefaults",
"(",
"ctx",
",",
"\"",
"\"",
",",
... | // validateServiceAccountsCfg checks deserialized service_accounts.cfg. | [
"validateServiceAccountsCfg",
"checks",
"deserialized",
"service_accounts",
".",
"cfg",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/config_validation.go#L42-L81 |
6,996 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/config_validation.go | validateDefaults | func validateDefaults(ctx *validation.Context, title string, d *admin.ServiceAccountRuleDefaults) {
ctx.Enter(title)
defer ctx.Exit()
validateScopes(ctx, "allowed_scope", d.AllowedScope)
validateMaxGrantValidityDuration(ctx, d.MaxGrantValidityDuration)
} | go | func validateDefaults(ctx *validation.Context, title string, d *admin.ServiceAccountRuleDefaults) {
ctx.Enter(title)
defer ctx.Exit()
validateScopes(ctx, "allowed_scope", d.AllowedScope)
validateMaxGrantValidityDuration(ctx, d.MaxGrantValidityDuration)
} | [
"func",
"validateDefaults",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"title",
"string",
",",
"d",
"*",
"admin",
".",
"ServiceAccountRuleDefaults",
")",
"{",
"ctx",
".",
"Enter",
"(",
"title",
")",
"\n",
"defer",
"ctx",
".",
"Exit",
"(",
")",
... | // validateDefaults checks ServiceAccountRuleDefaults proto. | [
"validateDefaults",
"checks",
"ServiceAccountRuleDefaults",
"proto",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/config_validation.go#L84-L89 |
6,997 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/config_validation.go | validateRule | func validateRule(ctx *validation.Context, title string, r *admin.ServiceAccountRule) {
ctx.Enter(title)
defer ctx.Exit()
if r.Name == "" {
ctx.Errorf(`"name" is required`)
}
// Note: we allow any of the sets to be empty. The rule will just not match
// anything in this case, this is fine.
validateEmails(ctx, "service_account", r.ServiceAccount)
validateGroups(ctx, "service_account_group", r.ServiceAccountGroup)
validateScopes(ctx, "allowed_scope", r.AllowedScope)
validateIDSet(ctx, "end_user", r.EndUser)
validateIDSet(ctx, "proxy", r.Proxy)
validateIDSet(ctx, "trusted_proxy", r.TrustedProxy)
validateMaxGrantValidityDuration(ctx, r.MaxGrantValidityDuration)
} | go | func validateRule(ctx *validation.Context, title string, r *admin.ServiceAccountRule) {
ctx.Enter(title)
defer ctx.Exit()
if r.Name == "" {
ctx.Errorf(`"name" is required`)
}
// Note: we allow any of the sets to be empty. The rule will just not match
// anything in this case, this is fine.
validateEmails(ctx, "service_account", r.ServiceAccount)
validateGroups(ctx, "service_account_group", r.ServiceAccountGroup)
validateScopes(ctx, "allowed_scope", r.AllowedScope)
validateIDSet(ctx, "end_user", r.EndUser)
validateIDSet(ctx, "proxy", r.Proxy)
validateIDSet(ctx, "trusted_proxy", r.TrustedProxy)
validateMaxGrantValidityDuration(ctx, r.MaxGrantValidityDuration)
} | [
"func",
"validateRule",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"title",
"string",
",",
"r",
"*",
"admin",
".",
"ServiceAccountRule",
")",
"{",
"ctx",
".",
"Enter",
"(",
"title",
")",
"\n",
"defer",
"ctx",
".",
"Exit",
"(",
")",
"\n\n",
"... | // validateRule checks single ServiceAccountRule proto. | [
"validateRule",
"checks",
"single",
"ServiceAccountRule",
"proto",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/config_validation.go#L92-L109 |
6,998 | luci/luci-go | grpc/prpc/error.go | withStatus | func withStatus(err error, status int) *protocolError {
if _, ok := err.(*protocolError); ok {
panic("protocolError in protocolError")
}
if err == nil {
return nil
}
return &protocolError{err, status}
} | go | func withStatus(err error, status int) *protocolError {
if _, ok := err.(*protocolError); ok {
panic("protocolError in protocolError")
}
if err == nil {
return nil
}
return &protocolError{err, status}
} | [
"func",
"withStatus",
"(",
"err",
"error",
",",
"status",
"int",
")",
"*",
"protocolError",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"protocolError",
")",
";",
"ok",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
... | // withStatus wraps an error with an HTTP status.
// If err is nil, returns nil. | [
"withStatus",
"wraps",
"an",
"error",
"with",
"an",
"HTTP",
"status",
".",
"If",
"err",
"is",
"nil",
"returns",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/error.go#L33-L41 |
6,999 | luci/luci-go | grpc/prpc/error.go | errorf | func errorf(status int, format string, a ...interface{}) *protocolError {
return withStatus(fmt.Errorf(format, a...), status)
} | go | func errorf(status int, format string, a ...interface{}) *protocolError {
return withStatus(fmt.Errorf(format, a...), status)
} | [
"func",
"errorf",
"(",
"status",
"int",
",",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"*",
"protocolError",
"{",
"return",
"withStatus",
"(",
"fmt",
".",
"Errorf",
"(",
"format",
",",
"a",
"...",
")",
",",
"status",
")",
"\n",... | // errorf creates a new protocol error. | [
"errorf",
"creates",
"a",
"new",
"protocol",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/error.go#L44-L46 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.