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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
7,900 | luci/luci-go | scheduler/appengine/engine/utils.go | structFromMap | func structFromMap(m map[string]string) *structpb.Struct {
out := &structpb.Struct{
Fields: make(map[string]*structpb.Value, len(m)),
}
for k, v := range m {
out.Fields[k] = &structpb.Value{
Kind: &structpb.Value_StringValue{StringValue: v},
}
}
return out
} | go | func structFromMap(m map[string]string) *structpb.Struct {
out := &structpb.Struct{
Fields: make(map[string]*structpb.Value, len(m)),
}
for k, v := range m {
out.Fields[k] = &structpb.Value{
Kind: &structpb.Value_StringValue{StringValue: v},
}
}
return out
} | [
"func",
"structFromMap",
"(",
"m",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"structpb",
".",
"Struct",
"{",
"out",
":=",
"&",
"structpb",
".",
"Struct",
"{",
"Fields",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"structpb",
".",
"Value",
",",
"len",
"(",
"m",
")",
")",
",",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"out",
".",
"Fields",
"[",
"k",
"]",
"=",
"&",
"structpb",
".",
"Value",
"{",
"Kind",
":",
"&",
"structpb",
".",
"Value_StringValue",
"{",
"StringValue",
":",
"v",
"}",
",",
"}",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // structFromMap constructs protobuf.Struct with string keys and values. | [
"structFromMap",
"constructs",
"protobuf",
".",
"Struct",
"with",
"string",
"keys",
"and",
"values",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L249-L259 |
7,901 | luci/luci-go | scheduler/appengine/engine/utils.go | marshalFinishedInvs | func marshalFinishedInvs(invs []*internal.FinishedInvocation) []byte {
if len(invs) == 0 {
return nil
}
blob, err := proto.Marshal(&internal.FinishedInvocationList{Invocations: invs})
if err != nil {
panic(err)
}
return blob
} | go | func marshalFinishedInvs(invs []*internal.FinishedInvocation) []byte {
if len(invs) == 0 {
return nil
}
blob, err := proto.Marshal(&internal.FinishedInvocationList{Invocations: invs})
if err != nil {
panic(err)
}
return blob
} | [
"func",
"marshalFinishedInvs",
"(",
"invs",
"[",
"]",
"*",
"internal",
".",
"FinishedInvocation",
")",
"[",
"]",
"byte",
"{",
"if",
"len",
"(",
"invs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"blob",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&",
"internal",
".",
"FinishedInvocationList",
"{",
"Invocations",
":",
"invs",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"blob",
"\n",
"}"
] | // marshalFinishedInvs marshals list of invocations into FinishedInvocationList.
//
// Panics on errors. | [
"marshalFinishedInvs",
"marshals",
"list",
"of",
"invocations",
"into",
"FinishedInvocationList",
".",
"Panics",
"on",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L264-L273 |
7,902 | luci/luci-go | scheduler/appengine/engine/utils.go | unmarshalFinishedInvs | func unmarshalFinishedInvs(raw []byte) ([]*internal.FinishedInvocation, error) {
if len(raw) == 0 {
return nil, nil
}
invs := internal.FinishedInvocationList{}
if err := proto.Unmarshal(raw, &invs); err != nil {
return nil, err
}
return invs.Invocations, nil
} | go | func unmarshalFinishedInvs(raw []byte) ([]*internal.FinishedInvocation, error) {
if len(raw) == 0 {
return nil, nil
}
invs := internal.FinishedInvocationList{}
if err := proto.Unmarshal(raw, &invs); err != nil {
return nil, err
}
return invs.Invocations, nil
} | [
"func",
"unmarshalFinishedInvs",
"(",
"raw",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"*",
"internal",
".",
"FinishedInvocation",
",",
"error",
")",
"{",
"if",
"len",
"(",
"raw",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"invs",
":=",
"internal",
".",
"FinishedInvocationList",
"{",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"raw",
",",
"&",
"invs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"invs",
".",
"Invocations",
",",
"nil",
"\n",
"}"
] | // unmarshalFinishedInvs unmarshals FinishedInvocationList proto message. | [
"unmarshalFinishedInvs",
"unmarshals",
"FinishedInvocationList",
"proto",
"message",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L276-L285 |
7,903 | luci/luci-go | scheduler/appengine/engine/utils.go | filteredFinishedInvs | func filteredFinishedInvs(raw []byte, oldest time.Time) ([]*internal.FinishedInvocation, error) {
invs, err := unmarshalFinishedInvs(raw)
if err != nil {
return nil, err
}
filtered := make([]*internal.FinishedInvocation, 0, len(invs))
for _, inv := range invs {
if google.TimeFromProto(inv.Finished).After(oldest) {
filtered = append(filtered, inv)
}
}
return filtered, nil
} | go | func filteredFinishedInvs(raw []byte, oldest time.Time) ([]*internal.FinishedInvocation, error) {
invs, err := unmarshalFinishedInvs(raw)
if err != nil {
return nil, err
}
filtered := make([]*internal.FinishedInvocation, 0, len(invs))
for _, inv := range invs {
if google.TimeFromProto(inv.Finished).After(oldest) {
filtered = append(filtered, inv)
}
}
return filtered, nil
} | [
"func",
"filteredFinishedInvs",
"(",
"raw",
"[",
"]",
"byte",
",",
"oldest",
"time",
".",
"Time",
")",
"(",
"[",
"]",
"*",
"internal",
".",
"FinishedInvocation",
",",
"error",
")",
"{",
"invs",
",",
"err",
":=",
"unmarshalFinishedInvs",
"(",
"raw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"filtered",
":=",
"make",
"(",
"[",
"]",
"*",
"internal",
".",
"FinishedInvocation",
",",
"0",
",",
"len",
"(",
"invs",
")",
")",
"\n",
"for",
"_",
",",
"inv",
":=",
"range",
"invs",
"{",
"if",
"google",
".",
"TimeFromProto",
"(",
"inv",
".",
"Finished",
")",
".",
"After",
"(",
"oldest",
")",
"{",
"filtered",
"=",
"append",
"(",
"filtered",
",",
"inv",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"filtered",
",",
"nil",
"\n",
"}"
] | // filteredFinishedInvocations unmarshals FinishedInvocationList and filters
// it to keep only entries whose Finished timestamp is newer than 'oldest'. | [
"filteredFinishedInvocations",
"unmarshals",
"FinishedInvocationList",
"and",
"filters",
"it",
"to",
"keep",
"only",
"entries",
"whose",
"Finished",
"timestamp",
"is",
"newer",
"than",
"oldest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L289-L301 |
7,904 | luci/luci-go | logdog/appengine/coordinator/endpoints/services/getConfig.go | GetConfig | func (s *server) GetConfig(c context.Context, req *empty.Empty) (*logdog.GetConfigResponse, error) {
gcfg, err := endpoints.GetServices(c).Config(c)
if err != nil {
log.WithError(err).Errorf(c, "Failed to load configuration.")
return nil, grpcutil.Internal
}
// Load our config service host from settings.
settings, err := gaeconfig.FetchCachedSettings(c)
if err != nil {
log.WithError(err).Errorf(c, "Failed to load settings.")
return nil, grpcutil.Internal
}
return &logdog.GetConfigResponse{
ConfigServiceHost: settings.ConfigServiceHost,
ConfigSet: string(gcfg.ConfigSet),
ServiceConfigPath: gcfg.ServiceConfigPath,
// TODO(dnj): Deprecate this field once everything has switched over to
// using host.
ConfigServiceUrl: gcfg.ConfigServiceURL.String(),
}, nil
} | go | func (s *server) GetConfig(c context.Context, req *empty.Empty) (*logdog.GetConfigResponse, error) {
gcfg, err := endpoints.GetServices(c).Config(c)
if err != nil {
log.WithError(err).Errorf(c, "Failed to load configuration.")
return nil, grpcutil.Internal
}
// Load our config service host from settings.
settings, err := gaeconfig.FetchCachedSettings(c)
if err != nil {
log.WithError(err).Errorf(c, "Failed to load settings.")
return nil, grpcutil.Internal
}
return &logdog.GetConfigResponse{
ConfigServiceHost: settings.ConfigServiceHost,
ConfigSet: string(gcfg.ConfigSet),
ServiceConfigPath: gcfg.ServiceConfigPath,
// TODO(dnj): Deprecate this field once everything has switched over to
// using host.
ConfigServiceUrl: gcfg.ConfigServiceURL.String(),
}, nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"GetConfig",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"empty",
".",
"Empty",
")",
"(",
"*",
"logdog",
".",
"GetConfigResponse",
",",
"error",
")",
"{",
"gcfg",
",",
"err",
":=",
"endpoints",
".",
"GetServices",
"(",
"c",
")",
".",
"Config",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"grpcutil",
".",
"Internal",
"\n",
"}",
"\n\n",
"// Load our config service host from settings.",
"settings",
",",
"err",
":=",
"gaeconfig",
".",
"FetchCachedSettings",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"grpcutil",
".",
"Internal",
"\n",
"}",
"\n\n",
"return",
"&",
"logdog",
".",
"GetConfigResponse",
"{",
"ConfigServiceHost",
":",
"settings",
".",
"ConfigServiceHost",
",",
"ConfigSet",
":",
"string",
"(",
"gcfg",
".",
"ConfigSet",
")",
",",
"ServiceConfigPath",
":",
"gcfg",
".",
"ServiceConfigPath",
",",
"// TODO(dnj): Deprecate this field once everything has switched over to",
"// using host.",
"ConfigServiceUrl",
":",
"gcfg",
".",
"ConfigServiceURL",
".",
"String",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GetConfig allows a service to retrieve the current service configuration
// parameters. | [
"GetConfig",
"allows",
"a",
"service",
"to",
"retrieve",
"the",
"current",
"service",
"configuration",
"parameters",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services/getConfig.go#L30-L53 |
7,905 | luci/luci-go | tokenserver/cmd/luci_machine_tokend/file.go | AtomicWriteFile | func AtomicWriteFile(c context.Context, path string, body []byte, perm os.FileMode) error {
// Write the body to some temp file in the same directory.
tmp := fmt.Sprintf(
"%s.%d_%d_%d.tmp", path, os.Getpid(),
atomic.AddInt32(&counter, 1), time.Now().UnixNano())
if err := ioutil.WriteFile(tmp, body, perm); err != nil {
return err
}
// Try to replace the target file a bunch of times, retrying "Access denied"
// errors. They happen on Windows if file is locked by some other process.
// We assume other processes do not lock token file for too long.
c, _ = context.WithTimeout(c, 10*time.Second)
var err error
loop:
for {
switch err = atomicRename(tmp, path); {
case err == nil:
return nil // success!
case !os.IsPermission(err):
break loop // some unretriable fatal error
default: // permission error
logging.Warningf(c, "Failed to replace %q - %s", path, err)
if tr := clock.Sleep(c, 500*time.Millisecond); tr.Incomplete() {
break loop // timeout, giving up
}
}
}
// Best effort in cleaning up the garbage.
os.Remove(tmp)
return err
} | go | func AtomicWriteFile(c context.Context, path string, body []byte, perm os.FileMode) error {
// Write the body to some temp file in the same directory.
tmp := fmt.Sprintf(
"%s.%d_%d_%d.tmp", path, os.Getpid(),
atomic.AddInt32(&counter, 1), time.Now().UnixNano())
if err := ioutil.WriteFile(tmp, body, perm); err != nil {
return err
}
// Try to replace the target file a bunch of times, retrying "Access denied"
// errors. They happen on Windows if file is locked by some other process.
// We assume other processes do not lock token file for too long.
c, _ = context.WithTimeout(c, 10*time.Second)
var err error
loop:
for {
switch err = atomicRename(tmp, path); {
case err == nil:
return nil // success!
case !os.IsPermission(err):
break loop // some unretriable fatal error
default: // permission error
logging.Warningf(c, "Failed to replace %q - %s", path, err)
if tr := clock.Sleep(c, 500*time.Millisecond); tr.Incomplete() {
break loop // timeout, giving up
}
}
}
// Best effort in cleaning up the garbage.
os.Remove(tmp)
return err
} | [
"func",
"AtomicWriteFile",
"(",
"c",
"context",
".",
"Context",
",",
"path",
"string",
",",
"body",
"[",
"]",
"byte",
",",
"perm",
"os",
".",
"FileMode",
")",
"error",
"{",
"// Write the body to some temp file in the same directory.",
"tmp",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
",",
"os",
".",
"Getpid",
"(",
")",
",",
"atomic",
".",
"AddInt32",
"(",
"&",
"counter",
",",
"1",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"tmp",
",",
"body",
",",
"perm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Try to replace the target file a bunch of times, retrying \"Access denied\"",
"// errors. They happen on Windows if file is locked by some other process.",
"// We assume other processes do not lock token file for too long.",
"c",
",",
"_",
"=",
"context",
".",
"WithTimeout",
"(",
"c",
",",
"10",
"*",
"time",
".",
"Second",
")",
"\n",
"var",
"err",
"error",
"\n\n",
"loop",
":",
"for",
"{",
"switch",
"err",
"=",
"atomicRename",
"(",
"tmp",
",",
"path",
")",
";",
"{",
"case",
"err",
"==",
"nil",
":",
"return",
"nil",
"// success!",
"\n",
"case",
"!",
"os",
".",
"IsPermission",
"(",
"err",
")",
":",
"break",
"loop",
"// some unretriable fatal error",
"\n",
"default",
":",
"// permission error",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"if",
"tr",
":=",
"clock",
".",
"Sleep",
"(",
"c",
",",
"500",
"*",
"time",
".",
"Millisecond",
")",
";",
"tr",
".",
"Incomplete",
"(",
")",
"{",
"break",
"loop",
"// timeout, giving up",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Best effort in cleaning up the garbage.",
"os",
".",
"Remove",
"(",
"tmp",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // AtomicWriteFile atomically replaces the content of a given file.
//
// It will retry a bunch of times on permission errors on Windows, where reader
// may lock the file. | [
"AtomicWriteFile",
"atomically",
"replaces",
"the",
"content",
"of",
"a",
"given",
"file",
".",
"It",
"will",
"retry",
"a",
"bunch",
"of",
"times",
"on",
"permission",
"errors",
"on",
"Windows",
"where",
"reader",
"may",
"lock",
"the",
"file",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/file.go#L35-L68 |
7,906 | luci/luci-go | grpc/grpcutil/paniccatcher.go | NewUnaryServerPanicCatcher | func NewUnaryServerPanicCatcher(next grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
defer paniccatcher.Catch(func(p *paniccatcher.Panic) {
logging.Fields{
"panic.error": p.Reason,
}.Errorf(ctx, "Caught panic during handling of %q: %s\n%s", info.FullMethod, p.Reason, p.Stack)
err = Internal
})
if next != nil {
return next(ctx, req, info, handler)
}
return handler(ctx, req)
}
} | go | func NewUnaryServerPanicCatcher(next grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
defer paniccatcher.Catch(func(p *paniccatcher.Panic) {
logging.Fields{
"panic.error": p.Reason,
}.Errorf(ctx, "Caught panic during handling of %q: %s\n%s", info.FullMethod, p.Reason, p.Stack)
err = Internal
})
if next != nil {
return next(ctx, req, info, handler)
}
return handler(ctx, req)
}
} | [
"func",
"NewUnaryServerPanicCatcher",
"(",
"next",
"grpc",
".",
"UnaryServerInterceptor",
")",
"grpc",
".",
"UnaryServerInterceptor",
"{",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"interface",
"{",
"}",
",",
"info",
"*",
"grpc",
".",
"UnaryServerInfo",
",",
"handler",
"grpc",
".",
"UnaryHandler",
")",
"(",
"resp",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"defer",
"paniccatcher",
".",
"Catch",
"(",
"func",
"(",
"p",
"*",
"paniccatcher",
".",
"Panic",
")",
"{",
"logging",
".",
"Fields",
"{",
"\"",
"\"",
":",
"p",
".",
"Reason",
",",
"}",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\\n",
"\"",
",",
"info",
".",
"FullMethod",
",",
"p",
".",
"Reason",
",",
"p",
".",
"Stack",
")",
"\n",
"err",
"=",
"Internal",
"\n",
"}",
")",
"\n",
"if",
"next",
"!=",
"nil",
"{",
"return",
"next",
"(",
"ctx",
",",
"req",
",",
"info",
",",
"handler",
")",
"\n",
"}",
"\n",
"return",
"handler",
"(",
"ctx",
",",
"req",
")",
"\n",
"}",
"\n",
"}"
] | // NewUnaryServerPanicCatcher returns a unary interceptor that catches panics
// in RPC handlers, recovers them and returns codes.Internal gRPC errors
// instead.
//
// It can be optionally chained with other interceptor. | [
"NewUnaryServerPanicCatcher",
"returns",
"a",
"unary",
"interceptor",
"that",
"catches",
"panics",
"in",
"RPC",
"handlers",
"recovers",
"them",
"and",
"returns",
"codes",
".",
"Internal",
"gRPC",
"errors",
"instead",
".",
"It",
"can",
"be",
"optionally",
"chained",
"with",
"other",
"interceptor",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcutil/paniccatcher.go#L31-L44 |
7,907 | luci/luci-go | common/logging/gologger/config.go | PickStdFormat | func PickStdFormat(w io.Writer) string {
if file, _ := w.(*os.File); file != nil {
if terminal.IsTerminal(int(file.Fd())) {
return StdFormatWithColor
}
}
return StdFormat
} | go | func PickStdFormat(w io.Writer) string {
if file, _ := w.(*os.File); file != nil {
if terminal.IsTerminal(int(file.Fd())) {
return StdFormatWithColor
}
}
return StdFormat
} | [
"func",
"PickStdFormat",
"(",
"w",
"io",
".",
"Writer",
")",
"string",
"{",
"if",
"file",
",",
"_",
":=",
"w",
".",
"(",
"*",
"os",
".",
"File",
")",
";",
"file",
"!=",
"nil",
"{",
"if",
"terminal",
".",
"IsTerminal",
"(",
"int",
"(",
"file",
".",
"Fd",
"(",
")",
")",
")",
"{",
"return",
"StdFormatWithColor",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"StdFormat",
"\n",
"}"
] | // PickStdFormat returns StdFormat for non terminal-backed files or
// StdFormatWithColor for io.Writers that are io.Files backed by a terminal.
//
// Used by default StdConfig. | [
"PickStdFormat",
"returns",
"StdFormat",
"for",
"non",
"terminal",
"-",
"backed",
"files",
"or",
"StdFormatWithColor",
"for",
"io",
".",
"Writers",
"that",
"are",
"io",
".",
"Files",
"backed",
"by",
"a",
"terminal",
".",
"Used",
"by",
"default",
"StdConfig",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/gologger/config.go#L48-L55 |
7,908 | luci/luci-go | common/logging/gologger/config.go | Use | func (lc *LoggerConfig) Use(c context.Context) context.Context {
return logging.SetFactory(c, lc.NewLogger)
} | go | func (lc *LoggerConfig) Use(c context.Context) context.Context {
return logging.SetFactory(c, lc.NewLogger)
} | [
"func",
"(",
"lc",
"*",
"LoggerConfig",
")",
"Use",
"(",
"c",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"return",
"logging",
".",
"SetFactory",
"(",
"c",
",",
"lc",
".",
"NewLogger",
")",
"\n",
"}"
] | // Use registers go-logging based logger as default logger of the context. | [
"Use",
"registers",
"go",
"-",
"logging",
"based",
"logger",
"as",
"default",
"logger",
"of",
"the",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/gologger/config.go#L116-L118 |
7,909 | luci/luci-go | tokenserver/appengine/impl/delegation/config_validation.go | validateDelegationCfg | func validateDelegationCfg(ctx *validation.Context, cfg *admin.DelegationPermissions) {
names := stringset.New(0)
for i, rule := range cfg.Rules {
if rule.Name != "" {
if names.Has(rule.Name) {
ctx.Errorf("two rules with identical name %q", rule.Name)
}
names.Add(rule.Name)
}
validateRule(ctx, fmt.Sprintf("rule #%d: %q", i+1, rule.Name), rule)
}
} | go | func validateDelegationCfg(ctx *validation.Context, cfg *admin.DelegationPermissions) {
names := stringset.New(0)
for i, rule := range cfg.Rules {
if rule.Name != "" {
if names.Has(rule.Name) {
ctx.Errorf("two rules with identical name %q", rule.Name)
}
names.Add(rule.Name)
}
validateRule(ctx, fmt.Sprintf("rule #%d: %q", i+1, rule.Name), rule)
}
} | [
"func",
"validateDelegationCfg",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"cfg",
"*",
"admin",
".",
"DelegationPermissions",
")",
"{",
"names",
":=",
"stringset",
".",
"New",
"(",
"0",
")",
"\n",
"for",
"i",
",",
"rule",
":=",
"range",
"cfg",
".",
"Rules",
"{",
"if",
"rule",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"if",
"names",
".",
"Has",
"(",
"rule",
".",
"Name",
")",
"{",
"ctx",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rule",
".",
"Name",
")",
"\n",
"}",
"\n",
"names",
".",
"Add",
"(",
"rule",
".",
"Name",
")",
"\n",
"}",
"\n",
"validateRule",
"(",
"ctx",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
"+",
"1",
",",
"rule",
".",
"Name",
")",
",",
"rule",
")",
"\n",
"}",
"\n",
"}"
] | // validateDelegationCfg checks deserialized delegation.cfg. | [
"validateDelegationCfg",
"checks",
"deserialized",
"delegation",
".",
"cfg",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config_validation.go#L42-L53 |
7,910 | luci/luci-go | tokenserver/appengine/impl/delegation/config_validation.go | validateRule | func validateRule(ctx *validation.Context, title string, r *admin.DelegationRule) {
ctx.Enter(title)
defer ctx.Exit()
if r.Name == "" {
ctx.Errorf(`"name" is required`)
}
v := identitySetValidator{
Field: "requestor",
Context: ctx,
AllowGroups: true,
}
v.validate(r.Requestor)
v = identitySetValidator{
Field: "allowed_to_impersonate",
Context: ctx,
AllowReservedWords: []string{Requestor, Projects}, // '*' is not allowed here though
AllowGroups: true,
}
v.validate(r.AllowedToImpersonate)
v = identitySetValidator{
Field: "allowed_audience",
Context: ctx,
AllowReservedWords: []string{Requestor, "*"},
AllowGroups: true,
}
v.validate(r.AllowedAudience)
v = identitySetValidator{
Field: "target_service",
Context: ctx,
AllowReservedWords: []string{"*"},
AllowIDKinds: []identity.Kind{identity.Service},
}
v.validate(r.TargetService)
switch {
case r.MaxValidityDuration == 0:
ctx.Errorf(`"max_validity_duration" is required`)
case r.MaxValidityDuration < 0:
ctx.Errorf(`"max_validity_duration" must be positive`)
case r.MaxValidityDuration > 24*3600:
ctx.Errorf(`"max_validity_duration" must be smaller than 86401`)
}
} | go | func validateRule(ctx *validation.Context, title string, r *admin.DelegationRule) {
ctx.Enter(title)
defer ctx.Exit()
if r.Name == "" {
ctx.Errorf(`"name" is required`)
}
v := identitySetValidator{
Field: "requestor",
Context: ctx,
AllowGroups: true,
}
v.validate(r.Requestor)
v = identitySetValidator{
Field: "allowed_to_impersonate",
Context: ctx,
AllowReservedWords: []string{Requestor, Projects}, // '*' is not allowed here though
AllowGroups: true,
}
v.validate(r.AllowedToImpersonate)
v = identitySetValidator{
Field: "allowed_audience",
Context: ctx,
AllowReservedWords: []string{Requestor, "*"},
AllowGroups: true,
}
v.validate(r.AllowedAudience)
v = identitySetValidator{
Field: "target_service",
Context: ctx,
AllowReservedWords: []string{"*"},
AllowIDKinds: []identity.Kind{identity.Service},
}
v.validate(r.TargetService)
switch {
case r.MaxValidityDuration == 0:
ctx.Errorf(`"max_validity_duration" is required`)
case r.MaxValidityDuration < 0:
ctx.Errorf(`"max_validity_duration" must be positive`)
case r.MaxValidityDuration > 24*3600:
ctx.Errorf(`"max_validity_duration" must be smaller than 86401`)
}
} | [
"func",
"validateRule",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"title",
"string",
",",
"r",
"*",
"admin",
".",
"DelegationRule",
")",
"{",
"ctx",
".",
"Enter",
"(",
"title",
")",
"\n",
"defer",
"ctx",
".",
"Exit",
"(",
")",
"\n\n",
"if",
"r",
".",
"Name",
"==",
"\"",
"\"",
"{",
"ctx",
".",
"Errorf",
"(",
"`\"name\" is required`",
")",
"\n",
"}",
"\n\n",
"v",
":=",
"identitySetValidator",
"{",
"Field",
":",
"\"",
"\"",
",",
"Context",
":",
"ctx",
",",
"AllowGroups",
":",
"true",
",",
"}",
"\n",
"v",
".",
"validate",
"(",
"r",
".",
"Requestor",
")",
"\n\n",
"v",
"=",
"identitySetValidator",
"{",
"Field",
":",
"\"",
"\"",
",",
"Context",
":",
"ctx",
",",
"AllowReservedWords",
":",
"[",
"]",
"string",
"{",
"Requestor",
",",
"Projects",
"}",
",",
"// '*' is not allowed here though",
"AllowGroups",
":",
"true",
",",
"}",
"\n",
"v",
".",
"validate",
"(",
"r",
".",
"AllowedToImpersonate",
")",
"\n\n",
"v",
"=",
"identitySetValidator",
"{",
"Field",
":",
"\"",
"\"",
",",
"Context",
":",
"ctx",
",",
"AllowReservedWords",
":",
"[",
"]",
"string",
"{",
"Requestor",
",",
"\"",
"\"",
"}",
",",
"AllowGroups",
":",
"true",
",",
"}",
"\n",
"v",
".",
"validate",
"(",
"r",
".",
"AllowedAudience",
")",
"\n\n",
"v",
"=",
"identitySetValidator",
"{",
"Field",
":",
"\"",
"\"",
",",
"Context",
":",
"ctx",
",",
"AllowReservedWords",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"AllowIDKinds",
":",
"[",
"]",
"identity",
".",
"Kind",
"{",
"identity",
".",
"Service",
"}",
",",
"}",
"\n",
"v",
".",
"validate",
"(",
"r",
".",
"TargetService",
")",
"\n\n",
"switch",
"{",
"case",
"r",
".",
"MaxValidityDuration",
"==",
"0",
":",
"ctx",
".",
"Errorf",
"(",
"`\"max_validity_duration\" is required`",
")",
"\n",
"case",
"r",
".",
"MaxValidityDuration",
"<",
"0",
":",
"ctx",
".",
"Errorf",
"(",
"`\"max_validity_duration\" must be positive`",
")",
"\n",
"case",
"r",
".",
"MaxValidityDuration",
">",
"24",
"*",
"3600",
":",
"ctx",
".",
"Errorf",
"(",
"`\"max_validity_duration\" must be smaller than 86401`",
")",
"\n",
"}",
"\n",
"}"
] | // validateRule checks single DelegationRule proto.
//
// See config.proto, DelegationRule for the description of allowed values. | [
"validateRule",
"checks",
"single",
"DelegationRule",
"proto",
".",
"See",
"config",
".",
"proto",
"DelegationRule",
"for",
"the",
"description",
"of",
"allowed",
"values",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/delegation/config_validation.go#L58-L105 |
7,911 | luci/luci-go | logdog/client/cli/main.go | coordinatorClient | func (a *application) coordinatorClient(host string) (*coordinator.Client, error) {
host, err := a.resolveHost(host)
if err != nil {
return nil, errors.Annotate(err, "").Err()
}
// Get our Coordinator client instance.
prpcClient := prpc.Client{
C: a.httpClient,
Host: host,
Options: prpc.DefaultOptions(),
}
prpcClient.Options.Insecure = a.insecure
return coordinator.NewClient(&prpcClient), nil
} | go | func (a *application) coordinatorClient(host string) (*coordinator.Client, error) {
host, err := a.resolveHost(host)
if err != nil {
return nil, errors.Annotate(err, "").Err()
}
// Get our Coordinator client instance.
prpcClient := prpc.Client{
C: a.httpClient,
Host: host,
Options: prpc.DefaultOptions(),
}
prpcClient.Options.Insecure = a.insecure
return coordinator.NewClient(&prpcClient), nil
} | [
"func",
"(",
"a",
"*",
"application",
")",
"coordinatorClient",
"(",
"host",
"string",
")",
"(",
"*",
"coordinator",
".",
"Client",
",",
"error",
")",
"{",
"host",
",",
"err",
":=",
"a",
".",
"resolveHost",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"// Get our Coordinator client instance.",
"prpcClient",
":=",
"prpc",
".",
"Client",
"{",
"C",
":",
"a",
".",
"httpClient",
",",
"Host",
":",
"host",
",",
"Options",
":",
"prpc",
".",
"DefaultOptions",
"(",
")",
",",
"}",
"\n",
"prpcClient",
".",
"Options",
".",
"Insecure",
"=",
"a",
".",
"insecure",
"\n",
"return",
"coordinator",
".",
"NewClient",
"(",
"&",
"prpcClient",
")",
",",
"nil",
"\n",
"}"
] | // coordinatorClient returns a Coordinator client for the specified host. If
// no host is provided, the command-line host will be used. | [
"coordinatorClient",
"returns",
"a",
"Coordinator",
"client",
"for",
"the",
"specified",
"host",
".",
"If",
"no",
"host",
"is",
"provided",
"the",
"command",
"-",
"line",
"host",
"will",
"be",
"used",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cli/main.go#L132-L146 |
7,912 | luci/luci-go | logdog/client/cli/main.go | Main | func Main(ctx context.Context, params Parameters) int {
ctx = gologger.StdConfig.Use(ctx)
authOptions := params.DefaultAuthOptions
authOptions.Scopes = coordinator.Scopes
a := application{
Application: cli.Application{
Name: "logdog",
Title: "LogDog log data access CLI",
Context: func(context.Context) context.Context { return ctx },
Commands: []*subcommands.Command{
subcommands.CmdHelp,
newCatCommand(),
newQueryCommand(),
newLatestCommand(),
authcli.SubcommandLogin(authOptions, "auth-login", false),
authcli.SubcommandLogout(authOptions, "auth-logout", false),
authcli.SubcommandInfo(authOptions, "auth-info", false),
},
},
p: params,
authFlags: authcli.Flags{},
}
loggingConfig := log.Config{
Level: log.Level(log.Info),
}
flags := &flag.FlagSet{}
a.addToFlagSet(ctx, flags)
loggingConfig.AddFlags(flags)
a.authFlags.Register(flags, authOptions)
// Parse flags.
if err := flags.Parse(params.Args); err != nil {
log.Errorf(log.SetError(ctx, err), "Failed to parse command-line.")
return 1
}
// Install our log formatter.
ctx = loggingConfig.Set(ctx)
// Signal handler will cancel our context when interrupted.
ctx, cancelFunc := context.WithCancel(ctx)
signalC := make(chan os.Signal, 1)
signal.Notify(signalC, os.Interrupt, os.Kill)
go func() {
triggered := false
for sig := range signalC {
if triggered {
os.Exit(2)
}
triggered = true
log.Fields{
"signal": sig,
}.Warningf(ctx, "Caught signal; terminating.")
cancelFunc()
}
}()
defer func() {
signal.Stop(signalC)
close(signalC)
}()
// Instantiate our authenticated HTTP client.
authOpts, err := a.authFlags.Options()
if err != nil {
log.Errorf(log.SetError(ctx, err), "Failed to create auth options.")
return 1
}
if a.httpClient, err = auth.NewAuthenticator(ctx, auth.OptionalLogin, authOpts).Client(); err != nil {
log.Errorf(log.SetError(ctx, err), "Failed to create authenticated client.")
return 1
}
a.Context = ctx
return subcommands.Run(&a, flags.Args())
} | go | func Main(ctx context.Context, params Parameters) int {
ctx = gologger.StdConfig.Use(ctx)
authOptions := params.DefaultAuthOptions
authOptions.Scopes = coordinator.Scopes
a := application{
Application: cli.Application{
Name: "logdog",
Title: "LogDog log data access CLI",
Context: func(context.Context) context.Context { return ctx },
Commands: []*subcommands.Command{
subcommands.CmdHelp,
newCatCommand(),
newQueryCommand(),
newLatestCommand(),
authcli.SubcommandLogin(authOptions, "auth-login", false),
authcli.SubcommandLogout(authOptions, "auth-logout", false),
authcli.SubcommandInfo(authOptions, "auth-info", false),
},
},
p: params,
authFlags: authcli.Flags{},
}
loggingConfig := log.Config{
Level: log.Level(log.Info),
}
flags := &flag.FlagSet{}
a.addToFlagSet(ctx, flags)
loggingConfig.AddFlags(flags)
a.authFlags.Register(flags, authOptions)
// Parse flags.
if err := flags.Parse(params.Args); err != nil {
log.Errorf(log.SetError(ctx, err), "Failed to parse command-line.")
return 1
}
// Install our log formatter.
ctx = loggingConfig.Set(ctx)
// Signal handler will cancel our context when interrupted.
ctx, cancelFunc := context.WithCancel(ctx)
signalC := make(chan os.Signal, 1)
signal.Notify(signalC, os.Interrupt, os.Kill)
go func() {
triggered := false
for sig := range signalC {
if triggered {
os.Exit(2)
}
triggered = true
log.Fields{
"signal": sig,
}.Warningf(ctx, "Caught signal; terminating.")
cancelFunc()
}
}()
defer func() {
signal.Stop(signalC)
close(signalC)
}()
// Instantiate our authenticated HTTP client.
authOpts, err := a.authFlags.Options()
if err != nil {
log.Errorf(log.SetError(ctx, err), "Failed to create auth options.")
return 1
}
if a.httpClient, err = auth.NewAuthenticator(ctx, auth.OptionalLogin, authOpts).Client(); err != nil {
log.Errorf(log.SetError(ctx, err), "Failed to create authenticated client.")
return 1
}
a.Context = ctx
return subcommands.Run(&a, flags.Args())
} | [
"func",
"Main",
"(",
"ctx",
"context",
".",
"Context",
",",
"params",
"Parameters",
")",
"int",
"{",
"ctx",
"=",
"gologger",
".",
"StdConfig",
".",
"Use",
"(",
"ctx",
")",
"\n\n",
"authOptions",
":=",
"params",
".",
"DefaultAuthOptions",
"\n",
"authOptions",
".",
"Scopes",
"=",
"coordinator",
".",
"Scopes",
"\n\n",
"a",
":=",
"application",
"{",
"Application",
":",
"cli",
".",
"Application",
"{",
"Name",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
",",
"Context",
":",
"func",
"(",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"return",
"ctx",
"}",
",",
"Commands",
":",
"[",
"]",
"*",
"subcommands",
".",
"Command",
"{",
"subcommands",
".",
"CmdHelp",
",",
"newCatCommand",
"(",
")",
",",
"newQueryCommand",
"(",
")",
",",
"newLatestCommand",
"(",
")",
",",
"authcli",
".",
"SubcommandLogin",
"(",
"authOptions",
",",
"\"",
"\"",
",",
"false",
")",
",",
"authcli",
".",
"SubcommandLogout",
"(",
"authOptions",
",",
"\"",
"\"",
",",
"false",
")",
",",
"authcli",
".",
"SubcommandInfo",
"(",
"authOptions",
",",
"\"",
"\"",
",",
"false",
")",
",",
"}",
",",
"}",
",",
"p",
":",
"params",
",",
"authFlags",
":",
"authcli",
".",
"Flags",
"{",
"}",
",",
"}",
"\n",
"loggingConfig",
":=",
"log",
".",
"Config",
"{",
"Level",
":",
"log",
".",
"Level",
"(",
"log",
".",
"Info",
")",
",",
"}",
"\n\n",
"flags",
":=",
"&",
"flag",
".",
"FlagSet",
"{",
"}",
"\n",
"a",
".",
"addToFlagSet",
"(",
"ctx",
",",
"flags",
")",
"\n",
"loggingConfig",
".",
"AddFlags",
"(",
"flags",
")",
"\n",
"a",
".",
"authFlags",
".",
"Register",
"(",
"flags",
",",
"authOptions",
")",
"\n\n",
"// Parse flags.",
"if",
"err",
":=",
"flags",
".",
"Parse",
"(",
"params",
".",
"Args",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"log",
".",
"SetError",
"(",
"ctx",
",",
"err",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n\n",
"// Install our log formatter.",
"ctx",
"=",
"loggingConfig",
".",
"Set",
"(",
"ctx",
")",
"\n\n",
"// Signal handler will cancel our context when interrupted.",
"ctx",
",",
"cancelFunc",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"signalC",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n",
"signal",
".",
"Notify",
"(",
"signalC",
",",
"os",
".",
"Interrupt",
",",
"os",
".",
"Kill",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"triggered",
":=",
"false",
"\n",
"for",
"sig",
":=",
"range",
"signalC",
"{",
"if",
"triggered",
"{",
"os",
".",
"Exit",
"(",
"2",
")",
"\n",
"}",
"\n\n",
"triggered",
"=",
"true",
"\n",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"sig",
",",
"}",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"cancelFunc",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"signal",
".",
"Stop",
"(",
"signalC",
")",
"\n",
"close",
"(",
"signalC",
")",
"\n",
"}",
"(",
")",
"\n\n",
"// Instantiate our authenticated HTTP client.",
"authOpts",
",",
"err",
":=",
"a",
".",
"authFlags",
".",
"Options",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"log",
".",
"SetError",
"(",
"ctx",
",",
"err",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n\n",
"if",
"a",
".",
"httpClient",
",",
"err",
"=",
"auth",
".",
"NewAuthenticator",
"(",
"ctx",
",",
"auth",
".",
"OptionalLogin",
",",
"authOpts",
")",
".",
"Client",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"log",
".",
"SetError",
"(",
"ctx",
",",
"err",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n\n",
"a",
".",
"Context",
"=",
"ctx",
"\n",
"return",
"subcommands",
".",
"Run",
"(",
"&",
"a",
",",
"flags",
".",
"Args",
"(",
")",
")",
"\n",
"}"
] | // Main is the entry point for the CLI application. | [
"Main",
"is",
"the",
"entry",
"point",
"for",
"the",
"CLI",
"application",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cli/main.go#L156-L236 |
7,913 | luci/luci-go | cipd/appengine/impl/model/search.go | queryByTag | func queryByTag(c context.Context, pkg, tag string, cursor datastore.Cursor, pageSize int32) (
out []*datastore.Key,
next datastore.Cursor,
err error) {
// TODO(vadimsh): 'registered_ts' here is when the tag was attached. The
// callers likely expect results ordered by instance registration time. This
// is not possible currently. We'll need to copy Instance.registered_ts into
// InstanceTag entities, so we can order by instance registration time.
// TODO(vadimsh): Should we exclude unprocessed instances from the result?
q := datastore.NewQuery("InstanceTag").
Ancestor(PackageKey(c, pkg)).
Eq("tag", tag).
Order("-registered_ts").
Limit(pageSize).
KeysOnly(true)
if cursor != nil {
q = q.Start(cursor)
}
err = datastore.Run(c, q, func(k *datastore.Key, cb datastore.CursorCB) error {
out = append(out, k.Parent())
if len(out) >= int(pageSize) {
if next, err = cb(); err != nil {
return err
}
return datastore.Stop
}
return nil
})
if err != nil {
return nil, nil, errors.Annotate(err, "failed to query by tag %q", tag).Tag(transient.Tag).Err()
}
return
} | go | func queryByTag(c context.Context, pkg, tag string, cursor datastore.Cursor, pageSize int32) (
out []*datastore.Key,
next datastore.Cursor,
err error) {
// TODO(vadimsh): 'registered_ts' here is when the tag was attached. The
// callers likely expect results ordered by instance registration time. This
// is not possible currently. We'll need to copy Instance.registered_ts into
// InstanceTag entities, so we can order by instance registration time.
// TODO(vadimsh): Should we exclude unprocessed instances from the result?
q := datastore.NewQuery("InstanceTag").
Ancestor(PackageKey(c, pkg)).
Eq("tag", tag).
Order("-registered_ts").
Limit(pageSize).
KeysOnly(true)
if cursor != nil {
q = q.Start(cursor)
}
err = datastore.Run(c, q, func(k *datastore.Key, cb datastore.CursorCB) error {
out = append(out, k.Parent())
if len(out) >= int(pageSize) {
if next, err = cb(); err != nil {
return err
}
return datastore.Stop
}
return nil
})
if err != nil {
return nil, nil, errors.Annotate(err, "failed to query by tag %q", tag).Tag(transient.Tag).Err()
}
return
} | [
"func",
"queryByTag",
"(",
"c",
"context",
".",
"Context",
",",
"pkg",
",",
"tag",
"string",
",",
"cursor",
"datastore",
".",
"Cursor",
",",
"pageSize",
"int32",
")",
"(",
"out",
"[",
"]",
"*",
"datastore",
".",
"Key",
",",
"next",
"datastore",
".",
"Cursor",
",",
"err",
"error",
")",
"{",
"// TODO(vadimsh): 'registered_ts' here is when the tag was attached. The",
"// callers likely expect results ordered by instance registration time. This",
"// is not possible currently. We'll need to copy Instance.registered_ts into",
"// InstanceTag entities, so we can order by instance registration time.",
"// TODO(vadimsh): Should we exclude unprocessed instances from the result?",
"q",
":=",
"datastore",
".",
"NewQuery",
"(",
"\"",
"\"",
")",
".",
"Ancestor",
"(",
"PackageKey",
"(",
"c",
",",
"pkg",
")",
")",
".",
"Eq",
"(",
"\"",
"\"",
",",
"tag",
")",
".",
"Order",
"(",
"\"",
"\"",
")",
".",
"Limit",
"(",
"pageSize",
")",
".",
"KeysOnly",
"(",
"true",
")",
"\n",
"if",
"cursor",
"!=",
"nil",
"{",
"q",
"=",
"q",
".",
"Start",
"(",
"cursor",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"datastore",
".",
"Run",
"(",
"c",
",",
"q",
",",
"func",
"(",
"k",
"*",
"datastore",
".",
"Key",
",",
"cb",
"datastore",
".",
"CursorCB",
")",
"error",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"k",
".",
"Parent",
"(",
")",
")",
"\n",
"if",
"len",
"(",
"out",
")",
">=",
"int",
"(",
"pageSize",
")",
"{",
"if",
"next",
",",
"err",
"=",
"cb",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"datastore",
".",
"Stop",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"tag",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // queryByTag returns keys of Instances that have the given tag attached.
//
// Returns up to 'pageSize' of results, along with a cursor to continue the
// query or nil if it was the end of it. | [
"queryByTag",
"returns",
"keys",
"of",
"Instances",
"that",
"have",
"the",
"given",
"tag",
"attached",
".",
"Returns",
"up",
"to",
"pageSize",
"of",
"results",
"along",
"with",
"a",
"cursor",
"to",
"continue",
"the",
"query",
"or",
"nil",
"if",
"it",
"was",
"the",
"end",
"of",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/search.go#L129-L165 |
7,914 | luci/luci-go | cipd/appengine/impl/model/search.go | fetchExistingInstances | func fetchExistingInstances(c context.Context, keys []*datastore.Key) ([]*Instance, error) {
instances := make([]*Instance, len(keys))
for i, k := range keys {
instances[i] = &Instance{
InstanceID: k.StringID(),
Package: k.Parent(),
}
}
err := datastore.Get(c, instances)
if err == nil {
return instances, nil
}
merr, ok := err.(errors.MultiError)
if !ok {
return nil, errors.Annotate(err, "failed to fetch instances").Tag(transient.Tag).Err()
}
existing := instances[:0]
for i, inst := range instances {
switch err := merr[i]; {
case err == nil:
existing = append(existing, inst)
case err != datastore.ErrNoSuchEntity:
return nil, errors.Annotate(err, "failed to fetch instance %q", inst.InstanceID).Tag(transient.Tag).Err()
}
}
return existing, nil
} | go | func fetchExistingInstances(c context.Context, keys []*datastore.Key) ([]*Instance, error) {
instances := make([]*Instance, len(keys))
for i, k := range keys {
instances[i] = &Instance{
InstanceID: k.StringID(),
Package: k.Parent(),
}
}
err := datastore.Get(c, instances)
if err == nil {
return instances, nil
}
merr, ok := err.(errors.MultiError)
if !ok {
return nil, errors.Annotate(err, "failed to fetch instances").Tag(transient.Tag).Err()
}
existing := instances[:0]
for i, inst := range instances {
switch err := merr[i]; {
case err == nil:
existing = append(existing, inst)
case err != datastore.ErrNoSuchEntity:
return nil, errors.Annotate(err, "failed to fetch instance %q", inst.InstanceID).Tag(transient.Tag).Err()
}
}
return existing, nil
} | [
"func",
"fetchExistingInstances",
"(",
"c",
"context",
".",
"Context",
",",
"keys",
"[",
"]",
"*",
"datastore",
".",
"Key",
")",
"(",
"[",
"]",
"*",
"Instance",
",",
"error",
")",
"{",
"instances",
":=",
"make",
"(",
"[",
"]",
"*",
"Instance",
",",
"len",
"(",
"keys",
")",
")",
"\n",
"for",
"i",
",",
"k",
":=",
"range",
"keys",
"{",
"instances",
"[",
"i",
"]",
"=",
"&",
"Instance",
"{",
"InstanceID",
":",
"k",
".",
"StringID",
"(",
")",
",",
"Package",
":",
"k",
".",
"Parent",
"(",
")",
",",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"datastore",
".",
"Get",
"(",
"c",
",",
"instances",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"instances",
",",
"nil",
"\n",
"}",
"\n\n",
"merr",
",",
"ok",
":=",
"err",
".",
"(",
"errors",
".",
"MultiError",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"existing",
":=",
"instances",
"[",
":",
"0",
"]",
"\n",
"for",
"i",
",",
"inst",
":=",
"range",
"instances",
"{",
"switch",
"err",
":=",
"merr",
"[",
"i",
"]",
";",
"{",
"case",
"err",
"==",
"nil",
":",
"existing",
"=",
"append",
"(",
"existing",
",",
"inst",
")",
"\n",
"case",
"err",
"!=",
"datastore",
".",
"ErrNoSuchEntity",
":",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"inst",
".",
"InstanceID",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"existing",
",",
"nil",
"\n",
"}"
] | // fetchExistingInstances fetches Instance entities given their keys.
//
// Skips missing ones. | [
"fetchExistingInstances",
"fetches",
"Instance",
"entities",
"given",
"their",
"keys",
".",
"Skips",
"missing",
"ones",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/search.go#L195-L224 |
7,915 | luci/luci-go | luci_notify/config/settings.go | Load | func (s *Settings) Load(props datastore.PropertyMap) error {
if pdata, ok := props["Settings"]; ok {
settings := pdata.Slice()
if len(settings) != 1 {
return fmt.Errorf("property `Settings` is a property slice")
}
settingsBytes, ok := settings[0].Value().([]byte)
if !ok {
return fmt.Errorf("expected byte array for property `Settings`")
}
if err := proto.Unmarshal(settingsBytes, &s.Settings); err != nil {
return err
}
delete(props, "Settings")
}
return datastore.GetPLS(s).Load(props)
} | go | func (s *Settings) Load(props datastore.PropertyMap) error {
if pdata, ok := props["Settings"]; ok {
settings := pdata.Slice()
if len(settings) != 1 {
return fmt.Errorf("property `Settings` is a property slice")
}
settingsBytes, ok := settings[0].Value().([]byte)
if !ok {
return fmt.Errorf("expected byte array for property `Settings`")
}
if err := proto.Unmarshal(settingsBytes, &s.Settings); err != nil {
return err
}
delete(props, "Settings")
}
return datastore.GetPLS(s).Load(props)
} | [
"func",
"(",
"s",
"*",
"Settings",
")",
"Load",
"(",
"props",
"datastore",
".",
"PropertyMap",
")",
"error",
"{",
"if",
"pdata",
",",
"ok",
":=",
"props",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"settings",
":=",
"pdata",
".",
"Slice",
"(",
")",
"\n",
"if",
"len",
"(",
"settings",
")",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"settingsBytes",
",",
"ok",
":=",
"settings",
"[",
"0",
"]",
".",
"Value",
"(",
")",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"settingsBytes",
",",
"&",
"s",
".",
"Settings",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"delete",
"(",
"props",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"datastore",
".",
"GetPLS",
"(",
"s",
")",
".",
"Load",
"(",
"props",
")",
"\n",
"}"
] | // Load loads a Settings's information from props.
//
// This implements PropertyLoadSaver. Load unmarshals the property Settings
// stored in the datastore as a binary proto into the struct's Settings field. | [
"Load",
"loads",
"a",
"Settings",
"s",
"information",
"from",
"props",
".",
"This",
"implements",
"PropertyLoadSaver",
".",
"Load",
"unmarshals",
"the",
"property",
"Settings",
"stored",
"in",
"the",
"datastore",
"as",
"a",
"binary",
"proto",
"into",
"the",
"struct",
"s",
"Settings",
"field",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/settings.go#L48-L64 |
7,916 | luci/luci-go | luci_notify/config/settings.go | Save | func (s *Settings) Save(withMeta bool) (datastore.PropertyMap, error) {
props, err := datastore.GetPLS(s).Save(withMeta)
if err != nil {
return nil, err
}
settingsBytes, err := proto.Marshal(&s.Settings)
if err != nil {
return nil, err
}
props["Settings"] = datastore.MkProperty(settingsBytes)
return props, nil
} | go | func (s *Settings) Save(withMeta bool) (datastore.PropertyMap, error) {
props, err := datastore.GetPLS(s).Save(withMeta)
if err != nil {
return nil, err
}
settingsBytes, err := proto.Marshal(&s.Settings)
if err != nil {
return nil, err
}
props["Settings"] = datastore.MkProperty(settingsBytes)
return props, nil
} | [
"func",
"(",
"s",
"*",
"Settings",
")",
"Save",
"(",
"withMeta",
"bool",
")",
"(",
"datastore",
".",
"PropertyMap",
",",
"error",
")",
"{",
"props",
",",
"err",
":=",
"datastore",
".",
"GetPLS",
"(",
"s",
")",
".",
"Save",
"(",
"withMeta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"settingsBytes",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&",
"s",
".",
"Settings",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"props",
"[",
"\"",
"\"",
"]",
"=",
"datastore",
".",
"MkProperty",
"(",
"settingsBytes",
")",
"\n",
"return",
"props",
",",
"nil",
"\n",
"}"
] | // Save saves a Settings's information to a property map.
//
// This implements PropertyLoadSaver. Save marshals the Settings
// field as a binary proto and stores it in the Settings property. | [
"Save",
"saves",
"a",
"Settings",
"s",
"information",
"to",
"a",
"property",
"map",
".",
"This",
"implements",
"PropertyLoadSaver",
".",
"Save",
"marshals",
"the",
"Settings",
"field",
"as",
"a",
"binary",
"proto",
"and",
"stores",
"it",
"in",
"the",
"Settings",
"property",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/settings.go#L70-L81 |
7,917 | luci/luci-go | luci_notify/config/settings.go | updateSettings | func updateSettings(c context.Context) error {
// Load the settings from luci-config.
cs := cfgclient.CurrentServiceConfigSet(c)
lucicfg := GetConfigService(c)
cfg, err := lucicfg.GetConfig(c, cs, "settings.cfg", false)
if err != nil {
return errors.Annotate(err, "loading settings.cfg from luci-config").Err()
}
// Do the revision check & swap in a datastore transaction.
return datastore.RunInTransaction(c, func(c context.Context) error {
oldSettings := Settings{}
err := datastore.Get(c, &oldSettings)
switch err {
case datastore.ErrNoSuchEntity:
// This might be the first time this has run, so a warning here is ok.
logging.WithError(err).Warningf(c, "no existing service config")
case nil:
// Continue
default:
return errors.Annotate(err, "loading existing config").Err()
}
// Check to see if we need to update
if oldSettings.Revision == cfg.Revision {
logging.Debugf(c, "revisions matched (%s), no need to update", cfg.Revision)
return nil
}
newSettings := Settings{Revision: cfg.Revision}
if err := proto.UnmarshalText(cfg.Content, &newSettings.Settings); err != nil {
return errors.Annotate(err, "unmarshalling proto").Err()
}
ctx := &validation.Context{Context: c}
ctx.SetFile("settings.cfg")
validateSettings(ctx, &newSettings.Settings)
if err := ctx.Finalize(); err != nil {
return errors.Annotate(err, "validating settings").Err()
}
return datastore.Put(c, &newSettings)
}, nil)
} | go | func updateSettings(c context.Context) error {
// Load the settings from luci-config.
cs := cfgclient.CurrentServiceConfigSet(c)
lucicfg := GetConfigService(c)
cfg, err := lucicfg.GetConfig(c, cs, "settings.cfg", false)
if err != nil {
return errors.Annotate(err, "loading settings.cfg from luci-config").Err()
}
// Do the revision check & swap in a datastore transaction.
return datastore.RunInTransaction(c, func(c context.Context) error {
oldSettings := Settings{}
err := datastore.Get(c, &oldSettings)
switch err {
case datastore.ErrNoSuchEntity:
// This might be the first time this has run, so a warning here is ok.
logging.WithError(err).Warningf(c, "no existing service config")
case nil:
// Continue
default:
return errors.Annotate(err, "loading existing config").Err()
}
// Check to see if we need to update
if oldSettings.Revision == cfg.Revision {
logging.Debugf(c, "revisions matched (%s), no need to update", cfg.Revision)
return nil
}
newSettings := Settings{Revision: cfg.Revision}
if err := proto.UnmarshalText(cfg.Content, &newSettings.Settings); err != nil {
return errors.Annotate(err, "unmarshalling proto").Err()
}
ctx := &validation.Context{Context: c}
ctx.SetFile("settings.cfg")
validateSettings(ctx, &newSettings.Settings)
if err := ctx.Finalize(); err != nil {
return errors.Annotate(err, "validating settings").Err()
}
return datastore.Put(c, &newSettings)
}, nil)
} | [
"func",
"updateSettings",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"// Load the settings from luci-config.",
"cs",
":=",
"cfgclient",
".",
"CurrentServiceConfigSet",
"(",
"c",
")",
"\n",
"lucicfg",
":=",
"GetConfigService",
"(",
"c",
")",
"\n",
"cfg",
",",
"err",
":=",
"lucicfg",
".",
"GetConfig",
"(",
"c",
",",
"cs",
",",
"\"",
"\"",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"// Do the revision check & swap in a datastore transaction.",
"return",
"datastore",
".",
"RunInTransaction",
"(",
"c",
",",
"func",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"oldSettings",
":=",
"Settings",
"{",
"}",
"\n",
"err",
":=",
"datastore",
".",
"Get",
"(",
"c",
",",
"&",
"oldSettings",
")",
"\n",
"switch",
"err",
"{",
"case",
"datastore",
".",
"ErrNoSuchEntity",
":",
"// This might be the first time this has run, so a warning here is ok.",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"case",
"nil",
":",
"// Continue",
"default",
":",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"// Check to see if we need to update",
"if",
"oldSettings",
".",
"Revision",
"==",
"cfg",
".",
"Revision",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"cfg",
".",
"Revision",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"newSettings",
":=",
"Settings",
"{",
"Revision",
":",
"cfg",
".",
"Revision",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"UnmarshalText",
"(",
"cfg",
".",
"Content",
",",
"&",
"newSettings",
".",
"Settings",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"ctx",
":=",
"&",
"validation",
".",
"Context",
"{",
"Context",
":",
"c",
"}",
"\n",
"ctx",
".",
"SetFile",
"(",
"\"",
"\"",
")",
"\n",
"validateSettings",
"(",
"ctx",
",",
"&",
"newSettings",
".",
"Settings",
")",
"\n",
"if",
"err",
":=",
"ctx",
".",
"Finalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"datastore",
".",
"Put",
"(",
"c",
",",
"&",
"newSettings",
")",
"\n",
"}",
",",
"nil",
")",
"\n",
"}"
] | // updateSettings fetches the service config from luci-config and then stores
// the new config into the datastore. | [
"updateSettings",
"fetches",
"the",
"service",
"config",
"from",
"luci",
"-",
"config",
"and",
"then",
"stores",
"the",
"new",
"config",
"into",
"the",
"datastore",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/settings.go#L85-L124 |
7,918 | luci/luci-go | server/auth/authdb/erroring.go | IsInternalService | func (db ErroringDB) IsInternalService(c context.Context, hostname string) (bool, error) {
logging.Errorf(c, "%s", db.Error)
return false, db.Error
} | go | func (db ErroringDB) IsInternalService(c context.Context, hostname string) (bool, error) {
logging.Errorf(c, "%s", db.Error)
return false, db.Error
} | [
"func",
"(",
"db",
"ErroringDB",
")",
"IsInternalService",
"(",
"c",
"context",
".",
"Context",
",",
"hostname",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"db",
".",
"Error",
")",
"\n",
"return",
"false",
",",
"db",
".",
"Error",
"\n",
"}"
] | // IsInternalService returns true if the given hostname belongs to a service
// that is a part of the current LUCI deployment. | [
"IsInternalService",
"returns",
"true",
"if",
"the",
"given",
"hostname",
"belongs",
"to",
"a",
"service",
"that",
"is",
"a",
"part",
"of",
"the",
"current",
"LUCI",
"deployment",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/erroring.go#L40-L43 |
7,919 | luci/luci-go | server/auth/authdb/erroring.go | IsMember | func (db ErroringDB) IsMember(c context.Context, id identity.Identity, groups []string) (bool, error) {
logging.Errorf(c, "%s", db.Error)
return false, db.Error
} | go | func (db ErroringDB) IsMember(c context.Context, id identity.Identity, groups []string) (bool, error) {
logging.Errorf(c, "%s", db.Error)
return false, db.Error
} | [
"func",
"(",
"db",
"ErroringDB",
")",
"IsMember",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"identity",
".",
"Identity",
",",
"groups",
"[",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"db",
".",
"Error",
")",
"\n",
"return",
"false",
",",
"db",
".",
"Error",
"\n",
"}"
] | // IsMember returns true if the given identity belongs to any of the groups. | [
"IsMember",
"returns",
"true",
"if",
"the",
"given",
"identity",
"belongs",
"to",
"any",
"of",
"the",
"groups",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/erroring.go#L46-L49 |
7,920 | luci/luci-go | server/auth/authdb/erroring.go | CheckMembership | func (db ErroringDB) CheckMembership(c context.Context, id identity.Identity, groups []string) ([]string, error) {
logging.Errorf(c, "%s", db.Error)
return nil, db.Error
} | go | func (db ErroringDB) CheckMembership(c context.Context, id identity.Identity, groups []string) ([]string, error) {
logging.Errorf(c, "%s", db.Error)
return nil, db.Error
} | [
"func",
"(",
"db",
"ErroringDB",
")",
"CheckMembership",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"identity",
".",
"Identity",
",",
"groups",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"db",
".",
"Error",
")",
"\n",
"return",
"nil",
",",
"db",
".",
"Error",
"\n",
"}"
] | // CheckMembership returns groups from the given list the identity belongs to. | [
"CheckMembership",
"returns",
"groups",
"from",
"the",
"given",
"list",
"the",
"identity",
"belongs",
"to",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/authdb/erroring.go#L52-L55 |
7,921 | luci/luci-go | cipd/appengine/impl/model/processing.go | ReadResult | func (p *ProcessingResult) ReadResult(r interface{}) error {
if len(p.ResultRaw) == 0 {
return nil
}
z, err := zlib.NewReader(bytes.NewReader(p.ResultRaw))
if err != nil {
return errors.Annotate(err, "failed to open the blob for zlib decompression").Err()
}
if err := json.NewDecoder(z).Decode(r); err != nil {
z.Close()
return errors.Annotate(err, "failed to decompress or deserialize the result").Err()
}
if err := z.Close(); err != nil {
return errors.Annotate(err, "failed to close zlib reader").Err()
}
return nil
} | go | func (p *ProcessingResult) ReadResult(r interface{}) error {
if len(p.ResultRaw) == 0 {
return nil
}
z, err := zlib.NewReader(bytes.NewReader(p.ResultRaw))
if err != nil {
return errors.Annotate(err, "failed to open the blob for zlib decompression").Err()
}
if err := json.NewDecoder(z).Decode(r); err != nil {
z.Close()
return errors.Annotate(err, "failed to decompress or deserialize the result").Err()
}
if err := z.Close(); err != nil {
return errors.Annotate(err, "failed to close zlib reader").Err()
}
return nil
} | [
"func",
"(",
"p",
"*",
"ProcessingResult",
")",
"ReadResult",
"(",
"r",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"len",
"(",
"p",
".",
"ResultRaw",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"z",
",",
"err",
":=",
"zlib",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"p",
".",
"ResultRaw",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"z",
")",
".",
"Decode",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"z",
".",
"Close",
"(",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"z",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ReadResult deserializes the result into the given variable.
//
// Does nothing if there's no results stored. | [
"ReadResult",
"deserializes",
"the",
"result",
"into",
"the",
"given",
"variable",
".",
"Does",
"nothing",
"if",
"there",
"s",
"no",
"results",
"stored",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/processing.go#L81-L97 |
7,922 | luci/luci-go | cipd/appengine/impl/model/processing.go | ReadResultIntoStruct | func (p *ProcessingResult) ReadResultIntoStruct(s *structpb.Struct) error {
if len(p.ResultRaw) == 0 {
return nil
}
z, err := zlib.NewReader(bytes.NewReader(p.ResultRaw))
if err != nil {
return errors.Annotate(err, "failed to open the blob for zlib decompression").Err()
}
if err := (&jsonpb.Unmarshaler{}).Unmarshal(z, s); err != nil {
z.Close()
return errors.Annotate(err, "failed to decompress or deserialize the result").Err()
}
if err := z.Close(); err != nil {
return errors.Annotate(err, "failed to close zlib reader").Err()
}
return nil
} | go | func (p *ProcessingResult) ReadResultIntoStruct(s *structpb.Struct) error {
if len(p.ResultRaw) == 0 {
return nil
}
z, err := zlib.NewReader(bytes.NewReader(p.ResultRaw))
if err != nil {
return errors.Annotate(err, "failed to open the blob for zlib decompression").Err()
}
if err := (&jsonpb.Unmarshaler{}).Unmarshal(z, s); err != nil {
z.Close()
return errors.Annotate(err, "failed to decompress or deserialize the result").Err()
}
if err := z.Close(); err != nil {
return errors.Annotate(err, "failed to close zlib reader").Err()
}
return nil
} | [
"func",
"(",
"p",
"*",
"ProcessingResult",
")",
"ReadResultIntoStruct",
"(",
"s",
"*",
"structpb",
".",
"Struct",
")",
"error",
"{",
"if",
"len",
"(",
"p",
".",
"ResultRaw",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"z",
",",
"err",
":=",
"zlib",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"p",
".",
"ResultRaw",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"(",
"&",
"jsonpb",
".",
"Unmarshaler",
"{",
"}",
")",
".",
"Unmarshal",
"(",
"z",
",",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"z",
".",
"Close",
"(",
")",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"z",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ReadResultIntoStruct deserializes the result into the protobuf.Struct.
//
// Does nothing if there's no results stored. | [
"ReadResultIntoStruct",
"deserializes",
"the",
"result",
"into",
"the",
"protobuf",
".",
"Struct",
".",
"Does",
"nothing",
"if",
"there",
"s",
"no",
"results",
"stored",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/processing.go#L102-L118 |
7,923 | luci/luci-go | cipd/appengine/impl/model/processing.go | Proto | func (p *ProcessingResult) Proto() (*api.Processor, error) {
out := &api.Processor{Id: p.ProcID}
if p.CreatedTs.IsZero() {
out.State = api.Processor_PENDING // no result yet
return out, nil
}
out.FinishedTs = google.NewTimestamp(p.CreatedTs)
if p.Success {
out.State = api.Processor_SUCCEEDED
res := &structpb.Struct{}
if err := p.ReadResultIntoStruct(res); err != nil {
return nil, err
}
if len(res.Fields) != 0 {
out.Result = res
}
} else {
out.State = api.Processor_FAILED
out.Error = p.Error
}
return out, nil
} | go | func (p *ProcessingResult) Proto() (*api.Processor, error) {
out := &api.Processor{Id: p.ProcID}
if p.CreatedTs.IsZero() {
out.State = api.Processor_PENDING // no result yet
return out, nil
}
out.FinishedTs = google.NewTimestamp(p.CreatedTs)
if p.Success {
out.State = api.Processor_SUCCEEDED
res := &structpb.Struct{}
if err := p.ReadResultIntoStruct(res); err != nil {
return nil, err
}
if len(res.Fields) != 0 {
out.Result = res
}
} else {
out.State = api.Processor_FAILED
out.Error = p.Error
}
return out, nil
} | [
"func",
"(",
"p",
"*",
"ProcessingResult",
")",
"Proto",
"(",
")",
"(",
"*",
"api",
".",
"Processor",
",",
"error",
")",
"{",
"out",
":=",
"&",
"api",
".",
"Processor",
"{",
"Id",
":",
"p",
".",
"ProcID",
"}",
"\n\n",
"if",
"p",
".",
"CreatedTs",
".",
"IsZero",
"(",
")",
"{",
"out",
".",
"State",
"=",
"api",
".",
"Processor_PENDING",
"// no result yet",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}",
"\n",
"out",
".",
"FinishedTs",
"=",
"google",
".",
"NewTimestamp",
"(",
"p",
".",
"CreatedTs",
")",
"\n\n",
"if",
"p",
".",
"Success",
"{",
"out",
".",
"State",
"=",
"api",
".",
"Processor_SUCCEEDED",
"\n",
"res",
":=",
"&",
"structpb",
".",
"Struct",
"{",
"}",
"\n",
"if",
"err",
":=",
"p",
".",
"ReadResultIntoStruct",
"(",
"res",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"res",
".",
"Fields",
")",
"!=",
"0",
"{",
"out",
".",
"Result",
"=",
"res",
"\n",
"}",
"\n",
"}",
"else",
"{",
"out",
".",
"State",
"=",
"api",
".",
"Processor_FAILED",
"\n",
"out",
".",
"Error",
"=",
"p",
".",
"Error",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // Proto returns cipd.Processor proto with information from this entity. | [
"Proto",
"returns",
"cipd",
".",
"Processor",
"proto",
"with",
"information",
"from",
"this",
"entity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/processing.go#L121-L145 |
7,924 | luci/luci-go | machine-db/appengine/rpc/vm_slots.go | FindVMSlots | func (*Service) FindVMSlots(c context.Context, req *crimson.FindVMSlotsRequest) (*crimson.FindVMSlotsResponse, error) {
hosts, err := findVMSlots(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.FindVMSlotsResponse{
Hosts: hosts,
}, nil
} | go | func (*Service) FindVMSlots(c context.Context, req *crimson.FindVMSlotsRequest) (*crimson.FindVMSlotsResponse, error) {
hosts, err := findVMSlots(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.FindVMSlotsResponse{
Hosts: hosts,
}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"FindVMSlots",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"FindVMSlotsRequest",
")",
"(",
"*",
"crimson",
".",
"FindVMSlotsResponse",
",",
"error",
")",
"{",
"hosts",
",",
"err",
":=",
"findVMSlots",
"(",
"c",
",",
"database",
".",
"Get",
"(",
"c",
")",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"crimson",
".",
"FindVMSlotsResponse",
"{",
"Hosts",
":",
"hosts",
",",
"}",
",",
"nil",
"\n",
"}"
] | // FindVMSlots handles a request to find available VM slots. | [
"FindVMSlots",
"handles",
"a",
"request",
"to",
"find",
"available",
"VM",
"slots",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vm_slots.go#L29-L37 |
7,925 | luci/luci-go | machine-db/appengine/rpc/vm_slots.go | findVMSlots | func findVMSlots(c context.Context, q database.QueryerContext, req *crimson.FindVMSlotsRequest) ([]*crimson.PhysicalHost, error) {
stmt := squirrel.Select("h.name", "h.vlan_id", "ph.vm_slots - COUNT(v.physical_host_id)", "ph.virtual_datacenter", "m.state").
From("(physical_hosts ph, hostnames h, machines m)")
if len(req.Manufacturers) > 0 {
stmt = stmt.Join("platforms pl ON m.platform_id = pl.id")
}
stmt = stmt.LeftJoin("vms v on v.physical_host_id = ph.id").
Where("ph.hostname_id = h.id").
Where("ph.vm_slots > 0").
Where("ph.machine_id = m.id").
GroupBy("h.name", "h.vlan_id", "ph.vm_slots", "ph.virtual_datacenter", "m.state").
Having("ph.vm_slots > COUNT(v.physical_host_id)")
if req.Slots > 0 {
// In the worst case, each host with at least one available VM slot has only one available VM slot.
// Set the limit to assume the worst and refine the result later.
stmt = stmt.Limit(uint64(req.Slots))
}
stmt = selectInString(stmt, "pl.manufacturer", req.Manufacturers)
stmt = selectInString(stmt, "ph.virtual_datacenter", req.VirtualDatacenters)
stmt = selectInState(stmt, "m.state", req.States)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
rows, err := q.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch VM slots").Err()
}
defer rows.Close()
var hosts []*crimson.PhysicalHost
var slots int32
for rows.Next() && (slots < req.Slots || req.Slots < 1) {
h := &crimson.PhysicalHost{}
if err = rows.Scan(
&h.Name,
&h.Vlan,
&h.VmSlots,
&h.VirtualDatacenter,
&h.State,
); err != nil {
return nil, errors.Annotate(err, "failed to fetch VM slots").Err()
}
hosts = append(hosts, h)
slots += h.VmSlots
}
return hosts, nil
} | go | func findVMSlots(c context.Context, q database.QueryerContext, req *crimson.FindVMSlotsRequest) ([]*crimson.PhysicalHost, error) {
stmt := squirrel.Select("h.name", "h.vlan_id", "ph.vm_slots - COUNT(v.physical_host_id)", "ph.virtual_datacenter", "m.state").
From("(physical_hosts ph, hostnames h, machines m)")
if len(req.Manufacturers) > 0 {
stmt = stmt.Join("platforms pl ON m.platform_id = pl.id")
}
stmt = stmt.LeftJoin("vms v on v.physical_host_id = ph.id").
Where("ph.hostname_id = h.id").
Where("ph.vm_slots > 0").
Where("ph.machine_id = m.id").
GroupBy("h.name", "h.vlan_id", "ph.vm_slots", "ph.virtual_datacenter", "m.state").
Having("ph.vm_slots > COUNT(v.physical_host_id)")
if req.Slots > 0 {
// In the worst case, each host with at least one available VM slot has only one available VM slot.
// Set the limit to assume the worst and refine the result later.
stmt = stmt.Limit(uint64(req.Slots))
}
stmt = selectInString(stmt, "pl.manufacturer", req.Manufacturers)
stmt = selectInString(stmt, "ph.virtual_datacenter", req.VirtualDatacenters)
stmt = selectInState(stmt, "m.state", req.States)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
rows, err := q.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch VM slots").Err()
}
defer rows.Close()
var hosts []*crimson.PhysicalHost
var slots int32
for rows.Next() && (slots < req.Slots || req.Slots < 1) {
h := &crimson.PhysicalHost{}
if err = rows.Scan(
&h.Name,
&h.Vlan,
&h.VmSlots,
&h.VirtualDatacenter,
&h.State,
); err != nil {
return nil, errors.Annotate(err, "failed to fetch VM slots").Err()
}
hosts = append(hosts, h)
slots += h.VmSlots
}
return hosts, nil
} | [
"func",
"findVMSlots",
"(",
"c",
"context",
".",
"Context",
",",
"q",
"database",
".",
"QueryerContext",
",",
"req",
"*",
"crimson",
".",
"FindVMSlotsRequest",
")",
"(",
"[",
"]",
"*",
"crimson",
".",
"PhysicalHost",
",",
"error",
")",
"{",
"stmt",
":=",
"squirrel",
".",
"Select",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"From",
"(",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"req",
".",
"Manufacturers",
")",
">",
"0",
"{",
"stmt",
"=",
"stmt",
".",
"Join",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"stmt",
"=",
"stmt",
".",
"LeftJoin",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"GroupBy",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Having",
"(",
"\"",
"\"",
")",
"\n",
"if",
"req",
".",
"Slots",
">",
"0",
"{",
"// In the worst case, each host with at least one available VM slot has only one available VM slot.",
"// Set the limit to assume the worst and refine the result later.",
"stmt",
"=",
"stmt",
".",
"Limit",
"(",
"uint64",
"(",
"req",
".",
"Slots",
")",
")",
"\n",
"}",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Manufacturers",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"VirtualDatacenters",
")",
"\n",
"stmt",
"=",
"selectInState",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"States",
")",
"\n",
"query",
",",
"args",
",",
"err",
":=",
"stmt",
".",
"ToSql",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"rows",
",",
"err",
":=",
"q",
".",
"QueryContext",
"(",
"c",
",",
"query",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"var",
"hosts",
"[",
"]",
"*",
"crimson",
".",
"PhysicalHost",
"\n",
"var",
"slots",
"int32",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"&&",
"(",
"slots",
"<",
"req",
".",
"Slots",
"||",
"req",
".",
"Slots",
"<",
"1",
")",
"{",
"h",
":=",
"&",
"crimson",
".",
"PhysicalHost",
"{",
"}",
"\n",
"if",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"h",
".",
"Name",
",",
"&",
"h",
".",
"Vlan",
",",
"&",
"h",
".",
"VmSlots",
",",
"&",
"h",
".",
"VirtualDatacenter",
",",
"&",
"h",
".",
"State",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"hosts",
"=",
"append",
"(",
"hosts",
",",
"h",
")",
"\n",
"slots",
"+=",
"h",
".",
"VmSlots",
"\n",
"}",
"\n",
"return",
"hosts",
",",
"nil",
"\n",
"}"
] | // findVMSlots returns a slice of physical hosts with available VM slots in the database. | [
"findVMSlots",
"returns",
"a",
"slice",
"of",
"physical",
"hosts",
"with",
"available",
"VM",
"slots",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vm_slots.go#L40-L86 |
7,926 | luci/luci-go | vpython/run.go | Exec | func Exec(c context.Context, interp *python.Interpreter, cl *python.CommandLine, env environ.Env, dir string, setupFn func() error) error {
// Don't use cl.SetIsolatedFlags here, because they include -B and -E, which
// both turn off commonly-used aspects of the python interpreter. We do set
// '-s' though, because we don't want vpython to pick up the user's site
// directory by default (to maintain some semblance of isolation).
cl = cl.Clone()
cl.AddSingleFlag("s")
argv := append([]string{interp.Python}, cl.BuildArgs()...)
logging.Debugf(c, "Exec Python command: %#v", argv)
return execImpl(c, argv, env, dir, nil)
} | go | func Exec(c context.Context, interp *python.Interpreter, cl *python.CommandLine, env environ.Env, dir string, setupFn func() error) error {
// Don't use cl.SetIsolatedFlags here, because they include -B and -E, which
// both turn off commonly-used aspects of the python interpreter. We do set
// '-s' though, because we don't want vpython to pick up the user's site
// directory by default (to maintain some semblance of isolation).
cl = cl.Clone()
cl.AddSingleFlag("s")
argv := append([]string{interp.Python}, cl.BuildArgs()...)
logging.Debugf(c, "Exec Python command: %#v", argv)
return execImpl(c, argv, env, dir, nil)
} | [
"func",
"Exec",
"(",
"c",
"context",
".",
"Context",
",",
"interp",
"*",
"python",
".",
"Interpreter",
",",
"cl",
"*",
"python",
".",
"CommandLine",
",",
"env",
"environ",
".",
"Env",
",",
"dir",
"string",
",",
"setupFn",
"func",
"(",
")",
"error",
")",
"error",
"{",
"// Don't use cl.SetIsolatedFlags here, because they include -B and -E, which",
"// both turn off commonly-used aspects of the python interpreter. We do set",
"// '-s' though, because we don't want vpython to pick up the user's site",
"// directory by default (to maintain some semblance of isolation).",
"cl",
"=",
"cl",
".",
"Clone",
"(",
")",
"\n",
"cl",
".",
"AddSingleFlag",
"(",
"\"",
"\"",
")",
"\n\n",
"argv",
":=",
"append",
"(",
"[",
"]",
"string",
"{",
"interp",
".",
"Python",
"}",
",",
"cl",
".",
"BuildArgs",
"(",
")",
"...",
")",
"\n",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"argv",
")",
"\n",
"return",
"execImpl",
"(",
"c",
",",
"argv",
",",
"env",
",",
"dir",
",",
"nil",
")",
"\n",
"}"
] | // Exec runs the specified Python command.
//
// Once the process launches, Context cancellation will not have an impact.
//
// interp is the Python interperer to run.
//
// cl is the populated CommandLine to run.
//
// env is the environment to install.
//
// dir, if not empty, is the working directory of the command.
//
// setupFn, if not nil, is a function that will be run immediately before
// execution, after all operations that are permitted to fail have completed.
// Any error returned here will result in a panic.
//
// If an error occurs during execution, it will be returned here. Otherwise,
// Exec will not return, and this process will exit with the return code of the
// executed process.
//
// The implementation of Exec is platform-specific. | [
"Exec",
"runs",
"the",
"specified",
"Python",
"command",
".",
"Once",
"the",
"process",
"launches",
"Context",
"cancellation",
"will",
"not",
"have",
"an",
"impact",
".",
"interp",
"is",
"the",
"Python",
"interperer",
"to",
"run",
".",
"cl",
"is",
"the",
"populated",
"CommandLine",
"to",
"run",
".",
"env",
"is",
"the",
"environment",
"to",
"install",
".",
"dir",
"if",
"not",
"empty",
"is",
"the",
"working",
"directory",
"of",
"the",
"command",
".",
"setupFn",
"if",
"not",
"nil",
"is",
"a",
"function",
"that",
"will",
"be",
"run",
"immediately",
"before",
"execution",
"after",
"all",
"operations",
"that",
"are",
"permitted",
"to",
"fail",
"have",
"completed",
".",
"Any",
"error",
"returned",
"here",
"will",
"result",
"in",
"a",
"panic",
".",
"If",
"an",
"error",
"occurs",
"during",
"execution",
"it",
"will",
"be",
"returned",
"here",
".",
"Otherwise",
"Exec",
"will",
"not",
"return",
"and",
"this",
"process",
"will",
"exit",
"with",
"the",
"return",
"code",
"of",
"the",
"executed",
"process",
".",
"The",
"implementation",
"of",
"Exec",
"is",
"platform",
"-",
"specific",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/run.go#L105-L116 |
7,927 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go | MintOAuthTokenGrant | func (r *MintOAuthTokenGrantRPC) MintOAuthTokenGrant(c context.Context, req *minter.MintOAuthTokenGrantRequest) (*minter.MintOAuthTokenGrantResponse, error) {
state := auth.GetState(c)
// Don't allow delegation tokens here to reduce total number of possible
// scenarios. Proxies aren't expected to use delegation for these tokens.
callerID := state.User().Identity
if callerID != state.PeerIdentity() {
logging.Errorf(c, "Trying to use delegation, it's forbidden")
return nil, status.Errorf(codes.PermissionDenied, "delegation is forbidden for this API call")
}
// Check that the request is allowed by the rules, fill in defaults.
rule, err := r.validateRequest(c, req, callerID)
if err != nil {
return nil, err // the error is already logged
}
if req.ValidityDuration == 0 {
if rule.Rule.MaxGrantValidityDuration > 3600 {
req.ValidityDuration = 3600
} else {
req.ValidityDuration = rule.Rule.MaxGrantValidityDuration
}
}
// Grab a string that identifies token server version. This almost always
// just hits local memory cache.
serviceVer, err := utils.ServiceVersion(c, r.Signer)
if err != nil {
return nil, status.Errorf(codes.Internal, "can't grab service version - %s", err)
}
// Generate and sign the token.
var resp *minter.MintOAuthTokenGrantResponse
var body *tokenserver.OAuthTokenGrantBody
p := mintParams{
serviceAccount: req.ServiceAccount,
proxyID: callerID,
endUserID: identity.Identity(req.EndUser), // already validated
validityDuration: req.ValidityDuration,
serviceVer: serviceVer,
}
if r.mintMock != nil {
resp, body, err = r.mintMock(c, &p)
} else {
resp, body, err = r.mint(c, &p)
}
if err != nil {
return nil, err
}
// Log it to BigQuery.
if r.LogGrant != nil {
// Errors during logging are considered not fatal. bqlog library has
// a monitoring counter that tracks number of errors, so they are not
// totally invisible.
info := MintedGrantInfo{
Request: req,
Response: resp,
GrantBody: body,
ConfigRev: rule.Revision,
Rule: rule.Rule,
PeerIP: state.PeerIP(),
RequestID: info.RequestID(c),
AuthDBRev: authdb.Revision(state.DB()),
}
if logErr := r.LogGrant(c, &info); logErr != nil {
logging.WithError(logErr).Errorf(c, "Failed to insert the grant token into the BigQuery log")
}
}
return resp, nil
} | go | func (r *MintOAuthTokenGrantRPC) MintOAuthTokenGrant(c context.Context, req *minter.MintOAuthTokenGrantRequest) (*minter.MintOAuthTokenGrantResponse, error) {
state := auth.GetState(c)
// Don't allow delegation tokens here to reduce total number of possible
// scenarios. Proxies aren't expected to use delegation for these tokens.
callerID := state.User().Identity
if callerID != state.PeerIdentity() {
logging.Errorf(c, "Trying to use delegation, it's forbidden")
return nil, status.Errorf(codes.PermissionDenied, "delegation is forbidden for this API call")
}
// Check that the request is allowed by the rules, fill in defaults.
rule, err := r.validateRequest(c, req, callerID)
if err != nil {
return nil, err // the error is already logged
}
if req.ValidityDuration == 0 {
if rule.Rule.MaxGrantValidityDuration > 3600 {
req.ValidityDuration = 3600
} else {
req.ValidityDuration = rule.Rule.MaxGrantValidityDuration
}
}
// Grab a string that identifies token server version. This almost always
// just hits local memory cache.
serviceVer, err := utils.ServiceVersion(c, r.Signer)
if err != nil {
return nil, status.Errorf(codes.Internal, "can't grab service version - %s", err)
}
// Generate and sign the token.
var resp *minter.MintOAuthTokenGrantResponse
var body *tokenserver.OAuthTokenGrantBody
p := mintParams{
serviceAccount: req.ServiceAccount,
proxyID: callerID,
endUserID: identity.Identity(req.EndUser), // already validated
validityDuration: req.ValidityDuration,
serviceVer: serviceVer,
}
if r.mintMock != nil {
resp, body, err = r.mintMock(c, &p)
} else {
resp, body, err = r.mint(c, &p)
}
if err != nil {
return nil, err
}
// Log it to BigQuery.
if r.LogGrant != nil {
// Errors during logging are considered not fatal. bqlog library has
// a monitoring counter that tracks number of errors, so they are not
// totally invisible.
info := MintedGrantInfo{
Request: req,
Response: resp,
GrantBody: body,
ConfigRev: rule.Revision,
Rule: rule.Rule,
PeerIP: state.PeerIP(),
RequestID: info.RequestID(c),
AuthDBRev: authdb.Revision(state.DB()),
}
if logErr := r.LogGrant(c, &info); logErr != nil {
logging.WithError(logErr).Errorf(c, "Failed to insert the grant token into the BigQuery log")
}
}
return resp, nil
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenGrantRPC",
")",
"MintOAuthTokenGrant",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"minter",
".",
"MintOAuthTokenGrantRequest",
")",
"(",
"*",
"minter",
".",
"MintOAuthTokenGrantResponse",
",",
"error",
")",
"{",
"state",
":=",
"auth",
".",
"GetState",
"(",
"c",
")",
"\n\n",
"// Don't allow delegation tokens here to reduce total number of possible",
"// scenarios. Proxies aren't expected to use delegation for these tokens.",
"callerID",
":=",
"state",
".",
"User",
"(",
")",
".",
"Identity",
"\n",
"if",
"callerID",
"!=",
"state",
".",
"PeerIdentity",
"(",
")",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"PermissionDenied",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Check that the request is allowed by the rules, fill in defaults.",
"rule",
",",
"err",
":=",
"r",
".",
"validateRequest",
"(",
"c",
",",
"req",
",",
"callerID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"// the error is already logged",
"\n",
"}",
"\n",
"if",
"req",
".",
"ValidityDuration",
"==",
"0",
"{",
"if",
"rule",
".",
"Rule",
".",
"MaxGrantValidityDuration",
">",
"3600",
"{",
"req",
".",
"ValidityDuration",
"=",
"3600",
"\n",
"}",
"else",
"{",
"req",
".",
"ValidityDuration",
"=",
"rule",
".",
"Rule",
".",
"MaxGrantValidityDuration",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Grab a string that identifies token server version. This almost always",
"// just hits local memory cache.",
"serviceVer",
",",
"err",
":=",
"utils",
".",
"ServiceVersion",
"(",
"c",
",",
"r",
".",
"Signer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Generate and sign the token.",
"var",
"resp",
"*",
"minter",
".",
"MintOAuthTokenGrantResponse",
"\n",
"var",
"body",
"*",
"tokenserver",
".",
"OAuthTokenGrantBody",
"\n",
"p",
":=",
"mintParams",
"{",
"serviceAccount",
":",
"req",
".",
"ServiceAccount",
",",
"proxyID",
":",
"callerID",
",",
"endUserID",
":",
"identity",
".",
"Identity",
"(",
"req",
".",
"EndUser",
")",
",",
"// already validated",
"validityDuration",
":",
"req",
".",
"ValidityDuration",
",",
"serviceVer",
":",
"serviceVer",
",",
"}",
"\n",
"if",
"r",
".",
"mintMock",
"!=",
"nil",
"{",
"resp",
",",
"body",
",",
"err",
"=",
"r",
".",
"mintMock",
"(",
"c",
",",
"&",
"p",
")",
"\n",
"}",
"else",
"{",
"resp",
",",
"body",
",",
"err",
"=",
"r",
".",
"mint",
"(",
"c",
",",
"&",
"p",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Log it to BigQuery.",
"if",
"r",
".",
"LogGrant",
"!=",
"nil",
"{",
"// Errors during logging are considered not fatal. bqlog library has",
"// a monitoring counter that tracks number of errors, so they are not",
"// totally invisible.",
"info",
":=",
"MintedGrantInfo",
"{",
"Request",
":",
"req",
",",
"Response",
":",
"resp",
",",
"GrantBody",
":",
"body",
",",
"ConfigRev",
":",
"rule",
".",
"Revision",
",",
"Rule",
":",
"rule",
".",
"Rule",
",",
"PeerIP",
":",
"state",
".",
"PeerIP",
"(",
")",
",",
"RequestID",
":",
"info",
".",
"RequestID",
"(",
"c",
")",
",",
"AuthDBRev",
":",
"authdb",
".",
"Revision",
"(",
"state",
".",
"DB",
"(",
")",
")",
",",
"}",
"\n",
"if",
"logErr",
":=",
"r",
".",
"LogGrant",
"(",
"c",
",",
"&",
"info",
")",
";",
"logErr",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"logErr",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"resp",
",",
"nil",
"\n",
"}"
] | // MintOAuthTokenGrant produces new OAuth token grant. | [
"MintOAuthTokenGrant",
"produces",
"new",
"OAuth",
"token",
"grant",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go#L62-L133 |
7,928 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go | validateRequest | func (r *MintOAuthTokenGrantRPC) validateRequest(c context.Context, req *minter.MintOAuthTokenGrantRequest, caller identity.Identity) (*Rule, error) {
// Dump the whole request and relevant auth state to the debug log.
r.logRequest(c, req, caller)
// Reject obviously bad requests.
if err := r.checkRequestFormat(req); err != nil {
logging.WithError(err).Errorf(c, "Bad request")
return nil, status.Errorf(codes.InvalidArgument, "bad request - %s", err)
}
// TODO(vadimsh): Verify that this user is present by requiring the end user's
// credentials, e.g make Swarming forward user's OAuth token to the token
// server, so it can be validated here.
// Check that requested usage is allowed and grab the corresponding rule.
return r.checkRules(c, req, caller)
} | go | func (r *MintOAuthTokenGrantRPC) validateRequest(c context.Context, req *minter.MintOAuthTokenGrantRequest, caller identity.Identity) (*Rule, error) {
// Dump the whole request and relevant auth state to the debug log.
r.logRequest(c, req, caller)
// Reject obviously bad requests.
if err := r.checkRequestFormat(req); err != nil {
logging.WithError(err).Errorf(c, "Bad request")
return nil, status.Errorf(codes.InvalidArgument, "bad request - %s", err)
}
// TODO(vadimsh): Verify that this user is present by requiring the end user's
// credentials, e.g make Swarming forward user's OAuth token to the token
// server, so it can be validated here.
// Check that requested usage is allowed and grab the corresponding rule.
return r.checkRules(c, req, caller)
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenGrantRPC",
")",
"validateRequest",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"minter",
".",
"MintOAuthTokenGrantRequest",
",",
"caller",
"identity",
".",
"Identity",
")",
"(",
"*",
"Rule",
",",
"error",
")",
"{",
"// Dump the whole request and relevant auth state to the debug log.",
"r",
".",
"logRequest",
"(",
"c",
",",
"req",
",",
"caller",
")",
"\n\n",
"// Reject obviously bad requests.",
"if",
"err",
":=",
"r",
".",
"checkRequestFormat",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// TODO(vadimsh): Verify that this user is present by requiring the end user's",
"// credentials, e.g make Swarming forward user's OAuth token to the token",
"// server, so it can be validated here.",
"// Check that requested usage is allowed and grab the corresponding rule.",
"return",
"r",
".",
"checkRules",
"(",
"c",
",",
"req",
",",
"caller",
")",
"\n",
"}"
] | // validateRequest checks that the request is allowed.
//
// Returns corresponding config rule on success or a grpc error on error. | [
"validateRequest",
"checks",
"that",
"the",
"request",
"is",
"allowed",
".",
"Returns",
"corresponding",
"config",
"rule",
"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_grant.go#L138-L154 |
7,929 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go | logRequest | func (r *MintOAuthTokenGrantRPC) logRequest(c context.Context, req *minter.MintOAuthTokenGrantRequest, caller identity.Identity) {
if !logging.IsLogging(c, logging.Debug) {
return
}
m := jsonpb.Marshaler{Indent: " "}
dump, _ := m.MarshalToString(req)
logging.Debugf(c, "Identity: %s", caller)
logging.Debugf(c, "MintOAuthTokenGrantRequest:\n%s", dump)
} | go | func (r *MintOAuthTokenGrantRPC) logRequest(c context.Context, req *minter.MintOAuthTokenGrantRequest, caller identity.Identity) {
if !logging.IsLogging(c, logging.Debug) {
return
}
m := jsonpb.Marshaler{Indent: " "}
dump, _ := m.MarshalToString(req)
logging.Debugf(c, "Identity: %s", caller)
logging.Debugf(c, "MintOAuthTokenGrantRequest:\n%s", dump)
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenGrantRPC",
")",
"logRequest",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"minter",
".",
"MintOAuthTokenGrantRequest",
",",
"caller",
"identity",
".",
"Identity",
")",
"{",
"if",
"!",
"logging",
".",
"IsLogging",
"(",
"c",
",",
"logging",
".",
"Debug",
")",
"{",
"return",
"\n",
"}",
"\n",
"m",
":=",
"jsonpb",
".",
"Marshaler",
"{",
"Indent",
":",
"\"",
"\"",
"}",
"\n",
"dump",
",",
"_",
":=",
"m",
".",
"MarshalToString",
"(",
"req",
")",
"\n",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"caller",
")",
"\n",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\\n",
"\"",
",",
"dump",
")",
"\n",
"}"
] | // logRequest logs the body of the request. | [
"logRequest",
"logs",
"the",
"body",
"of",
"the",
"request",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go#L157-L165 |
7,930 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go | checkRequestFormat | func (r *MintOAuthTokenGrantRPC) checkRequestFormat(req *minter.MintOAuthTokenGrantRequest) error {
switch {
case req.ServiceAccount == "":
return fmt.Errorf("service_account is required")
case req.ValidityDuration < 0:
return fmt.Errorf("validity_duration must be positive, not %d", req.ValidityDuration)
case req.EndUser == "":
return fmt.Errorf("end_user is required")
}
if _, err := identity.MakeIdentity(req.EndUser); err != nil {
return fmt.Errorf("bad end_user - %s", err)
}
if err := utils.ValidateTags(req.AuditTags); err != nil {
return fmt.Errorf("bad audit_tags - %s", err)
}
return nil
} | go | func (r *MintOAuthTokenGrantRPC) checkRequestFormat(req *minter.MintOAuthTokenGrantRequest) error {
switch {
case req.ServiceAccount == "":
return fmt.Errorf("service_account is required")
case req.ValidityDuration < 0:
return fmt.Errorf("validity_duration must be positive, not %d", req.ValidityDuration)
case req.EndUser == "":
return fmt.Errorf("end_user is required")
}
if _, err := identity.MakeIdentity(req.EndUser); err != nil {
return fmt.Errorf("bad end_user - %s", err)
}
if err := utils.ValidateTags(req.AuditTags); err != nil {
return fmt.Errorf("bad audit_tags - %s", err)
}
return nil
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenGrantRPC",
")",
"checkRequestFormat",
"(",
"req",
"*",
"minter",
".",
"MintOAuthTokenGrantRequest",
")",
"error",
"{",
"switch",
"{",
"case",
"req",
".",
"ServiceAccount",
"==",
"\"",
"\"",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"case",
"req",
".",
"ValidityDuration",
"<",
"0",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"req",
".",
"ValidityDuration",
")",
"\n",
"case",
"req",
".",
"EndUser",
"==",
"\"",
"\"",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"identity",
".",
"MakeIdentity",
"(",
"req",
".",
"EndUser",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"utils",
".",
"ValidateTags",
"(",
"req",
".",
"AuditTags",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkRequestFormat returns an error if the request is obviously wrong. | [
"checkRequestFormat",
"returns",
"an",
"error",
"if",
"the",
"request",
"is",
"obviously",
"wrong",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go#L168-L184 |
7,931 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go | checkRules | func (r *MintOAuthTokenGrantRPC) checkRules(c context.Context, req *minter.MintOAuthTokenGrantRequest, caller identity.Identity) (*Rule, error) {
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")
}
rule, err := rules.Check(c, &RulesQuery{
ServiceAccount: req.ServiceAccount,
Proxy: caller,
EndUser: identity.Identity(req.EndUser),
})
if err != nil {
return nil, err // it is already gRPC error, and it's already logged
}
// ValidityDuration check is specific to this RPC, it's not done by 'Check'.
if req.ValidityDuration > rule.Rule.MaxGrantValidityDuration {
logging.Errorf(c, "Requested validity is larger than max allowed: %d > %d", req.ValidityDuration, rule.Rule.MaxGrantValidityDuration)
return nil, status.Errorf(codes.InvalidArgument, "per rule %q the validity duration should be <= %d", rule.Rule.Name, rule.Rule.MaxGrantValidityDuration)
}
// Note that AllowedScopes is checked later during MintOAuthTokenViaGrant.
// Here we don't even know what OAuth scopes will be requested.
return rule, nil
} | go | func (r *MintOAuthTokenGrantRPC) checkRules(c context.Context, req *minter.MintOAuthTokenGrantRequest, caller identity.Identity) (*Rule, error) {
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")
}
rule, err := rules.Check(c, &RulesQuery{
ServiceAccount: req.ServiceAccount,
Proxy: caller,
EndUser: identity.Identity(req.EndUser),
})
if err != nil {
return nil, err // it is already gRPC error, and it's already logged
}
// ValidityDuration check is specific to this RPC, it's not done by 'Check'.
if req.ValidityDuration > rule.Rule.MaxGrantValidityDuration {
logging.Errorf(c, "Requested validity is larger than max allowed: %d > %d", req.ValidityDuration, rule.Rule.MaxGrantValidityDuration)
return nil, status.Errorf(codes.InvalidArgument, "per rule %q the validity duration should be <= %d", rule.Rule.Name, rule.Rule.MaxGrantValidityDuration)
}
// Note that AllowedScopes is checked later during MintOAuthTokenViaGrant.
// Here we don't even know what OAuth scopes will be requested.
return rule, nil
} | [
"func",
"(",
"r",
"*",
"MintOAuthTokenGrantRPC",
")",
"checkRules",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"minter",
".",
"MintOAuthTokenGrantRequest",
",",
"caller",
"identity",
".",
"Identity",
")",
"(",
"*",
"Rule",
",",
"error",
")",
"{",
"rules",
",",
"err",
":=",
"r",
".",
"Rules",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"rule",
",",
"err",
":=",
"rules",
".",
"Check",
"(",
"c",
",",
"&",
"RulesQuery",
"{",
"ServiceAccount",
":",
"req",
".",
"ServiceAccount",
",",
"Proxy",
":",
"caller",
",",
"EndUser",
":",
"identity",
".",
"Identity",
"(",
"req",
".",
"EndUser",
")",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"// it is already gRPC error, and it's already logged",
"\n",
"}",
"\n\n",
"// ValidityDuration check is specific to this RPC, it's not done by 'Check'.",
"if",
"req",
".",
"ValidityDuration",
">",
"rule",
".",
"Rule",
".",
"MaxGrantValidityDuration",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"req",
".",
"ValidityDuration",
",",
"rule",
".",
"Rule",
".",
"MaxGrantValidityDuration",
")",
"\n",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"rule",
".",
"Rule",
".",
"Name",
",",
"rule",
".",
"Rule",
".",
"MaxGrantValidityDuration",
")",
"\n",
"}",
"\n\n",
"// Note that AllowedScopes is checked later during MintOAuthTokenViaGrant.",
"// Here we don't even know what OAuth scopes will be requested.",
"return",
"rule",
",",
"nil",
"\n",
"}"
] | // checkRules verifies the requested token is allowed by the rules.
//
// Returns the matching rule or a grpc error. | [
"checkRules",
"verifies",
"the",
"requested",
"token",
"is",
"allowed",
"by",
"the",
"rules",
".",
"Returns",
"the",
"matching",
"rule",
"or",
"a",
"grpc",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/rpc_mint_oauth_token_grant.go#L189-L215 |
7,932 | luci/luci-go | common/logging/exported.go | SetError | func SetError(c context.Context, err error) context.Context {
return SetField(c, ErrorKey, err)
} | go | func SetError(c context.Context, err error) context.Context {
return SetField(c, ErrorKey, err)
} | [
"func",
"SetError",
"(",
"c",
"context",
".",
"Context",
",",
"err",
"error",
")",
"context",
".",
"Context",
"{",
"return",
"SetField",
"(",
"c",
",",
"ErrorKey",
",",
"err",
")",
"\n",
"}"
] | // SetError returns a context with its error field set. | [
"SetError",
"returns",
"a",
"context",
"with",
"its",
"error",
"field",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/exported.go#L20-L22 |
7,933 | luci/luci-go | common/logging/exported.go | IsLogging | func IsLogging(c context.Context, l Level) bool {
return l >= GetLevel(c)
} | go | func IsLogging(c context.Context, l Level) bool {
return l >= GetLevel(c)
} | [
"func",
"IsLogging",
"(",
"c",
"context",
".",
"Context",
",",
"l",
"Level",
")",
"bool",
"{",
"return",
"l",
">=",
"GetLevel",
"(",
"c",
")",
"\n",
"}"
] | // IsLogging tests whether the context is configured to log at the specified
// level.
//
// Individual Logger implementations are supposed to call this function when
// deciding whether to log the message. | [
"IsLogging",
"tests",
"whether",
"the",
"context",
"is",
"configured",
"to",
"log",
"at",
"the",
"specified",
"level",
".",
"Individual",
"Logger",
"implementations",
"are",
"supposed",
"to",
"call",
"this",
"function",
"when",
"deciding",
"whether",
"to",
"log",
"the",
"message",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/exported.go#L29-L31 |
7,934 | luci/luci-go | common/logging/exported.go | Logf | func Logf(c context.Context, l Level, fmt string, args ...interface{}) {
Get(c).LogCall(l, 1, fmt, args)
} | go | func Logf(c context.Context, l Level, fmt string, args ...interface{}) {
Get(c).LogCall(l, 1, fmt, args)
} | [
"func",
"Logf",
"(",
"c",
"context",
".",
"Context",
",",
"l",
"Level",
",",
"fmt",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"Get",
"(",
"c",
")",
".",
"LogCall",
"(",
"l",
",",
"1",
",",
"fmt",
",",
"args",
")",
"\n",
"}"
] | // Logf is a shorthand method to call the current logger's logging method which
// corresponds to the supplied log level. | [
"Logf",
"is",
"a",
"shorthand",
"method",
"to",
"call",
"the",
"current",
"logger",
"s",
"logging",
"method",
"which",
"corresponds",
"to",
"the",
"supplied",
"log",
"level",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/exported.go#L55-L57 |
7,935 | luci/luci-go | machine-db/client/cli/kvms.go | printKVMs | func printKVMs(tsv bool, kvms ...*crimson.KVM) {
if len(kvms) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "VLAN", "Platform", "Datacenter", "Rack", "Description", "MAC Address", "IP Address", "State")
}
for _, k := range kvms {
p.Row(k.Name, k.Vlan, k.Platform, k.Datacenter, k.Rack, k.Description, k.MacAddress, k.Ipv4, k.State)
}
}
} | go | func printKVMs(tsv bool, kvms ...*crimson.KVM) {
if len(kvms) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "VLAN", "Platform", "Datacenter", "Rack", "Description", "MAC Address", "IP Address", "State")
}
for _, k := range kvms {
p.Row(k.Name, k.Vlan, k.Platform, k.Datacenter, k.Rack, k.Description, k.MacAddress, k.Ipv4, k.State)
}
}
} | [
"func",
"printKVMs",
"(",
"tsv",
"bool",
",",
"kvms",
"...",
"*",
"crimson",
".",
"KVM",
")",
"{",
"if",
"len",
"(",
"kvms",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush",
"(",
")",
"\n",
"if",
"!",
"tsv",
"{",
"p",
".",
"Row",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"kvms",
"{",
"p",
".",
"Row",
"(",
"k",
".",
"Name",
",",
"k",
".",
"Vlan",
",",
"k",
".",
"Platform",
",",
"k",
".",
"Datacenter",
",",
"k",
".",
"Rack",
",",
"k",
".",
"Description",
",",
"k",
".",
"MacAddress",
",",
"k",
".",
"Ipv4",
",",
"k",
".",
"State",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printKVMs prints KVM data to stdout in tab-separated columns. | [
"printKVMs",
"prints",
"KVM",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/kvms.go#L28-L39 |
7,936 | luci/luci-go | machine-db/client/cli/kvms.go | Run | func (c *GetKVMsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListKVMs(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printKVMs(c.f.tsv, resp.Kvms...)
return 0
} | go | func (c *GetKVMsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListKVMs(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printKVMs(c.f.tsv, resp.Kvms...)
return 0
} | [
"func",
"(",
"c",
"*",
"GetKVMsCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",",
"env",
")",
"\n",
"client",
":=",
"getClient",
"(",
"ctx",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"ListKVMs",
"(",
"ctx",
",",
"&",
"c",
".",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"ctx",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"printKVMs",
"(",
"c",
".",
"f",
".",
"tsv",
",",
"resp",
".",
"Kvms",
"...",
")",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to get KVMs. | [
"Run",
"runs",
"the",
"command",
"to",
"get",
"KVMs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/kvms.go#L48-L58 |
7,937 | luci/luci-go | machine-db/client/cli/kvms.go | getKVMsCmd | func getKVMsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-kvms [-name <name>]... [-vlan <id>]... [-plat <platform>]... [-rack <rack>]... [-dc <datacenter>]... [-mac <mac address>]... [-ip <ip address>]... [-state <state>]...",
ShortDesc: "retrieves KVMs",
LongDesc: "Retrieves KVMs matching the given filters, or all KVMs if filters are omitted.\n\nExample to get all KVMs:\ncrimson get-kvms\nExample to get KVMs in rack xx1:\ncrimson get-kvms -rack xx1",
CommandRun: func() subcommands.CommandRun {
cmd := &GetKVMsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a KVM to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Platforms), "plat", "Name of a platform to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.")
cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.")
return cmd
},
}
} | go | func getKVMsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-kvms [-name <name>]... [-vlan <id>]... [-plat <platform>]... [-rack <rack>]... [-dc <datacenter>]... [-mac <mac address>]... [-ip <ip address>]... [-state <state>]...",
ShortDesc: "retrieves KVMs",
LongDesc: "Retrieves KVMs matching the given filters, or all KVMs if filters are omitted.\n\nExample to get all KVMs:\ncrimson get-kvms\nExample to get KVMs in rack xx1:\ncrimson get-kvms -rack xx1",
CommandRun: func() subcommands.CommandRun {
cmd := &GetKVMsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a KVM to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Platforms), "plat", "Name of a platform to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.")
cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.")
return cmd
},
}
} | [
"func",
"getKVMsCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"GetKVMsCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Names",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"Int64Slice",
"(",
"&",
"cmd",
".",
"req",
".",
"Vlans",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Platforms",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Racks",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Datacenters",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"MacAddresses",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Ipv4S",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"StateSliceFlag",
"(",
"&",
"cmd",
".",
"req",
".",
"States",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // getKVMsCmd returns a command to get KVMs. | [
"getKVMsCmd",
"returns",
"a",
"command",
"to",
"get",
"KVMs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/kvms.go#L61-L80 |
7,938 | luci/luci-go | auth/internal/disk_cache.go | readCacheFile | func (c *DiskTokenCache) readCacheFile() (*cacheFile, error) {
// Minimize the time the file is locked on Windows by reading it all at once
// and decoding later.
//
// We also need to open it with FILE_SHARE_DELETE sharing mode to allow
// writeCacheFile() below to replace open files (even though it tries to wait
// for the file to be closed). For some reason, omitting FILE_SHARE_DELETE
// flag causes random sharing violation errors when opening the file for
// reading.
f, err := openSharedDelete(c.absPath())
switch {
case os.IsNotExist(err):
return &cacheFile{}, nil
case err != nil:
return nil, err
}
blob, err := ioutil.ReadAll(f)
f.Close()
if err != nil {
return nil, err
}
cache := &cacheFile{}
if err := json.Unmarshal(blob, cache); err != nil {
// If the cache file got broken somehow, it makes sense to treat it as
// empty (so it can later be overwritten), since it's unlikely it's going
// to "fix itself".
logging.WithError(err).Warningf(c.Context, "The token cache %s is broken", c.absPath())
return &cacheFile{}, nil
}
return cache, nil
} | go | func (c *DiskTokenCache) readCacheFile() (*cacheFile, error) {
// Minimize the time the file is locked on Windows by reading it all at once
// and decoding later.
//
// We also need to open it with FILE_SHARE_DELETE sharing mode to allow
// writeCacheFile() below to replace open files (even though it tries to wait
// for the file to be closed). For some reason, omitting FILE_SHARE_DELETE
// flag causes random sharing violation errors when opening the file for
// reading.
f, err := openSharedDelete(c.absPath())
switch {
case os.IsNotExist(err):
return &cacheFile{}, nil
case err != nil:
return nil, err
}
blob, err := ioutil.ReadAll(f)
f.Close()
if err != nil {
return nil, err
}
cache := &cacheFile{}
if err := json.Unmarshal(blob, cache); err != nil {
// If the cache file got broken somehow, it makes sense to treat it as
// empty (so it can later be overwritten), since it's unlikely it's going
// to "fix itself".
logging.WithError(err).Warningf(c.Context, "The token cache %s is broken", c.absPath())
return &cacheFile{}, nil
}
return cache, nil
} | [
"func",
"(",
"c",
"*",
"DiskTokenCache",
")",
"readCacheFile",
"(",
")",
"(",
"*",
"cacheFile",
",",
"error",
")",
"{",
"// Minimize the time the file is locked on Windows by reading it all at once",
"// and decoding later.",
"//",
"// We also need to open it with FILE_SHARE_DELETE sharing mode to allow",
"// writeCacheFile() below to replace open files (even though it tries to wait",
"// for the file to be closed). For some reason, omitting FILE_SHARE_DELETE",
"// flag causes random sharing violation errors when opening the file for",
"// reading.",
"f",
",",
"err",
":=",
"openSharedDelete",
"(",
"c",
".",
"absPath",
"(",
")",
")",
"\n",
"switch",
"{",
"case",
"os",
".",
"IsNotExist",
"(",
"err",
")",
":",
"return",
"&",
"cacheFile",
"{",
"}",
",",
"nil",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"blob",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"f",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"cache",
":=",
"&",
"cacheFile",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"blob",
",",
"cache",
")",
";",
"err",
"!=",
"nil",
"{",
"// If the cache file got broken somehow, it makes sense to treat it as",
"// empty (so it can later be overwritten), since it's unlikely it's going",
"// to \"fix itself\".",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"c",
".",
"Context",
",",
"\"",
"\"",
",",
"c",
".",
"absPath",
"(",
")",
")",
"\n",
"return",
"&",
"cacheFile",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"cache",
",",
"nil",
"\n",
"}"
] | // readCacheFile loads the file with cached tokens. | [
"readCacheFile",
"loads",
"the",
"file",
"with",
"cached",
"tokens",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/internal/disk_cache.go#L109-L141 |
7,939 | luci/luci-go | server/portal/handlers.go | replyError | func replyError(c context.Context, rw http.ResponseWriter, err error) {
if transient.Tag.In(err) {
rw.WriteHeader(http.StatusInternalServerError)
} else {
rw.WriteHeader(http.StatusBadRequest)
}
templates.MustRender(c, rw, "pages/error.html", templates.Args{
"Error": err.Error(),
})
} | go | func replyError(c context.Context, rw http.ResponseWriter, err error) {
if transient.Tag.In(err) {
rw.WriteHeader(http.StatusInternalServerError)
} else {
rw.WriteHeader(http.StatusBadRequest)
}
templates.MustRender(c, rw, "pages/error.html", templates.Args{
"Error": err.Error(),
})
} | [
"func",
"replyError",
"(",
"c",
"context",
".",
"Context",
",",
"rw",
"http",
".",
"ResponseWriter",
",",
"err",
"error",
")",
"{",
"if",
"transient",
".",
"Tag",
".",
"In",
"(",
"err",
")",
"{",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"else",
"{",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n",
"templates",
".",
"MustRender",
"(",
"c",
",",
"rw",
",",
"\"",
"\"",
",",
"templates",
".",
"Args",
"{",
"\"",
"\"",
":",
"err",
".",
"Error",
"(",
")",
",",
"}",
")",
"\n",
"}"
] | // replyError sends HTML error page with status 500 on transient errors or 400
// on fatal ones. | [
"replyError",
"sends",
"HTML",
"error",
"page",
"with",
"status",
"500",
"on",
"transient",
"errors",
"or",
"400",
"on",
"fatal",
"ones",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/portal/handlers.go#L94-L103 |
7,940 | luci/luci-go | machine-db/client/cli/vm_slots.go | printVMSlots | func printVMSlots(tsv bool, hosts ...*crimson.PhysicalHost) {
if len(hosts) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "VLAN", "VM Slots", "Virtual Datacenter", "State")
}
for _, h := range hosts {
p.Row(h.Name, h.Vlan, h.VmSlots, h.VirtualDatacenter, h.State)
}
}
} | go | func printVMSlots(tsv bool, hosts ...*crimson.PhysicalHost) {
if len(hosts) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "VLAN", "VM Slots", "Virtual Datacenter", "State")
}
for _, h := range hosts {
p.Row(h.Name, h.Vlan, h.VmSlots, h.VirtualDatacenter, h.State)
}
}
} | [
"func",
"printVMSlots",
"(",
"tsv",
"bool",
",",
"hosts",
"...",
"*",
"crimson",
".",
"PhysicalHost",
")",
"{",
"if",
"len",
"(",
"hosts",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush",
"(",
")",
"\n",
"if",
"!",
"tsv",
"{",
"p",
".",
"Row",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"hosts",
"{",
"p",
".",
"Row",
"(",
"h",
".",
"Name",
",",
"h",
".",
"Vlan",
",",
"h",
".",
"VmSlots",
",",
"h",
".",
"VirtualDatacenter",
",",
"h",
".",
"State",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printVMSlots prints available VM slot data to stdout in tab-separated columns. | [
"printVMSlots",
"prints",
"available",
"VM",
"slot",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vm_slots.go#L28-L39 |
7,941 | luci/luci-go | machine-db/client/cli/vm_slots.go | getVMSlotsCmd | func getVMSlotsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-slots -n <slots> [-man <manufacturer>]... [-vdc <virtual datacenter>]... [-state <state>]...",
ShortDesc: "retrieves available VM slots",
LongDesc: "Retrieves available VM slots.\n\nExample to get 5 free VM slots on Apple hardware:\ncrimson get-slots -n 5 -man apple",
CommandRun: func() subcommands.CommandRun {
cmd := &GetVMSlotsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.Int32(&cmd.req.Slots), "n", "The number of available VM slots to get.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Manufacturers), "man", "Manufacturer to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.VirtualDatacenters), "vdc", "Virtual datacenter to filter by. Can be specified multiple times.")
cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.")
return cmd
},
}
} | go | func getVMSlotsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-slots -n <slots> [-man <manufacturer>]... [-vdc <virtual datacenter>]... [-state <state>]...",
ShortDesc: "retrieves available VM slots",
LongDesc: "Retrieves available VM slots.\n\nExample to get 5 free VM slots on Apple hardware:\ncrimson get-slots -n 5 -man apple",
CommandRun: func() subcommands.CommandRun {
cmd := &GetVMSlotsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.Int32(&cmd.req.Slots), "n", "The number of available VM slots to get.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Manufacturers), "man", "Manufacturer to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.VirtualDatacenters), "vdc", "Virtual datacenter to filter by. Can be specified multiple times.")
cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.")
return cmd
},
}
} | [
"func",
"getVMSlotsCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"GetVMSlotsCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"Int32",
"(",
"&",
"cmd",
".",
"req",
".",
"Slots",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Manufacturers",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"VirtualDatacenters",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"StateSliceFlag",
"(",
"&",
"cmd",
".",
"req",
".",
"States",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // getVMSlotsCmd returns a command to get available VM slots. | [
"getVMSlotsCmd",
"returns",
"a",
"command",
"to",
"get",
"available",
"VM",
"slots",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vm_slots.go#L61-L76 |
7,942 | luci/luci-go | common/data/text/templateproto/loader.go | LoadFile | func LoadFile(data string) (file *File, err error) {
file = &File{}
if err = proto.UnmarshalTextML(data, file); err != nil {
return
}
err = file.Normalize()
return
} | go | func LoadFile(data string) (file *File, err error) {
file = &File{}
if err = proto.UnmarshalTextML(data, file); err != nil {
return
}
err = file.Normalize()
return
} | [
"func",
"LoadFile",
"(",
"data",
"string",
")",
"(",
"file",
"*",
"File",
",",
"err",
"error",
")",
"{",
"file",
"=",
"&",
"File",
"{",
"}",
"\n",
"if",
"err",
"=",
"proto",
".",
"UnmarshalTextML",
"(",
"data",
",",
"file",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"file",
".",
"Normalize",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // LoadFile loads a File from a string containing the template text protobuf.
//
// Expects config.Interface to be in the context already. | [
"LoadFile",
"loads",
"a",
"File",
"from",
"a",
"string",
"containing",
"the",
"template",
"text",
"protobuf",
".",
"Expects",
"config",
".",
"Interface",
"to",
"be",
"in",
"the",
"context",
"already",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/loader.go#L26-L33 |
7,943 | luci/luci-go | common/data/text/templateproto/loader.go | RenderL | func (f *File) RenderL(templName string, params LiteralMap) (ret string, err error) {
spec := &Specifier{TemplateName: templName}
spec.Params, err = params.Convert()
if err != nil {
return
}
return f.Render(spec)
} | go | func (f *File) RenderL(templName string, params LiteralMap) (ret string, err error) {
spec := &Specifier{TemplateName: templName}
spec.Params, err = params.Convert()
if err != nil {
return
}
return f.Render(spec)
} | [
"func",
"(",
"f",
"*",
"File",
")",
"RenderL",
"(",
"templName",
"string",
",",
"params",
"LiteralMap",
")",
"(",
"ret",
"string",
",",
"err",
"error",
")",
"{",
"spec",
":=",
"&",
"Specifier",
"{",
"TemplateName",
":",
"templName",
"}",
"\n",
"spec",
".",
"Params",
",",
"err",
"=",
"params",
".",
"Convert",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"f",
".",
"Render",
"(",
"spec",
")",
"\n",
"}"
] | // RenderL renders a specified template with go literal arguments. | [
"RenderL",
"renders",
"a",
"specified",
"template",
"with",
"go",
"literal",
"arguments",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/loader.go#L45-L52 |
7,944 | luci/luci-go | scheduler/appengine/internal/noop_trigger.go | NoopTrigger | func NoopTrigger(id, data string) Trigger {
return Trigger{
Id: id,
Payload: &Trigger_Noop{Noop: &api.NoopTrigger{Data: data}},
}
} | go | func NoopTrigger(id, data string) Trigger {
return Trigger{
Id: id,
Payload: &Trigger_Noop{Noop: &api.NoopTrigger{Data: data}},
}
} | [
"func",
"NoopTrigger",
"(",
"id",
",",
"data",
"string",
")",
"Trigger",
"{",
"return",
"Trigger",
"{",
"Id",
":",
"id",
",",
"Payload",
":",
"&",
"Trigger_Noop",
"{",
"Noop",
":",
"&",
"api",
".",
"NoopTrigger",
"{",
"Data",
":",
"data",
"}",
"}",
",",
"}",
"\n",
"}"
] | // NoopTrigger constructs a noop trigger proto with given ID and data payload.
//
// No other fields are populated. | [
"NoopTrigger",
"constructs",
"a",
"noop",
"trigger",
"proto",
"with",
"given",
"ID",
"and",
"data",
"payload",
".",
"No",
"other",
"fields",
"are",
"populated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/internal/noop_trigger.go#L24-L29 |
7,945 | luci/luci-go | cipd/client/cli/friendly.go | optionalSiteRoot | func optionalSiteRoot(siteRoot string) (string, error) {
if siteRoot == "" {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
siteRoot = findSiteRoot(cwd)
if siteRoot == "" {
return "", fmt.Errorf("directory %s is not in a site root, use 'init' to create one", cwd)
}
return siteRoot, nil
}
siteRoot, err := filepath.Abs(siteRoot)
if err != nil {
return "", err
}
if !isSiteRoot(siteRoot) {
return "", fmt.Errorf("directory %s doesn't look like a site root, use 'init' to create one", siteRoot)
}
return siteRoot, nil
} | go | func optionalSiteRoot(siteRoot string) (string, error) {
if siteRoot == "" {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
siteRoot = findSiteRoot(cwd)
if siteRoot == "" {
return "", fmt.Errorf("directory %s is not in a site root, use 'init' to create one", cwd)
}
return siteRoot, nil
}
siteRoot, err := filepath.Abs(siteRoot)
if err != nil {
return "", err
}
if !isSiteRoot(siteRoot) {
return "", fmt.Errorf("directory %s doesn't look like a site root, use 'init' to create one", siteRoot)
}
return siteRoot, nil
} | [
"func",
"optionalSiteRoot",
"(",
"siteRoot",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"siteRoot",
"==",
"\"",
"\"",
"{",
"cwd",
",",
"err",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"siteRoot",
"=",
"findSiteRoot",
"(",
"cwd",
")",
"\n",
"if",
"siteRoot",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cwd",
")",
"\n",
"}",
"\n",
"return",
"siteRoot",
",",
"nil",
"\n",
"}",
"\n",
"siteRoot",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"siteRoot",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"isSiteRoot",
"(",
"siteRoot",
")",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"siteRoot",
")",
"\n",
"}",
"\n",
"return",
"siteRoot",
",",
"nil",
"\n",
"}"
] | // optionalSiteRoot takes a path to a site root or an empty string. If some
// path is given, it normalizes it and ensures that it is indeed a site root
// directory. If empty string is given, it discovers a site root for current
// directory. | [
"optionalSiteRoot",
"takes",
"a",
"path",
"to",
"a",
"site",
"root",
"or",
"an",
"empty",
"string",
".",
"If",
"some",
"path",
"is",
"given",
"it",
"normalizes",
"it",
"and",
"ensures",
"that",
"it",
"is",
"indeed",
"a",
"site",
"root",
"directory",
".",
"If",
"empty",
"string",
"is",
"given",
"it",
"discovers",
"a",
"site",
"root",
"for",
"current",
"directory",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L66-L86 |
7,946 | luci/luci-go | cipd/client/cli/friendly.go | read | func (c *installationSiteConfig) read(path string) error {
*c = installationSiteConfig{}
r, err := os.Open(path)
if err != nil {
return err
}
defer r.Close()
return json.NewDecoder(r).Decode(c)
} | go | func (c *installationSiteConfig) read(path string) error {
*c = installationSiteConfig{}
r, err := os.Open(path)
if err != nil {
return err
}
defer r.Close()
return json.NewDecoder(r).Decode(c)
} | [
"func",
"(",
"c",
"*",
"installationSiteConfig",
")",
"read",
"(",
"path",
"string",
")",
"error",
"{",
"*",
"c",
"=",
"installationSiteConfig",
"{",
"}",
"\n",
"r",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"r",
".",
"Close",
"(",
")",
"\n",
"return",
"json",
".",
"NewDecoder",
"(",
"r",
")",
".",
"Decode",
"(",
"c",
")",
"\n",
"}"
] | // read loads JSON from given path. | [
"read",
"loads",
"JSON",
"from",
"given",
"path",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L110-L118 |
7,947 | luci/luci-go | cipd/client/cli/friendly.go | write | func (c *installationSiteConfig) write(path string) error {
blob, err := json.MarshalIndent(c, "", "\t")
if err != nil {
return err
}
return ioutil.WriteFile(path, blob, 0666)
} | go | func (c *installationSiteConfig) write(path string) error {
blob, err := json.MarshalIndent(c, "", "\t")
if err != nil {
return err
}
return ioutil.WriteFile(path, blob, 0666)
} | [
"func",
"(",
"c",
"*",
"installationSiteConfig",
")",
"write",
"(",
"path",
"string",
")",
"error",
"{",
"blob",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"c",
",",
"\"",
"\"",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"path",
",",
"blob",
",",
"0666",
")",
"\n",
"}"
] | // write dumps JSON to given path. | [
"write",
"dumps",
"JSON",
"to",
"given",
"path",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L121-L127 |
7,948 | luci/luci-go | cipd/client/cli/friendly.go | readConfig | func readConfig(siteRoot string) (installationSiteConfig, error) {
path := filepath.Join(siteRoot, fs.SiteServiceDir, "config.json")
c := installationSiteConfig{}
if err := c.read(path); err != nil && !os.IsNotExist(err) {
return c, err
}
return c, nil
} | go | func readConfig(siteRoot string) (installationSiteConfig, error) {
path := filepath.Join(siteRoot, fs.SiteServiceDir, "config.json")
c := installationSiteConfig{}
if err := c.read(path); err != nil && !os.IsNotExist(err) {
return c, err
}
return c, nil
} | [
"func",
"readConfig",
"(",
"siteRoot",
"string",
")",
"(",
"installationSiteConfig",
",",
"error",
")",
"{",
"path",
":=",
"filepath",
".",
"Join",
"(",
"siteRoot",
",",
"fs",
".",
"SiteServiceDir",
",",
"\"",
"\"",
")",
"\n",
"c",
":=",
"installationSiteConfig",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"read",
"(",
"path",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"c",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // readConfig reads config, returning default one if missing.
//
// The returned config may have ServiceURL set to "" due to previous buggy
// version of CIPD not setting it up correctly. | [
"readConfig",
"reads",
"config",
"returning",
"default",
"one",
"if",
"missing",
".",
"The",
"returned",
"config",
"may",
"have",
"ServiceURL",
"set",
"to",
"due",
"to",
"previous",
"buggy",
"version",
"of",
"CIPD",
"not",
"setting",
"it",
"up",
"correctly",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L133-L140 |
7,949 | luci/luci-go | cipd/client/cli/friendly.go | getInstallationSite | func getInstallationSite(siteRoot, defaultServiceURL string) (*installationSite, error) {
siteRoot, err := optionalSiteRoot(siteRoot)
if err != nil {
return nil, err
}
cfg, err := readConfig(siteRoot)
if err != nil {
return nil, err
}
if cfg.ServiceURL == "" {
cfg.ServiceURL = defaultServiceURL
}
return &installationSite{siteRoot, defaultServiceURL, &cfg, nil}, nil
} | go | func getInstallationSite(siteRoot, defaultServiceURL string) (*installationSite, error) {
siteRoot, err := optionalSiteRoot(siteRoot)
if err != nil {
return nil, err
}
cfg, err := readConfig(siteRoot)
if err != nil {
return nil, err
}
if cfg.ServiceURL == "" {
cfg.ServiceURL = defaultServiceURL
}
return &installationSite{siteRoot, defaultServiceURL, &cfg, nil}, nil
} | [
"func",
"getInstallationSite",
"(",
"siteRoot",
",",
"defaultServiceURL",
"string",
")",
"(",
"*",
"installationSite",
",",
"error",
")",
"{",
"siteRoot",
",",
"err",
":=",
"optionalSiteRoot",
"(",
"siteRoot",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cfg",
",",
"err",
":=",
"readConfig",
"(",
"siteRoot",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"ServiceURL",
"==",
"\"",
"\"",
"{",
"cfg",
".",
"ServiceURL",
"=",
"defaultServiceURL",
"\n",
"}",
"\n",
"return",
"&",
"installationSite",
"{",
"siteRoot",
",",
"defaultServiceURL",
",",
"&",
"cfg",
",",
"nil",
"}",
",",
"nil",
"\n",
"}"
] | // getInstallationSite finds site root directory, reads config and constructs
// installationSite object.
//
// If siteRoot is "", will find a site root based on the current directory,
// otherwise will use siteRoot. Doesn't create any new files or directories,
// just reads what's on disk. | [
"getInstallationSite",
"finds",
"site",
"root",
"directory",
"reads",
"config",
"and",
"constructs",
"installationSite",
"object",
".",
"If",
"siteRoot",
"is",
"will",
"find",
"a",
"site",
"root",
"based",
"on",
"the",
"current",
"directory",
"otherwise",
"will",
"use",
"siteRoot",
".",
"Doesn",
"t",
"create",
"any",
"new",
"files",
"or",
"directories",
"just",
"reads",
"what",
"s",
"on",
"disk",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L160-L173 |
7,950 | luci/luci-go | cipd/client/cli/friendly.go | initClient | func (site *installationSite) initClient(ctx context.Context, authFlags authcli.Flags) (err error) {
if site.client != nil {
return errors.New("client is already initialized")
}
clientOpts := clientOptions{
authFlags: authFlags,
serviceURL: site.cfg.ServiceURL,
cacheDir: site.cfg.CacheDir,
rootDir: site.siteRoot,
}
site.client, err = clientOpts.makeCIPDClient(ctx)
return err
} | go | func (site *installationSite) initClient(ctx context.Context, authFlags authcli.Flags) (err error) {
if site.client != nil {
return errors.New("client is already initialized")
}
clientOpts := clientOptions{
authFlags: authFlags,
serviceURL: site.cfg.ServiceURL,
cacheDir: site.cfg.CacheDir,
rootDir: site.siteRoot,
}
site.client, err = clientOpts.makeCIPDClient(ctx)
return err
} | [
"func",
"(",
"site",
"*",
"installationSite",
")",
"initClient",
"(",
"ctx",
"context",
".",
"Context",
",",
"authFlags",
"authcli",
".",
"Flags",
")",
"(",
"err",
"error",
")",
"{",
"if",
"site",
".",
"client",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"clientOpts",
":=",
"clientOptions",
"{",
"authFlags",
":",
"authFlags",
",",
"serviceURL",
":",
"site",
".",
"cfg",
".",
"ServiceURL",
",",
"cacheDir",
":",
"site",
".",
"cfg",
".",
"CacheDir",
",",
"rootDir",
":",
"site",
".",
"siteRoot",
",",
"}",
"\n",
"site",
".",
"client",
",",
"err",
"=",
"clientOpts",
".",
"makeCIPDClient",
"(",
"ctx",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // initClient initializes cipd.Client to use to talk to backend.
//
// Can be called only once. Use it directly via site.client. | [
"initClient",
"initializes",
"cipd",
".",
"Client",
"to",
"use",
"to",
"talk",
"to",
"backend",
".",
"Can",
"be",
"called",
"only",
"once",
".",
"Use",
"it",
"directly",
"via",
"site",
".",
"client",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L223-L235 |
7,951 | luci/luci-go | cipd/client/cli/friendly.go | modifyConfig | func (site *installationSite) modifyConfig(cb func(cfg *installationSiteConfig) error) error {
path := filepath.Join(site.siteRoot, fs.SiteServiceDir, "config.json")
c := installationSiteConfig{}
if err := c.read(path); err != nil && !os.IsNotExist(err) {
return err
}
if err := cb(&c); err != nil {
return err
}
// Fix broken config that doesn't have ServiceURL set. It is required now.
if c.ServiceURL == "" {
c.ServiceURL = site.defaultServiceURL
}
return c.write(path)
} | go | func (site *installationSite) modifyConfig(cb func(cfg *installationSiteConfig) error) error {
path := filepath.Join(site.siteRoot, fs.SiteServiceDir, "config.json")
c := installationSiteConfig{}
if err := c.read(path); err != nil && !os.IsNotExist(err) {
return err
}
if err := cb(&c); err != nil {
return err
}
// Fix broken config that doesn't have ServiceURL set. It is required now.
if c.ServiceURL == "" {
c.ServiceURL = site.defaultServiceURL
}
return c.write(path)
} | [
"func",
"(",
"site",
"*",
"installationSite",
")",
"modifyConfig",
"(",
"cb",
"func",
"(",
"cfg",
"*",
"installationSiteConfig",
")",
"error",
")",
"error",
"{",
"path",
":=",
"filepath",
".",
"Join",
"(",
"site",
".",
"siteRoot",
",",
"fs",
".",
"SiteServiceDir",
",",
"\"",
"\"",
")",
"\n",
"c",
":=",
"installationSiteConfig",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"read",
"(",
"path",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cb",
"(",
"&",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Fix broken config that doesn't have ServiceURL set. It is required now.",
"if",
"c",
".",
"ServiceURL",
"==",
"\"",
"\"",
"{",
"c",
".",
"ServiceURL",
"=",
"site",
".",
"defaultServiceURL",
"\n",
"}",
"\n",
"return",
"c",
".",
"write",
"(",
"path",
")",
"\n",
"}"
] | // modifyConfig reads config file, calls callback to mutate it, then writes
// it back. | [
"modifyConfig",
"reads",
"config",
"file",
"calls",
"callback",
"to",
"mutate",
"it",
"then",
"writes",
"it",
"back",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L239-L253 |
7,952 | luci/luci-go | cipd/client/cli/friendly.go | installedPackages | func (site *installationSite) installedPackages(ctx context.Context) (map[string][]pinInfo, error) {
d := deployer.New(site.siteRoot)
allPins, err := d.FindDeployed(ctx)
if err != nil {
return nil, err
}
output := make(map[string][]pinInfo, len(allPins))
for subdir, pins := range allPins {
output[subdir] = make([]pinInfo, len(pins))
for i, pin := range pins {
cpy := pin
output[subdir][i] = pinInfo{
Pkg: pin.PackageName,
Pin: &cpy,
Tracking: site.cfg.TrackedVersions[pin.PackageName],
}
}
}
return output, nil
} | go | func (site *installationSite) installedPackages(ctx context.Context) (map[string][]pinInfo, error) {
d := deployer.New(site.siteRoot)
allPins, err := d.FindDeployed(ctx)
if err != nil {
return nil, err
}
output := make(map[string][]pinInfo, len(allPins))
for subdir, pins := range allPins {
output[subdir] = make([]pinInfo, len(pins))
for i, pin := range pins {
cpy := pin
output[subdir][i] = pinInfo{
Pkg: pin.PackageName,
Pin: &cpy,
Tracking: site.cfg.TrackedVersions[pin.PackageName],
}
}
}
return output, nil
} | [
"func",
"(",
"site",
"*",
"installationSite",
")",
"installedPackages",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"pinInfo",
",",
"error",
")",
"{",
"d",
":=",
"deployer",
".",
"New",
"(",
"site",
".",
"siteRoot",
")",
"\n\n",
"allPins",
",",
"err",
":=",
"d",
".",
"FindDeployed",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"output",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"pinInfo",
",",
"len",
"(",
"allPins",
")",
")",
"\n",
"for",
"subdir",
",",
"pins",
":=",
"range",
"allPins",
"{",
"output",
"[",
"subdir",
"]",
"=",
"make",
"(",
"[",
"]",
"pinInfo",
",",
"len",
"(",
"pins",
")",
")",
"\n",
"for",
"i",
",",
"pin",
":=",
"range",
"pins",
"{",
"cpy",
":=",
"pin",
"\n",
"output",
"[",
"subdir",
"]",
"[",
"i",
"]",
"=",
"pinInfo",
"{",
"Pkg",
":",
"pin",
".",
"PackageName",
",",
"Pin",
":",
"&",
"cpy",
",",
"Tracking",
":",
"site",
".",
"cfg",
".",
"TrackedVersions",
"[",
"pin",
".",
"PackageName",
"]",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"output",
",",
"nil",
"\n",
"}"
] | // installedPackages discovers versions of packages installed in the site.
//
// If pkgs is empty array, it returns list of all installed packages. | [
"installedPackages",
"discovers",
"versions",
"of",
"packages",
"installed",
"in",
"the",
"site",
".",
"If",
"pkgs",
"is",
"empty",
"array",
"it",
"returns",
"list",
"of",
"all",
"installed",
"packages",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/friendly.go#L258-L278 |
7,953 | luci/luci-go | common/api/gitiles/rest.go | getRaw | func (c *client) getRaw(ctx context.Context, urlPath string, query url.Values) (http.Header, []byte, error) {
u := fmt.Sprintf("%s/%s", strings.TrimSuffix(c.BaseURL, "/"), strings.TrimPrefix(urlPath, "/"))
if query != nil {
u = fmt.Sprintf("%s?%s", u, query.Encode())
}
r, err := ctxhttp.Get(ctx, c.Client, u)
if err != nil {
return http.Header{}, []byte{}, transient.Tag.Apply(err)
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return r.Header, []byte{}, errors.Annotate(err, "could not read response body").Err()
}
switch r.StatusCode {
case http.StatusOK:
return r.Header, bytes.TrimPrefix(body, jsonPrefix), nil
case http.StatusTooManyRequests:
logging.Errorf(ctx, "Gitiles quota error.\nResponse headers: %v\nResponse body: %s",
r.Header, body)
return r.Header, body, status.Errorf(codes.ResourceExhausted, "insufficient Gitiles quota")
case http.StatusNotFound:
return r.Header, body, status.Errorf(codes.NotFound, "not found")
default:
logging.Errorf(ctx, "gitiles: unexpected HTTP %d response.\nResponse headers: %v\nResponse body: %s",
r.StatusCode,
r.Header, body)
return r.Header, body, status.Errorf(codes.Internal, "unexpected HTTP %d from Gitiles", r.StatusCode)
}
} | go | func (c *client) getRaw(ctx context.Context, urlPath string, query url.Values) (http.Header, []byte, error) {
u := fmt.Sprintf("%s/%s", strings.TrimSuffix(c.BaseURL, "/"), strings.TrimPrefix(urlPath, "/"))
if query != nil {
u = fmt.Sprintf("%s?%s", u, query.Encode())
}
r, err := ctxhttp.Get(ctx, c.Client, u)
if err != nil {
return http.Header{}, []byte{}, transient.Tag.Apply(err)
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return r.Header, []byte{}, errors.Annotate(err, "could not read response body").Err()
}
switch r.StatusCode {
case http.StatusOK:
return r.Header, bytes.TrimPrefix(body, jsonPrefix), nil
case http.StatusTooManyRequests:
logging.Errorf(ctx, "Gitiles quota error.\nResponse headers: %v\nResponse body: %s",
r.Header, body)
return r.Header, body, status.Errorf(codes.ResourceExhausted, "insufficient Gitiles quota")
case http.StatusNotFound:
return r.Header, body, status.Errorf(codes.NotFound, "not found")
default:
logging.Errorf(ctx, "gitiles: unexpected HTTP %d response.\nResponse headers: %v\nResponse body: %s",
r.StatusCode,
r.Header, body)
return r.Header, body, status.Errorf(codes.Internal, "unexpected HTTP %d from Gitiles", r.StatusCode)
}
} | [
"func",
"(",
"c",
"*",
"client",
")",
"getRaw",
"(",
"ctx",
"context",
".",
"Context",
",",
"urlPath",
"string",
",",
"query",
"url",
".",
"Values",
")",
"(",
"http",
".",
"Header",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"u",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"strings",
".",
"TrimSuffix",
"(",
"c",
".",
"BaseURL",
",",
"\"",
"\"",
")",
",",
"strings",
".",
"TrimPrefix",
"(",
"urlPath",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"query",
"!=",
"nil",
"{",
"u",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"u",
",",
"query",
".",
"Encode",
"(",
")",
")",
"\n",
"}",
"\n",
"r",
",",
"err",
":=",
"ctxhttp",
".",
"Get",
"(",
"ctx",
",",
"c",
".",
"Client",
",",
"u",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"http",
".",
"Header",
"{",
"}",
",",
"[",
"]",
"byte",
"{",
"}",
",",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"r",
".",
"Header",
",",
"[",
"]",
"byte",
"{",
"}",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"switch",
"r",
".",
"StatusCode",
"{",
"case",
"http",
".",
"StatusOK",
":",
"return",
"r",
".",
"Header",
",",
"bytes",
".",
"TrimPrefix",
"(",
"body",
",",
"jsonPrefix",
")",
",",
"nil",
"\n\n",
"case",
"http",
".",
"StatusTooManyRequests",
":",
"logging",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\\n",
"\\n",
"\"",
",",
"r",
".",
"Header",
",",
"body",
")",
"\n",
"return",
"r",
".",
"Header",
",",
"body",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"ResourceExhausted",
",",
"\"",
"\"",
")",
"\n\n",
"case",
"http",
".",
"StatusNotFound",
":",
"return",
"r",
".",
"Header",
",",
"body",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
")",
"\n\n",
"default",
":",
"logging",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\\n",
"\\n",
"\"",
",",
"r",
".",
"StatusCode",
",",
"r",
".",
"Header",
",",
"body",
")",
"\n",
"return",
"r",
".",
"Header",
",",
"body",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"r",
".",
"StatusCode",
")",
"\n",
"}",
"\n",
"}"
] | // getRaw makes a raw HTTP get request and returns the header and body returned.
//
// In case of errors, getRaw translates the generic HTTP errors to grpc errors. | [
"getRaw",
"makes",
"a",
"raw",
"HTTP",
"get",
"request",
"and",
"returns",
"the",
"header",
"and",
"body",
"returned",
".",
"In",
"case",
"of",
"errors",
"getRaw",
"translates",
"the",
"generic",
"HTTP",
"errors",
"to",
"grpc",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/rest.go#L209-L243 |
7,954 | luci/luci-go | cipd/appengine/impl/model/events.go | FromProto | func (e *Event) FromProto(c context.Context, p *api.Event) *Event {
blob, err := proto.Marshal(p)
if err != nil {
panic(err)
}
e.Package = PackageKey(c, p.Package)
e.Event = blob
e.Kind = p.Kind
e.Who = p.Who
e.When = google.TimeFromProto(p.When).Sub(EventsEpoch).Nanoseconds()
if p.Instance != "" {
e.Instance = p.Instance
} else {
e.Instance = NoInstance
}
e.Ref = p.Ref
e.Tag = p.Tag
return e
} | go | func (e *Event) FromProto(c context.Context, p *api.Event) *Event {
blob, err := proto.Marshal(p)
if err != nil {
panic(err)
}
e.Package = PackageKey(c, p.Package)
e.Event = blob
e.Kind = p.Kind
e.Who = p.Who
e.When = google.TimeFromProto(p.When).Sub(EventsEpoch).Nanoseconds()
if p.Instance != "" {
e.Instance = p.Instance
} else {
e.Instance = NoInstance
}
e.Ref = p.Ref
e.Tag = p.Tag
return e
} | [
"func",
"(",
"e",
"*",
"Event",
")",
"FromProto",
"(",
"c",
"context",
".",
"Context",
",",
"p",
"*",
"api",
".",
"Event",
")",
"*",
"Event",
"{",
"blob",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"e",
".",
"Package",
"=",
"PackageKey",
"(",
"c",
",",
"p",
".",
"Package",
")",
"\n",
"e",
".",
"Event",
"=",
"blob",
"\n",
"e",
".",
"Kind",
"=",
"p",
".",
"Kind",
"\n",
"e",
".",
"Who",
"=",
"p",
".",
"Who",
"\n",
"e",
".",
"When",
"=",
"google",
".",
"TimeFromProto",
"(",
"p",
".",
"When",
")",
".",
"Sub",
"(",
"EventsEpoch",
")",
".",
"Nanoseconds",
"(",
")",
"\n",
"if",
"p",
".",
"Instance",
"!=",
"\"",
"\"",
"{",
"e",
".",
"Instance",
"=",
"p",
".",
"Instance",
"\n",
"}",
"else",
"{",
"e",
".",
"Instance",
"=",
"NoInstance",
"\n",
"}",
"\n",
"e",
".",
"Ref",
"=",
"p",
".",
"Ref",
"\n",
"e",
".",
"Tag",
"=",
"p",
".",
"Tag",
"\n",
"return",
"e",
"\n",
"}"
] | // FromProto fills in the entity based on the proto message.
//
// Panics if the proto can't be serialized. This should never happen.
//
// Returns the entity itself for easier chaining. | [
"FromProto",
"fills",
"in",
"the",
"entity",
"based",
"on",
"the",
"proto",
"message",
".",
"Panics",
"if",
"the",
"proto",
"can",
"t",
"be",
"serialized",
".",
"This",
"should",
"never",
"happen",
".",
"Returns",
"the",
"entity",
"itself",
"for",
"easier",
"chaining",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/events.go#L96-L114 |
7,955 | luci/luci-go | cipd/appengine/impl/model/events.go | Emit | func (t *Events) Emit(e *api.Event) {
t.ev = append(t.ev, e)
} | go | func (t *Events) Emit(e *api.Event) {
t.ev = append(t.ev, e)
} | [
"func",
"(",
"t",
"*",
"Events",
")",
"Emit",
"(",
"e",
"*",
"api",
".",
"Event",
")",
"{",
"t",
".",
"ev",
"=",
"append",
"(",
"t",
".",
"ev",
",",
"e",
")",
"\n",
"}"
] | // Emit adds an event to be flushed later in Flush.
//
// 'Who' and 'When' fields are populated in Flush using values from the context. | [
"Emit",
"adds",
"an",
"event",
"to",
"be",
"flushed",
"later",
"in",
"Flush",
".",
"Who",
"and",
"When",
"fields",
"are",
"populated",
"in",
"Flush",
"using",
"values",
"from",
"the",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/events.go#L148-L150 |
7,956 | luci/luci-go | cipd/appengine/impl/model/events.go | EmitEvent | func EmitEvent(c context.Context, e *api.Event) error {
ev := Events{}
ev.Emit(e)
return ev.Flush(c)
} | go | func EmitEvent(c context.Context, e *api.Event) error {
ev := Events{}
ev.Emit(e)
return ev.Flush(c)
} | [
"func",
"EmitEvent",
"(",
"c",
"context",
".",
"Context",
",",
"e",
"*",
"api",
".",
"Event",
")",
"error",
"{",
"ev",
":=",
"Events",
"{",
"}",
"\n",
"ev",
".",
"Emit",
"(",
"e",
")",
"\n",
"return",
"ev",
".",
"Flush",
"(",
"c",
")",
"\n",
"}"
] | // EmitEvent adds a single event to the event log.
//
// Prefer using Events to add multiple events at once. | [
"EmitEvent",
"adds",
"a",
"single",
"event",
"to",
"the",
"event",
"log",
".",
"Prefer",
"using",
"Events",
"to",
"add",
"multiple",
"events",
"at",
"once",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/events.go#L189-L193 |
7,957 | luci/luci-go | cipd/appengine/impl/model/events.go | EmitMetadataEvents | func EmitMetadataEvents(c context.Context, before, after *api.PrefixMetadata) error {
if before.Prefix != after.Prefix {
panic(fmt.Sprintf("comparing metadata for different prefixes: %q != %q", before.Prefix, after.Prefix))
}
prefix := after.Prefix
prev := metadata.GetACLs(before)
next := metadata.GetACLs(after)
var granted []*api.PrefixMetadata_ACL
var revoked []*api.PrefixMetadata_ACL
for _, role := range sortedRoles {
if added := stringSetDiff(next[role], prev[role]); len(added) != 0 {
granted = append(granted, &api.PrefixMetadata_ACL{
Role: role,
Principals: added,
})
}
if removed := stringSetDiff(prev[role], next[role]); len(removed) != 0 {
revoked = append(revoked, &api.PrefixMetadata_ACL{
Role: role,
Principals: removed,
})
}
}
if len(granted) == 0 && len(revoked) == 0 {
return nil
}
return EmitEvent(c, &api.Event{
Kind: api.EventKind_PREFIX_ACL_CHANGED,
Package: prefix,
GrantedRole: granted,
RevokedRole: revoked,
})
} | go | func EmitMetadataEvents(c context.Context, before, after *api.PrefixMetadata) error {
if before.Prefix != after.Prefix {
panic(fmt.Sprintf("comparing metadata for different prefixes: %q != %q", before.Prefix, after.Prefix))
}
prefix := after.Prefix
prev := metadata.GetACLs(before)
next := metadata.GetACLs(after)
var granted []*api.PrefixMetadata_ACL
var revoked []*api.PrefixMetadata_ACL
for _, role := range sortedRoles {
if added := stringSetDiff(next[role], prev[role]); len(added) != 0 {
granted = append(granted, &api.PrefixMetadata_ACL{
Role: role,
Principals: added,
})
}
if removed := stringSetDiff(prev[role], next[role]); len(removed) != 0 {
revoked = append(revoked, &api.PrefixMetadata_ACL{
Role: role,
Principals: removed,
})
}
}
if len(granted) == 0 && len(revoked) == 0 {
return nil
}
return EmitEvent(c, &api.Event{
Kind: api.EventKind_PREFIX_ACL_CHANGED,
Package: prefix,
GrantedRole: granted,
RevokedRole: revoked,
})
} | [
"func",
"EmitMetadataEvents",
"(",
"c",
"context",
".",
"Context",
",",
"before",
",",
"after",
"*",
"api",
".",
"PrefixMetadata",
")",
"error",
"{",
"if",
"before",
".",
"Prefix",
"!=",
"after",
".",
"Prefix",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"before",
".",
"Prefix",
",",
"after",
".",
"Prefix",
")",
")",
"\n",
"}",
"\n",
"prefix",
":=",
"after",
".",
"Prefix",
"\n\n",
"prev",
":=",
"metadata",
".",
"GetACLs",
"(",
"before",
")",
"\n",
"next",
":=",
"metadata",
".",
"GetACLs",
"(",
"after",
")",
"\n\n",
"var",
"granted",
"[",
"]",
"*",
"api",
".",
"PrefixMetadata_ACL",
"\n",
"var",
"revoked",
"[",
"]",
"*",
"api",
".",
"PrefixMetadata_ACL",
"\n\n",
"for",
"_",
",",
"role",
":=",
"range",
"sortedRoles",
"{",
"if",
"added",
":=",
"stringSetDiff",
"(",
"next",
"[",
"role",
"]",
",",
"prev",
"[",
"role",
"]",
")",
";",
"len",
"(",
"added",
")",
"!=",
"0",
"{",
"granted",
"=",
"append",
"(",
"granted",
",",
"&",
"api",
".",
"PrefixMetadata_ACL",
"{",
"Role",
":",
"role",
",",
"Principals",
":",
"added",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"removed",
":=",
"stringSetDiff",
"(",
"prev",
"[",
"role",
"]",
",",
"next",
"[",
"role",
"]",
")",
";",
"len",
"(",
"removed",
")",
"!=",
"0",
"{",
"revoked",
"=",
"append",
"(",
"revoked",
",",
"&",
"api",
".",
"PrefixMetadata_ACL",
"{",
"Role",
":",
"role",
",",
"Principals",
":",
"removed",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"granted",
")",
"==",
"0",
"&&",
"len",
"(",
"revoked",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"EmitEvent",
"(",
"c",
",",
"&",
"api",
".",
"Event",
"{",
"Kind",
":",
"api",
".",
"EventKind_PREFIX_ACL_CHANGED",
",",
"Package",
":",
"prefix",
",",
"GrantedRole",
":",
"granted",
",",
"RevokedRole",
":",
"revoked",
",",
"}",
")",
"\n",
"}"
] | // EmitMetadataEvents compares two metadatum of a prefix and emits events for
// fields that have changed. | [
"EmitMetadataEvents",
"compares",
"two",
"metadatum",
"of",
"a",
"prefix",
"and",
"emits",
"events",
"for",
"fields",
"that",
"have",
"changed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/events.go#L222-L259 |
7,958 | luci/luci-go | common/data/recordio/writer.go | WriteFrame | func WriteFrame(w io.Writer, frame []byte) (int, error) {
count, err := writeFrameHeader(w, uint64(len(frame)))
if err != nil {
return count, err
}
amount, err := w.Write(frame)
count += amount
if err != nil {
return count, err
}
return count, nil
} | go | func WriteFrame(w io.Writer, frame []byte) (int, error) {
count, err := writeFrameHeader(w, uint64(len(frame)))
if err != nil {
return count, err
}
amount, err := w.Write(frame)
count += amount
if err != nil {
return count, err
}
return count, nil
} | [
"func",
"WriteFrame",
"(",
"w",
"io",
".",
"Writer",
",",
"frame",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"writeFrameHeader",
"(",
"w",
",",
"uint64",
"(",
"len",
"(",
"frame",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"count",
",",
"err",
"\n",
"}",
"\n\n",
"amount",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"frame",
")",
"\n",
"count",
"+=",
"amount",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"count",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"count",
",",
"nil",
"\n",
"}"
] | // WriteFrame writes a single frame to an io.Writer. | [
"WriteFrame",
"writes",
"a",
"single",
"frame",
"to",
"an",
"io",
".",
"Writer",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/recordio/writer.go#L29-L42 |
7,959 | luci/luci-go | common/tsmon/iface.go | SetStore | func SetStore(c context.Context, s store.Store) {
GetState(c).SetStore(s)
} | go | func SetStore(c context.Context, s store.Store) {
GetState(c).SetStore(s)
} | [
"func",
"SetStore",
"(",
"c",
"context",
".",
"Context",
",",
"s",
"store",
".",
"Store",
")",
"{",
"GetState",
"(",
"c",
")",
".",
"SetStore",
"(",
"s",
")",
"\n",
"}"
] | // SetStore changes the global metric store. All metrics that were registered
// with the old store will be re-registered on the new store. | [
"SetStore",
"changes",
"the",
"global",
"metric",
"store",
".",
"All",
"metrics",
"that",
"were",
"registered",
"with",
"the",
"old",
"store",
"will",
"be",
"re",
"-",
"registered",
"on",
"the",
"new",
"store",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/iface.go#L48-L50 |
7,960 | luci/luci-go | common/tsmon/iface.go | Initialize | func Initialize(c context.Context, m monitor.Monitor, s store.Store) {
state := GetState(c)
state.SetMonitor(m)
state.SetStore(s)
} | go | func Initialize(c context.Context, m monitor.Monitor, s store.Store) {
state := GetState(c)
state.SetMonitor(m)
state.SetStore(s)
} | [
"func",
"Initialize",
"(",
"c",
"context",
".",
"Context",
",",
"m",
"monitor",
".",
"Monitor",
",",
"s",
"store",
".",
"Store",
")",
"{",
"state",
":=",
"GetState",
"(",
"c",
")",
"\n",
"state",
".",
"SetMonitor",
"(",
"m",
")",
"\n",
"state",
".",
"SetStore",
"(",
"s",
")",
"\n",
"}"
] | // Initialize configures the tsmon library with the given monitor and store. | [
"Initialize",
"configures",
"the",
"tsmon",
"library",
"with",
"the",
"given",
"monitor",
"and",
"store",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/iface.go#L126-L130 |
7,961 | luci/luci-go | common/tsmon/iface.go | newAuthenticator | func newAuthenticator(ctx context.Context, credentials, actAs string, scopes []string) *auth.Authenticator {
// TODO(vadimsh): Don't hardcode auth options here, pass them from outside
// somehow.
authOpts := chromeinfra.DefaultAuthOptions()
authOpts.ServiceAccountJSONPath = credentials
authOpts.Scopes = scopes
authOpts.ActAsServiceAccount = actAs
return auth.NewAuthenticator(ctx, auth.SilentLogin, authOpts)
} | go | func newAuthenticator(ctx context.Context, credentials, actAs string, scopes []string) *auth.Authenticator {
// TODO(vadimsh): Don't hardcode auth options here, pass them from outside
// somehow.
authOpts := chromeinfra.DefaultAuthOptions()
authOpts.ServiceAccountJSONPath = credentials
authOpts.Scopes = scopes
authOpts.ActAsServiceAccount = actAs
return auth.NewAuthenticator(ctx, auth.SilentLogin, authOpts)
} | [
"func",
"newAuthenticator",
"(",
"ctx",
"context",
".",
"Context",
",",
"credentials",
",",
"actAs",
"string",
",",
"scopes",
"[",
"]",
"string",
")",
"*",
"auth",
".",
"Authenticator",
"{",
"// TODO(vadimsh): Don't hardcode auth options here, pass them from outside",
"// somehow.",
"authOpts",
":=",
"chromeinfra",
".",
"DefaultAuthOptions",
"(",
")",
"\n",
"authOpts",
".",
"ServiceAccountJSONPath",
"=",
"credentials",
"\n",
"authOpts",
".",
"Scopes",
"=",
"scopes",
"\n",
"authOpts",
".",
"ActAsServiceAccount",
"=",
"actAs",
"\n",
"return",
"auth",
".",
"NewAuthenticator",
"(",
"ctx",
",",
"auth",
".",
"SilentLogin",
",",
"authOpts",
")",
"\n",
"}"
] | // newAuthenticator returns a new authenticator for HTTP requests. | [
"newAuthenticator",
"returns",
"a",
"new",
"authenticator",
"for",
"HTTP",
"requests",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/iface.go#L196-L204 |
7,962 | luci/luci-go | logdog/server/cmd/logdog_archivist/main.go | settingsUpdater | func settingsUpdater(c context.Context) {
for {
set := coordinator.GetSettings(c)
logging.Debugf(c, "updating settings: %v", set)
if batchSize != set.ArchivistBatchSize {
batchSize = set.ArchivistBatchSize
}
if leaseTime != set.ArchivistLeaseTime {
leaseTime = set.ArchivistLeaseTime
}
clock.Sleep(c, 5*time.Minute)
}
} | go | func settingsUpdater(c context.Context) {
for {
set := coordinator.GetSettings(c)
logging.Debugf(c, "updating settings: %v", set)
if batchSize != set.ArchivistBatchSize {
batchSize = set.ArchivistBatchSize
}
if leaseTime != set.ArchivistLeaseTime {
leaseTime = set.ArchivistLeaseTime
}
clock.Sleep(c, 5*time.Minute)
}
} | [
"func",
"settingsUpdater",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"for",
"{",
"set",
":=",
"coordinator",
".",
"GetSettings",
"(",
"c",
")",
"\n",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"set",
")",
"\n",
"if",
"batchSize",
"!=",
"set",
".",
"ArchivistBatchSize",
"{",
"batchSize",
"=",
"set",
".",
"ArchivistBatchSize",
"\n",
"}",
"\n",
"if",
"leaseTime",
"!=",
"set",
".",
"ArchivistLeaseTime",
"{",
"leaseTime",
"=",
"set",
".",
"ArchivistLeaseTime",
"\n",
"}",
"\n",
"clock",
".",
"Sleep",
"(",
"c",
",",
"5",
"*",
"time",
".",
"Minute",
")",
"\n",
"}",
"\n",
"}"
] | // settingsUpdater updates the settings from datastore every once in a while. | [
"settingsUpdater",
"updates",
"the",
"settings",
"from",
"datastore",
"every",
"once",
"in",
"a",
"while",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/cmd/logdog_archivist/main.go#L182-L194 |
7,963 | luci/luci-go | logdog/server/cmd/logdog_archivist/main.go | GetSettingsLoader | func (a *application) GetSettingsLoader(acfg *svcconfig.Archivist) archivist.SettingsLoader {
serviceID := a.ServiceID()
return func(c context.Context, proj types.ProjectName) (*archivist.Settings, error) {
// Fold in our project-specific configuration, if valid.
pcfg, err := a.ProjectConfig(c, proj)
if err != nil {
log.Fields{
log.ErrorKey: err,
"project": proj,
}.Errorf(c, "Failed to fetch project configuration.")
return nil, err
}
indexParam := func(get func(ic *svcconfig.ArchiveIndexConfig) int32) int {
if ic := pcfg.ArchiveIndexConfig; ic != nil {
if v := get(ic); v > 0 {
return int(v)
}
}
if ic := acfg.ArchiveIndexConfig; ic != nil {
if v := get(ic); v > 0 {
return int(v)
}
}
return 0
}
// Load our base settings.
//
// Archival bases are:
// Staging: gs://<services:gs_staging_bucket>/<project-id>/...
// Archive: gs://<project:archive_gs_bucket>/<project-id>/...
st := archivist.Settings{
GSBase: gs.MakePath(pcfg.ArchiveGsBucket, "").Concat(serviceID),
GSStagingBase: gs.MakePath(acfg.GsStagingBucket, "").Concat(serviceID),
IndexStreamRange: indexParam(func(ic *svcconfig.ArchiveIndexConfig) int32 { return ic.StreamRange }),
IndexPrefixRange: indexParam(func(ic *svcconfig.ArchiveIndexConfig) int32 { return ic.PrefixRange }),
IndexByteRange: indexParam(func(ic *svcconfig.ArchiveIndexConfig) int32 { return ic.ByteRange }),
AlwaysRender: (acfg.RenderAllStreams || pcfg.RenderAllStreams),
}
// Fold project settings into loaded ones.
return &st, nil
}
} | go | func (a *application) GetSettingsLoader(acfg *svcconfig.Archivist) archivist.SettingsLoader {
serviceID := a.ServiceID()
return func(c context.Context, proj types.ProjectName) (*archivist.Settings, error) {
// Fold in our project-specific configuration, if valid.
pcfg, err := a.ProjectConfig(c, proj)
if err != nil {
log.Fields{
log.ErrorKey: err,
"project": proj,
}.Errorf(c, "Failed to fetch project configuration.")
return nil, err
}
indexParam := func(get func(ic *svcconfig.ArchiveIndexConfig) int32) int {
if ic := pcfg.ArchiveIndexConfig; ic != nil {
if v := get(ic); v > 0 {
return int(v)
}
}
if ic := acfg.ArchiveIndexConfig; ic != nil {
if v := get(ic); v > 0 {
return int(v)
}
}
return 0
}
// Load our base settings.
//
// Archival bases are:
// Staging: gs://<services:gs_staging_bucket>/<project-id>/...
// Archive: gs://<project:archive_gs_bucket>/<project-id>/...
st := archivist.Settings{
GSBase: gs.MakePath(pcfg.ArchiveGsBucket, "").Concat(serviceID),
GSStagingBase: gs.MakePath(acfg.GsStagingBucket, "").Concat(serviceID),
IndexStreamRange: indexParam(func(ic *svcconfig.ArchiveIndexConfig) int32 { return ic.StreamRange }),
IndexPrefixRange: indexParam(func(ic *svcconfig.ArchiveIndexConfig) int32 { return ic.PrefixRange }),
IndexByteRange: indexParam(func(ic *svcconfig.ArchiveIndexConfig) int32 { return ic.ByteRange }),
AlwaysRender: (acfg.RenderAllStreams || pcfg.RenderAllStreams),
}
// Fold project settings into loaded ones.
return &st, nil
}
} | [
"func",
"(",
"a",
"*",
"application",
")",
"GetSettingsLoader",
"(",
"acfg",
"*",
"svcconfig",
".",
"Archivist",
")",
"archivist",
".",
"SettingsLoader",
"{",
"serviceID",
":=",
"a",
".",
"ServiceID",
"(",
")",
"\n\n",
"return",
"func",
"(",
"c",
"context",
".",
"Context",
",",
"proj",
"types",
".",
"ProjectName",
")",
"(",
"*",
"archivist",
".",
"Settings",
",",
"error",
")",
"{",
"// Fold in our project-specific configuration, if valid.",
"pcfg",
",",
"err",
":=",
"a",
".",
"ProjectConfig",
"(",
"c",
",",
"proj",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fields",
"{",
"log",
".",
"ErrorKey",
":",
"err",
",",
"\"",
"\"",
":",
"proj",
",",
"}",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"indexParam",
":=",
"func",
"(",
"get",
"func",
"(",
"ic",
"*",
"svcconfig",
".",
"ArchiveIndexConfig",
")",
"int32",
")",
"int",
"{",
"if",
"ic",
":=",
"pcfg",
".",
"ArchiveIndexConfig",
";",
"ic",
"!=",
"nil",
"{",
"if",
"v",
":=",
"get",
"(",
"ic",
")",
";",
"v",
">",
"0",
"{",
"return",
"int",
"(",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"ic",
":=",
"acfg",
".",
"ArchiveIndexConfig",
";",
"ic",
"!=",
"nil",
"{",
"if",
"v",
":=",
"get",
"(",
"ic",
")",
";",
"v",
">",
"0",
"{",
"return",
"int",
"(",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"0",
"\n",
"}",
"\n\n",
"// Load our base settings.",
"//",
"// Archival bases are:",
"// Staging: gs://<services:gs_staging_bucket>/<project-id>/...",
"// Archive: gs://<project:archive_gs_bucket>/<project-id>/...",
"st",
":=",
"archivist",
".",
"Settings",
"{",
"GSBase",
":",
"gs",
".",
"MakePath",
"(",
"pcfg",
".",
"ArchiveGsBucket",
",",
"\"",
"\"",
")",
".",
"Concat",
"(",
"serviceID",
")",
",",
"GSStagingBase",
":",
"gs",
".",
"MakePath",
"(",
"acfg",
".",
"GsStagingBucket",
",",
"\"",
"\"",
")",
".",
"Concat",
"(",
"serviceID",
")",
",",
"IndexStreamRange",
":",
"indexParam",
"(",
"func",
"(",
"ic",
"*",
"svcconfig",
".",
"ArchiveIndexConfig",
")",
"int32",
"{",
"return",
"ic",
".",
"StreamRange",
"}",
")",
",",
"IndexPrefixRange",
":",
"indexParam",
"(",
"func",
"(",
"ic",
"*",
"svcconfig",
".",
"ArchiveIndexConfig",
")",
"int32",
"{",
"return",
"ic",
".",
"PrefixRange",
"}",
")",
",",
"IndexByteRange",
":",
"indexParam",
"(",
"func",
"(",
"ic",
"*",
"svcconfig",
".",
"ArchiveIndexConfig",
")",
"int32",
"{",
"return",
"ic",
".",
"ByteRange",
"}",
")",
",",
"AlwaysRender",
":",
"(",
"acfg",
".",
"RenderAllStreams",
"||",
"pcfg",
".",
"RenderAllStreams",
")",
",",
"}",
"\n\n",
"// Fold project settings into loaded ones.",
"return",
"&",
"st",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // GetSettingsLoader is an archivist.SettingsLoader implementation that merges
// global and project-specific settings.
//
// The resulting settings object will be verified by the Archivist. | [
"GetSettingsLoader",
"is",
"an",
"archivist",
".",
"SettingsLoader",
"implementation",
"that",
"merges",
"global",
"and",
"project",
"-",
"specific",
"settings",
".",
"The",
"resulting",
"settings",
"object",
"will",
"be",
"verified",
"by",
"the",
"Archivist",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/cmd/logdog_archivist/main.go#L266-L314 |
7,964 | luci/luci-go | logdog/server/cmd/logdog_archivist/main.go | main | func main() {
mathrand.SeedRandomly()
a := application{
Service: service.Service{
Name: "archivist",
DefaultAuthOptions: chromeinfra.DefaultAuthOptions(),
},
}
a.Run(context.Background(), a.runArchivist)
} | go | func main() {
mathrand.SeedRandomly()
a := application{
Service: service.Service{
Name: "archivist",
DefaultAuthOptions: chromeinfra.DefaultAuthOptions(),
},
}
a.Run(context.Background(), a.runArchivist)
} | [
"func",
"main",
"(",
")",
"{",
"mathrand",
".",
"SeedRandomly",
"(",
")",
"\n",
"a",
":=",
"application",
"{",
"Service",
":",
"service",
".",
"Service",
"{",
"Name",
":",
"\"",
"\"",
",",
"DefaultAuthOptions",
":",
"chromeinfra",
".",
"DefaultAuthOptions",
"(",
")",
",",
"}",
",",
"}",
"\n",
"a",
".",
"Run",
"(",
"context",
".",
"Background",
"(",
")",
",",
"a",
".",
"runArchivist",
")",
"\n",
"}"
] | // Entry point. | [
"Entry",
"point",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/cmd/logdog_archivist/main.go#L317-L326 |
7,965 | luci/luci-go | dm/appengine/distributor/registry.go | WithRegistry | func WithRegistry(c context.Context, r Registry) context.Context {
if r == nil {
panic(errors.New("you may not use WithRegistry on a nil Registry"))
}
return context.WithValue(c, ®Key, r)
} | go | func WithRegistry(c context.Context, r Registry) context.Context {
if r == nil {
panic(errors.New("you may not use WithRegistry on a nil Registry"))
}
return context.WithValue(c, ®Key, r)
} | [
"func",
"WithRegistry",
"(",
"c",
"context",
".",
"Context",
",",
"r",
"Registry",
")",
"context",
".",
"Context",
"{",
"if",
"r",
"==",
"nil",
"{",
"panic",
"(",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"regKey",
",",
"r",
")",
"\n",
"}"
] | // WithRegistry adds the registry to the Context. | [
"WithRegistry",
"adds",
"the",
"registry",
"to",
"the",
"Context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/registry.go#L38-L43 |
7,966 | luci/luci-go | dm/appengine/distributor/registry.go | GetRegistry | func GetRegistry(c context.Context) Registry {
ret, _ := c.Value(®Key).(Registry)
return ret
} | go | func GetRegistry(c context.Context) Registry {
ret, _ := c.Value(®Key).(Registry)
return ret
} | [
"func",
"GetRegistry",
"(",
"c",
"context",
".",
"Context",
")",
"Registry",
"{",
"ret",
",",
"_",
":=",
"c",
".",
"Value",
"(",
"&",
"regKey",
")",
".",
"(",
"Registry",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // GetRegistry gets the registry from the Context. This will return nil if the
// Context does not contain a Registry. | [
"GetRegistry",
"gets",
"the",
"registry",
"from",
"the",
"Context",
".",
"This",
"will",
"return",
"nil",
"if",
"the",
"Context",
"does",
"not",
"contain",
"a",
"Registry",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/registry.go#L47-L50 |
7,967 | luci/luci-go | dm/appengine/distributor/registry.go | NewRegistry | func NewRegistry(mapping FactoryMap, fFn FinishExecutionFn) Registry {
ret := ®istry{fFn, make(map[reflect.Type]Factory, len(mapping))}
add := func(p proto.Message, factory Factory) {
if factory == nil {
panic("factory is nil")
}
if p == nil {
panic("proto.Message is nil")
}
typ := reflect.TypeOf(p)
if _, ok := ret.data[typ]; ok {
panic(fmt.Errorf("trying to register %q twice", typ))
}
ret.data[typ] = factory
}
for p, f := range mapping {
add(p, f)
}
return ret
} | go | func NewRegistry(mapping FactoryMap, fFn FinishExecutionFn) Registry {
ret := ®istry{fFn, make(map[reflect.Type]Factory, len(mapping))}
add := func(p proto.Message, factory Factory) {
if factory == nil {
panic("factory is nil")
}
if p == nil {
panic("proto.Message is nil")
}
typ := reflect.TypeOf(p)
if _, ok := ret.data[typ]; ok {
panic(fmt.Errorf("trying to register %q twice", typ))
}
ret.data[typ] = factory
}
for p, f := range mapping {
add(p, f)
}
return ret
} | [
"func",
"NewRegistry",
"(",
"mapping",
"FactoryMap",
",",
"fFn",
"FinishExecutionFn",
")",
"Registry",
"{",
"ret",
":=",
"&",
"registry",
"{",
"fFn",
",",
"make",
"(",
"map",
"[",
"reflect",
".",
"Type",
"]",
"Factory",
",",
"len",
"(",
"mapping",
")",
")",
"}",
"\n",
"add",
":=",
"func",
"(",
"p",
"proto",
".",
"Message",
",",
"factory",
"Factory",
")",
"{",
"if",
"factory",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"p",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"p",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"ret",
".",
"data",
"[",
"typ",
"]",
";",
"ok",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"typ",
")",
")",
"\n",
"}",
"\n",
"ret",
".",
"data",
"[",
"typ",
"]",
"=",
"factory",
"\n",
"}",
"\n",
"for",
"p",
",",
"f",
":=",
"range",
"mapping",
"{",
"add",
"(",
"p",
",",
"f",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // NewRegistry builds a new implementation of Registry configured to load
// configuration data from luci-config.
//
// The mapping should hold nil-ptrs of various config protos -> respective
// Factory. When loading from luci-config, when we see a given message type,
// we'll construct the distributor instance using the provided Factory. | [
"NewRegistry",
"builds",
"a",
"new",
"implementation",
"of",
"Registry",
"configured",
"to",
"load",
"configuration",
"data",
"from",
"luci",
"-",
"config",
".",
"The",
"mapping",
"should",
"hold",
"nil",
"-",
"ptrs",
"of",
"various",
"config",
"protos",
"-",
">",
"respective",
"Factory",
".",
"When",
"loading",
"from",
"luci",
"-",
"config",
"when",
"we",
"see",
"a",
"given",
"message",
"type",
"we",
"ll",
"construct",
"the",
"distributor",
"instance",
"using",
"the",
"provided",
"Factory",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/registry.go#L81-L102 |
7,968 | luci/luci-go | dm/appengine/distributor/registry.go | loadConfig | func loadConfig(c context.Context, cfgName string) (ret *Config, err error) {
configSet := cfgclient.CurrentServiceConfigSet(c)
var (
distCfg distributor.Config
meta config.Meta
)
if err = cfgclient.Get(c, cfgclient.AsService, configSet, "distributors.cfg", textproto.Message(&distCfg), &meta); err != nil {
return
}
cfgVersion := meta.Revision
cfg, ok := distCfg.DistributorConfigs[cfgName]
if !ok {
err = fmt.Errorf("unknown distributor configuration: %q", cfgName)
return
}
if alias := cfg.GetAlias(); alias != nil {
cfg, ok = distCfg.DistributorConfigs[alias.OtherConfig]
if !ok {
err = fmt.Errorf("unknown distributor configuration: %q (via alias %q)", cfgName, alias.OtherConfig)
return
}
if cfg.GetAlias() != nil {
err = fmt.Errorf("too many levels of indirection for alias %q (points to alias %q)", cfgName, alias.OtherConfig)
return
}
}
dt := cfg.DistributorType
if dt == nil {
err = fmt.Errorf("blank or unrecognized distributor_type")
return
}
dVal := reflect.ValueOf(dt)
// All non-nil DistributorType's have a single field which is the actual oneof
// value.
implConfig := dVal.Elem().Field(0).Interface().(proto.Message)
ret = &Config{
info.DefaultVersionHostname(c),
cfgName,
cfgVersion,
implConfig,
}
return
} | go | func loadConfig(c context.Context, cfgName string) (ret *Config, err error) {
configSet := cfgclient.CurrentServiceConfigSet(c)
var (
distCfg distributor.Config
meta config.Meta
)
if err = cfgclient.Get(c, cfgclient.AsService, configSet, "distributors.cfg", textproto.Message(&distCfg), &meta); err != nil {
return
}
cfgVersion := meta.Revision
cfg, ok := distCfg.DistributorConfigs[cfgName]
if !ok {
err = fmt.Errorf("unknown distributor configuration: %q", cfgName)
return
}
if alias := cfg.GetAlias(); alias != nil {
cfg, ok = distCfg.DistributorConfigs[alias.OtherConfig]
if !ok {
err = fmt.Errorf("unknown distributor configuration: %q (via alias %q)", cfgName, alias.OtherConfig)
return
}
if cfg.GetAlias() != nil {
err = fmt.Errorf("too many levels of indirection for alias %q (points to alias %q)", cfgName, alias.OtherConfig)
return
}
}
dt := cfg.DistributorType
if dt == nil {
err = fmt.Errorf("blank or unrecognized distributor_type")
return
}
dVal := reflect.ValueOf(dt)
// All non-nil DistributorType's have a single field which is the actual oneof
// value.
implConfig := dVal.Elem().Field(0).Interface().(proto.Message)
ret = &Config{
info.DefaultVersionHostname(c),
cfgName,
cfgVersion,
implConfig,
}
return
} | [
"func",
"loadConfig",
"(",
"c",
"context",
".",
"Context",
",",
"cfgName",
"string",
")",
"(",
"ret",
"*",
"Config",
",",
"err",
"error",
")",
"{",
"configSet",
":=",
"cfgclient",
".",
"CurrentServiceConfigSet",
"(",
"c",
")",
"\n\n",
"var",
"(",
"distCfg",
"distributor",
".",
"Config",
"\n",
"meta",
"config",
".",
"Meta",
"\n",
")",
"\n",
"if",
"err",
"=",
"cfgclient",
".",
"Get",
"(",
"c",
",",
"cfgclient",
".",
"AsService",
",",
"configSet",
",",
"\"",
"\"",
",",
"textproto",
".",
"Message",
"(",
"&",
"distCfg",
")",
",",
"&",
"meta",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"cfgVersion",
":=",
"meta",
".",
"Revision",
"\n",
"cfg",
",",
"ok",
":=",
"distCfg",
".",
"DistributorConfigs",
"[",
"cfgName",
"]",
"\n",
"if",
"!",
"ok",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfgName",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"alias",
":=",
"cfg",
".",
"GetAlias",
"(",
")",
";",
"alias",
"!=",
"nil",
"{",
"cfg",
",",
"ok",
"=",
"distCfg",
".",
"DistributorConfigs",
"[",
"alias",
".",
"OtherConfig",
"]",
"\n",
"if",
"!",
"ok",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfgName",
",",
"alias",
".",
"OtherConfig",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"GetAlias",
"(",
")",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfgName",
",",
"alias",
".",
"OtherConfig",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"dt",
":=",
"cfg",
".",
"DistributorType",
"\n",
"if",
"dt",
"==",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"dt",
")",
"\n\n",
"// All non-nil DistributorType's have a single field which is the actual oneof",
"// value.",
"implConfig",
":=",
"dVal",
".",
"Elem",
"(",
")",
".",
"Field",
"(",
"0",
")",
".",
"Interface",
"(",
")",
".",
"(",
"proto",
".",
"Message",
")",
"\n\n",
"ret",
"=",
"&",
"Config",
"{",
"info",
".",
"DefaultVersionHostname",
"(",
"c",
")",
",",
"cfgName",
",",
"cfgVersion",
",",
"implConfig",
",",
"}",
"\n",
"return",
"\n",
"}"
] | // loadConfig loads the named distributor configuration from luci-config,
// possibly using the in-memory or memcache version. | [
"loadConfig",
"loads",
"the",
"named",
"distributor",
"configuration",
"from",
"luci",
"-",
"config",
"possibly",
"using",
"the",
"in",
"-",
"memory",
"or",
"memcache",
"version",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/registry.go#L137-L184 |
7,969 | luci/luci-go | gce/appengine/rpc/memory/projects.go | Delete | func (srv *Projects) Delete(c context.Context, req *projects.DeleteRequest) (*empty.Empty, error) {
srv.cfg.Delete(req.GetId())
return &empty.Empty{}, nil
} | go | func (srv *Projects) Delete(c context.Context, req *projects.DeleteRequest) (*empty.Empty, error) {
srv.cfg.Delete(req.GetId())
return &empty.Empty{}, nil
} | [
"func",
"(",
"srv",
"*",
"Projects",
")",
"Delete",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"projects",
".",
"DeleteRequest",
")",
"(",
"*",
"empty",
".",
"Empty",
",",
"error",
")",
"{",
"srv",
".",
"cfg",
".",
"Delete",
"(",
"req",
".",
"GetId",
"(",
")",
")",
"\n",
"return",
"&",
"empty",
".",
"Empty",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // Delete handles a request to delete a project. | [
"Delete",
"handles",
"a",
"request",
"to",
"delete",
"a",
"project",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/memory/projects.go#L39-L42 |
7,970 | luci/luci-go | logdog/client/butler/output/pubsub/pubsubOutput.go | New | func New(ctx context.Context, c Config) output.Output {
o := pubSubOutput{
Config: &c,
}
o.bufferPool.New = func() interface{} { return &buffer{} }
if c.Track {
o.et = &output.EntryTracker{}
}
o.Context = log.SetField(ctx, "pubsub", &o)
return &o
} | go | func New(ctx context.Context, c Config) output.Output {
o := pubSubOutput{
Config: &c,
}
o.bufferPool.New = func() interface{} { return &buffer{} }
if c.Track {
o.et = &output.EntryTracker{}
}
o.Context = log.SetField(ctx, "pubsub", &o)
return &o
} | [
"func",
"New",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"Config",
")",
"output",
".",
"Output",
"{",
"o",
":=",
"pubSubOutput",
"{",
"Config",
":",
"&",
"c",
",",
"}",
"\n",
"o",
".",
"bufferPool",
".",
"New",
"=",
"func",
"(",
")",
"interface",
"{",
"}",
"{",
"return",
"&",
"buffer",
"{",
"}",
"}",
"\n\n",
"if",
"c",
".",
"Track",
"{",
"o",
".",
"et",
"=",
"&",
"output",
".",
"EntryTracker",
"{",
"}",
"\n",
"}",
"\n\n",
"o",
".",
"Context",
"=",
"log",
".",
"SetField",
"(",
"ctx",
",",
"\"",
"\"",
",",
"&",
"o",
")",
"\n",
"return",
"&",
"o",
"\n",
"}"
] | // New instantiates a new GCPS output. | [
"New",
"instantiates",
"a",
"new",
"GCPS",
"output",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/pubsub/pubsubOutput.go#L93-L105 |
7,971 | luci/luci-go | logdog/client/butler/output/pubsub/pubsubOutput.go | publishMessage | func (o *pubSubOutput) publishMessage(message *pubsub.Message) error {
var messageID string
transientErrors := 0
err := retry.Retry(o, transient.Only(indefiniteRetry), func() (err error) {
ctx := o.Context
if o.RPCTimeout > 0 {
var cancelFunc context.CancelFunc
ctx, cancelFunc = clock.WithTimeout(o, o.RPCTimeout)
defer cancelFunc()
}
messageID, err = o.Topic.Publish(ctx, message)
if err == context.DeadlineExceeded {
// If we hit our publish deadline, retry.
err = transient.Tag.Apply(err)
} else {
err = grpcutil.WrapIfTransient(err)
}
return
}, func(err error, d time.Duration) {
log.Fields{
log.ErrorKey: err,
"delay": d,
}.Warningf(o, "TRANSIENT error publishing messages; retrying...")
transientErrors++
})
if err != nil {
log.WithError(err).Errorf(o, "Failed to send PubSub message.")
return err
}
if transientErrors > 0 {
// We successfully published, but we hit a transient error, so explicitly
// acknowledge this at warning-level for log message closure.
log.Fields{
"messageId": messageID,
"transientErrors": transientErrors,
}.Warningf(o, "Successfully published messages after transient errors.")
} else {
log.Fields{
"messageId": messageID,
}.Debugf(o, "Published messages.")
}
return nil
} | go | func (o *pubSubOutput) publishMessage(message *pubsub.Message) error {
var messageID string
transientErrors := 0
err := retry.Retry(o, transient.Only(indefiniteRetry), func() (err error) {
ctx := o.Context
if o.RPCTimeout > 0 {
var cancelFunc context.CancelFunc
ctx, cancelFunc = clock.WithTimeout(o, o.RPCTimeout)
defer cancelFunc()
}
messageID, err = o.Topic.Publish(ctx, message)
if err == context.DeadlineExceeded {
// If we hit our publish deadline, retry.
err = transient.Tag.Apply(err)
} else {
err = grpcutil.WrapIfTransient(err)
}
return
}, func(err error, d time.Duration) {
log.Fields{
log.ErrorKey: err,
"delay": d,
}.Warningf(o, "TRANSIENT error publishing messages; retrying...")
transientErrors++
})
if err != nil {
log.WithError(err).Errorf(o, "Failed to send PubSub message.")
return err
}
if transientErrors > 0 {
// We successfully published, but we hit a transient error, so explicitly
// acknowledge this at warning-level for log message closure.
log.Fields{
"messageId": messageID,
"transientErrors": transientErrors,
}.Warningf(o, "Successfully published messages after transient errors.")
} else {
log.Fields{
"messageId": messageID,
}.Debugf(o, "Published messages.")
}
return nil
} | [
"func",
"(",
"o",
"*",
"pubSubOutput",
")",
"publishMessage",
"(",
"message",
"*",
"pubsub",
".",
"Message",
")",
"error",
"{",
"var",
"messageID",
"string",
"\n",
"transientErrors",
":=",
"0",
"\n",
"err",
":=",
"retry",
".",
"Retry",
"(",
"o",
",",
"transient",
".",
"Only",
"(",
"indefiniteRetry",
")",
",",
"func",
"(",
")",
"(",
"err",
"error",
")",
"{",
"ctx",
":=",
"o",
".",
"Context",
"\n",
"if",
"o",
".",
"RPCTimeout",
">",
"0",
"{",
"var",
"cancelFunc",
"context",
".",
"CancelFunc",
"\n",
"ctx",
",",
"cancelFunc",
"=",
"clock",
".",
"WithTimeout",
"(",
"o",
",",
"o",
".",
"RPCTimeout",
")",
"\n",
"defer",
"cancelFunc",
"(",
")",
"\n",
"}",
"\n\n",
"messageID",
",",
"err",
"=",
"o",
".",
"Topic",
".",
"Publish",
"(",
"ctx",
",",
"message",
")",
"\n",
"if",
"err",
"==",
"context",
".",
"DeadlineExceeded",
"{",
"// If we hit our publish deadline, retry.",
"err",
"=",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"grpcutil",
".",
"WrapIfTransient",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
",",
"func",
"(",
"err",
"error",
",",
"d",
"time",
".",
"Duration",
")",
"{",
"log",
".",
"Fields",
"{",
"log",
".",
"ErrorKey",
":",
"err",
",",
"\"",
"\"",
":",
"d",
",",
"}",
".",
"Warningf",
"(",
"o",
",",
"\"",
"\"",
")",
"\n",
"transientErrors",
"++",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"o",
",",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"transientErrors",
">",
"0",
"{",
"// We successfully published, but we hit a transient error, so explicitly",
"// acknowledge this at warning-level for log message closure.",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"messageID",
",",
"\"",
"\"",
":",
"transientErrors",
",",
"}",
".",
"Warningf",
"(",
"o",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"messageID",
",",
"}",
".",
"Debugf",
"(",
"o",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // publishMessage handles an individual publish request. It will indefinitely
// retry transient errors until the publish succeeds. | [
"publishMessage",
"handles",
"an",
"individual",
"publish",
"request",
".",
"It",
"will",
"indefinitely",
"retry",
"transient",
"errors",
"until",
"the",
"publish",
"succeeds",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/pubsub/pubsubOutput.go#L205-L249 |
7,972 | luci/luci-go | logdog/client/butler/output/pubsub/pubsubOutput.go | indefiniteRetry | func indefiniteRetry() retry.Iterator {
return &retry.ExponentialBackoff{
Limited: retry.Limited{
Retries: -1,
Delay: 500 * time.Millisecond,
},
MaxDelay: 30 * time.Second,
}
} | go | func indefiniteRetry() retry.Iterator {
return &retry.ExponentialBackoff{
Limited: retry.Limited{
Retries: -1,
Delay: 500 * time.Millisecond,
},
MaxDelay: 30 * time.Second,
}
} | [
"func",
"indefiniteRetry",
"(",
")",
"retry",
".",
"Iterator",
"{",
"return",
"&",
"retry",
".",
"ExponentialBackoff",
"{",
"Limited",
":",
"retry",
".",
"Limited",
"{",
"Retries",
":",
"-",
"1",
",",
"Delay",
":",
"500",
"*",
"time",
".",
"Millisecond",
",",
"}",
",",
"MaxDelay",
":",
"30",
"*",
"time",
".",
"Second",
",",
"}",
"\n",
"}"
] | // indefiniteRetry is a retry.Iterator that will indefinitely retry errors with
// a maximum backoff. | [
"indefiniteRetry",
"is",
"a",
"retry",
".",
"Iterator",
"that",
"will",
"indefinitely",
"retry",
"errors",
"with",
"a",
"maximum",
"backoff",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/pubsub/pubsubOutput.go#L260-L268 |
7,973 | luci/luci-go | logdog/client/butler/butler.go | Validate | func (c *Config) Validate() error {
if c.Output == nil {
return errors.New("butler: an Output must be supplied")
}
if err := c.Project.Validate(); err != nil {
return fmt.Errorf("invalid project: %v", err)
}
if err := c.Prefix.Validate(); err != nil {
return fmt.Errorf("invalid prefix: %v", err)
}
return nil
} | go | func (c *Config) Validate() error {
if c.Output == nil {
return errors.New("butler: an Output must be supplied")
}
if err := c.Project.Validate(); err != nil {
return fmt.Errorf("invalid project: %v", err)
}
if err := c.Prefix.Validate(); err != nil {
return fmt.Errorf("invalid prefix: %v", err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"c",
".",
"Output",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Project",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Prefix",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate validates that the configuration is sufficient to instantiate a
// Butler instance. | [
"Validate",
"validates",
"that",
"the",
"configuration",
"is",
"sufficient",
"to",
"instantiate",
"a",
"Butler",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L124-L135 |
7,974 | luci/luci-go | logdog/client/butler/butler.go | Wait | func (b *Butler) Wait() error {
// Run until our stream monitor shuts down, meaning all streams have finished.
//
// A race can exist here when a stream server may add new streams after we've
// drained our streams, but before we've shut them down. Since "all streams
// are done" is the edge that we use to begin shutdown, we can't simply tell
// stream servers to stop in advance.
//
// We manage this race as follows:
// 1) Wait until our stream monitor finishes. This will happen when there's a
// point that no streams are running.
// 2) Start a new stream monitor to handle (3).
// 3) Initiate stream server shutdown, wait until they have all finished.
// 4) Wait until the stream monitor in (2) has finished.
log.Debugf(b.ctx, "Waiting for Butler primary stream monitor to finish...")
<-b.streamsFinishedC
log.Debugf(b.ctx, "Butler streams have finished.")
log.Debugf(b.ctx, "Shutting down stream servers, starting residual stream monitor.")
auxStreamsFinishedC := make(chan struct{})
auxActivateC := make(chan struct{})
go func() {
defer close(auxStreamsFinishedC)
b.runStreams(auxActivateC)
}()
close(b.streamServerStopC)
b.streamServerWG.Wait()
log.Debugf(b.ctx, "Stream servers have shut down.")
log.Debugf(b.ctx, "Waiting for residual streams to finish...")
close(b.streamC)
close(auxActivateC)
<-auxStreamsFinishedC
log.Debugf(b.ctx, "Residual streams have finished.")
log.Debugf(b.ctx, "Waiting for bundler to flush.")
b.bundler.CloseAndFlush()
log.Debugf(b.ctx, "Bundler has flushed.")
if b.keepAliveC != nil {
log.Debugf(b.ctx, "Closing keep-alive monitor.")
close(b.keepAliveC)
<-b.keepAliveFinishedC
log.Debugf(b.ctx, "Keep-alive monitor has finished.")
}
log.Debugf(b.ctx, "Waiting for output queue to shut down.")
<-b.bundlerDrainedC
log.Debugf(b.ctx, "Output queue has shut down.")
log.Fields{
"stats": b.c.Output.Stats(),
}.Infof(b.ctx, "Message output has closed")
return b.getRunErr()
} | go | func (b *Butler) Wait() error {
// Run until our stream monitor shuts down, meaning all streams have finished.
//
// A race can exist here when a stream server may add new streams after we've
// drained our streams, but before we've shut them down. Since "all streams
// are done" is the edge that we use to begin shutdown, we can't simply tell
// stream servers to stop in advance.
//
// We manage this race as follows:
// 1) Wait until our stream monitor finishes. This will happen when there's a
// point that no streams are running.
// 2) Start a new stream monitor to handle (3).
// 3) Initiate stream server shutdown, wait until they have all finished.
// 4) Wait until the stream monitor in (2) has finished.
log.Debugf(b.ctx, "Waiting for Butler primary stream monitor to finish...")
<-b.streamsFinishedC
log.Debugf(b.ctx, "Butler streams have finished.")
log.Debugf(b.ctx, "Shutting down stream servers, starting residual stream monitor.")
auxStreamsFinishedC := make(chan struct{})
auxActivateC := make(chan struct{})
go func() {
defer close(auxStreamsFinishedC)
b.runStreams(auxActivateC)
}()
close(b.streamServerStopC)
b.streamServerWG.Wait()
log.Debugf(b.ctx, "Stream servers have shut down.")
log.Debugf(b.ctx, "Waiting for residual streams to finish...")
close(b.streamC)
close(auxActivateC)
<-auxStreamsFinishedC
log.Debugf(b.ctx, "Residual streams have finished.")
log.Debugf(b.ctx, "Waiting for bundler to flush.")
b.bundler.CloseAndFlush()
log.Debugf(b.ctx, "Bundler has flushed.")
if b.keepAliveC != nil {
log.Debugf(b.ctx, "Closing keep-alive monitor.")
close(b.keepAliveC)
<-b.keepAliveFinishedC
log.Debugf(b.ctx, "Keep-alive monitor has finished.")
}
log.Debugf(b.ctx, "Waiting for output queue to shut down.")
<-b.bundlerDrainedC
log.Debugf(b.ctx, "Output queue has shut down.")
log.Fields{
"stats": b.c.Output.Stats(),
}.Infof(b.ctx, "Message output has closed")
return b.getRunErr()
} | [
"func",
"(",
"b",
"*",
"Butler",
")",
"Wait",
"(",
")",
"error",
"{",
"// Run until our stream monitor shuts down, meaning all streams have finished.",
"//",
"// A race can exist here when a stream server may add new streams after we've",
"// drained our streams, but before we've shut them down. Since \"all streams",
"// are done\" is the edge that we use to begin shutdown, we can't simply tell",
"// stream servers to stop in advance.",
"//",
"// We manage this race as follows:",
"// 1) Wait until our stream monitor finishes. This will happen when there's a",
"// point that no streams are running.",
"// 2) Start a new stream monitor to handle (3).",
"// 3) Initiate stream server shutdown, wait until they have all finished.",
"// 4) Wait until the stream monitor in (2) has finished.",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"<-",
"b",
".",
"streamsFinishedC",
"\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"auxStreamsFinishedC",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"auxActivateC",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"auxStreamsFinishedC",
")",
"\n",
"b",
".",
"runStreams",
"(",
"auxActivateC",
")",
"\n",
"}",
"(",
")",
"\n\n",
"close",
"(",
"b",
".",
"streamServerStopC",
")",
"\n",
"b",
".",
"streamServerWG",
".",
"Wait",
"(",
")",
"\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"close",
"(",
"b",
".",
"streamC",
")",
"\n",
"close",
"(",
"auxActivateC",
")",
"\n",
"<-",
"auxStreamsFinishedC",
"\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"b",
".",
"bundler",
".",
"CloseAndFlush",
"(",
")",
"\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"b",
".",
"keepAliveC",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"close",
"(",
"b",
".",
"keepAliveC",
")",
"\n",
"<-",
"b",
".",
"keepAliveFinishedC",
"\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"<-",
"b",
".",
"bundlerDrainedC",
"\n",
"log",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"b",
".",
"c",
".",
"Output",
".",
"Stats",
"(",
")",
",",
"}",
".",
"Infof",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"return",
"b",
".",
"getRunErr",
"(",
")",
"\n",
"}"
] | // Wait blocks until the Butler instance has completed, returning with the
// Butler's return code. | [
"Wait",
"blocks",
"until",
"the",
"Butler",
"instance",
"has",
"completed",
"returning",
"with",
"the",
"Butler",
"s",
"return",
"code",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L291-L347 |
7,975 | luci/luci-go | logdog/client/butler/butler.go | Streams | func (b *Butler) Streams() []types.StreamName {
var streams types.StreamNameSlice
func() {
b.streamSeenLock.Lock()
defer b.streamSeenLock.Unlock()
streams = make([]types.StreamName, 0, b.streamSeen.Len())
b.streamSeen.Iter(func(s string) bool {
streams = append(streams, types.StreamName(s))
return true
})
}()
sort.Sort(streams)
return ([]types.StreamName)(streams)
} | go | func (b *Butler) Streams() []types.StreamName {
var streams types.StreamNameSlice
func() {
b.streamSeenLock.Lock()
defer b.streamSeenLock.Unlock()
streams = make([]types.StreamName, 0, b.streamSeen.Len())
b.streamSeen.Iter(func(s string) bool {
streams = append(streams, types.StreamName(s))
return true
})
}()
sort.Sort(streams)
return ([]types.StreamName)(streams)
} | [
"func",
"(",
"b",
"*",
"Butler",
")",
"Streams",
"(",
")",
"[",
"]",
"types",
".",
"StreamName",
"{",
"var",
"streams",
"types",
".",
"StreamNameSlice",
"\n",
"func",
"(",
")",
"{",
"b",
".",
"streamSeenLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"streamSeenLock",
".",
"Unlock",
"(",
")",
"\n\n",
"streams",
"=",
"make",
"(",
"[",
"]",
"types",
".",
"StreamName",
",",
"0",
",",
"b",
".",
"streamSeen",
".",
"Len",
"(",
")",
")",
"\n",
"b",
".",
"streamSeen",
".",
"Iter",
"(",
"func",
"(",
"s",
"string",
")",
"bool",
"{",
"streams",
"=",
"append",
"(",
"streams",
",",
"types",
".",
"StreamName",
"(",
"s",
")",
")",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}",
"(",
")",
"\n\n",
"sort",
".",
"Sort",
"(",
"streams",
")",
"\n",
"return",
"(",
"[",
"]",
"types",
".",
"StreamName",
")",
"(",
"streams",
")",
"\n",
"}"
] | // Streams returns a sorted list of stream names that have been registered to
// the Butler. | [
"Streams",
"returns",
"a",
"sorted",
"list",
"of",
"stream",
"names",
"that",
"have",
"been",
"registered",
"to",
"the",
"Butler",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L351-L366 |
7,976 | luci/luci-go | logdog/client/butler/butler.go | AddStreamServer | func (b *Butler) AddStreamServer(streamServer streamserver.StreamServer) {
ctx := log.SetField(b.ctx, "streamServer", streamServer)
log.Debugf(ctx, "Adding stream server.")
// Pull streams from the streamserver and add them to the Butler.
streamServerFinishedC := make(chan struct{})
go func() {
defer close(streamServerFinishedC)
defer paniccatcher.Catch(func(p *paniccatcher.Panic) {
log.Fields{
"panic.error": p.Reason,
}.Errorf(b.ctx, "Panic while running StreamServer:\n%s", p.Stack)
b.shutdown(fmt.Errorf("butler: panic while running StreamServer: %v", p.Reason))
})
for {
rc, config := streamServer.Next()
if rc == nil {
log.Debugf(ctx, "StreamServer returned nil stream; terminating.")
return
}
// Add this Stream to the Butler.
//
// We run this in a function so we can ensure cleanup on failure.
if err := b.AddStream(rc, config); err != nil {
log.Fields{
log.ErrorKey: err,
}.Errorf(ctx, "Failed to add stream.")
if err := rc.Close(); err != nil {
log.Fields{
log.ErrorKey: err,
}.Warningf(ctx, "Failed to close stream.")
}
}
}
}()
// Monitor the StreamServer's close signal channel; terminate our server when
// it's set.
b.streamServerWG.Add(1)
go func() {
defer b.streamServerWG.Done()
<-b.streamServerStopC
log.Debugf(ctx, "Stop signal received for StreamServer.")
streamServer.Close()
<-streamServerFinishedC
}()
} | go | func (b *Butler) AddStreamServer(streamServer streamserver.StreamServer) {
ctx := log.SetField(b.ctx, "streamServer", streamServer)
log.Debugf(ctx, "Adding stream server.")
// Pull streams from the streamserver and add them to the Butler.
streamServerFinishedC := make(chan struct{})
go func() {
defer close(streamServerFinishedC)
defer paniccatcher.Catch(func(p *paniccatcher.Panic) {
log.Fields{
"panic.error": p.Reason,
}.Errorf(b.ctx, "Panic while running StreamServer:\n%s", p.Stack)
b.shutdown(fmt.Errorf("butler: panic while running StreamServer: %v", p.Reason))
})
for {
rc, config := streamServer.Next()
if rc == nil {
log.Debugf(ctx, "StreamServer returned nil stream; terminating.")
return
}
// Add this Stream to the Butler.
//
// We run this in a function so we can ensure cleanup on failure.
if err := b.AddStream(rc, config); err != nil {
log.Fields{
log.ErrorKey: err,
}.Errorf(ctx, "Failed to add stream.")
if err := rc.Close(); err != nil {
log.Fields{
log.ErrorKey: err,
}.Warningf(ctx, "Failed to close stream.")
}
}
}
}()
// Monitor the StreamServer's close signal channel; terminate our server when
// it's set.
b.streamServerWG.Add(1)
go func() {
defer b.streamServerWG.Done()
<-b.streamServerStopC
log.Debugf(ctx, "Stop signal received for StreamServer.")
streamServer.Close()
<-streamServerFinishedC
}()
} | [
"func",
"(",
"b",
"*",
"Butler",
")",
"AddStreamServer",
"(",
"streamServer",
"streamserver",
".",
"StreamServer",
")",
"{",
"ctx",
":=",
"log",
".",
"SetField",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
",",
"streamServer",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"// Pull streams from the streamserver and add them to the Butler.",
"streamServerFinishedC",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"streamServerFinishedC",
")",
"\n\n",
"defer",
"paniccatcher",
".",
"Catch",
"(",
"func",
"(",
"p",
"*",
"paniccatcher",
".",
"Panic",
")",
"{",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"p",
".",
"Reason",
",",
"}",
".",
"Errorf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\\n",
"\"",
",",
"p",
".",
"Stack",
")",
"\n",
"b",
".",
"shutdown",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"Reason",
")",
")",
"\n",
"}",
")",
"\n\n",
"for",
"{",
"rc",
",",
"config",
":=",
"streamServer",
".",
"Next",
"(",
")",
"\n",
"if",
"rc",
"==",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Add this Stream to the Butler.",
"//",
"// We run this in a function so we can ensure cleanup on failure.",
"if",
"err",
":=",
"b",
".",
"AddStream",
"(",
"rc",
",",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fields",
"{",
"log",
".",
"ErrorKey",
":",
"err",
",",
"}",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
":=",
"rc",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fields",
"{",
"log",
".",
"ErrorKey",
":",
"err",
",",
"}",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Monitor the StreamServer's close signal channel; terminate our server when",
"// it's set.",
"b",
".",
"streamServerWG",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"b",
".",
"streamServerWG",
".",
"Done",
"(",
")",
"\n\n",
"<-",
"b",
".",
"streamServerStopC",
"\n",
"log",
".",
"Debugf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"streamServer",
".",
"Close",
"(",
")",
"\n",
"<-",
"streamServerFinishedC",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // AddStreamServer adds a StreamServer to the Butler. This is goroutine-safe
// and may be called anytime before or during Butler execution.
//
// After this call completes, the Butler assumes ownership of the StreamServer. | [
"AddStreamServer",
"adds",
"a",
"StreamServer",
"to",
"the",
"Butler",
".",
"This",
"is",
"goroutine",
"-",
"safe",
"and",
"may",
"be",
"called",
"anytime",
"before",
"or",
"during",
"Butler",
"execution",
".",
"After",
"this",
"call",
"completes",
"the",
"Butler",
"assumes",
"ownership",
"of",
"the",
"StreamServer",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L372-L424 |
7,977 | luci/luci-go | logdog/client/butler/butler.go | AddStream | func (b *Butler) AddStream(rc io.ReadCloser, p *streamproto.Properties) error {
p = p.Clone()
if p.Timestamp == nil || google.TimeFromProto(p.Timestamp).IsZero() {
p.Timestamp = google.NewTimestamp(clock.Now(b.ctx))
}
if err := p.Validate(); err != nil {
return err
}
// Build per-stream tag map.
if l := len(b.c.GlobalTags); l > 0 {
if p.Tags == nil {
p.Tags = make(map[string]string, l)
}
for k, v := range b.c.GlobalTags {
// Add only global flags that aren't already present (overridden) in
// stream tags.
if _, ok := p.Tags[k]; !ok {
p.Tags[k] = v
}
}
}
if p.Timeout > 0 {
if rts, ok := rc.(iotools.ReadTimeoutSetter); ok {
if err := rts.SetReadTimeout(p.Timeout); err != nil {
log.Fields{
log.ErrorKey: err,
"timeout": p.Timeout,
}.Warningf(b.ctx, "Failed to set stream timeout.")
}
} else {
log.Fields{
"connection": rc,
"connectionType": fmt.Sprintf("%T", rc),
}.Warningf(b.ctx, "Don't know how to set timeout for type, so ignoring Timeout parameter.")
}
}
// If this stream is configured to tee, set that up.
reader := io.Reader(rc)
isKeepAlive := false
switch p.Tee {
case streamproto.TeeNone:
break
case streamproto.TeeStdout:
if b.c.TeeStdout == nil {
return errors.New("butler: cannot tee through STDOUT; no STDOUT is configured")
}
reader = io.TeeReader(rc, b.c.TeeStdout)
isKeepAlive = true
case streamproto.TeeStderr:
if b.c.TeeStderr == nil {
return errors.New("butler: cannot tee through STDERR; no STDERR is configured")
}
reader = io.TeeReader(rc, b.c.TeeStderr)
isKeepAlive = true
default:
return fmt.Errorf("invalid tee value: %v", p.Tee)
}
if err := b.registerStream(p.Name); err != nil {
return err
}
// Build our stream struct.
streamCtx := log.SetField(b.ctx, "stream", p.Name)
s := stream{
Context: streamCtx,
r: reader,
c: rc,
isKeepAlive: isKeepAlive,
}
// Register this stream with our Bundler. It will take ownership of "p", so
// we should not use it after this point.
var err error
if s.bs, err = b.bundler.Register(p); err != nil {
return err
}
p = nil
b.streamC <- &s
return nil
} | go | func (b *Butler) AddStream(rc io.ReadCloser, p *streamproto.Properties) error {
p = p.Clone()
if p.Timestamp == nil || google.TimeFromProto(p.Timestamp).IsZero() {
p.Timestamp = google.NewTimestamp(clock.Now(b.ctx))
}
if err := p.Validate(); err != nil {
return err
}
// Build per-stream tag map.
if l := len(b.c.GlobalTags); l > 0 {
if p.Tags == nil {
p.Tags = make(map[string]string, l)
}
for k, v := range b.c.GlobalTags {
// Add only global flags that aren't already present (overridden) in
// stream tags.
if _, ok := p.Tags[k]; !ok {
p.Tags[k] = v
}
}
}
if p.Timeout > 0 {
if rts, ok := rc.(iotools.ReadTimeoutSetter); ok {
if err := rts.SetReadTimeout(p.Timeout); err != nil {
log.Fields{
log.ErrorKey: err,
"timeout": p.Timeout,
}.Warningf(b.ctx, "Failed to set stream timeout.")
}
} else {
log.Fields{
"connection": rc,
"connectionType": fmt.Sprintf("%T", rc),
}.Warningf(b.ctx, "Don't know how to set timeout for type, so ignoring Timeout parameter.")
}
}
// If this stream is configured to tee, set that up.
reader := io.Reader(rc)
isKeepAlive := false
switch p.Tee {
case streamproto.TeeNone:
break
case streamproto.TeeStdout:
if b.c.TeeStdout == nil {
return errors.New("butler: cannot tee through STDOUT; no STDOUT is configured")
}
reader = io.TeeReader(rc, b.c.TeeStdout)
isKeepAlive = true
case streamproto.TeeStderr:
if b.c.TeeStderr == nil {
return errors.New("butler: cannot tee through STDERR; no STDERR is configured")
}
reader = io.TeeReader(rc, b.c.TeeStderr)
isKeepAlive = true
default:
return fmt.Errorf("invalid tee value: %v", p.Tee)
}
if err := b.registerStream(p.Name); err != nil {
return err
}
// Build our stream struct.
streamCtx := log.SetField(b.ctx, "stream", p.Name)
s := stream{
Context: streamCtx,
r: reader,
c: rc,
isKeepAlive: isKeepAlive,
}
// Register this stream with our Bundler. It will take ownership of "p", so
// we should not use it after this point.
var err error
if s.bs, err = b.bundler.Register(p); err != nil {
return err
}
p = nil
b.streamC <- &s
return nil
} | [
"func",
"(",
"b",
"*",
"Butler",
")",
"AddStream",
"(",
"rc",
"io",
".",
"ReadCloser",
",",
"p",
"*",
"streamproto",
".",
"Properties",
")",
"error",
"{",
"p",
"=",
"p",
".",
"Clone",
"(",
")",
"\n",
"if",
"p",
".",
"Timestamp",
"==",
"nil",
"||",
"google",
".",
"TimeFromProto",
"(",
"p",
".",
"Timestamp",
")",
".",
"IsZero",
"(",
")",
"{",
"p",
".",
"Timestamp",
"=",
"google",
".",
"NewTimestamp",
"(",
"clock",
".",
"Now",
"(",
"b",
".",
"ctx",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"p",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Build per-stream tag map.",
"if",
"l",
":=",
"len",
"(",
"b",
".",
"c",
".",
"GlobalTags",
")",
";",
"l",
">",
"0",
"{",
"if",
"p",
".",
"Tags",
"==",
"nil",
"{",
"p",
".",
"Tags",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"l",
")",
"\n",
"}",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"b",
".",
"c",
".",
"GlobalTags",
"{",
"// Add only global flags that aren't already present (overridden) in",
"// stream tags.",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"Tags",
"[",
"k",
"]",
";",
"!",
"ok",
"{",
"p",
".",
"Tags",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"Timeout",
">",
"0",
"{",
"if",
"rts",
",",
"ok",
":=",
"rc",
".",
"(",
"iotools",
".",
"ReadTimeoutSetter",
")",
";",
"ok",
"{",
"if",
"err",
":=",
"rts",
".",
"SetReadTimeout",
"(",
"p",
".",
"Timeout",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fields",
"{",
"log",
".",
"ErrorKey",
":",
"err",
",",
"\"",
"\"",
":",
"p",
".",
"Timeout",
",",
"}",
".",
"Warningf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"rc",
",",
"\"",
"\"",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rc",
")",
",",
"}",
".",
"Warningf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If this stream is configured to tee, set that up.",
"reader",
":=",
"io",
".",
"Reader",
"(",
"rc",
")",
"\n",
"isKeepAlive",
":=",
"false",
"\n",
"switch",
"p",
".",
"Tee",
"{",
"case",
"streamproto",
".",
"TeeNone",
":",
"break",
"\n\n",
"case",
"streamproto",
".",
"TeeStdout",
":",
"if",
"b",
".",
"c",
".",
"TeeStdout",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"reader",
"=",
"io",
".",
"TeeReader",
"(",
"rc",
",",
"b",
".",
"c",
".",
"TeeStdout",
")",
"\n",
"isKeepAlive",
"=",
"true",
"\n\n",
"case",
"streamproto",
".",
"TeeStderr",
":",
"if",
"b",
".",
"c",
".",
"TeeStderr",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"reader",
"=",
"io",
".",
"TeeReader",
"(",
"rc",
",",
"b",
".",
"c",
".",
"TeeStderr",
")",
"\n",
"isKeepAlive",
"=",
"true",
"\n\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
".",
"Tee",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"b",
".",
"registerStream",
"(",
"p",
".",
"Name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Build our stream struct.",
"streamCtx",
":=",
"log",
".",
"SetField",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n",
"s",
":=",
"stream",
"{",
"Context",
":",
"streamCtx",
",",
"r",
":",
"reader",
",",
"c",
":",
"rc",
",",
"isKeepAlive",
":",
"isKeepAlive",
",",
"}",
"\n\n",
"// Register this stream with our Bundler. It will take ownership of \"p\", so",
"// we should not use it after this point.",
"var",
"err",
"error",
"\n",
"if",
"s",
".",
"bs",
",",
"err",
"=",
"b",
".",
"bundler",
".",
"Register",
"(",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
"=",
"nil",
"\n\n",
"b",
".",
"streamC",
"<-",
"&",
"s",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddStream adds a Stream to the Butler. This is goroutine-safe.
//
// If no error is returned, the Butler assumes ownership of the supplied stream.
// The stream will be closed when processing is finished.
//
// If an error is occurred, the caller is still the owner of the stream and
// is responsible for closing it. | [
"AddStream",
"adds",
"a",
"Stream",
"to",
"the",
"Butler",
".",
"This",
"is",
"goroutine",
"-",
"safe",
".",
"If",
"no",
"error",
"is",
"returned",
"the",
"Butler",
"assumes",
"ownership",
"of",
"the",
"supplied",
"stream",
".",
"The",
"stream",
"will",
"be",
"closed",
"when",
"processing",
"is",
"finished",
".",
"If",
"an",
"error",
"is",
"occurred",
"the",
"caller",
"is",
"still",
"the",
"owner",
"of",
"the",
"stream",
"and",
"is",
"responsible",
"for",
"closing",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L433-L521 |
7,978 | luci/luci-go | logdog/client/butler/butler.go | registerStream | func (b *Butler) registerStream(name string) error {
b.streamSeenLock.Lock()
defer b.streamSeenLock.Unlock()
if added := b.streamSeen.Add(name); added {
return nil
}
return fmt.Errorf("a stream has already been registered with name %q", name)
} | go | func (b *Butler) registerStream(name string) error {
b.streamSeenLock.Lock()
defer b.streamSeenLock.Unlock()
if added := b.streamSeen.Add(name); added {
return nil
}
return fmt.Errorf("a stream has already been registered with name %q", name)
} | [
"func",
"(",
"b",
"*",
"Butler",
")",
"registerStream",
"(",
"name",
"string",
")",
"error",
"{",
"b",
".",
"streamSeenLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"streamSeenLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"added",
":=",
"b",
".",
"streamSeen",
".",
"Add",
"(",
"name",
")",
";",
"added",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
] | // registerStream registers awareness of the named Stream with the Butler. An
// error will be returned if the Stream has ever been registered. | [
"registerStream",
"registers",
"awareness",
"of",
"the",
"named",
"Stream",
"with",
"the",
"Butler",
".",
"An",
"error",
"will",
"be",
"returned",
"if",
"the",
"Stream",
"has",
"ever",
"been",
"registered",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L609-L617 |
7,979 | luci/luci-go | logdog/client/butler/butler.go | shutdown | func (b *Butler) shutdown(err error) {
log.Fields{
log.ErrorKey: err,
}.Debugf(b.ctx, "Received 'shutdown()' command; shutting down streams.")
func() {
b.shutdownMu.Lock()
defer b.shutdownMu.Unlock()
if b.isShutdown {
// Already shut down.
return
}
// Signal our streams to shutdown prematurely.
close(b.streamStopC)
b.runErr = err
b.isShutdown = true
}()
// Activate the Butler, if it hasn't already been activated. The Butler will
// block pending stream draining, but we've instructed our streams to
// shutdown prematurely, so this should be reasonably quick.
b.Activate()
} | go | func (b *Butler) shutdown(err error) {
log.Fields{
log.ErrorKey: err,
}.Debugf(b.ctx, "Received 'shutdown()' command; shutting down streams.")
func() {
b.shutdownMu.Lock()
defer b.shutdownMu.Unlock()
if b.isShutdown {
// Already shut down.
return
}
// Signal our streams to shutdown prematurely.
close(b.streamStopC)
b.runErr = err
b.isShutdown = true
}()
// Activate the Butler, if it hasn't already been activated. The Butler will
// block pending stream draining, but we've instructed our streams to
// shutdown prematurely, so this should be reasonably quick.
b.Activate()
} | [
"func",
"(",
"b",
"*",
"Butler",
")",
"shutdown",
"(",
"err",
"error",
")",
"{",
"log",
".",
"Fields",
"{",
"log",
".",
"ErrorKey",
":",
"err",
",",
"}",
".",
"Debugf",
"(",
"b",
".",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"func",
"(",
")",
"{",
"b",
".",
"shutdownMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"shutdownMu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"b",
".",
"isShutdown",
"{",
"// Already shut down.",
"return",
"\n",
"}",
"\n\n",
"// Signal our streams to shutdown prematurely.",
"close",
"(",
"b",
".",
"streamStopC",
")",
"\n\n",
"b",
".",
"runErr",
"=",
"err",
"\n",
"b",
".",
"isShutdown",
"=",
"true",
"\n",
"}",
"(",
")",
"\n\n",
"// Activate the Butler, if it hasn't already been activated. The Butler will",
"// block pending stream draining, but we've instructed our streams to",
"// shutdown prematurely, so this should be reasonably quick.",
"b",
".",
"Activate",
"(",
")",
"\n",
"}"
] | // shutdown is a goroutine-safe method instructing the Butler to terminate
// with the supplied error code. It may be called more than once, although
// the first supplied error message will be the one returned by Run. | [
"shutdown",
"is",
"a",
"goroutine",
"-",
"safe",
"method",
"instructing",
"the",
"Butler",
"to",
"terminate",
"with",
"the",
"supplied",
"error",
"code",
".",
"It",
"may",
"be",
"called",
"more",
"than",
"once",
"although",
"the",
"first",
"supplied",
"error",
"message",
"will",
"be",
"the",
"one",
"returned",
"by",
"Run",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L672-L697 |
7,980 | luci/luci-go | logdog/client/butler/butler.go | getRunErr | func (b *Butler) getRunErr() error {
b.shutdownMu.Lock()
defer b.shutdownMu.Unlock()
return b.runErr
} | go | func (b *Butler) getRunErr() error {
b.shutdownMu.Lock()
defer b.shutdownMu.Unlock()
return b.runErr
} | [
"func",
"(",
"b",
"*",
"Butler",
")",
"getRunErr",
"(",
")",
"error",
"{",
"b",
".",
"shutdownMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"shutdownMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"b",
".",
"runErr",
"\n",
"}"
] | // Returns the configured Butler error. | [
"Returns",
"the",
"configured",
"Butler",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L700-L704 |
7,981 | luci/luci-go | logdog/client/butler/butler.go | wrapStreamRegistrationCallback | func wrapStreamRegistrationCallback(reg streamRegistrationCallback) streamRegistrationCallback {
if reg == nil {
return reg
}
return func(desc *logpb.LogStreamDescriptor) bundler.StreamChunkCallback {
cb := reg(desc)
switch desc.StreamType {
case logpb.StreamType_TEXT:
return buffered_callback.GetWrappedTextCallback(cb)
case logpb.StreamType_DATAGRAM:
return buffered_callback.GetWrappedDatagramCallback(cb)
default:
return cb
}
}
} | go | func wrapStreamRegistrationCallback(reg streamRegistrationCallback) streamRegistrationCallback {
if reg == nil {
return reg
}
return func(desc *logpb.LogStreamDescriptor) bundler.StreamChunkCallback {
cb := reg(desc)
switch desc.StreamType {
case logpb.StreamType_TEXT:
return buffered_callback.GetWrappedTextCallback(cb)
case logpb.StreamType_DATAGRAM:
return buffered_callback.GetWrappedDatagramCallback(cb)
default:
return cb
}
}
} | [
"func",
"wrapStreamRegistrationCallback",
"(",
"reg",
"streamRegistrationCallback",
")",
"streamRegistrationCallback",
"{",
"if",
"reg",
"==",
"nil",
"{",
"return",
"reg",
"\n",
"}",
"\n",
"return",
"func",
"(",
"desc",
"*",
"logpb",
".",
"LogStreamDescriptor",
")",
"bundler",
".",
"StreamChunkCallback",
"{",
"cb",
":=",
"reg",
"(",
"desc",
")",
"\n",
"switch",
"desc",
".",
"StreamType",
"{",
"case",
"logpb",
".",
"StreamType_TEXT",
":",
"return",
"buffered_callback",
".",
"GetWrappedTextCallback",
"(",
"cb",
")",
"\n",
"case",
"logpb",
".",
"StreamType_DATAGRAM",
":",
"return",
"buffered_callback",
".",
"GetWrappedDatagramCallback",
"(",
"cb",
")",
"\n",
"default",
":",
"return",
"cb",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // wrapStreamRegistrationCallback wraps the given callback to dispatch on the correct stream type. | [
"wrapStreamRegistrationCallback",
"wraps",
"the",
"given",
"callback",
"to",
"dispatch",
"on",
"the",
"correct",
"stream",
"type",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/butler.go#L709-L724 |
7,982 | luci/luci-go | cipd/appengine/impl/model/package.go | PackageKey | func PackageKey(c context.Context, pkg string) *datastore.Key {
return datastore.NewKey(c, "Package", pkg, 0, nil)
} | go | func PackageKey(c context.Context, pkg string) *datastore.Key {
return datastore.NewKey(c, "Package", pkg, 0, nil)
} | [
"func",
"PackageKey",
"(",
"c",
"context",
".",
"Context",
",",
"pkg",
"string",
")",
"*",
"datastore",
".",
"Key",
"{",
"return",
"datastore",
".",
"NewKey",
"(",
"c",
",",
"\"",
"\"",
",",
"pkg",
",",
"0",
",",
"nil",
")",
"\n",
"}"
] | // PackageKey returns a datastore key of some package, given its name. | [
"PackageKey",
"returns",
"a",
"datastore",
"key",
"of",
"some",
"package",
"given",
"its",
"name",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/package.go#L61-L63 |
7,983 | luci/luci-go | cipd/appengine/impl/model/package.go | ListPackages | func ListPackages(c context.Context, prefix string, includeHidden bool) (out []string, err error) {
if prefix, err = common.ValidatePackagePrefix(prefix); err != nil {
return nil, err
}
// Note: __key__ queries are already ordered by key.
q := datastore.NewQuery("Package")
if prefix != "" {
q = q.Gt("__key__", PackageKey(c, prefix+"/\x00"))
q = q.Lt("__key__", PackageKey(c, prefix+"/\xff"))
}
err = datastore.Run(c, q, func(p *Package) error {
// We filter by Hidden manually since not all entities in the datastore have
// it set, so filtering using Eq("Hidden", false) actually skips all
// entities that don't have Hidden field at all.
if !p.Hidden || includeHidden {
out = append(out, p.Name)
}
return nil
})
if err != nil {
return nil, errors.Annotate(err, "failed to query the list of packages").Tag(transient.Tag).Err()
}
return out, nil
} | go | func ListPackages(c context.Context, prefix string, includeHidden bool) (out []string, err error) {
if prefix, err = common.ValidatePackagePrefix(prefix); err != nil {
return nil, err
}
// Note: __key__ queries are already ordered by key.
q := datastore.NewQuery("Package")
if prefix != "" {
q = q.Gt("__key__", PackageKey(c, prefix+"/\x00"))
q = q.Lt("__key__", PackageKey(c, prefix+"/\xff"))
}
err = datastore.Run(c, q, func(p *Package) error {
// We filter by Hidden manually since not all entities in the datastore have
// it set, so filtering using Eq("Hidden", false) actually skips all
// entities that don't have Hidden field at all.
if !p.Hidden || includeHidden {
out = append(out, p.Name)
}
return nil
})
if err != nil {
return nil, errors.Annotate(err, "failed to query the list of packages").Tag(transient.Tag).Err()
}
return out, nil
} | [
"func",
"ListPackages",
"(",
"c",
"context",
".",
"Context",
",",
"prefix",
"string",
",",
"includeHidden",
"bool",
")",
"(",
"out",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"if",
"prefix",
",",
"err",
"=",
"common",
".",
"ValidatePackagePrefix",
"(",
"prefix",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Note: __key__ queries are already ordered by key.",
"q",
":=",
"datastore",
".",
"NewQuery",
"(",
"\"",
"\"",
")",
"\n",
"if",
"prefix",
"!=",
"\"",
"\"",
"{",
"q",
"=",
"q",
".",
"Gt",
"(",
"\"",
"\"",
",",
"PackageKey",
"(",
"c",
",",
"prefix",
"+",
"\"",
"\\x00",
"\"",
")",
")",
"\n",
"q",
"=",
"q",
".",
"Lt",
"(",
"\"",
"\"",
",",
"PackageKey",
"(",
"c",
",",
"prefix",
"+",
"\"",
"\\xff",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"datastore",
".",
"Run",
"(",
"c",
",",
"q",
",",
"func",
"(",
"p",
"*",
"Package",
")",
"error",
"{",
"// We filter by Hidden manually since not all entities in the datastore have",
"// it set, so filtering using Eq(\"Hidden\", false) actually skips all",
"// entities that don't have Hidden field at all.",
"if",
"!",
"p",
".",
"Hidden",
"||",
"includeHidden",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"p",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // ListPackages returns a list of names of packages under the given prefix.
//
// Lists all packages recursively. If there's package named as 'prefix' it is
// NOT included in the result. Only packaged under the prefix are included.
//
// The result is sorted by the package name. Returns only transient errors. | [
"ListPackages",
"returns",
"a",
"list",
"of",
"names",
"of",
"packages",
"under",
"the",
"given",
"prefix",
".",
"Lists",
"all",
"packages",
"recursively",
".",
"If",
"there",
"s",
"package",
"named",
"as",
"prefix",
"it",
"is",
"NOT",
"included",
"in",
"the",
"result",
".",
"Only",
"packaged",
"under",
"the",
"prefix",
"are",
"included",
".",
"The",
"result",
"is",
"sorted",
"by",
"the",
"package",
"name",
".",
"Returns",
"only",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/package.go#L71-L96 |
7,984 | luci/luci-go | cipd/appengine/impl/model/package.go | CheckPackages | func CheckPackages(c context.Context, names []string, includeHidden bool) ([]string, error) {
if len(names) == 0 {
return nil, nil
}
pkgs := make([]*Package, len(names))
for i, n := range names {
pkgs[i] = &Package{Name: n}
}
if err := datastore.Get(c, pkgs); err != nil {
merr, ok := err.(errors.MultiError)
if !ok {
return nil, transient.Tag.Apply(err)
}
existing := pkgs[:0]
for i, pkg := range pkgs {
switch err := merr[i]; {
case err == nil:
existing = append(existing, pkg)
case err != datastore.ErrNoSuchEntity:
return nil, errors.Annotate(err, "failed to fetch %q", pkg.Name).Tag(transient.Tag).Err()
}
}
pkgs = existing
}
out := make([]string, 0, len(pkgs))
for _, p := range pkgs {
if !p.Hidden || includeHidden {
out = append(out, p.Name)
}
}
return out, nil
} | go | func CheckPackages(c context.Context, names []string, includeHidden bool) ([]string, error) {
if len(names) == 0 {
return nil, nil
}
pkgs := make([]*Package, len(names))
for i, n := range names {
pkgs[i] = &Package{Name: n}
}
if err := datastore.Get(c, pkgs); err != nil {
merr, ok := err.(errors.MultiError)
if !ok {
return nil, transient.Tag.Apply(err)
}
existing := pkgs[:0]
for i, pkg := range pkgs {
switch err := merr[i]; {
case err == nil:
existing = append(existing, pkg)
case err != datastore.ErrNoSuchEntity:
return nil, errors.Annotate(err, "failed to fetch %q", pkg.Name).Tag(transient.Tag).Err()
}
}
pkgs = existing
}
out := make([]string, 0, len(pkgs))
for _, p := range pkgs {
if !p.Hidden || includeHidden {
out = append(out, p.Name)
}
}
return out, nil
} | [
"func",
"CheckPackages",
"(",
"c",
"context",
".",
"Context",
",",
"names",
"[",
"]",
"string",
",",
"includeHidden",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"len",
"(",
"names",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"pkgs",
":=",
"make",
"(",
"[",
"]",
"*",
"Package",
",",
"len",
"(",
"names",
")",
")",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"names",
"{",
"pkgs",
"[",
"i",
"]",
"=",
"&",
"Package",
"{",
"Name",
":",
"n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"datastore",
".",
"Get",
"(",
"c",
",",
"pkgs",
")",
";",
"err",
"!=",
"nil",
"{",
"merr",
",",
"ok",
":=",
"err",
".",
"(",
"errors",
".",
"MultiError",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"}",
"\n",
"existing",
":=",
"pkgs",
"[",
":",
"0",
"]",
"\n",
"for",
"i",
",",
"pkg",
":=",
"range",
"pkgs",
"{",
"switch",
"err",
":=",
"merr",
"[",
"i",
"]",
";",
"{",
"case",
"err",
"==",
"nil",
":",
"existing",
"=",
"append",
"(",
"existing",
",",
"pkg",
")",
"\n",
"case",
"err",
"!=",
"datastore",
".",
"ErrNoSuchEntity",
":",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"pkg",
".",
"Name",
")",
".",
"Tag",
"(",
"transient",
".",
"Tag",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"pkgs",
"=",
"existing",
"\n",
"}",
"\n\n",
"out",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"pkgs",
")",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"pkgs",
"{",
"if",
"!",
"p",
".",
"Hidden",
"||",
"includeHidden",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"p",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // CheckPackages given a list of package names returns packages that exist, in
// the order they are listed in the list.
//
// If includeHidden is false, omits hidden packages from the result.
//
// Returns only transient errors. | [
"CheckPackages",
"given",
"a",
"list",
"of",
"package",
"names",
"returns",
"packages",
"that",
"exist",
"in",
"the",
"order",
"they",
"are",
"listed",
"in",
"the",
"list",
".",
"If",
"includeHidden",
"is",
"false",
"omits",
"hidden",
"packages",
"from",
"the",
"result",
".",
"Returns",
"only",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/package.go#L104-L138 |
7,985 | luci/luci-go | cipd/appengine/impl/model/package.go | CheckPackageExists | func CheckPackageExists(c context.Context, pkg string) error {
switch res, err := CheckPackages(c, []string{pkg}, true); {
case err != nil:
return errors.Annotate(err, "failed to check the package presence").Err()
case len(res) == 0:
return errors.Reason("no such package").Tag(grpcutil.NotFoundTag).Err()
default:
return nil
}
} | go | func CheckPackageExists(c context.Context, pkg string) error {
switch res, err := CheckPackages(c, []string{pkg}, true); {
case err != nil:
return errors.Annotate(err, "failed to check the package presence").Err()
case len(res) == 0:
return errors.Reason("no such package").Tag(grpcutil.NotFoundTag).Err()
default:
return nil
}
} | [
"func",
"CheckPackageExists",
"(",
"c",
"context",
".",
"Context",
",",
"pkg",
"string",
")",
"error",
"{",
"switch",
"res",
",",
"err",
":=",
"CheckPackages",
"(",
"c",
",",
"[",
"]",
"string",
"{",
"pkg",
"}",
",",
"true",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"case",
"len",
"(",
"res",
")",
"==",
"0",
":",
"return",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
")",
".",
"Tag",
"(",
"grpcutil",
".",
"NotFoundTag",
")",
".",
"Err",
"(",
")",
"\n",
"default",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // CheckPackageExists verifies the package exists.
//
// Returns gRPC-tagged NotFound error if there's no such package. | [
"CheckPackageExists",
"verifies",
"the",
"package",
"exists",
".",
"Returns",
"gRPC",
"-",
"tagged",
"NotFound",
"error",
"if",
"there",
"s",
"no",
"such",
"package",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/package.go#L143-L152 |
7,986 | luci/luci-go | cipd/appengine/impl/model/package.go | SetPackageHidden | func SetPackageHidden(c context.Context, pkg string, hidden bool) error {
return Txn(c, "SetPackageHidden", func(c context.Context) error {
p := &Package{Name: pkg}
switch err := datastore.Get(c, p); {
case err == datastore.ErrNoSuchEntity:
return err
case err != nil:
return transient.Tag.Apply(err)
case p.Hidden == hidden:
return nil
}
p.Hidden = hidden
if err := datastore.Put(c, p); err != nil {
return transient.Tag.Apply(err)
}
ev := api.EventKind_PACKAGE_HIDDEN
if !hidden {
ev = api.EventKind_PACKAGE_UNHIDDEN
}
return EmitEvent(c, &api.Event{Kind: ev, Package: pkg})
})
} | go | func SetPackageHidden(c context.Context, pkg string, hidden bool) error {
return Txn(c, "SetPackageHidden", func(c context.Context) error {
p := &Package{Name: pkg}
switch err := datastore.Get(c, p); {
case err == datastore.ErrNoSuchEntity:
return err
case err != nil:
return transient.Tag.Apply(err)
case p.Hidden == hidden:
return nil
}
p.Hidden = hidden
if err := datastore.Put(c, p); err != nil {
return transient.Tag.Apply(err)
}
ev := api.EventKind_PACKAGE_HIDDEN
if !hidden {
ev = api.EventKind_PACKAGE_UNHIDDEN
}
return EmitEvent(c, &api.Event{Kind: ev, Package: pkg})
})
} | [
"func",
"SetPackageHidden",
"(",
"c",
"context",
".",
"Context",
",",
"pkg",
"string",
",",
"hidden",
"bool",
")",
"error",
"{",
"return",
"Txn",
"(",
"c",
",",
"\"",
"\"",
",",
"func",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"p",
":=",
"&",
"Package",
"{",
"Name",
":",
"pkg",
"}",
"\n",
"switch",
"err",
":=",
"datastore",
".",
"Get",
"(",
"c",
",",
"p",
")",
";",
"{",
"case",
"err",
"==",
"datastore",
".",
"ErrNoSuchEntity",
":",
"return",
"err",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"case",
"p",
".",
"Hidden",
"==",
"hidden",
":",
"return",
"nil",
"\n",
"}",
"\n\n",
"p",
".",
"Hidden",
"=",
"hidden",
"\n",
"if",
"err",
":=",
"datastore",
".",
"Put",
"(",
"c",
",",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"ev",
":=",
"api",
".",
"EventKind_PACKAGE_HIDDEN",
"\n",
"if",
"!",
"hidden",
"{",
"ev",
"=",
"api",
".",
"EventKind_PACKAGE_UNHIDDEN",
"\n",
"}",
"\n",
"return",
"EmitEvent",
"(",
"c",
",",
"&",
"api",
".",
"Event",
"{",
"Kind",
":",
"ev",
",",
"Package",
":",
"pkg",
"}",
")",
"\n",
"}",
")",
"\n",
"}"
] | // SetPackageHidden updates Hidden field of the package.
//
// If the package is missing returns datastore.ErrNoSuchEntity. All other errors
// are transient. | [
"SetPackageHidden",
"updates",
"Hidden",
"field",
"of",
"the",
"package",
".",
"If",
"the",
"package",
"is",
"missing",
"returns",
"datastore",
".",
"ErrNoSuchEntity",
".",
"All",
"other",
"errors",
"are",
"transient",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/package.go#L158-L181 |
7,987 | luci/luci-go | milo/buildsource/buildbucket/build.go | BuildAddress | func BuildAddress(build *buildbucketpb.Build) string {
if build == nil {
return ""
}
num := strconv.FormatInt(build.Id, 10)
if build.Number != 0 {
num = strconv.FormatInt(int64(build.Number), 10)
}
b := build.Builder
return fmt.Sprintf("luci.%s.%s/%s/%s", b.Project, b.Bucket, b.Builder, num)
} | go | func BuildAddress(build *buildbucketpb.Build) string {
if build == nil {
return ""
}
num := strconv.FormatInt(build.Id, 10)
if build.Number != 0 {
num = strconv.FormatInt(int64(build.Number), 10)
}
b := build.Builder
return fmt.Sprintf("luci.%s.%s/%s/%s", b.Project, b.Bucket, b.Builder, num)
} | [
"func",
"BuildAddress",
"(",
"build",
"*",
"buildbucketpb",
".",
"Build",
")",
"string",
"{",
"if",
"build",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"num",
":=",
"strconv",
".",
"FormatInt",
"(",
"build",
".",
"Id",
",",
"10",
")",
"\n",
"if",
"build",
".",
"Number",
"!=",
"0",
"{",
"num",
"=",
"strconv",
".",
"FormatInt",
"(",
"int64",
"(",
"build",
".",
"Number",
")",
",",
"10",
")",
"\n",
"}",
"\n",
"b",
":=",
"build",
".",
"Builder",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"Project",
",",
"b",
".",
"Bucket",
",",
"b",
".",
"Builder",
",",
"num",
")",
"\n",
"}"
] | // BuildAddress constructs the build address of a buildbucketpb.Build.
// This is used as the key for the BuildSummary entity. | [
"BuildAddress",
"constructs",
"the",
"build",
"address",
"of",
"a",
"buildbucketpb",
".",
"Build",
".",
"This",
"is",
"used",
"as",
"the",
"key",
"for",
"the",
"BuildSummary",
"entity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L57-L67 |
7,988 | luci/luci-go | milo/buildsource/buildbucket/build.go | GetBuildSummary | func GetBuildSummary(c context.Context, id int64) (*model.BuildSummary, error) {
// The host is set to prod because buildbot is hardcoded to talk to prod.
uri := fmt.Sprintf("buildbucket://cr-buildbucket.appspot.com/build/%d", id)
bs := make([]*model.BuildSummary, 0, 1)
q := datastore.NewQuery("BuildSummary").Eq("ContextURI", uri).Limit(1)
switch err := datastore.GetAll(c, q, &bs); {
case err != nil:
return nil, common.ReplaceNSEWith(err.(errors.MultiError), ErrNotFound)
case len(bs) == 0:
return nil, ErrNotFound
default:
return bs[0], nil
}
} | go | func GetBuildSummary(c context.Context, id int64) (*model.BuildSummary, error) {
// The host is set to prod because buildbot is hardcoded to talk to prod.
uri := fmt.Sprintf("buildbucket://cr-buildbucket.appspot.com/build/%d", id)
bs := make([]*model.BuildSummary, 0, 1)
q := datastore.NewQuery("BuildSummary").Eq("ContextURI", uri).Limit(1)
switch err := datastore.GetAll(c, q, &bs); {
case err != nil:
return nil, common.ReplaceNSEWith(err.(errors.MultiError), ErrNotFound)
case len(bs) == 0:
return nil, ErrNotFound
default:
return bs[0], nil
}
} | [
"func",
"GetBuildSummary",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"int64",
")",
"(",
"*",
"model",
".",
"BuildSummary",
",",
"error",
")",
"{",
"// The host is set to prod because buildbot is hardcoded to talk to prod.",
"uri",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"bs",
":=",
"make",
"(",
"[",
"]",
"*",
"model",
".",
"BuildSummary",
",",
"0",
",",
"1",
")",
"\n",
"q",
":=",
"datastore",
".",
"NewQuery",
"(",
"\"",
"\"",
")",
".",
"Eq",
"(",
"\"",
"\"",
",",
"uri",
")",
".",
"Limit",
"(",
"1",
")",
"\n",
"switch",
"err",
":=",
"datastore",
".",
"GetAll",
"(",
"c",
",",
"q",
",",
"&",
"bs",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"common",
".",
"ReplaceNSEWith",
"(",
"err",
".",
"(",
"errors",
".",
"MultiError",
")",
",",
"ErrNotFound",
")",
"\n",
"case",
"len",
"(",
"bs",
")",
"==",
"0",
":",
"return",
"nil",
",",
"ErrNotFound",
"\n",
"default",
":",
"return",
"bs",
"[",
"0",
"]",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // GetBuildSummary fetches a build summary where the Context URI matches the
// given address. | [
"GetBuildSummary",
"fetches",
"a",
"build",
"summary",
"where",
"the",
"Context",
"URI",
"matches",
"the",
"given",
"address",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L146-L159 |
7,989 | luci/luci-go | milo/buildsource/buildbucket/build.go | getBlame | func getBlame(c context.Context, host string, b *buildbucketpb.Build) ([]*ui.Commit, error) {
commit := b.GetInput().GetGitilesCommit()
// No commit? No blamelist.
if commit == nil {
return nil, nil
}
// TODO(hinoka): This converts a buildbucketpb.Commit into a string
// and back into a buildbucketpb.Commit. That's a bit silly.
return simplisticBlamelist(c, &model.BuildSummary{
BuildKey: MakeBuildKey(c, host, BuildAddress(b)),
BuildSet: []string{protoutil.GitilesBuildSet(commit)},
BuilderID: BuilderID{BuilderID: *b.Builder}.String(),
})
} | go | func getBlame(c context.Context, host string, b *buildbucketpb.Build) ([]*ui.Commit, error) {
commit := b.GetInput().GetGitilesCommit()
// No commit? No blamelist.
if commit == nil {
return nil, nil
}
// TODO(hinoka): This converts a buildbucketpb.Commit into a string
// and back into a buildbucketpb.Commit. That's a bit silly.
return simplisticBlamelist(c, &model.BuildSummary{
BuildKey: MakeBuildKey(c, host, BuildAddress(b)),
BuildSet: []string{protoutil.GitilesBuildSet(commit)},
BuilderID: BuilderID{BuilderID: *b.Builder}.String(),
})
} | [
"func",
"getBlame",
"(",
"c",
"context",
".",
"Context",
",",
"host",
"string",
",",
"b",
"*",
"buildbucketpb",
".",
"Build",
")",
"(",
"[",
"]",
"*",
"ui",
".",
"Commit",
",",
"error",
")",
"{",
"commit",
":=",
"b",
".",
"GetInput",
"(",
")",
".",
"GetGitilesCommit",
"(",
")",
"\n",
"// No commit? No blamelist.",
"if",
"commit",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"// TODO(hinoka): This converts a buildbucketpb.Commit into a string",
"// and back into a buildbucketpb.Commit. That's a bit silly.",
"return",
"simplisticBlamelist",
"(",
"c",
",",
"&",
"model",
".",
"BuildSummary",
"{",
"BuildKey",
":",
"MakeBuildKey",
"(",
"c",
",",
"host",
",",
"BuildAddress",
"(",
"b",
")",
")",
",",
"BuildSet",
":",
"[",
"]",
"string",
"{",
"protoutil",
".",
"GitilesBuildSet",
"(",
"commit",
")",
"}",
",",
"BuilderID",
":",
"BuilderID",
"{",
"BuilderID",
":",
"*",
"b",
".",
"Builder",
"}",
".",
"String",
"(",
")",
",",
"}",
")",
"\n",
"}"
] | // getBlame fetches blame information from Gitiles.
// This requires the BuildSummary to be indexed in Milo. | [
"getBlame",
"fetches",
"blame",
"information",
"from",
"Gitiles",
".",
"This",
"requires",
"the",
"BuildSummary",
"to",
"be",
"indexed",
"in",
"Milo",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L163-L176 |
7,990 | luci/luci-go | milo/buildsource/buildbucket/build.go | getBugLink | func getBugLink(c *router.Context, b *buildbucketpb.Build) (string, error) {
project, err := common.GetProject(c.Context, b.Builder.GetProject())
if err != nil || proto.Equal(&project.BuildBugTemplate, &config.BugTemplate{}) {
return "", err
}
builderPath := fmt.Sprintf("/p/%s/builders/%s/%s", b.Builder.GetProject(), b.Builder.GetBucket(), b.Builder.GetBuilder())
buildURL, err := c.Request.URL.Parse(builderPath + "/" + c.Params.ByName("numberOrId"))
if err != nil {
return "", errors.Annotate(err, "Unable to make build URL for build bug link.").Err()
}
builderURL, err := c.Request.URL.Parse(builderPath)
if err != nil {
return "", errors.Annotate(err, "Unable to make builder URL for build bug link.").Err()
}
return MakeBuildBugLink(&project.BuildBugTemplate, map[string]interface{}{
"Build": b,
"MiloBuildUrl": buildURL,
"MiloBuilderUrl": builderURL,
})
} | go | func getBugLink(c *router.Context, b *buildbucketpb.Build) (string, error) {
project, err := common.GetProject(c.Context, b.Builder.GetProject())
if err != nil || proto.Equal(&project.BuildBugTemplate, &config.BugTemplate{}) {
return "", err
}
builderPath := fmt.Sprintf("/p/%s/builders/%s/%s", b.Builder.GetProject(), b.Builder.GetBucket(), b.Builder.GetBuilder())
buildURL, err := c.Request.URL.Parse(builderPath + "/" + c.Params.ByName("numberOrId"))
if err != nil {
return "", errors.Annotate(err, "Unable to make build URL for build bug link.").Err()
}
builderURL, err := c.Request.URL.Parse(builderPath)
if err != nil {
return "", errors.Annotate(err, "Unable to make builder URL for build bug link.").Err()
}
return MakeBuildBugLink(&project.BuildBugTemplate, map[string]interface{}{
"Build": b,
"MiloBuildUrl": buildURL,
"MiloBuilderUrl": builderURL,
})
} | [
"func",
"getBugLink",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"b",
"*",
"buildbucketpb",
".",
"Build",
")",
"(",
"string",
",",
"error",
")",
"{",
"project",
",",
"err",
":=",
"common",
".",
"GetProject",
"(",
"c",
".",
"Context",
",",
"b",
".",
"Builder",
".",
"GetProject",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"proto",
".",
"Equal",
"(",
"&",
"project",
".",
"BuildBugTemplate",
",",
"&",
"config",
".",
"BugTemplate",
"{",
"}",
")",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"builderPath",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"Builder",
".",
"GetProject",
"(",
")",
",",
"b",
".",
"Builder",
".",
"GetBucket",
"(",
")",
",",
"b",
".",
"Builder",
".",
"GetBuilder",
"(",
")",
")",
"\n",
"buildURL",
",",
"err",
":=",
"c",
".",
"Request",
".",
"URL",
".",
"Parse",
"(",
"builderPath",
"+",
"\"",
"\"",
"+",
"c",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"builderURL",
",",
"err",
":=",
"c",
".",
"Request",
".",
"URL",
".",
"Parse",
"(",
"builderPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"MakeBuildBugLink",
"(",
"&",
"project",
".",
"BuildBugTemplate",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"b",
",",
"\"",
"\"",
":",
"buildURL",
",",
"\"",
"\"",
":",
"builderURL",
",",
"}",
")",
"\n",
"}"
] | // getBugLink attempts to formulate and return the build page bug link
// for the given build. | [
"getBugLink",
"attempts",
"to",
"formulate",
"and",
"return",
"the",
"build",
"page",
"bug",
"link",
"for",
"the",
"given",
"build",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L180-L201 |
7,991 | luci/luci-go | milo/buildsource/buildbucket/build.go | searchBuildset | func searchBuildset(buildset string, fields *field_mask.FieldMask) *buildbucketpb.SearchBuildsRequest {
return &buildbucketpb.SearchBuildsRequest{
Predicate: &buildbucketpb.BuildPredicate{
Tags: []*buildbucketpb.StringPair{{Key: "buildset", Value: buildset}},
},
Fields: fields,
PageSize: 1000,
}
} | go | func searchBuildset(buildset string, fields *field_mask.FieldMask) *buildbucketpb.SearchBuildsRequest {
return &buildbucketpb.SearchBuildsRequest{
Predicate: &buildbucketpb.BuildPredicate{
Tags: []*buildbucketpb.StringPair{{Key: "buildset", Value: buildset}},
},
Fields: fields,
PageSize: 1000,
}
} | [
"func",
"searchBuildset",
"(",
"buildset",
"string",
",",
"fields",
"*",
"field_mask",
".",
"FieldMask",
")",
"*",
"buildbucketpb",
".",
"SearchBuildsRequest",
"{",
"return",
"&",
"buildbucketpb",
".",
"SearchBuildsRequest",
"{",
"Predicate",
":",
"&",
"buildbucketpb",
".",
"BuildPredicate",
"{",
"Tags",
":",
"[",
"]",
"*",
"buildbucketpb",
".",
"StringPair",
"{",
"{",
"Key",
":",
"\"",
"\"",
",",
"Value",
":",
"buildset",
"}",
"}",
",",
"}",
",",
"Fields",
":",
"fields",
",",
"PageSize",
":",
"1000",
",",
"}",
"\n",
"}"
] | // searchBuildset creates a searchBuildsRequest that looks for a buildset tag. | [
"searchBuildset",
"creates",
"a",
"searchBuildsRequest",
"that",
"looks",
"for",
"a",
"buildset",
"tag",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L204-L212 |
7,992 | luci/luci-go | milo/buildsource/buildbucket/build.go | getRelatedBuilds | func getRelatedBuilds(c context.Context, client buildbucketpb.BuildsClient, b *buildbucketpb.Build) ([]*ui.Build, error) {
var bs []string
for _, buildset := range protoutil.BuildSets(b) {
// HACK(hinoka): Remove the commit/git/ buildsets because we know they're redundant
// with the commit/gitiles/ buildsets, and we don't need to ask Buildbucket twice.
if strings.HasPrefix(buildset, "commit/git/") {
continue
}
bs = append(bs, buildset)
}
if len(bs) == 0 {
// No buildset? No builds.
return nil, nil
}
// Do the search request.
// Use multiple requests instead of a single batch request.
// A single large request is CPU bound to a single GAE instance on the buildbucket side.
// Multiple requests allows the use of multiple GAE instances, therefore more parallelism.
resps := make([]*buildbucketpb.SearchBuildsResponse, len(bs))
if err := parallel.FanOutIn(func(ch chan<- func() error) {
for i, buildset := range bs {
i := i
buildset := buildset
ch <- func() (err error) {
logging.Debugf(c, "Searching for %s (%d)", buildset, i)
resps[i], err = client.SearchBuilds(c, searchBuildset(buildset, summaryBuildsMask))
return
}
}
}); err != nil {
return nil, err
}
// Dedupe builds.
// It's possible since we've made multiple requests that we got back the same builds
// multiple times.
seen := map[int64]bool{} // set of build IDs.
result := []*ui.Build{}
for _, resp := range resps {
for _, rb := range resp.GetBuilds() {
if seen[rb.Id] {
continue
}
seen[rb.Id] = true
result = append(result, &ui.Build{rb})
}
}
// Sort builds by ID.
sort.Slice(result, func(i, j int) bool { return result[i].Id < result[j].Id })
return result, nil
} | go | func getRelatedBuilds(c context.Context, client buildbucketpb.BuildsClient, b *buildbucketpb.Build) ([]*ui.Build, error) {
var bs []string
for _, buildset := range protoutil.BuildSets(b) {
// HACK(hinoka): Remove the commit/git/ buildsets because we know they're redundant
// with the commit/gitiles/ buildsets, and we don't need to ask Buildbucket twice.
if strings.HasPrefix(buildset, "commit/git/") {
continue
}
bs = append(bs, buildset)
}
if len(bs) == 0 {
// No buildset? No builds.
return nil, nil
}
// Do the search request.
// Use multiple requests instead of a single batch request.
// A single large request is CPU bound to a single GAE instance on the buildbucket side.
// Multiple requests allows the use of multiple GAE instances, therefore more parallelism.
resps := make([]*buildbucketpb.SearchBuildsResponse, len(bs))
if err := parallel.FanOutIn(func(ch chan<- func() error) {
for i, buildset := range bs {
i := i
buildset := buildset
ch <- func() (err error) {
logging.Debugf(c, "Searching for %s (%d)", buildset, i)
resps[i], err = client.SearchBuilds(c, searchBuildset(buildset, summaryBuildsMask))
return
}
}
}); err != nil {
return nil, err
}
// Dedupe builds.
// It's possible since we've made multiple requests that we got back the same builds
// multiple times.
seen := map[int64]bool{} // set of build IDs.
result := []*ui.Build{}
for _, resp := range resps {
for _, rb := range resp.GetBuilds() {
if seen[rb.Id] {
continue
}
seen[rb.Id] = true
result = append(result, &ui.Build{rb})
}
}
// Sort builds by ID.
sort.Slice(result, func(i, j int) bool { return result[i].Id < result[j].Id })
return result, nil
} | [
"func",
"getRelatedBuilds",
"(",
"c",
"context",
".",
"Context",
",",
"client",
"buildbucketpb",
".",
"BuildsClient",
",",
"b",
"*",
"buildbucketpb",
".",
"Build",
")",
"(",
"[",
"]",
"*",
"ui",
".",
"Build",
",",
"error",
")",
"{",
"var",
"bs",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"buildset",
":=",
"range",
"protoutil",
".",
"BuildSets",
"(",
"b",
")",
"{",
"// HACK(hinoka): Remove the commit/git/ buildsets because we know they're redundant",
"// with the commit/gitiles/ buildsets, and we don't need to ask Buildbucket twice.",
"if",
"strings",
".",
"HasPrefix",
"(",
"buildset",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"bs",
"=",
"append",
"(",
"bs",
",",
"buildset",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"bs",
")",
"==",
"0",
"{",
"// No buildset? No builds.",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// Do the search request.",
"// Use multiple requests instead of a single batch request.",
"// A single large request is CPU bound to a single GAE instance on the buildbucket side.",
"// Multiple requests allows the use of multiple GAE instances, therefore more parallelism.",
"resps",
":=",
"make",
"(",
"[",
"]",
"*",
"buildbucketpb",
".",
"SearchBuildsResponse",
",",
"len",
"(",
"bs",
")",
")",
"\n",
"if",
"err",
":=",
"parallel",
".",
"FanOutIn",
"(",
"func",
"(",
"ch",
"chan",
"<-",
"func",
"(",
")",
"error",
")",
"{",
"for",
"i",
",",
"buildset",
":=",
"range",
"bs",
"{",
"i",
":=",
"i",
"\n",
"buildset",
":=",
"buildset",
"\n",
"ch",
"<-",
"func",
"(",
")",
"(",
"err",
"error",
")",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"buildset",
",",
"i",
")",
"\n",
"resps",
"[",
"i",
"]",
",",
"err",
"=",
"client",
".",
"SearchBuilds",
"(",
"c",
",",
"searchBuildset",
"(",
"buildset",
",",
"summaryBuildsMask",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Dedupe builds.",
"// It's possible since we've made multiple requests that we got back the same builds",
"// multiple times.",
"seen",
":=",
"map",
"[",
"int64",
"]",
"bool",
"{",
"}",
"// set of build IDs.",
"\n",
"result",
":=",
"[",
"]",
"*",
"ui",
".",
"Build",
"{",
"}",
"\n",
"for",
"_",
",",
"resp",
":=",
"range",
"resps",
"{",
"for",
"_",
",",
"rb",
":=",
"range",
"resp",
".",
"GetBuilds",
"(",
")",
"{",
"if",
"seen",
"[",
"rb",
".",
"Id",
"]",
"{",
"continue",
"\n",
"}",
"\n",
"seen",
"[",
"rb",
".",
"Id",
"]",
"=",
"true",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"&",
"ui",
".",
"Build",
"{",
"rb",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Sort builds by ID.",
"sort",
".",
"Slice",
"(",
"result",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"result",
"[",
"i",
"]",
".",
"Id",
"<",
"result",
"[",
"j",
"]",
".",
"Id",
"}",
")",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // getRelatedBuilds fetches build summaries of builds with the same buildset as b. | [
"getRelatedBuilds",
"fetches",
"build",
"summaries",
"of",
"builds",
"with",
"the",
"same",
"buildset",
"as",
"b",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L229-L282 |
7,993 | luci/luci-go | milo/buildsource/buildbucket/build.go | GetBuilderID | func GetBuilderID(c context.Context, id int64) (builder *buildbucketpb.BuilderID, number int32, err error) {
host, err := getHost(c)
if err != nil {
return
}
client, err := buildbucketClient(c, host, auth.AsUser)
if err != nil {
return
}
br, err := client.GetBuild(c, &buildbucketpb.GetBuildRequest{
Id: id,
Fields: builderIDMask,
})
switch grpcutil.Code(err) {
case codes.OK:
builder = br.Builder
number = br.Number
case codes.NotFound:
if auth.CurrentIdentity(c) == identity.AnonymousIdentity {
err = ErrNotLoggedIn
return
}
fallthrough
case codes.PermissionDenied:
err = ErrNotFound
}
return
} | go | func GetBuilderID(c context.Context, id int64) (builder *buildbucketpb.BuilderID, number int32, err error) {
host, err := getHost(c)
if err != nil {
return
}
client, err := buildbucketClient(c, host, auth.AsUser)
if err != nil {
return
}
br, err := client.GetBuild(c, &buildbucketpb.GetBuildRequest{
Id: id,
Fields: builderIDMask,
})
switch grpcutil.Code(err) {
case codes.OK:
builder = br.Builder
number = br.Number
case codes.NotFound:
if auth.CurrentIdentity(c) == identity.AnonymousIdentity {
err = ErrNotLoggedIn
return
}
fallthrough
case codes.PermissionDenied:
err = ErrNotFound
}
return
} | [
"func",
"GetBuilderID",
"(",
"c",
"context",
".",
"Context",
",",
"id",
"int64",
")",
"(",
"builder",
"*",
"buildbucketpb",
".",
"BuilderID",
",",
"number",
"int32",
",",
"err",
"error",
")",
"{",
"host",
",",
"err",
":=",
"getHost",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"client",
",",
"err",
":=",
"buildbucketClient",
"(",
"c",
",",
"host",
",",
"auth",
".",
"AsUser",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"br",
",",
"err",
":=",
"client",
".",
"GetBuild",
"(",
"c",
",",
"&",
"buildbucketpb",
".",
"GetBuildRequest",
"{",
"Id",
":",
"id",
",",
"Fields",
":",
"builderIDMask",
",",
"}",
")",
"\n",
"switch",
"grpcutil",
".",
"Code",
"(",
"err",
")",
"{",
"case",
"codes",
".",
"OK",
":",
"builder",
"=",
"br",
".",
"Builder",
"\n",
"number",
"=",
"br",
".",
"Number",
"\n",
"case",
"codes",
".",
"NotFound",
":",
"if",
"auth",
".",
"CurrentIdentity",
"(",
"c",
")",
"==",
"identity",
".",
"AnonymousIdentity",
"{",
"err",
"=",
"ErrNotLoggedIn",
"\n",
"return",
"\n",
"}",
"\n",
"fallthrough",
"\n",
"case",
"codes",
".",
"PermissionDenied",
":",
"err",
"=",
"ErrNotFound",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // GetBuilderID returns the builder, and maybe the build number, for a build id. | [
"GetBuilderID",
"returns",
"the",
"builder",
"and",
"maybe",
"the",
"build",
"number",
"for",
"a",
"build",
"id",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L292-L319 |
7,994 | luci/luci-go | milo/buildsource/buildbucket/build.go | GetBuildPage | func GetBuildPage(ctx *router.Context, br buildbucketpb.GetBuildRequest, forceBlamelist bool) (*ui.BuildPage, error) {
c := ctx.Context
host, err := getHost(c)
if err != nil {
return nil, err
}
client, err := buildbucketClient(c, host, auth.AsUser)
if err != nil {
return nil, err
}
var b *buildbucketpb.Build
var relatedBuilds []*ui.Build
var blame []*ui.Commit
var blameErr error
if err = parallel.FanOutIn(func(ch chan<- func() error) {
ch <- func() (err error) {
fullbr := br // Copy request
fullbr.Fields = fullBuildMask
b, err = client.GetBuild(c, &fullbr)
return common.TagGRPC(c, err)
}
// Fetch a small build with just a tiny bit of information.
// We use this to get the Gitiles tag so that we can fetch
// related builds and blamelist in parallel.
smallbr := br // Copy request
smallbr.Fields = tagsAndGitilesMask
sb, err := client.GetBuild(c, &smallbr)
if err != nil {
return
}
ch <- func() (err error) {
relatedBuilds, err = getRelatedBuilds(c, client, sb)
return
}
ch <- func() error {
timeout := 1 * time.Second
if forceBlamelist {
timeout = 55 * time.Second
}
nc, cancel := context.WithTimeout(c, timeout)
defer cancel()
blame, blameErr = getBlame(nc, host, sb)
return nil
}
}); err != nil {
return nil, err
}
link, err := getBugLink(ctx, b)
logging.Infof(c, "Got all the things")
return &ui.BuildPage{
Build: ui.Build{b},
Blame: blame,
RelatedBuilds: relatedBuilds,
BuildBugLink: link,
BuildbucketHost: host,
Now: clock.Now(c),
BlamelistError: blameErr,
ForcedBlamelist: forceBlamelist,
}, err
} | go | func GetBuildPage(ctx *router.Context, br buildbucketpb.GetBuildRequest, forceBlamelist bool) (*ui.BuildPage, error) {
c := ctx.Context
host, err := getHost(c)
if err != nil {
return nil, err
}
client, err := buildbucketClient(c, host, auth.AsUser)
if err != nil {
return nil, err
}
var b *buildbucketpb.Build
var relatedBuilds []*ui.Build
var blame []*ui.Commit
var blameErr error
if err = parallel.FanOutIn(func(ch chan<- func() error) {
ch <- func() (err error) {
fullbr := br // Copy request
fullbr.Fields = fullBuildMask
b, err = client.GetBuild(c, &fullbr)
return common.TagGRPC(c, err)
}
// Fetch a small build with just a tiny bit of information.
// We use this to get the Gitiles tag so that we can fetch
// related builds and blamelist in parallel.
smallbr := br // Copy request
smallbr.Fields = tagsAndGitilesMask
sb, err := client.GetBuild(c, &smallbr)
if err != nil {
return
}
ch <- func() (err error) {
relatedBuilds, err = getRelatedBuilds(c, client, sb)
return
}
ch <- func() error {
timeout := 1 * time.Second
if forceBlamelist {
timeout = 55 * time.Second
}
nc, cancel := context.WithTimeout(c, timeout)
defer cancel()
blame, blameErr = getBlame(nc, host, sb)
return nil
}
}); err != nil {
return nil, err
}
link, err := getBugLink(ctx, b)
logging.Infof(c, "Got all the things")
return &ui.BuildPage{
Build: ui.Build{b},
Blame: blame,
RelatedBuilds: relatedBuilds,
BuildBugLink: link,
BuildbucketHost: host,
Now: clock.Now(c),
BlamelistError: blameErr,
ForcedBlamelist: forceBlamelist,
}, err
} | [
"func",
"GetBuildPage",
"(",
"ctx",
"*",
"router",
".",
"Context",
",",
"br",
"buildbucketpb",
".",
"GetBuildRequest",
",",
"forceBlamelist",
"bool",
")",
"(",
"*",
"ui",
".",
"BuildPage",
",",
"error",
")",
"{",
"c",
":=",
"ctx",
".",
"Context",
"\n",
"host",
",",
"err",
":=",
"getHost",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"client",
",",
"err",
":=",
"buildbucketClient",
"(",
"c",
",",
"host",
",",
"auth",
".",
"AsUser",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"b",
"*",
"buildbucketpb",
".",
"Build",
"\n",
"var",
"relatedBuilds",
"[",
"]",
"*",
"ui",
".",
"Build",
"\n",
"var",
"blame",
"[",
"]",
"*",
"ui",
".",
"Commit",
"\n",
"var",
"blameErr",
"error",
"\n",
"if",
"err",
"=",
"parallel",
".",
"FanOutIn",
"(",
"func",
"(",
"ch",
"chan",
"<-",
"func",
"(",
")",
"error",
")",
"{",
"ch",
"<-",
"func",
"(",
")",
"(",
"err",
"error",
")",
"{",
"fullbr",
":=",
"br",
"// Copy request",
"\n",
"fullbr",
".",
"Fields",
"=",
"fullBuildMask",
"\n",
"b",
",",
"err",
"=",
"client",
".",
"GetBuild",
"(",
"c",
",",
"&",
"fullbr",
")",
"\n",
"return",
"common",
".",
"TagGRPC",
"(",
"c",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Fetch a small build with just a tiny bit of information.",
"// We use this to get the Gitiles tag so that we can fetch",
"// related builds and blamelist in parallel.",
"smallbr",
":=",
"br",
"// Copy request",
"\n",
"smallbr",
".",
"Fields",
"=",
"tagsAndGitilesMask",
"\n",
"sb",
",",
"err",
":=",
"client",
".",
"GetBuild",
"(",
"c",
",",
"&",
"smallbr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"ch",
"<-",
"func",
"(",
")",
"(",
"err",
"error",
")",
"{",
"relatedBuilds",
",",
"err",
"=",
"getRelatedBuilds",
"(",
"c",
",",
"client",
",",
"sb",
")",
"\n",
"return",
"\n",
"}",
"\n",
"ch",
"<-",
"func",
"(",
")",
"error",
"{",
"timeout",
":=",
"1",
"*",
"time",
".",
"Second",
"\n",
"if",
"forceBlamelist",
"{",
"timeout",
"=",
"55",
"*",
"time",
".",
"Second",
"\n",
"}",
"\n",
"nc",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"c",
",",
"timeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"blame",
",",
"blameErr",
"=",
"getBlame",
"(",
"nc",
",",
"host",
",",
"sb",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"link",
",",
"err",
":=",
"getBugLink",
"(",
"ctx",
",",
"b",
")",
"\n",
"logging",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"&",
"ui",
".",
"BuildPage",
"{",
"Build",
":",
"ui",
".",
"Build",
"{",
"b",
"}",
",",
"Blame",
":",
"blame",
",",
"RelatedBuilds",
":",
"relatedBuilds",
",",
"BuildBugLink",
":",
"link",
",",
"BuildbucketHost",
":",
"host",
",",
"Now",
":",
"clock",
".",
"Now",
"(",
"c",
")",
",",
"BlamelistError",
":",
"blameErr",
",",
"ForcedBlamelist",
":",
"forceBlamelist",
",",
"}",
",",
"err",
"\n",
"}"
] | // GetBuildPage fetches the full set of information for a Milo build page from Buildbucket.
// Including the blamelist and other auxiliary information. | [
"GetBuildPage",
"fetches",
"the",
"full",
"set",
"of",
"information",
"for",
"a",
"Milo",
"build",
"page",
"from",
"Buildbucket",
".",
"Including",
"the",
"blamelist",
"and",
"other",
"auxiliary",
"information",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/build.go#L354-L415 |
7,995 | luci/luci-go | cipd/client/cipd/internal/instancecache.go | NewInstanceCache | func NewInstanceCache(fs fs.FileSystem) *InstanceCache {
return &InstanceCache{
fs: fs,
maxSize: instanceCacheMaxSize,
maxAge: instanceCacheMaxAge,
}
} | go | func NewInstanceCache(fs fs.FileSystem) *InstanceCache {
return &InstanceCache{
fs: fs,
maxSize: instanceCacheMaxSize,
maxAge: instanceCacheMaxAge,
}
} | [
"func",
"NewInstanceCache",
"(",
"fs",
"fs",
".",
"FileSystem",
")",
"*",
"InstanceCache",
"{",
"return",
"&",
"InstanceCache",
"{",
"fs",
":",
"fs",
",",
"maxSize",
":",
"instanceCacheMaxSize",
",",
"maxAge",
":",
"instanceCacheMaxAge",
",",
"}",
"\n",
"}"
] | // NewInstanceCache initializes InstanceCache.
//
// fs will be the root of the cache. | [
"NewInstanceCache",
"initializes",
"InstanceCache",
".",
"fs",
"will",
"be",
"the",
"root",
"of",
"the",
"cache",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L75-L81 |
7,996 | luci/luci-go | cipd/client/cipd/internal/instancecache.go | Close | func (f *cacheFile) Close(ctx context.Context, corrupt bool) error {
var err error
if err = f.File.Close(); err != nil && err != os.ErrClosed {
corruptText := ""
if corrupt {
corruptText = " corrupt"
}
logging.WithError(err).Warningf(ctx, "failed to close%s cache file", corruptText)
} else {
err = nil
}
if corrupt {
var err2 error
if err2 = f.fs.EnsureFileGone(ctx, f.Name()); err2 != nil {
logging.WithError(err2).Warningf(ctx, "failed to delete corrupt cache file")
}
// only return err2 if err was already nil
if err == nil {
err = err2
}
}
return err
} | go | func (f *cacheFile) Close(ctx context.Context, corrupt bool) error {
var err error
if err = f.File.Close(); err != nil && err != os.ErrClosed {
corruptText := ""
if corrupt {
corruptText = " corrupt"
}
logging.WithError(err).Warningf(ctx, "failed to close%s cache file", corruptText)
} else {
err = nil
}
if corrupt {
var err2 error
if err2 = f.fs.EnsureFileGone(ctx, f.Name()); err2 != nil {
logging.WithError(err2).Warningf(ctx, "failed to delete corrupt cache file")
}
// only return err2 if err was already nil
if err == nil {
err = err2
}
}
return err
} | [
"func",
"(",
"f",
"*",
"cacheFile",
")",
"Close",
"(",
"ctx",
"context",
".",
"Context",
",",
"corrupt",
"bool",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"if",
"err",
"=",
"f",
".",
"File",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"os",
".",
"ErrClosed",
"{",
"corruptText",
":=",
"\"",
"\"",
"\n",
"if",
"corrupt",
"{",
"corruptText",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
",",
"corruptText",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"corrupt",
"{",
"var",
"err2",
"error",
"\n",
"if",
"err2",
"=",
"f",
".",
"fs",
".",
"EnsureFileGone",
"(",
"ctx",
",",
"f",
".",
"Name",
"(",
")",
")",
";",
"err2",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err2",
")",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// only return err2 if err was already nil",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"err2",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Close removes this file from the cache if corrupt is true.
//
// This will be true if the cached file is determined to be broken at a higher
// level.
//
// This implements pkg.Source. | [
"Close",
"removes",
"this",
"file",
"from",
"the",
"cache",
"if",
"corrupt",
"is",
"true",
".",
"This",
"will",
"be",
"true",
"if",
"the",
"cached",
"file",
"is",
"determined",
"to",
"be",
"broken",
"at",
"a",
"higher",
"level",
".",
"This",
"implements",
"pkg",
".",
"Source",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L94-L116 |
7,997 | luci/luci-go | cipd/client/cipd/internal/instancecache.go | Get | func (c *InstanceCache) Get(ctx context.Context, pin common.Pin, now time.Time) (pkg.Source, error) {
if err := common.ValidatePin(pin, common.AnyHash); err != nil {
return nil, err
}
path, err := c.fs.RootRelToAbs(pin.InstanceID)
if err != nil {
return nil, fmt.Errorf("invalid instance ID %q", pin.InstanceID)
}
f, err := c.fs.OpenFile(path)
if err != nil {
return nil, err
}
c.withState(ctx, now, func(s *messages.InstanceCache) {
touch(s, pin.InstanceID, now)
})
return &cacheFile{f, c.fs}, nil
} | go | func (c *InstanceCache) Get(ctx context.Context, pin common.Pin, now time.Time) (pkg.Source, error) {
if err := common.ValidatePin(pin, common.AnyHash); err != nil {
return nil, err
}
path, err := c.fs.RootRelToAbs(pin.InstanceID)
if err != nil {
return nil, fmt.Errorf("invalid instance ID %q", pin.InstanceID)
}
f, err := c.fs.OpenFile(path)
if err != nil {
return nil, err
}
c.withState(ctx, now, func(s *messages.InstanceCache) {
touch(s, pin.InstanceID, now)
})
return &cacheFile{f, c.fs}, nil
} | [
"func",
"(",
"c",
"*",
"InstanceCache",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"pin",
"common",
".",
"Pin",
",",
"now",
"time",
".",
"Time",
")",
"(",
"pkg",
".",
"Source",
",",
"error",
")",
"{",
"if",
"err",
":=",
"common",
".",
"ValidatePin",
"(",
"pin",
",",
"common",
".",
"AnyHash",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"path",
",",
"err",
":=",
"c",
".",
"fs",
".",
"RootRelToAbs",
"(",
"pin",
".",
"InstanceID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pin",
".",
"InstanceID",
")",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"c",
".",
"fs",
".",
"OpenFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"withState",
"(",
"ctx",
",",
"now",
",",
"func",
"(",
"s",
"*",
"messages",
".",
"InstanceCache",
")",
"{",
"touch",
"(",
"s",
",",
"pin",
".",
"InstanceID",
",",
"now",
")",
"\n",
"}",
")",
"\n\n",
"return",
"&",
"cacheFile",
"{",
"f",
",",
"c",
".",
"fs",
"}",
",",
"nil",
"\n",
"}"
] | // Get searches for the instance in the cache and opens it for reading.
//
// If the instance is not found, returns an os.IsNotExists error. | [
"Get",
"searches",
"for",
"the",
"instance",
"in",
"the",
"cache",
"and",
"opens",
"it",
"for",
"reading",
".",
"If",
"the",
"instance",
"is",
"not",
"found",
"returns",
"an",
"os",
".",
"IsNotExists",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L126-L146 |
7,998 | luci/luci-go | cipd/client/cipd/internal/instancecache.go | Put | func (c *InstanceCache) Put(ctx context.Context, pin common.Pin, now time.Time, write func(*os.File) error) error {
if err := common.ValidatePin(pin, common.AnyHash); err != nil {
return err
}
path, err := c.fs.RootRelToAbs(pin.InstanceID)
if err != nil {
return fmt.Errorf("invalid instance ID %q", pin.InstanceID)
}
if err := c.fs.EnsureFile(ctx, path, write); err != nil {
return err
}
c.withState(ctx, now, func(s *messages.InstanceCache) {
touch(s, pin.InstanceID, now)
c.gc(ctx, s, now)
})
return nil
} | go | func (c *InstanceCache) Put(ctx context.Context, pin common.Pin, now time.Time, write func(*os.File) error) error {
if err := common.ValidatePin(pin, common.AnyHash); err != nil {
return err
}
path, err := c.fs.RootRelToAbs(pin.InstanceID)
if err != nil {
return fmt.Errorf("invalid instance ID %q", pin.InstanceID)
}
if err := c.fs.EnsureFile(ctx, path, write); err != nil {
return err
}
c.withState(ctx, now, func(s *messages.InstanceCache) {
touch(s, pin.InstanceID, now)
c.gc(ctx, s, now)
})
return nil
} | [
"func",
"(",
"c",
"*",
"InstanceCache",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"pin",
"common",
".",
"Pin",
",",
"now",
"time",
".",
"Time",
",",
"write",
"func",
"(",
"*",
"os",
".",
"File",
")",
"error",
")",
"error",
"{",
"if",
"err",
":=",
"common",
".",
"ValidatePin",
"(",
"pin",
",",
"common",
".",
"AnyHash",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"path",
",",
"err",
":=",
"c",
".",
"fs",
".",
"RootRelToAbs",
"(",
"pin",
".",
"InstanceID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pin",
".",
"InstanceID",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"c",
".",
"fs",
".",
"EnsureFile",
"(",
"ctx",
",",
"path",
",",
"write",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"withState",
"(",
"ctx",
",",
"now",
",",
"func",
"(",
"s",
"*",
"messages",
".",
"InstanceCache",
")",
"{",
"touch",
"(",
"s",
",",
"pin",
".",
"InstanceID",
",",
"now",
")",
"\n",
"c",
".",
"gc",
"(",
"ctx",
",",
"s",
",",
"now",
")",
"\n",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Put caches an instance.
//
// write must write the instance contents. May remove some instances from the
// cache that were not accessed for a long time. | [
"Put",
"caches",
"an",
"instance",
".",
"write",
"must",
"write",
"the",
"instance",
"contents",
".",
"May",
"remove",
"some",
"instances",
"from",
"the",
"cache",
"that",
"were",
"not",
"accessed",
"for",
"a",
"long",
"time",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L152-L170 |
7,999 | luci/luci-go | cipd/client/cipd/internal/instancecache.go | GC | func (c *InstanceCache) GC(ctx context.Context, now time.Time) {
c.withState(ctx, now, func(s *messages.InstanceCache) {
c.gc(ctx, s, now)
})
} | go | func (c *InstanceCache) GC(ctx context.Context, now time.Time) {
c.withState(ctx, now, func(s *messages.InstanceCache) {
c.gc(ctx, s, now)
})
} | [
"func",
"(",
"c",
"*",
"InstanceCache",
")",
"GC",
"(",
"ctx",
"context",
".",
"Context",
",",
"now",
"time",
".",
"Time",
")",
"{",
"c",
".",
"withState",
"(",
"ctx",
",",
"now",
",",
"func",
"(",
"s",
"*",
"messages",
".",
"InstanceCache",
")",
"{",
"c",
".",
"gc",
"(",
"ctx",
",",
"s",
",",
"now",
")",
"\n",
"}",
")",
"\n",
"}"
] | // GC opportunistically purges entries that haven't been touched for too long. | [
"GC",
"opportunistically",
"purges",
"entries",
"that",
"haven",
"t",
"been",
"touched",
"for",
"too",
"long",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L173-L177 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.